From d6ea018634873095679cc5fdae3d1d19cb09621b Mon Sep 17 00:00:00 2001 From: Maximiliano Lira Del Canto <8040628+mliradelc@users.noreply.github.com> Date: Tue, 12 Apr 2022 16:03:21 +0200 Subject: [PATCH 1/8] Update Paella Player to version 6.5.6 --- node_modules/.package-lock.json | 1827 ++ node_modules/paellaplayer/.babelrc | 8 + node_modules/paellaplayer/.browserslistrc | 1 + node_modules/paellaplayer/.eslintrc.js | 27 + .../paellaplayer/.github/CONTRIBUTING.md | 47 + .../.github/ISSUE_TEMPLATE/bug_report.md | 36 + .../.github/ISSUE_TEMPLATE/feature_request.md | 12 + .../.github/ISSUE_TEMPLATE/usage_question.md | 14 + .../.github/PULL_REQUEST_TEMPLATE.md | 28 + .../paellaplayer/.github/dependabot.yml | 36 + .../.github/workflows/node.js.yml | 23 + node_modules/paellaplayer/.jshintrc | 9 + node_modules/paellaplayer/.markdownlint.json | 14 + node_modules/paellaplayer/.npmignore | 14 + .../.publish_scripts/bower/bower.json | 11 + .../.publish_scripts/bower/publish.sh | 144 + .../.publish_scripts/is_prerelease_version.sh | 26 + .../.publish_scripts/npm/publish.sh | 128 + .../paellaplayer/.publish_scripts/publish.sh | 45 + .../.publish_scripts/publish_on_branch.sh | 75 + .../.publish_scripts/publish_on_tag.sh | 67 + .../.publish_scripts/tarball/publish.sh | 93 + .../paellaplayer/.publish_scripts/utility.sh | 44 + .../.publish_scripts/webpage/publish_doc.sh | 142 + .../webpage/publish_player.sh | 152 + node_modules/paellaplayer/.travis.yml | 46 + .../.travis_scripts/prepate_deploy.sh | 6 + node_modules/paellaplayer/CHANGELOG | 858 + node_modules/paellaplayer/CHANGELOG-DEV | 6 + node_modules/paellaplayer/README.md | 24 +- .../build/player/javascript/bg2e-es2015.js | 18403 ------------ .../player/javascript/cookieconsent.min.js | 1 - .../build/player/javascript/hls.min.js | 2 - .../build/player/javascript/jquery.min.js | 2 - .../build/player/javascript/lunr.min.js | 51 - .../build/player/javascript/paella_player.js | 24700 ---------------- .../player/javascript/paella_player_es2015.js | 19469 ------------ .../build/player/javascript/polyfill.min.js | 1 - .../build/player/javascript/require.js | 2145 -- .../build/player/localization/paella_de.json | 64 - .../build/player/localization/paella_en.json | 1 - .../build/player/localization/paella_es.json | 102 - .../build/player/localization/paella_eu.json | 90 - .../build/player/localization/paella_fr.json | 100 - .../build/player/localization/paella_gl.json | 90 - .../build/player/localization/paella_zh.json | 126 - .../player/resources/style/style_dark.css | 4227 --- .../resources/style/style_dark_small.css | 4227 --- .../player/resources/style/style_light.css | 4227 --- .../resources/style/style_light_small.css | 4227 --- .../repository/hls-multiquality/data.json | 28 - .../javascript/jquery.min.js | 2 - .../build/tools/rtmp-test/jquery.min.js | 2 - .../{build/player => }/config/config.json | 6 +- .../player => }/config/profiles/profiles.json | 0 .../profiles/resources/default_background.jpg | Bin .../resources/default_background_paella.jpg | Bin .../config/profiles/resources/logo.png | Bin .../config/profiles/resources/paella_logo.png | Bin .../profiles/resources/paella_logo_old.png | Bin .../profiles/resources/professor_slide.jpg | Bin .../resources/professor_slide_paella.jpg | Bin .../profiles/resources/slide_professor.jpg | Bin .../resources/slide_professor_paella.jpg | Bin .../doc/adopters/analytics_elasticsearch.md | 21 + .../doc/adopters/analytics_google.md | 21 + .../doc/adopters/browser_compability.md | 14 + .../paellaplayer/doc/adopters/build_paella.md | 52 + .../paellaplayer/doc/adopters/configure.md | 121 + .../doc/adopters/download_paella.md | 6 + .../adopters/download_precompiled_paella.md | 55 + .../paellaplayer/doc/adopters/encoding.md | 41 + .../doc/adopters/hls_multiaudio.md | 145 + .../doc/adopters/icon-photo-sample.jpg | Bin 0 -> 17013 bytes .../doc/adopters/integrate/integrate.md | 55 + .../adopters/integrate/integrate_advanced.md | 177 + .../doc/adopters/integrate/integrate_basic.md | 38 + .../integrate/integrate_intermediate.md | 134 + .../doc/adopters/integrate_datajson.md | 292 + .../paellaplayer/doc/adopters/plugins.md | 67 + ...arvard.dce.paella.flexSkipForwardPlugin.md | 30 + .../edu.harvard.dce.paella.flexSkipPlugin.md | 30 + ...s.upv.paella.arrowSlidesNavigatorPlugin.md | 32 + .../plugins/es.upv.paella.blackBoardPlugin.md | 24 + .../es.upv.paella.breaksPlayerPlugin.md | 22 + ...es.upv.paella.captions.DFXPParserPlugin.md | 27 + .../plugins/es.upv.paella.captionsPlugin.md | 39 + .../plugins/es.upv.paella.commentsPlugin.md | 25 + .../es.upv.paella.extendedTabAdapterPlugin.md | 25 + .../plugins/es.upv.paella.footprintsPlugin.md | 47 + .../es.upv.paella.frameControlPlugin.md | 33 + .../es.upv.paella.fullScreenButtonPlugin.md | 44 + .../plugins/es.upv.paella.helpPlugin.md | 23 + ....upv.paella.liveStramingIndicatorPlugin.md | 22 + .../plugins/es.upv.paella.mpegDashPlayer.md | 10 + .../es.upv.paella.multipleQualitiesPlugin.md | 46 + .../es.upv.paella.overlayCaptionsPlugin.md | 31 + .../es.upv.paella.playButtonOnScreenPlugin.md | 22 + .../es.upv.paella.playPauseButtonPlugin.md | 26 + .../es.upv.paella.playbackRatePlugin.md | 33 + .../plugins/es.upv.paella.rtmpPlayer.md | 11 + ....upv.paella.search.captionsSearchPlugin.md | 26 + .../plugins/es.upv.paella.searchPlugin.md | 46 + .../plugins/es.upv.paella.showEditorPlugin.md | 40 + .../plugins/es.upv.paella.socialPlugin.md | 23 + .../es.upv.paella.test.tabBarExamplePlugin.md | 25 + .../es.upv.paella.themeChooserPlugin.md | 25 + ....upv.paella.translecture.captionsPlugin.md | 46 + .../es.upv.paella.trimmingPlayerPlugin.md | 22 + ...a.usertracking.elasticsearchSaverPlugin.md | 39 + ...usertracking.googleAnalyticsSaverPlugin.md | 39 + ...pv.paella.usertracking.piwikSaverPlugIn.md | 40 + .../plugins/es.upv.paella.viewModePlugin.md | 41 + .../es.upv.paella.visualAnnotationPlugin.md | 139 + .../es.upv.paella.volumeRangePlugin.md | 40 + .../es.upv.paella.windowTitlePlugin.md | 22 + .../plugins/images/arrowSlidesNavigator.png | Bin 0 -> 143406 bytes .../plugins/images/blackBoardPlugin.jpg | Bin 0 -> 26305 bytes .../plugins/images/captionsButtonPlugin.jpg | Bin 0 -> 21282 bytes .../images/extendedTabAdapterPlugin.jpg | Bin 0 -> 17578 bytes .../plugins/images/flexSkipPlugin.jpg | Bin 0 -> 16191 bytes .../plugins}/images/footprintsPlugin.jpg | Bin .../plugins/images/frameControlPlugin.jpg | Bin 0 -> 27017 bytes .../plugins/images/fullScreenButtonPlugin.jpg | Bin 0 -> 16982 bytes .../adopters/plugins}/images/helpPlugin.jpg | Bin .../images/multipleQualitiesPlugin.jpg | Bin 0 -> 23331 bytes .../plugins/images/overlayCaptionsPlugin.jpg | Bin 0 -> 24183 bytes .../plugins/images/playPauseButtonPlugin.jpg | Bin 0 -> 18201 bytes .../adopters/plugins/images/playbackRate.jpg | Bin 0 -> 22189 bytes .../adopters/plugins/images/searchPlugin.jpg | Bin 0 -> 20574 bytes .../adopters/plugins/images/socialPlugin.jpg | Bin 0 -> 21159 bytes .../plugins}/images/tabBarExamplePlugin.jpg | Bin .../plugins}/images/themeChooserPlugin.jpg | Bin .../plugins}/images/viewModePlugin.jpg | Bin .../plugins/images/visualAnnotations0.png | Bin 0 -> 323593 bytes .../plugins/images/visualAnnotations1.png | Bin 0 -> 345682 bytes .../plugins/images/visualAnnotations2.png | Bin 0 -> 565535 bytes .../plugins/images/visualAnnotations3.png | Bin 0 -> 343839 bytes .../plugins/images/visualAnnotations4.png | Bin 0 -> 168071 bytes .../plugins/images/volumeRangePlugin.jpg | Bin 0 -> 18825 bytes .../paellaplayer/doc/adopters/setup.md | 9 + .../paellaplayer/doc/adopters/skining.md | 59 + .../doc/assets/images/capture_player.jpg | Bin 0 -> 66266 bytes .../paella_5_3_plugin_migration.md | 80 + .../doc/developers/introduction.md | 36 + .../doc/developers/paella_data.md | 106 + .../doc/developers/plugin_config.md | 48 + .../doc/developers/plugin_creation.md | 127 + .../doc/developers/plugin_types.md | 242 + .../doc/developers/url_parameters.md | 32 + .../doc/examples/buffered_playback_canvas.md | 88 + .../doc/examples/button_plugin.md | 110 + .../doc/examples/es.upv.paella.hlsPlayer.md | 443 + .../es.upv.paella.playButtonOnScreenPlugin.md | 54 + ...usertracking.googleAnalyticsSaverPlugin.md | 67 + .../paellaplayer/doc/examples/key_plugin.md | 107 + .../doc/examples/multi_quality_plugin.md | 76 + .../paellaplayer/doc/examples/popup_plugin.md | 45 + .../doc/examples/timeline_plugin.md | 58 + .../doc/examples/video_overlay.md | 37 + node_modules/paellaplayer/doc/faq.md | 59 + node_modules/paellaplayer/doc/introduction.md | 26 + node_modules/paellaplayer/doc/toc.yml | 37 + node_modules/paellaplayer/doc/upgrade.md | 42 + .../doc/users/images/Paella tools.png | Bin 0 -> 231047 bytes .../doc/users/images/paella_tools.png | Bin 0 -> 231047 bytes .../doc/users/images/player_composition.jpg | Bin 0 -> 75585 bytes .../doc/users/images/player_editor.jpg | Bin 0 -> 71896 bytes .../doc/users/images/player_editor2.jpg | Bin 0 -> 78224 bytes .../doc/users/images/player_footprints.jpg | Bin 0 -> 88538 bytes .../doc/users/images/player_fullscreen.jpg | Bin 0 -> 67983 bytes .../doc/users/images/player_main.jpg | Bin 0 -> 67335 bytes .../doc/users/images/player_play.jpg | Bin 0 -> 68343 bytes .../doc/users/images/player_repeat.jpg | Bin 0 -> 68735 bytes .../doc/users/images/player_resolution.jpg | Bin 0 -> 70923 bytes .../doc/users/images/player_share.jpg | Bin 0 -> 70805 bytes .../doc/users/images/player_skin.jpg | Bin 0 -> 71440 bytes .../doc/users/images/player_slides.jpg | Bin 0 -> 73579 bytes .../doc/users/images/player_speed.jpg | Bin 0 -> 71691 bytes .../doc/users/images/player_volume.jpg | Bin 0 -> 68362 bytes .../doc/users/images/player_zoom.jpg | Bin 0 -> 68457 bytes .../doc/users/images/player_zoom2.jpg | Bin 0 -> 59286 bytes .../paellaplayer/doc/users/usage_guide.md | 123 + .../{build/player => }/example.html | 0 node_modules/paellaplayer/example.js | 261 + node_modules/paellaplayer/gulpfile.js | 313 + .../paellaplayer/icons-src/airplay.svg | 11 + .../paellaplayer/icons-src/arrow-down.svg | 7 + .../paellaplayer/icons-src/arrow-left.svg | 7 + .../paellaplayer/icons-src/arrow-right.svg | 7 + .../paellaplayer/icons-src/arrow-up.svg | 7 + .../paellaplayer/icons-src/back-10-s.svg | 16 + .../paellaplayer/icons-src/back-30-s.svg | 16 + .../paellaplayer/icons-src/captions.svg | 5 + .../icons-src/comments-disabled.svg | 5 + .../paellaplayer/icons-src/comments.svg | 5 + node_modules/paellaplayer/icons-src/edit.svg | 14 + .../paellaplayer/icons-src/facebook.svg | 7 + .../paellaplayer/icons-src/folder.svg | 15 + .../paellaplayer/icons-src/forward-30-s.svg | 16 + .../paellaplayer/icons-src/frames.svg | 7 + .../paellaplayer/icons-src/fullscreen.svg | 27 + .../paellaplayer/icons-src/headphone.svg | 13 + node_modules/paellaplayer/icons-src/help.svg | 5 + node_modules/paellaplayer/icons-src/info.svg | 9 + node_modules/paellaplayer/icons-src/link.svg | 7 + .../paellaplayer/icons-src/mini-camera.svg | 5 + .../paellaplayer/icons-src/mini-frames.svg | 14 + .../icons-src/mini-videocamera.svg | 5 + .../paellaplayer/icons-src/mini-window.svg | 5 + .../paellaplayer/icons-src/mini-zoom-in.svg | 5 + .../paellaplayer/icons-src/mini-zoom-out.svg | 5 + .../paellaplayer/icons-src/paintbrush.svg | 7 + node_modules/paellaplayer/icons-src/pause.svg | 7 + node_modules/paellaplayer/icons-src/photo.svg | 5 + node_modules/paellaplayer/icons-src/pip.svg | 5 + node_modules/paellaplayer/icons-src/play.svg | 7 + .../paellaplayer/icons-src/player-mode-1.svg | 5 + .../paellaplayer/icons-src/player-mode-2.svg | 5 + .../paellaplayer/icons-src/player-mode-3.svg | 5 + .../present-mode-1.svg} | 0 .../present-mode-10.svg} | 0 .../icons-src/present-mode-11.afdesign | Bin 0 -> 24169 bytes .../present-mode-2.svg} | 0 .../present-mode-3.svg} | 0 .../present-mode-4.svg} | 0 .../present-mode-5.svg} | 0 .../present-mode-6.svg} | 0 .../present-mode-7.svg} | 0 .../present-mode-8.svg} | 0 .../present-mode-9.svg} | 0 .../icons-src/presentation-mode.svg | 5 + .../paellaplayer/icons-src/screen.svg | 7 + .../paellaplayer/icons-src/slideshow.svg | 5 + .../paellaplayer/icons-src/social.svg | 7 + .../paellaplayer/icons-src/star-empty.svg | 5 + node_modules/paellaplayer/icons-src/star.svg | 9 + node_modules/paellaplayer/icons-src/stats.svg | 11 + .../paellaplayer/icons-src/twitter.svg | 7 + node_modules/paellaplayer/icons-src/user.svg | 14 + .../paellaplayer/icons-src/volume-high.svg | 16 + .../paellaplayer/icons-src/volume-low.svg | 14 + .../paellaplayer/icons-src/volume-mid.svg | 17 + .../paellaplayer/icons-src/volume-mute.svg | 7 + .../paellaplayer/icons-src/windowed.svg | 23 + .../paellaplayer/icons-src/zoom-in.svg | 5 + node_modules/paellaplayer/icons-src/zoom.svg | 5 + .../{build/player => }/index-custom.html | 0 .../{build/player => }/index-debug.html | 0 .../{build/player => }/index.html | 0 node_modules/paellaplayer/license.txt | 128 + .../localization/dictionary_de.json | 54 + .../localization/dictionary_en.json | 1 + .../localization/dictionary_es.json | 56 + .../localization/dictionary_eu.json | 55 + .../localization/dictionary_fr.json | 103 + .../localization/dictionary_gl.json | 55 + .../dictionary_ru.json} | 14 +- .../localization/dictionary_zh.json | 79 + node_modules/paellaplayer/main.js | 53 + node_modules/paellaplayer/package-lock.json | 10910 +++++++ node_modules/paellaplayer/package.json | 67 +- node_modules/paellaplayer/paella-debug.js | 70 + .../paellaplayer/paella-standalone.js | 466 + .../paellaplayer/paella_icons.afdesign | Bin 0 -> 125486 bytes .../README.md | 34 + .../playButtonOnScreenAlwaysPlugin.js | 106 + .../playButtonOnScreenAlwaysPlugin.less | 27 + .../screenshot.png | Bin 0 -> 870954 bytes .../flexskipbutton.js | 58 + .../flexskipbutton.less | 7 + .../webvtt_parser.js | 71 + .../deps/random_name_generator.js | 0 .../deps/xapiwrapper.min.js | 0 .../xAPISaverPlugin.js | 529 + .../plugins/es.upv.defaultProfiles/main.js | 483 + .../resources/chroma.svg | 6 + .../resources}/default_background.jpg | Bin .../resources}/default_background_paella.jpg | Bin .../resources}/icon_rotate.svg | 0 .../resources}/icon_switch.svg | 0 .../resources}/logo.png | Bin .../resources}/minimize.svg | 0 .../resources}/paella_logo.png | Bin .../resources}/paella_logo_old.png | Bin .../resources/professor_icon.svg | 5 + .../resources/professor_over_slide_icon.svg | 6 + .../professor_over_slide_right_icon.svg | 6 + .../resources}/professor_slide.jpg | Bin .../resources/professor_slide_icon.svg | 14 + .../resources}/professor_slide_paella.jpg | Bin .../resources/s_p_blackboard.svg | 17 + .../resources/slide_icon.svg | 5 + .../resources/slide_over_professor_icon.svg | 6 + .../slide_over_professor_right_icon.svg | 14 + .../resources}/slide_professor.jpg | Bin .../resources/slide_professor_icon.svg | 5 + .../resources}/slide_professor_paella.jpg | Bin .../resources}/three_streams_icon.svg | 0 .../plugins/es.upv.defaultProfiles/style.css | 14 + .../localization/es.json | 3 + .../localization/eu.json | 3 + .../localization/gl.json | 3 + .../localization/zh.json | 3 + .../trimming_player.js | 50 + .../es.upv.paella.airplayPlugin/main.js | 51 + .../es.upv.paella.airplayPlugin/style.css | 7 + .../arrowSlidesNavigator.js | 217 + .../arrowSlidesNavigator.less | 19 + .../audio-selector.less | 25 + .../es.upv.paella.audioSelector/index.js | 108 + .../blackBoard.js | 341 + .../blackBoard.less | 23 + .../editor.js.disabled | 144 + .../localization/es.json | 9 + .../localization/eu.json | 7 + .../localization/gl.json | 9 + .../localization/zh.json | 7 + .../es.upv.paella.breakPlugins/player.js | 91 + .../es.upv.paella.breakPlugins/player.less | 10 + .../main.js | 29 + .../dfxp_parser.js | 76 + .../captions.less | 129 + .../captionsPlugin.js | 400 + .../localization/es.json | 5 + .../localization/eu.json | 5 + .../localization/gl.json | 5 + .../localization/zh.json | 5 + .../overlayCaptionsPlugin.js | 148 + .../chroma-player.js | 531 + .../es.upv.paella.commentsPlugin/comments.js | 425 + .../comments.less | 74 + .../localization/es.json | 5 + .../localization/eu.json | 5 + .../localization/gl.json | 5 + .../localization/zh.json | 5 + .../description.js | 30 + .../description.less | 0 .../adapter.js | 29 + .../adapter.less | 90 + .../footprints.js | 181 + .../footprints.less | 18 + .../localization/es.json | 3 + .../localization/eu.json | 3 + .../localization/gl.json | 3 + .../localization/zh.json | 3 + .../resources}/statistics_icon.png | Bin .../framecontrol.js | 404 + .../framecontrol.less | 140 + .../localization/es.json | 3 + .../localization/eu.json | 3 + .../localization/gl.json | 3 + .../localization/zh.json | 3 + .../resources}/hscroll_arrows.png | Bin .../resources}/hscroll_arrows_orange.png | Bin .../resources}/slides_icon.png | Bin .../fullscreenbutton.js | 90 + .../fullscreenbutton.less | 7 + .../localization/es.json | 5 + .../localization/eu.json | 4 + .../localization/gl.json | 5 + .../localization/zh.json | 5 + .../plugins/es.upv.paella.helpPlugin/help.js | 36 + .../es.upv.paella.helpPlugin/help.less | 3 + .../localization/es.json | 4 + .../localization/eu.json | 4 + .../localization/gl.json | 4 + .../localization/zh.json | 4 + .../resources}/help/help_en.html | 0 .../resources}/help/help_es.html | 0 .../resources}/help/help_ru.html | 0 .../resources}/help/help_zh.html | 0 .../help/images/blackBoardPlugin.jpg | Bin .../help/images/captionsButtonPlugin.jpg | Bin .../resources}/help/images/editor.jpg | Bin .../resources}/help/images/flexSkipPlugin.jpg | Bin .../help/images/footprintsPlugin.jpg | Bin 0 -> 16351 bytes .../help/images/frameControlPlugin.jpg | Bin .../help/images/fullScreenButtonPlugin.jpg | Bin .../resources/help/images/helpPlugin.jpg | Bin 0 -> 17448 bytes .../help/images/multipleQualitiesPlugin.jpg | Bin .../help/images/playPauseButtonPlugin.jpg | Bin .../resources}/help/images/playbackRate.jpg | Bin .../resources}/help/images/player_main.jpg | Bin .../resources}/help/images/ratePlugin.jpg | Bin .../resources}/help/images/searchPlugin.jpg | Bin .../resources}/help/images/socialPlugin.jpg | Bin .../help/images/tabBarExamplePlugin.jpg | Bin 0 -> 27765 bytes .../help/images/themeChooserPlugin.jpg | Bin 0 -> 23839 bytes .../resources/help/images/viewModePlugin.jpg | Bin 0 -> 25530 bytes .../help/images/volumeRangePlugin.jpg | Bin .../resources}/help/style.css | 0 .../es.upv.paella.hlsPlayer/hls-player.js | 498 + .../plugins/es.upv.paella.keyPlugin/main.js | 171 + .../plugins/es.upv.paella.legal/main.js | 28 + .../plugins/es.upv.paella.legal/style.css | 26 + .../live_stream_indicator.js | 21 + .../live_stream_indicator.less | 9 + .../localization/es.json | 4 + .../localization/eu.json | 4 + .../localization/gl.json | 4 + .../localization/zh.json | 4 + .../resources}/live_video.png | Bin .../deps/dash.all.js | 0 .../mpeg-dash-player.js | 238 + .../localization/es.json | 5 + .../localization/eu.json | 5 + .../localization/gl.json | 5 + .../localization/zh.json | 5 + .../qualities.js | 69 + .../qualities.less | 8 + .../es.upv.paella.pipModePlugin/main.js | 52 + .../es.upv.paella.pipModePlugin/style.css | 3 + .../localization/es.json | 4 + .../localization/eu.json | 4 + .../localization/gl.json | 4 + .../localization/zh.json | 4 + .../playbutton.js | 61 + .../playbutton.less | 35 + .../playbutton_onscreen.js | 118 + .../playback_rate.js | 62 + .../playback_rate.less | 11 + .../localization/es.json | 6 + .../localization/eu.json | 6 + .../localization/gl.json | 6 + .../localization/zh.json | 6 + .../plugins/es.upv.paella.ratePlugin/main.js | 139 + .../es.upv.paella.ratePlugin/rates.less | 34 + .../main.css | 43 + .../es.upv.paella.relatedVideosPlugin/main.js | 104 + .../captionsSearch.js | 12 + .../localization/es.json | 4 + .../localization/eu.json | 4 + .../localization/gl.json | 4 + .../localization/zh.json | 4 + .../es.upv.paella.searchPlugin/search.js | 282 + .../es.upv.paella.searchPlugin/search.less | 119 + .../localization/es.json | 8 + .../localization/zh.json | 8 + .../es.upv.paella.sharePlugin/share.js | 197 + .../es.upv.paella.sharePlugin/share.less | 30 + .../localization/es.json | 3 + .../localization/eu.json | 3 + .../localization/gl.json | 3 + .../localization/zh.json | 3 + .../themechooser.js | 43 + .../themechooser.less | 24 + .../main.js | 37 + .../es.upv.paella.track4kPlugin/main.js | 289 + .../es.upv.paella.track4kPlugin/style.css | 20 + .../localization/es.json | 6 + .../localization/eu.json | 6 + .../localization/gl.json | 6 + .../localization/zh.json | 6 + .../resources}/caption_mlangs_anonymous.png | Bin .../resources}/caption_mlangs_lock.png | Bin .../translectures.js | 172 + .../translectures.less | 36 + .../elasticsearchSaverPlugin.js | 45 + .../usertracking_googleanalytics_saver.js | 52 + .../piwik_saver.js | 39 + .../es.upv.paella.video360Player/video360.js | 59 + .../video360theta.js | 166 + .../plugins/es.upv.paella.videoData/index.js | 77 + .../es.upv.paella.videoData/videoData.less | 42 + .../es.upv.paella.videoZoom/video_zoom.js | 237 + .../es.upv.paella.videoZoom/video_zoom.less | 123 + .../localization/es.json | 3 + .../localization/eu.json | 3 + .../localization/gl.json | 3 + .../localization/zh.json | 3 + .../es.upv.paella.viewModePlugin/viewmode.js | 111 + .../viewmode.less | 13 + .../localization/es.json | 3 + .../localization/eu.json | 3 + .../localization/gl.json | 3 + .../localization/zh.json | 3 + .../volumeRange.js | 113 + .../volumeRange.less | 126 + .../es.upv.paella.webmPlayer/webm-player.js | 33 + .../window_title.js | 23 + .../youtube-player.js | 394 + node_modules/paellaplayer/plugins/ignore.json | 5 + .../localization/de.json | 7 + .../localization/zh.json | 7 + .../usertracking_matomo_saver.js | 298 + .../usertracking_matomo_saver.less | 341 + .../localization/de.json | 7 + .../localization/es.json | 7 + .../localization/zh.json | 7 + .../usertracking_x5gon_saver.js | 183 + .../usertracking_x5gon_saver.less | 341 + .../{build => repository_test}/index.html | 0 .../repository/audio-and-images/data.json | 0 .../belmar-multiresolution-remote/data.json | 0 .../episode.json | 0 .../trackhd.json | 0 .../repository/chroma/data.json | 0 .../repository/convert.js | 0 .../repository/dual-video-audio/data.json | 0 .../repository/ethz/data.json | 0 .../repository/hevc-test/data.json | 0 .../repository/hls-live/data.json | 0 .../blender-foundation-sintel.jpg | Bin .../repository/hls-multiaudio/data.json | 0 .../repository/hls-multiquality/data.json | 41 + .../repository/hls/data.json | 5 +- .../jordan-blackboard-remote/data.json | 0 .../jordan-blackboard-remote/episode.json | 0 .../repository/mpeg-dash/data.json | 0 .../repository/multi-format/data.json | 0 .../repository/multi-lang-audio/data.json | 0 .../repository/multi-lang-captions/data.json | 0 .../repository/n-stream/data.json | 0 .../repository/video-remote-1/data.json | 0 .../repository/video-remote-1/episode.json | 0 .../repository/video360-theta/data.json | 0 .../repository/video360/data.json | 0 .../webvtt-captions/captions.es.vtt | 0 .../repository/webvtt-captions/data.json | 0 .../repository/webvtt-captions/episode.json | 0 .../repository/youtube/data.json | 0 .../test_player.html | 0 .../resources/bootstrap/css/bootstrap.min.css | 0 .../bootstrap/css/bootstrap.slate.min.css | 0 .../fonts/glyphicons-halflings-regular.eot | Bin .../fonts/glyphicons-halflings-regular.svg | 0 .../fonts/glyphicons-halflings-regular.ttf | Bin .../fonts/glyphicons-halflings-regular.woff | Bin .../fonts/glyphicons-halflings-regular.woff2 | Bin .../img/glyphicons-halflings-white.png | Bin .../bootstrap/img/glyphicons-halflings.png | Bin .../resources/bootstrap/js/bootstrap.js | 0 .../resources/bootstrap/js/bootstrap.min.js | 0 .../player => }/resources/bootstrap/js/npm.js | 0 .../player => }/resources/images/chrome.png | Bin .../resources/images/error_icon.png | Bin .../player => }/resources/images/explorer.png | Bin .../player => }/resources/images/firefox.png | Bin .../resources/images/paella_icons_dark.png | Bin .../resources/images/paella_icons_light.png | Bin .../player => }/resources/images/play.svg | 0 .../player => }/resources/images/safari.png | Bin .../resources/style/controls.less | 619 + .../resources/style/defaultvars.less | 1 + .../paellaplayer/resources/style/editor.less | 241 + .../resources/style/fonts/icomoon.eot | Bin .../resources/style/fonts/icomoon.svg | 0 .../resources/style/fonts/icomoon.ttf | Bin .../resources/style/fonts/icomoon.woff | Bin .../resources/style/icon-index.html | 9047 ++++++ .../paellaplayer/resources/style/icons.css | 1679 ++ .../resources/style/skins/dark.less | 52 + .../resources/style/skins/dark_small.less | 52 + .../resources/style/skins/light.less | 52 + .../resources/style/skins/light_small.less | 52 + node_modules/paellaplayer/src/00_base.js | 102 + .../paellaplayer/src/00_utils_ajax.js | 229 + .../paellaplayer/src/00_utils_data.js | 169 + .../paellaplayer/src/00_utils_dictionary.js | 28 + .../paellaplayer/src/00_utils_message_box.js | 233 + .../paellaplayer/src/00_utils_parameters.js | 182 + .../paellaplayer/src/00_utils_user_agent.js | 355 + node_modules/paellaplayer/src/01_utils.js | 608 + node_modules/paellaplayer/src/02_nodes.js | 160 + node_modules/paellaplayer/src/02_profiles.js | 323 + .../paellaplayer/src/02_video_utils.js | 166 + .../paellaplayer/src/03_audio_nodes.js | 265 + .../paellaplayer/src/03_video_nodes.js | 1658 ++ .../paellaplayer/src/04_video_container.js | 1560 + .../paellaplayer/src/05_plugin_base.js | 854 + .../paellaplayer/src/05_video_canvas.js | 451 + .../paellaplayer/src/06_1_captions.js | 306 + .../paellaplayer/src/06_2_search_service.js | 95 + .../paellaplayer/src/06_3_user_tracking.js | 162 + .../paellaplayer/src/06_ui_controls.js | 1000 + node_modules/paellaplayer/src/07_ui_extras.js | 136 + .../paellaplayer/src/08_paella_core.js | 319 + .../paellaplayer/src/09_paella_player.js | 577 + node_modules/paellaplayer/src/10_loader.js | 366 + .../src/10_paella_extended_adapter.js | 189 + node_modules/paellaplayer/src/99_export.js | 4 + .../tests/nightwatch/nightwatch.js | 43 + .../playButtonOnScreen/playButtonTest.js | 14 + .../nightwatch/tests/simple/simpleTests.js | 9 + .../testExtendedTabAdapterButton.js | 23 + .../tests/testHelpButton/testHelpButton.js | 26 + .../tests/testRateButton/testRateButton.js | 25 + .../paellaplayer/tests/start_selenium.sh | 7 + .../paellaplayer/tests/stop_selenium.sh | 7 + node_modules/paellaplayer/tools/index.html | 29 + .../tools/layout_calculator/index.html | 66 + .../javascript/layoutCalculator.js | 49 + .../tools/mediapackagecreator/index.html | 71 + .../javascript/jsoneditor.min.js | 10 + .../mediapackagecreator/paella.schema.json | 273 + .../videostream.schema.json | 42 + .../paellaplayer/vendor/images/.gitkeep | 0 .../paellaplayer/vendor/plugins/.gitkeep | 0 .../paellaplayer/vendor/skins/.gitkeep | 0 package-lock.json | 1864 +- package.json | 2 +- 602 files changed, 57974 insertions(+), 82375 deletions(-) create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/paellaplayer/.babelrc create mode 100644 node_modules/paellaplayer/.browserslistrc create mode 100644 node_modules/paellaplayer/.eslintrc.js create mode 100644 node_modules/paellaplayer/.github/CONTRIBUTING.md create mode 100644 node_modules/paellaplayer/.github/ISSUE_TEMPLATE/bug_report.md create mode 100644 node_modules/paellaplayer/.github/ISSUE_TEMPLATE/feature_request.md create mode 100644 node_modules/paellaplayer/.github/ISSUE_TEMPLATE/usage_question.md create mode 100644 node_modules/paellaplayer/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 node_modules/paellaplayer/.github/dependabot.yml create mode 100644 node_modules/paellaplayer/.github/workflows/node.js.yml create mode 100644 node_modules/paellaplayer/.jshintrc create mode 100644 node_modules/paellaplayer/.markdownlint.json create mode 100644 node_modules/paellaplayer/.npmignore create mode 100644 node_modules/paellaplayer/.publish_scripts/bower/bower.json create mode 100755 node_modules/paellaplayer/.publish_scripts/bower/publish.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/is_prerelease_version.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/npm/publish.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/publish.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/publish_on_branch.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/publish_on_tag.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/tarball/publish.sh create mode 100644 node_modules/paellaplayer/.publish_scripts/utility.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/webpage/publish_doc.sh create mode 100755 node_modules/paellaplayer/.publish_scripts/webpage/publish_player.sh create mode 100644 node_modules/paellaplayer/.travis.yml create mode 100755 node_modules/paellaplayer/.travis_scripts/prepate_deploy.sh create mode 100644 node_modules/paellaplayer/CHANGELOG create mode 100644 node_modules/paellaplayer/CHANGELOG-DEV delete mode 100644 node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/hls.min.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/jquery.min.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/lunr.min.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/paella_player.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/paella_player_es2015.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/polyfill.min.js delete mode 100644 node_modules/paellaplayer/build/player/javascript/require.js delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_de.json delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_en.json delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_es.json delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_eu.json delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_fr.json delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_gl.json delete mode 100644 node_modules/paellaplayer/build/player/localization/paella_zh.json delete mode 100644 node_modules/paellaplayer/build/player/resources/style/style_dark.css delete mode 100644 node_modules/paellaplayer/build/player/resources/style/style_dark_small.css delete mode 100644 node_modules/paellaplayer/build/player/resources/style/style_light.css delete mode 100644 node_modules/paellaplayer/build/player/resources/style/style_light_small.css delete mode 100644 node_modules/paellaplayer/build/repository/hls-multiquality/data.json delete mode 100644 node_modules/paellaplayer/build/tools/layout_calculator/javascript/jquery.min.js delete mode 100644 node_modules/paellaplayer/build/tools/rtmp-test/jquery.min.js rename node_modules/paellaplayer/{build/player => }/config/config.json (98%) rename node_modules/paellaplayer/{build/player => }/config/profiles/profiles.json (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/default_background.jpg (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/default_background_paella.jpg (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/logo.png (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/paella_logo.png (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/paella_logo_old.png (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/professor_slide.jpg (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/professor_slide_paella.jpg (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/slide_professor.jpg (100%) rename node_modules/paellaplayer/{build/player => }/config/profiles/resources/slide_professor_paella.jpg (100%) create mode 100644 node_modules/paellaplayer/doc/adopters/analytics_elasticsearch.md create mode 100644 node_modules/paellaplayer/doc/adopters/analytics_google.md create mode 100644 node_modules/paellaplayer/doc/adopters/browser_compability.md create mode 100644 node_modules/paellaplayer/doc/adopters/build_paella.md create mode 100644 node_modules/paellaplayer/doc/adopters/configure.md create mode 100644 node_modules/paellaplayer/doc/adopters/download_paella.md create mode 100644 node_modules/paellaplayer/doc/adopters/download_precompiled_paella.md create mode 100644 node_modules/paellaplayer/doc/adopters/encoding.md create mode 100644 node_modules/paellaplayer/doc/adopters/hls_multiaudio.md create mode 100644 node_modules/paellaplayer/doc/adopters/icon-photo-sample.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/integrate/integrate.md create mode 100644 node_modules/paellaplayer/doc/adopters/integrate/integrate_advanced.md create mode 100644 node_modules/paellaplayer/doc/adopters/integrate/integrate_basic.md create mode 100644 node_modules/paellaplayer/doc/adopters/integrate/integrate_intermediate.md create mode 100644 node_modules/paellaplayer/doc/adopters/integrate_datajson.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/edu.harvard.dce.paella.flexSkipForwardPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/edu.harvard.dce.paella.flexSkipPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.arrowSlidesNavigatorPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.blackBoardPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.breaksPlayerPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.captions.DFXPParserPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.captionsPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.commentsPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.extendedTabAdapterPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.footprintsPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.frameControlPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.fullScreenButtonPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.helpPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.liveStramingIndicatorPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.mpegDashPlayer.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.multipleQualitiesPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.overlayCaptionsPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.playButtonOnScreenPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.playPauseButtonPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.playbackRatePlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.rtmpPlayer.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.search.captionsSearchPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.searchPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.showEditorPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.socialPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.test.tabBarExamplePlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.themeChooserPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.translecture.captionsPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.trimmingPlayerPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.usertracking.elasticsearchSaverPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.usertracking.googleAnalyticsSaverPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.usertracking.piwikSaverPlugIn.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.viewModePlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.visualAnnotationPlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.volumeRangePlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/es.upv.paella.windowTitlePlugin.md create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/arrowSlidesNavigator.png create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/blackBoardPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/captionsButtonPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/extendedTabAdapterPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/flexSkipPlugin.jpg rename node_modules/paellaplayer/{build/player/resources/style/help => doc/adopters/plugins}/images/footprintsPlugin.jpg (100%) create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/frameControlPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/fullScreenButtonPlugin.jpg rename node_modules/paellaplayer/{build/player/resources/style/help => doc/adopters/plugins}/images/helpPlugin.jpg (100%) create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/multipleQualitiesPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/overlayCaptionsPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/playPauseButtonPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/playbackRate.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/searchPlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/socialPlugin.jpg rename node_modules/paellaplayer/{build/player/resources/style/help => doc/adopters/plugins}/images/tabBarExamplePlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style/help => doc/adopters/plugins}/images/themeChooserPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style/help => doc/adopters/plugins}/images/viewModePlugin.jpg (100%) create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/visualAnnotations0.png create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/visualAnnotations1.png create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/visualAnnotations2.png create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/visualAnnotations3.png create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/visualAnnotations4.png create mode 100644 node_modules/paellaplayer/doc/adopters/plugins/images/volumeRangePlugin.jpg create mode 100644 node_modules/paellaplayer/doc/adopters/setup.md create mode 100644 node_modules/paellaplayer/doc/adopters/skining.md create mode 100644 node_modules/paellaplayer/doc/assets/images/capture_player.jpg create mode 100644 node_modules/paellaplayer/doc/developers/api_changes/paella_5_3_plugin_migration.md create mode 100644 node_modules/paellaplayer/doc/developers/introduction.md create mode 100644 node_modules/paellaplayer/doc/developers/paella_data.md create mode 100644 node_modules/paellaplayer/doc/developers/plugin_config.md create mode 100644 node_modules/paellaplayer/doc/developers/plugin_creation.md create mode 100644 node_modules/paellaplayer/doc/developers/plugin_types.md create mode 100644 node_modules/paellaplayer/doc/developers/url_parameters.md create mode 100644 node_modules/paellaplayer/doc/examples/buffered_playback_canvas.md create mode 100644 node_modules/paellaplayer/doc/examples/button_plugin.md create mode 100644 node_modules/paellaplayer/doc/examples/es.upv.paella.hlsPlayer.md create mode 100644 node_modules/paellaplayer/doc/examples/es.upv.paella.playButtonOnScreenPlugin.md create mode 100644 node_modules/paellaplayer/doc/examples/es.upv.paella.usertracking.googleAnalyticsSaverPlugin.md create mode 100644 node_modules/paellaplayer/doc/examples/key_plugin.md create mode 100644 node_modules/paellaplayer/doc/examples/multi_quality_plugin.md create mode 100644 node_modules/paellaplayer/doc/examples/popup_plugin.md create mode 100644 node_modules/paellaplayer/doc/examples/timeline_plugin.md create mode 100644 node_modules/paellaplayer/doc/examples/video_overlay.md create mode 100644 node_modules/paellaplayer/doc/faq.md create mode 100644 node_modules/paellaplayer/doc/introduction.md create mode 100644 node_modules/paellaplayer/doc/toc.yml create mode 100644 node_modules/paellaplayer/doc/upgrade.md create mode 100644 node_modules/paellaplayer/doc/users/images/Paella tools.png create mode 100644 node_modules/paellaplayer/doc/users/images/paella_tools.png create mode 100644 node_modules/paellaplayer/doc/users/images/player_composition.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_editor.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_editor2.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_footprints.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_fullscreen.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_main.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_play.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_repeat.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_resolution.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_share.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_skin.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_slides.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_speed.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_volume.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_zoom.jpg create mode 100644 node_modules/paellaplayer/doc/users/images/player_zoom2.jpg create mode 100644 node_modules/paellaplayer/doc/users/usage_guide.md rename node_modules/paellaplayer/{build/player => }/example.html (100%) create mode 100644 node_modules/paellaplayer/example.js create mode 100644 node_modules/paellaplayer/gulpfile.js create mode 100644 node_modules/paellaplayer/icons-src/airplay.svg create mode 100644 node_modules/paellaplayer/icons-src/arrow-down.svg create mode 100644 node_modules/paellaplayer/icons-src/arrow-left.svg create mode 100644 node_modules/paellaplayer/icons-src/arrow-right.svg create mode 100644 node_modules/paellaplayer/icons-src/arrow-up.svg create mode 100644 node_modules/paellaplayer/icons-src/back-10-s.svg create mode 100644 node_modules/paellaplayer/icons-src/back-30-s.svg create mode 100644 node_modules/paellaplayer/icons-src/captions.svg create mode 100644 node_modules/paellaplayer/icons-src/comments-disabled.svg create mode 100644 node_modules/paellaplayer/icons-src/comments.svg create mode 100644 node_modules/paellaplayer/icons-src/edit.svg create mode 100644 node_modules/paellaplayer/icons-src/facebook.svg create mode 100644 node_modules/paellaplayer/icons-src/folder.svg create mode 100644 node_modules/paellaplayer/icons-src/forward-30-s.svg create mode 100644 node_modules/paellaplayer/icons-src/frames.svg create mode 100644 node_modules/paellaplayer/icons-src/fullscreen.svg create mode 100644 node_modules/paellaplayer/icons-src/headphone.svg create mode 100644 node_modules/paellaplayer/icons-src/help.svg create mode 100644 node_modules/paellaplayer/icons-src/info.svg create mode 100644 node_modules/paellaplayer/icons-src/link.svg create mode 100644 node_modules/paellaplayer/icons-src/mini-camera.svg create mode 100644 node_modules/paellaplayer/icons-src/mini-frames.svg create mode 100644 node_modules/paellaplayer/icons-src/mini-videocamera.svg create mode 100644 node_modules/paellaplayer/icons-src/mini-window.svg create mode 100644 node_modules/paellaplayer/icons-src/mini-zoom-in.svg create mode 100644 node_modules/paellaplayer/icons-src/mini-zoom-out.svg create mode 100644 node_modules/paellaplayer/icons-src/paintbrush.svg create mode 100644 node_modules/paellaplayer/icons-src/pause.svg create mode 100644 node_modules/paellaplayer/icons-src/photo.svg create mode 100644 node_modules/paellaplayer/icons-src/pip.svg create mode 100644 node_modules/paellaplayer/icons-src/play.svg create mode 100644 node_modules/paellaplayer/icons-src/player-mode-1.svg create mode 100644 node_modules/paellaplayer/icons-src/player-mode-2.svg create mode 100644 node_modules/paellaplayer/icons-src/player-mode-3.svg rename node_modules/paellaplayer/{build/player/resources/style/slide_icon.svg => icons-src/present-mode-1.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/chroma.svg => icons-src/present-mode-10.svg} (100%) create mode 100644 node_modules/paellaplayer/icons-src/present-mode-11.afdesign rename node_modules/paellaplayer/{build/player/resources/style/professor_icon.svg => icons-src/present-mode-2.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/slide_professor_icon.svg => icons-src/present-mode-3.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/professor_slide_icon.svg => icons-src/present-mode-4.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/slide_over_professor_right_icon.svg => icons-src/present-mode-5.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/slide_over_professor_icon.svg => icons-src/present-mode-6.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/s_p_blackboard.svg => icons-src/present-mode-7.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/professor_over_slide_right_icon.svg => icons-src/present-mode-8.svg} (100%) rename node_modules/paellaplayer/{build/player/resources/style/professor_over_slide_icon.svg => icons-src/present-mode-9.svg} (100%) create mode 100644 node_modules/paellaplayer/icons-src/presentation-mode.svg create mode 100644 node_modules/paellaplayer/icons-src/screen.svg create mode 100644 node_modules/paellaplayer/icons-src/slideshow.svg create mode 100644 node_modules/paellaplayer/icons-src/social.svg create mode 100644 node_modules/paellaplayer/icons-src/star-empty.svg create mode 100644 node_modules/paellaplayer/icons-src/star.svg create mode 100644 node_modules/paellaplayer/icons-src/stats.svg create mode 100644 node_modules/paellaplayer/icons-src/twitter.svg create mode 100644 node_modules/paellaplayer/icons-src/user.svg create mode 100644 node_modules/paellaplayer/icons-src/volume-high.svg create mode 100644 node_modules/paellaplayer/icons-src/volume-low.svg create mode 100644 node_modules/paellaplayer/icons-src/volume-mid.svg create mode 100644 node_modules/paellaplayer/icons-src/volume-mute.svg create mode 100644 node_modules/paellaplayer/icons-src/windowed.svg create mode 100644 node_modules/paellaplayer/icons-src/zoom-in.svg create mode 100644 node_modules/paellaplayer/icons-src/zoom.svg rename node_modules/paellaplayer/{build/player => }/index-custom.html (100%) rename node_modules/paellaplayer/{build/player => }/index-debug.html (100%) rename node_modules/paellaplayer/{build/player => }/index.html (100%) create mode 100644 node_modules/paellaplayer/license.txt create mode 100644 node_modules/paellaplayer/localization/dictionary_de.json create mode 100644 node_modules/paellaplayer/localization/dictionary_en.json create mode 100644 node_modules/paellaplayer/localization/dictionary_es.json create mode 100644 node_modules/paellaplayer/localization/dictionary_eu.json create mode 100644 node_modules/paellaplayer/localization/dictionary_fr.json create mode 100644 node_modules/paellaplayer/localization/dictionary_gl.json rename node_modules/paellaplayer/{build/player/localization/paella_ru.json => localization/dictionary_ru.json} (95%) create mode 100644 node_modules/paellaplayer/localization/dictionary_zh.json create mode 100644 node_modules/paellaplayer/main.js create mode 100644 node_modules/paellaplayer/package-lock.json create mode 100644 node_modules/paellaplayer/paella-debug.js create mode 100644 node_modules/paellaplayer/paella-standalone.js create mode 100644 node_modules/paellaplayer/paella_icons.afdesign create mode 100644 node_modules/paellaplayer/plugins/ch.cern.paella.playButtonOnScreenAlwaysPlugin/README.md create mode 100644 node_modules/paellaplayer/plugins/ch.cern.paella.playButtonOnScreenAlwaysPlugin/playButtonOnScreenAlwaysPlugin.js create mode 100644 node_modules/paellaplayer/plugins/ch.cern.paella.playButtonOnScreenAlwaysPlugin/playButtonOnScreenAlwaysPlugin.less create mode 100644 node_modules/paellaplayer/plugins/ch.cern.paella.playButtonOnScreenAlwaysPlugin/screenshot.png create mode 100644 node_modules/paellaplayer/plugins/edu.harvard.dce.paella.flexSkipPlugin/flexskipbutton.js create mode 100644 node_modules/paellaplayer/plugins/edu.harvard.dce.paella.flexSkipPlugin/flexskipbutton.less create mode 100644 node_modules/paellaplayer/plugins/es.teltek.paella.captions.WebVTTParserPlugin/webvtt_parser.js rename node_modules/paellaplayer/{build/player/resources => plugins/es.teltek.paella.usertracking.xAPISaverPlugin}/deps/random_name_generator.js (100%) rename node_modules/paellaplayer/{build/player/resources => plugins/es.teltek.paella.usertracking.xAPISaverPlugin}/deps/xapiwrapper.min.js (100%) create mode 100644 node_modules/paellaplayer/plugins/es.teltek.paella.usertracking.xAPISaverPlugin/xAPISaverPlugin.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/chroma.svg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/default_background.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/default_background_paella.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/icon_rotate.svg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/icon_switch.svg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/logo.png (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/minimize.svg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/paella_logo.png (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/paella_logo_old.png (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/professor_icon.svg create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/professor_over_slide_icon.svg create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/professor_over_slide_right_icon.svg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/professor_slide.jpg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/professor_slide_icon.svg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/professor_slide_paella.jpg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/s_p_blackboard.svg create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/slide_icon.svg create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/slide_over_professor_icon.svg create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/slide_over_professor_right_icon.svg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/slide_professor.jpg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/resources/slide_professor_icon.svg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/slide_professor_paella.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.defaultProfiles/resources}/three_streams_icon.svg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.defaultProfiles/style.css create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.TrimmingPlugins/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.TrimmingPlugins/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.TrimmingPlugins/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.TrimmingPlugins/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.TrimmingPlugins/trimming_player.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.airplayPlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.airplayPlugin/style.css create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.arrowSlidesNavigatorPlugin/arrowSlidesNavigator.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.arrowSlidesNavigatorPlugin/arrowSlidesNavigator.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.audioSelector/audio-selector.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.audioSelector/index.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.blackBoardPlugin/blackBoard.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.blackBoardPlugin/blackBoard.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/editor.js.disabled create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/player.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.breakPlugins/player.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.bufferedPlaybackCanvasPlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captions.DFXPParserPlugin/dfxp_parser.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/captions.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/captionsPlugin.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.captionsPlugin/overlayCaptionsPlugin.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.chromaPlayer/chroma-player.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.commentsPlugin/comments.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.commentsPlugin/comments.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.commentsPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.commentsPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.commentsPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.commentsPlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.descriptionPlugin/description.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.descriptionPlugin/description.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.extendedTabAdapterPlugin/adapter.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.extendedTabAdapterPlugin/adapter.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.footprintsPlugin/footprints.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.footprintsPlugin/footprints.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.footprintsPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.footprintsPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.footprintsPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.footprintsPlugin/localization/zh.json rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.footprintsPlugin/resources}/statistics_icon.png (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.frameControlPlugin/framecontrol.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.frameControlPlugin/framecontrol.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.frameControlPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.frameControlPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.frameControlPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.frameControlPlugin/localization/zh.json rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.frameControlPlugin/resources}/hscroll_arrows.png (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.frameControlPlugin/resources}/hscroll_arrows_orange.png (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.frameControlPlugin/resources}/slides_icon.png (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.fullScreenButtonPlugin/fullscreenbutton.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.fullScreenButtonPlugin/fullscreenbutton.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.fullScreenButtonPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.fullScreenButtonPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.fullScreenButtonPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.fullScreenButtonPlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/help.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/help.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/localization/zh.json rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/help_en.html (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/help_es.html (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/help_ru.html (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/help_zh.html (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/blackBoardPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/captionsButtonPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/editor.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/flexSkipPlugin.jpg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/resources/help/images/footprintsPlugin.jpg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/frameControlPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/fullScreenButtonPlugin.jpg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/resources/help/images/helpPlugin.jpg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/multipleQualitiesPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/playPauseButtonPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/playbackRate.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/player_main.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/ratePlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/searchPlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/socialPlugin.jpg (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/resources/help/images/tabBarExamplePlugin.jpg create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/resources/help/images/themeChooserPlugin.jpg create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.helpPlugin/resources/help/images/viewModePlugin.jpg rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/images/volumeRangePlugin.jpg (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.helpPlugin/resources}/help/style.css (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.hlsPlayer/hls-player.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.keyPlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.legal/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.legal/style.css create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.liveStreamingIndicatorPlugin/live_stream_indicator.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.liveStreamingIndicatorPlugin/live_stream_indicator.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.liveStreamingIndicatorPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.liveStreamingIndicatorPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.liveStreamingIndicatorPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.liveStreamingIndicatorPlugin/localization/zh.json rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.liveStreamingIndicatorPlugin/resources}/live_video.png (100%) rename node_modules/paellaplayer/{build/player/resources => plugins/es.upv.paella.mpegDashPlayer}/deps/dash.all.js (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.mpegDashPlayer/mpeg-dash-player.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.multipleQualitiesPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.multipleQualitiesPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.multipleQualitiesPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.multipleQualitiesPlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.multipleQualitiesPlugin/qualities.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.multipleQualitiesPlugin/qualities.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.pipModePlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.pipModePlugin/style.css create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/playbutton.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/playbutton.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playPauseButtonPlugin/playbutton_onscreen.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playbackRatePlugin/playback_rate.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.playbackRatePlugin/playback_rate.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.ratePlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.ratePlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.ratePlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.ratePlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.ratePlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.ratePlugin/rates.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.relatedVideosPlugin/main.css create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.relatedVideosPlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.search.CaptionsSearchPlugIn/captionsSearch.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.searchPlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.searchPlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.searchPlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.searchPlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.searchPlugin/search.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.searchPlugin/search.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.sharePlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.sharePlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.sharePlugin/share.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.sharePlugin/share.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.themeChooser/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.themeChooser/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.themeChooser/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.themeChooser/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.themeChooser/themechooser.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.themeChooser/themechooser.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.timeMarksPlaybackCanvasPlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.track4kPlugin/main.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.track4kPlugin/style.css create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.translectures.CaptionsPlugIn/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.translectures.CaptionsPlugIn/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.translectures.CaptionsPlugIn/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.translectures.CaptionsPlugIn/localization/zh.json rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.translectures.CaptionsPlugIn/resources}/caption_mlangs_anonymous.png (100%) rename node_modules/paellaplayer/{build/player/resources/style => plugins/es.upv.paella.translectures.CaptionsPlugIn/resources}/caption_mlangs_lock.png (100%) create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.translectures.CaptionsPlugIn/translectures.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.translectures.CaptionsPlugIn/translectures.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.usertracking.elasticsearchSaverPlugin/elasticsearchSaverPlugin.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.usertracking.googleAnalyticsSaverPlugin/usertracking_googleanalytics_saver.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.usertracking.piwikSaverPlugIn/piwik_saver.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.video360Player/video360.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.video360PlayerTheta/video360theta.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.videoData/index.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.videoData/videoData.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.videoZoom/video_zoom.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.videoZoom/video_zoom.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.viewModePlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.viewModePlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.viewModePlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.viewModePlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.viewModePlugin/viewmode.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.viewModePlugin/viewmode.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.volumeRangePlugin/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.volumeRangePlugin/localization/eu.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.volumeRangePlugin/localization/gl.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.volumeRangePlugin/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.volumeRangePlugin/volumeRange.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.volumeRangePlugin/volumeRange.less create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.webmPlayer/webm-player.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.windowTitlePlugin/window_title.js create mode 100644 node_modules/paellaplayer/plugins/es.upv.paella.youtubePlayer/youtube-player.js create mode 100644 node_modules/paellaplayer/plugins/ignore.json create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.MatomoSaverPlugIn/localization/de.json create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.MatomoSaverPlugIn/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.MatomoSaverPlugIn/usertracking_matomo_saver.js create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.MatomoSaverPlugIn/usertracking_matomo_saver.less create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.x5gonSaverPlugIn/localization/de.json create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.x5gonSaverPlugIn/localization/es.json create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.x5gonSaverPlugIn/localization/zh.json create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.x5gonSaverPlugIn/usertracking_x5gon_saver.js create mode 100644 node_modules/paellaplayer/plugins/org.opencast.usertracking.x5gonSaverPlugIn/usertracking_x5gon_saver.less rename node_modules/paellaplayer/{build => repository_test}/index.html (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/audio-and-images/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/belmar-multiresolution-remote/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/belmar-multiresolution-remote/episode.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/belmar-multiresolution-remote/trackhd.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/chroma/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/convert.js (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/dual-video-audio/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/ethz/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/hevc-test/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/hls-live/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/hls-multiaudio/blender-foundation-sintel.jpg (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/hls-multiaudio/data.json (100%) create mode 100644 node_modules/paellaplayer/repository_test/repository/hls-multiquality/data.json rename node_modules/paellaplayer/{build => repository_test}/repository/hls/data.json (88%) rename node_modules/paellaplayer/{build => repository_test}/repository/jordan-blackboard-remote/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/jordan-blackboard-remote/episode.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/mpeg-dash/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/multi-format/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/multi-lang-audio/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/multi-lang-captions/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/n-stream/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/video-remote-1/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/video-remote-1/episode.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/video360-theta/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/video360/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/webvtt-captions/captions.es.vtt (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/webvtt-captions/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/webvtt-captions/episode.json (100%) rename node_modules/paellaplayer/{build => repository_test}/repository/youtube/data.json (100%) rename node_modules/paellaplayer/{build => repository_test}/test_player.html (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/css/bootstrap.min.css (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/css/bootstrap.slate.min.css (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/fonts/glyphicons-halflings-regular.eot (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/fonts/glyphicons-halflings-regular.svg (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/fonts/glyphicons-halflings-regular.ttf (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/fonts/glyphicons-halflings-regular.woff (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/fonts/glyphicons-halflings-regular.woff2 (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/img/glyphicons-halflings-white.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/img/glyphicons-halflings.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/js/bootstrap.js (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/js/bootstrap.min.js (100%) rename node_modules/paellaplayer/{build/player => }/resources/bootstrap/js/npm.js (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/chrome.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/error_icon.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/explorer.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/firefox.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/paella_icons_dark.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/paella_icons_light.png (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/play.svg (100%) rename node_modules/paellaplayer/{build/player => }/resources/images/safari.png (100%) create mode 100644 node_modules/paellaplayer/resources/style/controls.less create mode 100644 node_modules/paellaplayer/resources/style/defaultvars.less create mode 100644 node_modules/paellaplayer/resources/style/editor.less rename node_modules/paellaplayer/{build/player => }/resources/style/fonts/icomoon.eot (100%) rename node_modules/paellaplayer/{build/player => }/resources/style/fonts/icomoon.svg (100%) rename node_modules/paellaplayer/{build/player => }/resources/style/fonts/icomoon.ttf (100%) rename node_modules/paellaplayer/{build/player => }/resources/style/fonts/icomoon.woff (100%) create mode 100644 node_modules/paellaplayer/resources/style/icon-index.html create mode 100755 node_modules/paellaplayer/resources/style/icons.css create mode 100644 node_modules/paellaplayer/resources/style/skins/dark.less create mode 100644 node_modules/paellaplayer/resources/style/skins/dark_small.less create mode 100644 node_modules/paellaplayer/resources/style/skins/light.less create mode 100644 node_modules/paellaplayer/resources/style/skins/light_small.less create mode 100644 node_modules/paellaplayer/src/00_base.js create mode 100644 node_modules/paellaplayer/src/00_utils_ajax.js create mode 100644 node_modules/paellaplayer/src/00_utils_data.js create mode 100644 node_modules/paellaplayer/src/00_utils_dictionary.js create mode 100644 node_modules/paellaplayer/src/00_utils_message_box.js create mode 100644 node_modules/paellaplayer/src/00_utils_parameters.js create mode 100644 node_modules/paellaplayer/src/00_utils_user_agent.js create mode 100644 node_modules/paellaplayer/src/01_utils.js create mode 100644 node_modules/paellaplayer/src/02_nodes.js create mode 100644 node_modules/paellaplayer/src/02_profiles.js create mode 100644 node_modules/paellaplayer/src/02_video_utils.js create mode 100644 node_modules/paellaplayer/src/03_audio_nodes.js create mode 100644 node_modules/paellaplayer/src/03_video_nodes.js create mode 100644 node_modules/paellaplayer/src/04_video_container.js create mode 100644 node_modules/paellaplayer/src/05_plugin_base.js create mode 100644 node_modules/paellaplayer/src/05_video_canvas.js create mode 100644 node_modules/paellaplayer/src/06_1_captions.js create mode 100644 node_modules/paellaplayer/src/06_2_search_service.js create mode 100644 node_modules/paellaplayer/src/06_3_user_tracking.js create mode 100644 node_modules/paellaplayer/src/06_ui_controls.js create mode 100644 node_modules/paellaplayer/src/07_ui_extras.js create mode 100644 node_modules/paellaplayer/src/08_paella_core.js create mode 100644 node_modules/paellaplayer/src/09_paella_player.js create mode 100644 node_modules/paellaplayer/src/10_loader.js create mode 100644 node_modules/paellaplayer/src/10_paella_extended_adapter.js create mode 100644 node_modules/paellaplayer/src/99_export.js create mode 100644 node_modules/paellaplayer/tests/nightwatch/nightwatch.js create mode 100644 node_modules/paellaplayer/tests/nightwatch/tests/playButtonOnScreen/playButtonTest.js create mode 100644 node_modules/paellaplayer/tests/nightwatch/tests/simple/simpleTests.js create mode 100644 node_modules/paellaplayer/tests/nightwatch/tests/testExtendedTabAdapterButton/testExtendedTabAdapterButton.js create mode 100644 node_modules/paellaplayer/tests/nightwatch/tests/testHelpButton/testHelpButton.js create mode 100644 node_modules/paellaplayer/tests/nightwatch/tests/testRateButton/testRateButton.js create mode 100755 node_modules/paellaplayer/tests/start_selenium.sh create mode 100755 node_modules/paellaplayer/tests/stop_selenium.sh create mode 100644 node_modules/paellaplayer/tools/index.html create mode 100644 node_modules/paellaplayer/tools/layout_calculator/index.html create mode 100644 node_modules/paellaplayer/tools/layout_calculator/javascript/layoutCalculator.js create mode 100644 node_modules/paellaplayer/tools/mediapackagecreator/index.html create mode 100644 node_modules/paellaplayer/tools/mediapackagecreator/javascript/jsoneditor.min.js create mode 100644 node_modules/paellaplayer/tools/mediapackagecreator/paella.schema.json create mode 100644 node_modules/paellaplayer/tools/mediapackagecreator/videostream.schema.json create mode 100644 node_modules/paellaplayer/vendor/images/.gitkeep create mode 100644 node_modules/paellaplayer/vendor/plugins/.gitkeep create mode 100644 node_modules/paellaplayer/vendor/skins/.gitkeep diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 000000000..6d9153da3 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1827 @@ +{ + "name": "srag.plugins.opencast", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@babel/code-frame": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.7.tgz", + "integrity": "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==", + "dependencies": { + "@babel/highlight": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz", + "integrity": "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.10.tgz", + "integrity": "sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==", + "dependencies": { + "@babel/helper-validator-identifier": "^7.16.7", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@socket.io/base64-arraybuffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@socket.io/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", + "integrity": "sha512-dOlCBKnDw4iShaIsH/bxujKTM18+2TOAsYz+KSc11Am38H4q5Xw8Bbz97ZYdrVNM+um3p7w86Bvvmcn9q+5+eQ==", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/@types/component-emitter": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz", + "integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==" + }, + "node_modules/@types/cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" + }, + "node_modules/@types/cors": { + "version": "2.8.12", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz", + "integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==" + }, + "node_modules/@types/minimist": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.2.tgz", + "integrity": "sha512-jhuKLIRrhvCPLqwPcx6INqmKeiA5EWrsCOPhrlFSrbrmU4ZMPjj5Ul/oLCMDO98XRUIwVm78xICz4EPCektzeQ==" + }, + "node_modules/@types/node": { + "version": "17.0.19", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.19.tgz", + "integrity": "sha512-PfeQhvcMR4cPFVuYfBN4ifG7p9c+Dlh3yUZR6k+5yQK7wX3gDgVxBly4/WkBRs9x4dmcy1TVl08SY67wwtEvmA==" + }, + "node_modules/@types/normalize-package-data": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz", + "integrity": "sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==" + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "dependencies": { + "mime-db": "1.51.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "node_modules/arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "node_modules/bg2e-js": { + "version": "1.3.32", + "resolved": "https://registry.npmjs.org/bg2e-js/-/bg2e-js-1.3.32.tgz", + "integrity": "sha512-A1SLLAem5WN5TGOukwXOXd5QyaHHmUJs4QhgVJYlBDNq53qBSePVE/TCarBoPIS05X6QXZIaR5cMaUEO+MDeGA==" + }, + "node_modules/bignumber.js": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", + "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==", + "engines": { + "node": "*" + } + }, + "node_modules/body-parser": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.2.tgz", + "integrity": "sha512-SAAwOxgoCKMGs9uUAUFHygfLAyaniaoun6I8mFY9pRAJL9+Kec34aU+oIjDhTycub1jozEfEwx1W1IuOYxVSFw==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.8.1", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.9.7", + "raw-body": "2.4.3", + "type-is": "~1.6.18" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/camelcase-keys": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-7.0.2.tgz", + "integrity": "sha512-Rjs1H+A9R+Ig+4E/9oyB66UC5Mj9Xq3N//vcLf2WzgdTi/3gUu3Z9KoqmlrEG4VuuLK8wJHofxzdQXz/knhiYg==", + "dependencies": { + "camelcase": "^6.3.0", + "map-obj": "^4.1.0", + "quick-lru": "^5.1.1", + "type-fest": "^1.2.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/camelcase-keys/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dependencies": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/chalk/node_modules/ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/chalk/node_modules/strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dependencies": { + "ansi-regex": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "node_modules/component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" + }, + "node_modules/console-stamp": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/console-stamp/-/console-stamp-0.2.10.tgz", + "integrity": "sha512-HjPHHsUGj5xcwkcwolgBg9SxhVqLzktH16GmvGsdZJ+FJPNq+xr+wSdYh8744JEAbCkJ0pNJuDN+34Bx14vERg==", + "dependencies": { + "chalk": "^1.1.1", + "dateformat": "1.0.11" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-disposition/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "node_modules/cookieconsent": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/cookieconsent/-/cookieconsent-3.1.1.tgz", + "integrity": "sha512-v8JWLJcI7Zs9NWrs8hiVldVtm3EBF70TJI231vxn6YToBGj0c9dvdnYwltydkAnrbBMOM/qX1xLFrnTfm5wTag==" + }, + "node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/dateformat": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.11.tgz", + "integrity": "sha1-8ny+56ASu/uC6gUVYtOXf2CT27E=", + "dependencies": { + "get-stdin": "*", + "meow": "*" + }, + "bin": { + "dateformat": "bin/cli.js" + }, + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decamelize-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", + "integrity": "sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk=", + "dependencies": { + "decamelize": "^1.1.0", + "map-obj": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decamelize-keys/node_modules/map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "node_modules/ejs": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-2.7.4.tgz", + "integrity": "sha512-7vmuyh5+kuUyJKePhQfRQBhXV5Ce+RnaeeQArKu1EAMpL3WbgMt5WG6uQZpEVvYSSsxMXRKOewtDk9RaTKXRlA==", + "hasInstallScript": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/engine.io": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.1.2.tgz", + "integrity": "sha512-v/7eGHxPvO2AWsksyx2PUsQvBafuvqs0jJJQ0FdmJG1b9qIvgSbqDRGwNhfk2XHaTTbTXiC4quRE8Q9nRjsrQQ==", + "dependencies": { + "@types/cookie": "^0.4.1", + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.4.1", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.0", + "ws": "~8.2.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.3.tgz", + "integrity": "sha512-BtQxwF27XUNnSafQLvDi0dQ8s3i6VgzSoQMJacpIcGNrlUdfHSKbgm3jmjCVvQluGzqwujQMPAoMai3oYSTurg==", + "dependencies": { + "@socket.io/base64-arraybuffer": "~1.0.2" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.17.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.17.3.tgz", + "integrity": "sha512-yuSQpz5I+Ch7gFrPCk4/c+dIBKlQUxtgwqzph132bsT6qhuzss6I8cLJQz7B3rFblzd6wtcI0ZbGltH/C4LjUg==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.19.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.4.2", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.9.7", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.17.2", + "serve-static": "1.14.2", + "setprototypeof": "1.2.0", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express/node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "dependencies": { + "mime-db": "1.51.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/express/node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-stdin": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-9.0.0.tgz", + "integrity": "sha512-dVKBjfWisLAicarI2Sf+JuBE/DghV4UzNAVe9yhEJuzeREd3JhOTE9cUaJTeSa77fsbQUK3pcOpJfM59+VKZaA==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hard-rejection": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", + "integrity": "sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dependencies": { + "ansi-regex": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-ansi/node_modules/ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "engines": { + "node": ">=4" + } + }, + "node_modules/hls.js": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.1.5.tgz", + "integrity": "sha512-mQX5TSNtJEzGo5HPpvcQgCu+BWoKDQM6YYtg/KbgWkmVAcqOCvSTi0SuqG2ZJLXxIzdnFcKU2z7Mrw/YQWhPOA==" + }, + "node_modules/hosted-git-info": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", + "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/indent-string": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", + "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=" + }, + "node_modules/is-core-module": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz", + "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-plain-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", + "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "node_modules/jquery": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.0.tgz", + "integrity": "sha512-JVzAR/AjBvVt2BmYhxRCSYysDsPcssdmTFnzyLEts9qNwmjmu4JTAMYubEfwVOSwpQ1I1sKKFcxhZCI2buerfw==" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==" + }, + "node_modules/map-obj": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz", + "integrity": "sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/meow": { + "version": "10.1.2", + "resolved": "https://registry.npmjs.org/meow/-/meow-10.1.2.tgz", + "integrity": "sha512-zbuAlN+V/sXlbGchNS9WTWjUzeamwMt/BApKCJi7B0QyZstZaMx0n4Unll/fg0njGtMdC9UP5SAscvOCLYdM+Q==", + "dependencies": { + "@types/minimist": "^1.2.2", + "camelcase-keys": "^7.0.0", + "decamelize": "^5.0.0", + "decamelize-keys": "^1.1.0", + "hard-rejection": "^2.1.0", + "minimist-options": "4.1.0", + "normalize-package-data": "^3.0.2", + "read-pkg-up": "^8.0.0", + "redent": "^4.0.0", + "trim-newlines": "^4.0.2", + "type-fest": "^1.2.2", + "yargs-parser": "^20.2.9" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/meow/node_modules/decamelize": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-5.0.1.tgz", + "integrity": "sha512-VfxadyCECXgQlkoEAjeghAr5gY3Hf+IKjKb+X8tGVDtveCjN+USwprd2q3QXBR9T1+x2DG0XZF5/w+7HAtSaXA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/meow/node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "engines": { + "node": ">=10" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.45.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.45.0.tgz", + "integrity": "sha512-CkqLUxUk15hofLoLyljJSrukZi8mAtgd+yE5uO4tqRZsdsAJKv0O+rFMhVDRJgozy+yG6md5KwuXhD4ocIoP+w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.28", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.28.tgz", + "integrity": "sha512-0TO2yJ5YHYr7M2zzT7gDU1tbwHxEUWBCLt0lscSNpcdAfFyJOVEpRYNS7EXVcTLNj/25QO8gulHC5JtTzSE2UQ==", + "dependencies": { + "mime-db": "1.45.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "engines": { + "node": ">=4" + } + }, + "node_modules/minimist-options": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-4.1.0.tgz", + "integrity": "sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==", + "dependencies": { + "arrify": "^1.0.1", + "is-plain-obj": "^1.1.0", + "kind-of": "^6.0.3" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/moment": { + "version": "2.29.1", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.29.1.tgz", + "integrity": "sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ==", + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/mysql": { + "version": "2.18.1", + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz", + "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==", + "dependencies": { + "bignumber.js": "9.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/normalize-package-data": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-3.0.3.tgz", + "integrity": "sha512-p2W1sgqij3zMMyRC067Dg16bfzVH+w7hyegmpIvZ4JNjqtGOVAIvLmjBx3yP7YTe9vKJgkoNOPjwQGogDoMXFA==", + "dependencies": { + "hosted-git-info": "^4.0.1", + "is-core-module": "^2.5.0", + "semver": "^7.3.4", + "validate-npm-package-license": "^3.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/paellaplayer": { + "version": "6.5.6", + "resolved": "https://github.com/polimediaupv/paella/tarball/6.5.6", + "integrity": "sha512-ukFHinlVfhWx7aJ5JbWcrs6/RG7vdq9iiNjzy3dPhekceSi7hyVYVvrVkS07a09hBQzeYYLaOEOqdoem6+p6Eg==", + "license": "ECL-2.0", + "dependencies": { + "bg2e-js": "=1.3.32", + "cookieconsent": "^3.1.1", + "hls.js": "^1.0.0", + "jquery": "^3.5.1", + "lunr": "^2.3.9", + "requirejs": "^2.3.6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-IhMFgUmuNpyRfxA90umL7ByLlgRXu6tIfKPpF5TmcfRLlLCckfP/g3IQmju6jjpu+Hh8rA+2p6A27ZSPOOHdKw==", + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.3.tgz", + "integrity": "sha512-UlTNLIcu0uzb4D2f4WltY6cVjLi+/jEN4lgEUj3E04tpMDpUlkBo/eSn6zou9hum2VMNpCCUone0O0WeJim07g==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "1.8.1", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/read-pkg": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-6.0.0.tgz", + "integrity": "sha512-X1Fu3dPuk/8ZLsMhEj5f4wFAF0DWoK7qhGJvgaijocXxBmSToKfbFtqbxMO7bVjNA1dmE5huAzjXj/ey86iw9Q==", + "dependencies": { + "@types/normalize-package-data": "^2.4.0", + "normalize-package-data": "^3.0.2", + "parse-json": "^5.2.0", + "type-fest": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-8.0.0.tgz", + "integrity": "sha512-snVCqPczksT0HS2EC+SxUndvSzn6LRCwpfSvLrIfR5BKDQQZMaI6jPRC9dYvYFDRAuFEAnkwww8kBBNE/3VvzQ==", + "dependencies": { + "find-up": "^5.0.0", + "read-pkg": "^6.0.0", + "type-fest": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up/node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/redent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-4.0.0.tgz", + "integrity": "sha512-tYkDkVVtYkSVhuQ4zBgfvciymHaeuel+zFKXShfDnFP5SyVEP7qo70Rf1jTOTCx3vGNAbnEi/xFkcfQVMIBWag==", + "dependencies": { + "indent-string": "^5.0.0", + "strip-indent": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/requirejs": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.6.tgz", + "integrity": "sha512-ipEzlWQe6RK3jkzikgCupiTbTvm4S0/CAU5GlgptkN5SO6F3u0UD0K18wy6ErDqiCyP4J4YYe1HuAShvsxePLg==", + "bin": { + "r_js": "bin/r.js", + "r.js": "bin/r.js" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.17.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.17.2.tgz", + "integrity": "sha512-UJYB6wFSJE3G00nEivR5rgWp8c2xXvJ3OPWPhmuteU0IKj8nKbG3DrjiOmLwpnHGYWAVwA69zmTm++YG0Hmwww==", + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "1.8.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/serve-static": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.2.tgz", + "integrity": "sha512-+TMNA9AFxUEGuC0z2mevogSnn9MXKb4fa7ngeRMJaaGv8vTwnIEkKi+QGvPt33HSnf8pRS+WGM0EbMtCJLKMBQ==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/socket.io": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.4.1.tgz", + "integrity": "sha512-s04vrBswdQBUmuWJuuNTmXUVJhP0cVky8bBDhdkf8y0Ptsu7fKU2LuLbts9g+pdmAdyMMn8F/9Mf1/wbtUN0fg==", + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "debug": "~4.3.2", + "engine.io": "~6.1.0", + "socket.io-adapter": "~2.3.3", + "socket.io-parser": "~4.0.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.3.3.tgz", + "integrity": "sha512-Qd/iwn3VskrpNO60BeRyCyr8ZWw9CPZyitW4AQwmRZ8zCiyDiL+znRnWX6tDHXnWn1sJrM1+b6Mn6wEDJJ4aYQ==" + }, + "node_modules/socket.io-parser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.0.4.tgz", + "integrity": "sha512-t+b0SS+IxG7Rxzda2EVvyBZbvFPBCjJoyHuE0P//7OAsN23GItzDRdWa6ALxZI/8R5ygK7jAR6t028/z+7295g==", + "dependencies": { + "@types/component-emitter": "^1.2.10", + "component-emitter": "~1.3.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==" + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.11.tgz", + "integrity": "sha512-Ctl2BrFiM0X3MANYgj3CkygxhRmr9mi6xhejbdO960nF6EDJApTYpn0BQnDKlnNBULKiCN1n3w9EBkHK8ZWg+g==" + }, + "node_modules/sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-4.0.0.tgz", + "integrity": "sha512-mnVSV2l+Zv6BLpSD/8V87CW/y9EmmbYzGCIavsnsI6/nwn26DwffM/yztm30Z/I2DY9wdS3vXVCMnHDgZaVNoA==", + "dependencies": { + "min-indent": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/trim-newlines": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-4.0.2.tgz", + "integrity": "sha512-GJtWyq9InR/2HRiLZgpIKv+ufIKrVrvjQWEj7PxAXNc5dwbNJkqhAUoAGgzRmULAnoOM5EIpveYd3J2VeSAIew==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-fest": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-1.4.0.tgz", + "integrity": "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/yargs": { + "version": "17.3.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.3.1.tgz", + "integrity": "sha512-WUANQeVgjLbNsEmGk20f+nlHgOqzRFpiGWVaBrYGYIGANIIu3lWjoyi0fNlFmJkvfhCZ6BXINe7/W2O2bV4iaA==", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-z9kApYUOCwoeZ78rfRYYWdiU/iNL6mwwYlkkZfJoyMR1xps+NEBX5X7XmRpxkZHhXJ6+Ey00IwKxBBSW9FIjyA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/node_modules/paellaplayer/.babelrc b/node_modules/paellaplayer/.babelrc new file mode 100644 index 000000000..8dd0b616f --- /dev/null +++ b/node_modules/paellaplayer/.babelrc @@ -0,0 +1,8 @@ +{ + "compact": false, + "presets": [ + [ + "@babel/preset-env" + ] + ] +} \ No newline at end of file diff --git a/node_modules/paellaplayer/.browserslistrc b/node_modules/paellaplayer/.browserslistrc new file mode 100644 index 000000000..496d1ef56 --- /dev/null +++ b/node_modules/paellaplayer/.browserslistrc @@ -0,0 +1 @@ +defaults \ No newline at end of file diff --git a/node_modules/paellaplayer/.eslintrc.js b/node_modules/paellaplayer/.eslintrc.js new file mode 100644 index 000000000..f307b35d4 --- /dev/null +++ b/node_modules/paellaplayer/.eslintrc.js @@ -0,0 +1,27 @@ +module.exports = { + "env": { + "browser": true + }, + "extends": "eslint:recommended", + "parserOptions": { + "ecmaVersion": 5 + }, + "rules": { + "indent": [ + "error", + "tab" + ], + "linebreak-style": [ + "error", + "unix" + ], + "quotes": [ + "error", + "double" + ], + "semi": [ + "error", + "always" + ] + } +}; \ No newline at end of file diff --git a/node_modules/paellaplayer/.github/CONTRIBUTING.md b/node_modules/paellaplayer/.github/CONTRIBUTING.md new file mode 100644 index 000000000..10570fc24 --- /dev/null +++ b/node_modules/paellaplayer/.github/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing + +## Branching model + +We use [git-flow](http://nvie.com/posts/a-successful-git-branching-model/) as our branching model. + +So, paella have two main branches: + +* `master` is the stable version. And only is updated in each new release version. + +* `develop` is the develop branch, all new features will be commited to this branch. + +When we want to release a new stable version of paella, we create a new branch (`release/`) + +* `release/` is a release candidate branch. In this branch we only anccept bug fixes. + No new features will be accepted in this branch. All new features will be commited to `develop` branch. + + +## Contributing + +If you want to create a new feature, you need to branch of `develop`. When your feature is finished, +you can make a pull-request to the `develop` branch. + +If you are fixing a bug in a `release` version, you need to branch of `release/`. +Once the bug is fixed, you can make a pull-request to the `release` branch. + +### Making a new feature + +You have to create a new branch from `develop` + +``` +$git checkout develop +$git checkout -b feature/my-new-feature +``` + +When your new feature is finished, edit the `CHANGELOG` file and add a line explaining your new feature. +Then make a pull-request to de `develop` branch. + + +## Syntax + +Before making a pull request, ensure that syntax style is correct. You can check this by running the line: + +``` +grunt checksyntax +``` + diff --git a/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/bug_report.md b/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..8ae692db1 --- /dev/null +++ b/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,36 @@ +--- +name: Bug report +about: Create a report to help us improve +labels: bug + +--- + +# Describe the bug +A clear and concise description of what the bug is. + +# To Reproduce +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +# Workaround (if any) + +# Environment Information + - OS: [e.g. Windows, MacOS, iOS 8.1, CentOS 7] + - Browser [e.g. Safari, Chrome] + - Browser Version [e.g. 22] + - Paella version [e.g. 6.0.0, 6.2.2, 6.2.x if using a branch] + +# Additional context +Add any other context about the problem here. + +If applicable, add screenshots to help explain your problem. + +# None + +Please note that this bug reporting system is intended for software developers who implement Paella Player features or who integrate it into their institutions. If you are an end user of Paella Player, please contact your institution so that they can determine if the problems are due to the video player or if they are due to other configuration or integration issues. + + +Thank you for contributing! diff --git a/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/feature_request.md b/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..c7f5098cb --- /dev/null +++ b/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,12 @@ +--- +name: Feature request +about: Suggest an idea +labels: 'new feature' + +--- + +# End of Paella Player 6.x development + +As of the official release of Paella Player 7 in December 2021, we will no longer continue development of new features for Paella Player 6.x. Please refer to the [official repository readme file](https://github.com/polimediaupv/paella/blob/develop/README.md) for more information. + +Note that all issues about new feature request in Paella 6 will be closed. diff --git a/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/usage_question.md b/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/usage_question.md new file mode 100644 index 000000000..fd8c481dd --- /dev/null +++ b/node_modules/paellaplayer/.github/ISSUE_TEMPLATE/usage_question.md @@ -0,0 +1,14 @@ +--- +name: Support request +about: Have a usage question? +labels: question + +--- + + +Have a usage question? +====================== +The issue tracker isn't the best place for usage questions. This format is not well-suited for Q&A, and questions here don't have as much visibility as they do elsewhere. Before you ask a question, here are some resources to get help first: + +- Check the paella documentation: https://paellaplayer.upv.es/docs/ +- Ask the question in the Paella Player mailing list: https://listas.upv.es/mailman/listinfo/paellaplayer diff --git a/node_modules/paellaplayer/.github/PULL_REQUEST_TEMPLATE.md b/node_modules/paellaplayer/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..994a35524 --- /dev/null +++ b/node_modules/paellaplayer/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,28 @@ + + + +## What kind of change does this PR introduce? (Bug fix, feature, docs update, ...) +… + + +## What is the current behavior? (You can also link to an open issue here) +… + + +## What does this implement/fix? Explain your changes. +… + + +## Does this [close any currently open issues](https://help.github.com/en/articles/closing-issues-using-keywords)? +close # + + +## Does this PR introduce a breaking change? What changes might users need to make in their application due to this PR? +… + + +## Any other comments? +… diff --git a/node_modules/paellaplayer/.github/dependabot.yml b/node_modules/paellaplayer/.github/dependabot.yml new file mode 100644 index 000000000..e31903a86 --- /dev/null +++ b/node_modules/paellaplayer/.github/dependabot.yml @@ -0,0 +1,36 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: daily + time: "04:00" + open-pull-requests-limit: 10 + reviewers: + - ferserc1 + ignore: + - dependency-name: bg2e-js + versions: + - ">= 1.4.a, < 1.5" + - dependency-name: "@babel/core" + versions: + - 7.12.16 + - 7.13.1 + - 7.13.14 + - 7.13.16 + - 7.13.8 + - dependency-name: nightwatch + versions: + - 1.6.1 + - 1.6.2 + - dependency-name: "@babel/preset-env" + versions: + - 7.13.0 + - 7.13.10 + - 7.13.5 + - dependency-name: chromedriver + versions: + - 89.0.0 + - dependency-name: jquery + versions: + - 3.6.0 diff --git a/node_modules/paellaplayer/.github/workflows/node.js.yml b/node_modules/paellaplayer/.github/workflows/node.js.yml new file mode 100644 index 000000000..f852880b3 --- /dev/null +++ b/node_modules/paellaplayer/.github/workflows/node.js.yml @@ -0,0 +1,23 @@ +name: Paella tests + +on: + push: + branches: [ develop ] + pull_request: + branches: [ develop ] + +jobs: + tests: + + runs-on: ubuntu-latest + + + steps: + - uses: actions/checkout@v2 + - name: Tests + uses: actions/setup-node@v1 + with: + node-version: '14.x' + - run: npm ci + - run: npm run markdownlint + - run: npm test diff --git a/node_modules/paellaplayer/.jshintrc b/node_modules/paellaplayer/.jshintrc new file mode 100644 index 000000000..6ccc25189 --- /dev/null +++ b/node_modules/paellaplayer/.jshintrc @@ -0,0 +1,9 @@ +{ + "laxbreak" : true, + "eqnull": true, + "-W041": false, + "scripturl": true, + "loopfunc": true, + "-W069": true, + "sub": true +} diff --git a/node_modules/paellaplayer/.markdownlint.json b/node_modules/paellaplayer/.markdownlint.json new file mode 100644 index 000000000..c7976dc5e --- /dev/null +++ b/node_modules/paellaplayer/.markdownlint.json @@ -0,0 +1,14 @@ +{ + "default": true, + "headers": { "style": "atx" }, + "indentation": { "indent": 4 }, + "line_length": false, + "no-trailing-punctuation": { "punctuation": ".,;:" }, + "ul-style": { "style": "sublist" }, + "ol-prefix": false, + "no-hard-tabs": false, + + + "no-alt-text": false, + "whitespace": false + } \ No newline at end of file diff --git a/node_modules/paellaplayer/.npmignore b/node_modules/paellaplayer/.npmignore new file mode 100644 index 000000000..2e465826c --- /dev/null +++ b/node_modules/paellaplayer/.npmignore @@ -0,0 +1,14 @@ +.DS_Store +desktop.ini +test +*~ +tmp +build +node_modules +repository_test/repository/local* +.idea +tests/nightwatch/reports/* +\.vscode/ +.eslintrc +chromedriver.log +dist \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/bower/bower.json b/node_modules/paellaplayer/.publish_scripts/bower/bower.json new file mode 100644 index 000000000..103ea3a0d --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/bower/bower.json @@ -0,0 +1,11 @@ +{ + "name": "paella", + "description": "Paella Player", + "keywords": "HTML5 paella player", + "homepage": "http://paellaplayer.upv.es/", + "license": "ECL-2.0", + "ignore": [ + ], + "dependencies": { + } +} \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/bower/publish.sh b/node_modules/paellaplayer/.publish_scripts/bower/publish.sh new file mode 100755 index 000000000..6f496a1bc --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/bower/publish.sh @@ -0,0 +1,144 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +source $SCRIPT_PARENT_FOLDER/utility.sh +#. _scripts/github.sh + +usage() { + echo "usage: $0 -d" + echo " -v VERSION" + echo " [-f FOLDER]" + echo " [-r GITHUB_BOWER_REPO]" + echo " [-c GITHUB_BOWER_TOKEN]" + echo " [-n GIT_NAME]" + echo " [-e GIT_EMAIL]" + echo +} + +## MAIN +DEPLOY_FOLDER="." +GIT_EMAIL="travis@travis-ci.org" +GIT_NAME="Travis CI" + +while getopts ":du:v:f:r:c:n:e:" opt; do + case $opt in + d) + DEBUG=1 + ;; + v) + VERSION="$OPTARG" + ;; + f) + DEPLOY_FOLDER="$OPTARG" + ;; + r) + GIT_BOWER_REPO="$OPTARG" + ;; + c) + GIT_BOWER_TOKEN="$OPTARG" + ;; + n) + GIT_NAME="$OPTARG" + ;; + e) + GIT_EMAIL="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${VERSION}x" == "x" ]; then + echo "[ERROR] No version defined" + usage + exit 1 +fi + +if [ "${DEPLOY_FOLDER}x" == "x" ]; then + echo "[ERROR] No deploy folder defined" + usage + exit 1 +fi + +if [ ! -d "${DEPLOY_FOLDER}" ]; then + echo "[ERROR] Deploy folder does not exists" + exit 1 +fi + +if [ "${GIT_BOWER_REPO}x" == "x" ] ; then + echo "[ERROR] No git repo for bower defined" + exit 1 +fi + +if [ "${GIT_BOWER_TOKEN}x" == "x" ] ; then + echo "[ERROR] No git token for bower defined" + exit 1 +fi + + +ret=$( is_proper_version $VERSION ) +if [[ ! 0 == $ret ]]; then # it is a proper semver VERSION + echo "[INFO] Nothing published as version $VERSION is not a proper version format" + exit 0 +fi + + +echo "[INFO] Publishing bower package version=$VERSION" + +COMMIT_AUTHOR=$(git --no-pager show -s --format='%an <%ae>' ${TRAVIS_COMMIT}) + +TMP_FOLDER=$(mktemp -d -t deploy-bower.XXXXXX) +echo "[INFO] Using $TMP_FOLDER as temporal folder" + +git clone https://${GIT_BOWER_TOKEN}@github.com/${GIT_BOWER_REPO}.git $TMP_FOLDER +rm -rf $TMP_FOLDER/* + +cp -r $DEPLOY_FOLDER/ $TMP_FOLDER + +if [ -f "$SCRIPT_FOLDER/bower.json" ]; then + cp $SCRIPT_FOLDER/bower.json $TMP_FOLDER +fi +if [ -f "$SCRIPT_FOLDER/README.md" ]; then + cp $SCRIPT_FOLDER/README.md $TMP_FOLDER +fi + + +pushd $TMP_FOLDER > /dev/null + +echo "[INFO] Setup git name=$GIT_NAME email=$GIT_EMAIL" +git config --local user.email "$GIT_EMAIL" +git config --local user.name "$GIT_NAME" + +git add -A +GIT_COMMITTER_NAME="${GIT_NAME}" GIT_COMMITTER_EMAIL="${GIT_EMAIL}" git commit --author "${COMMIT_AUTHOR}" \ + -m "[automated publishing] version ${VERSION}" \ + -m "Triggered by https://github.com/${TRAVIS_REPO_SLUG}/commit/${TRAVIS_COMMIT}" \ +|| true +git tag $VERSION +git push --tags https://${GIT_BOWER_TOKEN}@github.com/${GIT_BOWER_REPO}.git master + +popd > /dev/null + +echo "[INFO] Removing temporal folder" +rm -rf $TMP_FOLDER +echo "[INFO] Done!" \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/is_prerelease_version.sh b/node_modules/paellaplayer/.publish_scripts/is_prerelease_version.sh new file mode 100755 index 000000000..f4ed569e0 --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/is_prerelease_version.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" +VERSION=$1 + +is_prerelease_version(){ + version="$1" + + if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(\-[0-9A-Za-z\.\-]+)(\+[0-9A-Za-z\.\-]+)?$ ]] + then + echo 0 + return 0 + fi + + echo 1 + return 0 +} + +ret=$( is_prerelease_version $VERSION ) +if [[ ! 0 == $ret ]]; then + echo false +else + echo true +fi diff --git a/node_modules/paellaplayer/.publish_scripts/npm/publish.sh b/node_modules/paellaplayer/.publish_scripts/npm/publish.sh new file mode 100755 index 000000000..b9363f196 --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/npm/publish.sh @@ -0,0 +1,128 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +source $SCRIPT_PARENT_FOLDER/utility.sh +#. _scripts/github.sh + +usage() { + echo "usage: $0 -d" + echo " -v VERSION" + echo " [-f FOLDER]" + echo " [-c NPM_TOKEN]" + echo " [-t NPM_TAG]" + echo +} + +## MAIN +DEPLOY_FOLDER="." +NPM_TAG="latest" + + +while getopts ":du:v:f:t:c:" opt; do + case $opt in + d) + DEBUG=1 + ;; + v) + VERSION="$OPTARG" + ;; + f) + DEPLOY_FOLDER="$OPTARG" + ;; + t) + NPM_TAG="$OPTARG" + ;; + c) + NPM_TOKEN="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${VERSION}x" == "x" ]; then + echo "[ERROR] No version defined" + usage + exit 1 +fi + +if [ "${DEPLOY_FOLDER}x" == "x" ]; then + echo "[ERROR] No deploy folder defined" + usage + exit 1 +fi + +if [ ! -d "${DEPLOY_FOLDER}" ]; then + echo "[ERROR] Deploy folder does not exists" + exit 1 +fi + +if [ "${NPM_TOKEN}x" == "x" ] ; then + echo "[ERROR] No npm token defined" + usage + exit 1 +fi + + + +ret=$( is_proper_version $VERSION ) +if [[ ! 0 == $ret ]]; then # it is a proper semver VERSION + echo "[INFO] Nothing published as version $VERSION is not a proper version format" + exit 0 +fi + +TMP_FOLDER=$(mktemp -d -t deploy-npm.XXXXXX) +echo "[INFO] Using $TMP_FOLDER as temporal folder" + +cp -r $DEPLOY_FOLDER/ $TMP_FOLDER + +if [ -f "package.json" ]; then + cp package.json $TMP_FOLDER +fi +if [ -f "$SCRIPT_FOLDER/package.json" ]; then + cp $SCRIPT_FOLDER/package.json $TMP_FOLDER +fi + +if [ -f "README.md" ]; then + cp README.md $TMP_FOLDER +fi +if [ -f "$SCRIPT_FOLDER/README.md" ]; then + cp $SCRIPT_FOLDER/README.md $TMP_FOLDER +fi +replaceJsonProp "$TMP_FOLDER/package.json" "version" ".*" "$VERSION" + +cat > "$TMP_FOLDER/.npmrc" < "$TMP_FOLDER/.npmignore" < /dev/null +echo "[INFO] Publishing npm package version=$VERSION tag=$NPM_TAG" +npm publish --tag $NPM_TAG +popd > /dev/null + +echo "[INFO] Removing temporal folder" +rm -rf $TMP_FOLDER +echo "[INFO] Done!" \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/publish.sh b/node_modules/paellaplayer/.publish_scripts/publish.sh new file mode 100755 index 000000000..711d7ebea --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/publish.sh @@ -0,0 +1,45 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +# NPM_TOKEN and GITHUB_AUTH_TOKEN are stored in travis secure env + +TGZ_OUTPUT=$HOME/prebuilt + +GITHUB_BOWER_REPO="polimediaupv/bower-paella" +GITHUB_WEBPAGE_REPO="polimediaupv/paellaplayer.upv.es" +POLIMEDIA_NAME="Polimedia Team" +POLIMEDIA_EMAIL="polim@upvnet.upv.es" + + +DEPLOY_FOLDER=`pwd`/build/ + +if [ ! "${TRAVIS_PULL_REQUEST}x" == "falsex" ]; then + echo "[ERROR] This is a pull request. You can not publish a PR" + exit 1 +fi + +if [ ! -z "${TRAVIS_TAG}" ]; then + echo "[INFO] Publishing on TAG ${TRAVIS_TAG}" + VERSION=${TRAVIS_TAG} + ./$SCRIPT_FOLDER/webpage/publish_player.sh -v $VERSION -f `pwd` -r $GITHUB_WEBPAGE_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN + ./$SCRIPT_FOLDER/npm/publish.sh -v $VERSION -c $NPM_TOKEN -f "$DEPLOY_FOLDER" + ./$SCRIPT_FOLDER/bower/publish.sh -v $VERSION -f "$DEPLOY_FOLDER" -r $GITHUB_BOWER_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN + ./$SCRIPT_FOLDER/tarball/publish.sh -v $VERSION -f "$DEPLOY_FOLDER" -o $TGZ_OUTPUT +elif [ ! -z "${TRAVIS_BRANCH}" ]; then + echo "[INFO] Commit on branch ${TRAVIS_BRANCH} (${TRAVIS_COMMIT})" + if [[ "$TRAVIS_BRANCH" =~ ^([0-9]+\.[0-9]+\.x)$ ]] ; then + VERSION=${BASH_REMATCH[1]} + elif [[ "${TRAVIS_BRANCH}x" == "developx" ]] ; then + VERSION=develop + fi + if [ -z "${VERSION}" ]; then + echo "[ERROR] No publication for branch ${TRAVIS_BRANCH}" + else + echo "[INFO] Publishing on branch ${TRAVIS_BRANCH} (VERSION=${VERSION})" + ./$SCRIPT_FOLDER/webpage/publish_player.sh -v $VERSION -f `pwd` -r $GITHUB_WEBPAGE_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN -y + ./$SCRIPT_FOLDER/webpage/publish_doc.sh -v $VERSION -f `pwd` -r $GITHUB_WEBPAGE_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN + fi +fi diff --git a/node_modules/paellaplayer/.publish_scripts/publish_on_branch.sh b/node_modules/paellaplayer/.publish_scripts/publish_on_branch.sh new file mode 100755 index 000000000..07e3464d4 --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/publish_on_branch.sh @@ -0,0 +1,75 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +# NPM_TOKEN and GITHUB_AUTH_TOKEN are stored in travis secure env + +TGZ_OUTPUT=$HOME/prebuilt + +GITHUB_BOWER_REPO="polimediaupv/bower-paella" +GITHUB_WEBPAGE_REPO="polimediaupv/paellaplayer.upv.es" +POLIMEDIA_NAME="Polimedia Team" +POLIMEDIA_EMAIL="polim@upvnet.upv.es" + +DEPLOY_FOLDER=`pwd`/build/ + + + +usage() { + echo "usage: $0 -d" + echo " -b branch" + echo +} + +while getopts ":d:b:" opt; do + case $opt in + d) + DEBUG=1 + ;; + b) + BRANCH="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${BRANCH}x" == "x" ]; then + echo "[ERROR] No branch defined" + usage + exit 1 +fi + + +echo "[INFO] Commit on branch ${BRANCH}" +if [[ "$BRANCH" =~ ^([0-9]+\.[0-9]+\.x)$ ]] ; then + VERSION=${BASH_REMATCH[1]} +elif [[ "${BRANCH}x" == "developx" ]] ; then + VERSION=develop +fi +if [ -z "${VERSION}" ]; then + echo "[ERROR] No publication for branch ${BRANCH}" +else + echo "[INFO] Publishing on branch ${BRANCH} (VERSION=${VERSION})" + ./$SCRIPT_FOLDER/webpage/publish_player.sh -v $VERSION -f `pwd` -r $GITHUB_WEBPAGE_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN -y + ./$SCRIPT_FOLDER/webpage/publish_doc.sh -v $VERSION -f `pwd` -r $GITHUB_WEBPAGE_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN +fi \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/publish_on_tag.sh b/node_modules/paellaplayer/.publish_scripts/publish_on_tag.sh new file mode 100755 index 000000000..5e2570098 --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/publish_on_tag.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +# NPM_TOKEN and GITHUB_AUTH_TOKEN are stored in travis secure env + +TGZ_OUTPUT=$HOME/prebuilt + +GITHUB_BOWER_REPO="polimediaupv/bower-paella" +GITHUB_WEBPAGE_REPO="polimediaupv/paellaplayer.upv.es" +POLIMEDIA_NAME="Polimedia Team" +POLIMEDIA_EMAIL="polim@upvnet.upv.es" + +DEPLOY_FOLDER=`pwd`/build/ + + + +usage() { + echo "usage: $0 -d" + echo " -v VERSION" + echo +} + +while getopts ":d:v:" opt; do + case $opt in + d) + DEBUG=1 + ;; + v) + VERSION="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${VERSION}x" == "x" ]; then + echo "[ERROR] No version defined" + usage + exit 1 +fi + + +echo "[INFO] Publishing VERSION ${VERSION}" +./$SCRIPT_FOLDER/webpage/publish_player.sh -v $VERSION -f `pwd` -r $GITHUB_WEBPAGE_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN +./$SCRIPT_FOLDER/npm/publish.sh -v $VERSION -c $NPM_TOKEN -f "$DEPLOY_FOLDER" +./$SCRIPT_FOLDER/bower/publish.sh -v $VERSION -f "$DEPLOY_FOLDER" -r $GITHUB_BOWER_REPO -n "$POLIMEDIA_NAME" -e "$POLIMEDIA_EMAIL" -c $GITHUB_AUTH_TOKEN +./$SCRIPT_FOLDER/tarball/publish.sh -v $VERSION -f "$DEPLOY_FOLDER" -o $TGZ_OUTPUT diff --git a/node_modules/paellaplayer/.publish_scripts/tarball/publish.sh b/node_modules/paellaplayer/.publish_scripts/tarball/publish.sh new file mode 100755 index 000000000..c8f400230 --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/tarball/publish.sh @@ -0,0 +1,93 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +source $SCRIPT_PARENT_FOLDER/utility.sh +#. _scripts/github.sh + +usage() { + echo "usage: $0 -d" + echo " -v VERSION" + echo " [-f FOLDER]" + echo " [-o OUTPUT_FOLDER]" + echo +} + +## MAIN +DEPLOY_FOLDER="." +OUTPUT_FOLDER="." + + +while getopts ":du:v:f:o:" opt; do + case $opt in + d) + DEBUG=1 + ;; + v) + VERSION="$OPTARG" + ;; + f) + DEPLOY_FOLDER="$OPTARG" + ;; + o) + OUTPUT_FOLDER="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${VERSION}x" == "x" ]; then + echo "[ERROR] No version defined" + usage + exit 1 +fi + +if [ "${DEPLOY_FOLDER}x" == "x" ]; then + echo "[ERROR] No deploy folder defined" + usage + exit 1 +fi + +if [ ! -d "${DEPLOY_FOLDER}" ]; then + echo "[ERROR] Deploy folder does not exists" + exit 1 +fi + +mkdir -p ${OUTPUT_FOLDER} +if [ ! -d "${OUTPUT_FOLDER}" ]; then + echo "[ERROR] Output folder does not exists" + exit 1 +fi + + +ret=$( is_proper_version $VERSION ) +if [[ ! 0 == $ret ]]; then # it is a proper semver VERSION + echo "[INFO] Nothing published as version $VERSION is not a proper version format" + exit 0 +fi + +echo "[INFO] Publishing tarball package version=$VERSION to $OUTPUT_FOLDER" + +tar czf $OUTPUT_FOLDER/paella-prebuilt-${VERSION}.tar.gz -C $DEPLOY_FOLDER . + +echo "[INFO] Done!" \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/utility.sh b/node_modules/paellaplayer/.publish_scripts/utility.sh new file mode 100644 index 000000000..8bc42f84d --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/utility.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +# decides whether it is proper semver +is_proper_version(){ + version="$1" + + if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(\-[0-9A-Za-z\.\-]+)?(\+[0-9A-Za-z\.\-]+)?$ ]] + then + echo 0 + return 0 + fi + + echo 1 + return 0 +} + + +is_prerelease_version(){ + version="$1" + + if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(\-[0-9A-Za-z\.\-]+)(\+[0-9A-Za-z\.\-]+)?$ ]] + then + echo 0 + return 0 + fi + + echo 1 + return 0 +} + +# copied from https://github.com/angular/angular.js/blob/master/scripts/utils.inc +# replaceInFile file findPattern replacePattern +replaceInFile() { + sed -i.tmp -E "s/$2/$3/" $1 + rm $1.tmp +} + +# copied from https://github.com/angular/angular.js/blob/master/scripts/utils.inc +# replaceJsonProp jsonFile propertyRegex valueRegex replacePattern +# - note: propertyRegex will be automatically placed into a +# capturing group! -> all other groups start at index 2! +replaceJsonProp() { + replaceInFile $1 '"('$2')"[ ]*:[ ]*"'$3'"' '"\1": "'$4'"' +} diff --git a/node_modules/paellaplayer/.publish_scripts/webpage/publish_doc.sh b/node_modules/paellaplayer/.publish_scripts/webpage/publish_doc.sh new file mode 100755 index 000000000..ed7e451b3 --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/webpage/publish_doc.sh @@ -0,0 +1,142 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +source $SCRIPT_PARENT_FOLDER/utility.sh +#. _scripts/github.sh + +usage() { + echo "usage: $0 -d" + echo " -v VERSION" + echo " [-f SRC_PAELLA_FOLDER]" + echo " [-r GITHUB_WEBPAGE_REPO]" + echo " [-c GITHUB_WEBPAGE_TOKEN]" + echo " [-n GIT_NAME]" + echo " [-e GIT_EMAIL]" + echo +} + +## MAIN +SRC_PAELLA_FOLDER="." +GIT_EMAIL="travis@travis-ci.org" +GIT_NAME="Travis CI" + +while getopts ":du:v:f:r:c:n:e:" opt; do + case $opt in + d) + DEBUG=1 + ;; + v) + VERSION="$OPTARG" + ;; + f) + SRC_PAELLA_FOLDER="$OPTARG" + ;; + r) + GITHUB_WEBPAGE_REPO="$OPTARG" + ;; + c) + GITHUB_WEBPAGE_TOKEN="$OPTARG" + ;; + n) + GIT_NAME="$OPTARG" + ;; + e) + GIT_EMAIL="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${VERSION}x" == "x" ]; then + echo "[ERROR] No version defined" + usage + exit 1 +fi + +if [ "${SRC_PAELLA_FOLDER}x" == "x" ]; then + echo "[ERROR] No source paella folder defined" + usage + exit 1 +fi + +if [ ! -d "${SRC_PAELLA_FOLDER}" ]; then + echo "[ERROR] Source paella folder does not exists" + exit 1 +fi + +if [ "${GITHUB_WEBPAGE_REPO}x" == "x" ] ; then + echo "[ERROR] No git repo for webpage defined" + exit 1 +fi + +if [ "${GITHUB_WEBPAGE_TOKEN}x" == "x" ] ; then + echo "[ERROR] No git token defined" + exit 1 +fi + + + +echo "[INFO] Publishing documentation for version=$VERSION" + +TMP_FOLDER=$(mktemp -d -t deploy-doc.XXXXXX) +echo "[INFO] Using $TMP_FOLDER as temporal folder" + +git clone https://${GITHUB_WEBPAGE_TOKEN}@github.com/${GITHUB_WEBPAGE_REPO}.git --branch gh-pages $TMP_FOLDER +COMMIT_AUTHOR=$(git --no-pager show -s --format='%an <%ae>' ${TRAVIS_COMMIT}) + + +if [ -f "${SRC_PAELLA_FOLDER}/doc/toc.yml" ] ; then + + pushd $TMP_FOLDER > /dev/null + + echo "[INFO] Copy documentation for version=${VERSION}" + if [ -d "_docs/${VERSION}" ] ; then + git rm -r _docs/${VERSION}/* + fi + cp -r ${SRC_PAELLA_FOLDER}/doc ${TMP_FOLDER}/_docs/${VERSION} + mv ${TMP_FOLDER}/_docs/${VERSION}/toc.yml ${TMP_FOLDER}/_data/docs/${VERSION}.yml + if [ ! -f "${SRC_PAELLA_FOLDER}/doc/changelog.md" ] ; then + echo -e "---\n---\n\n" >${TMP_FOLDER}/_docs/${VERSION}/changelog.md + cat ${SRC_PAELLA_FOLDER}/CHANGELOG >> ${TMP_FOLDER}/_docs/${VERSION}/changelog.md + fi + + echo "[INFO] Setup git name=$GIT_NAME email=$GIT_EMAIL" + git config --local user.email "$GIT_EMAIL" + git config --local user.name "$GIT_NAME" + + git add ./* + git status + GIT_COMMITTER_NAME="${GIT_NAME}" GIT_COMMITTER_EMAIL="${GIT_EMAIL}" git commit --author "${COMMIT_AUTHOR}" \ + -m "Update documentation for paella ${VERSION}" \ + -m "Triggered by https://github.com/${TRAVIS_REPO_SLUG}/commit/${TRAVIS_COMMIT}" \ + || true + + + git push https://${GITHUB_WEBPAGE_TOKEN}@github.com/${GITHUB_WEBPAGE_REPO}.git gh-pages || true + popd > /dev/null +fi + +echo "[INFO] Removing temporal folder" +rm -rf $TMP_FOLDER +echo "[INFO] Done!" \ No newline at end of file diff --git a/node_modules/paellaplayer/.publish_scripts/webpage/publish_player.sh b/node_modules/paellaplayer/.publish_scripts/webpage/publish_player.sh new file mode 100755 index 000000000..6eda6e63e --- /dev/null +++ b/node_modules/paellaplayer/.publish_scripts/webpage/publish_player.sh @@ -0,0 +1,152 @@ +#!/bin/bash + +SCRIPT_FOLDER=$(dirname $0) +SCRIPT_PARENT_FOLDER=$(dirname $SCRIPT_FOLDER) +SCRIPT_FILENAME="$(basename "$0")" + +source $SCRIPT_PARENT_FOLDER/utility.sh +#. _scripts/github.sh + +usage() { + echo "usage: $0 -d" + echo " -v VERSION" + echo " [-f SRC_PAELLA_FOLDER]" + echo " [-r GITHUB_WEBPAGE_REPO]" + echo " [-c GITHUB_WEBPAGE_TOKEN]" + echo " [-n GIT_NAME]" + echo " [-e GIT_EMAIL]" + echo +} + +## MAIN +SRC_PAELLA_FOLDER="." +GIT_EMAIL="travis@travis-ci.org" +GIT_NAME="Travis CI" + +while getopts ":du:yu:v:f:r:c:n:e:" opt; do + case $opt in + d) + DEBUG=1 + ;; + y) + FORCE=1 + ;; + v) + VERSION="$OPTARG" + ;; + f) + SRC_PAELLA_FOLDER="$OPTARG" + ;; + r) + GITHUB_WEBPAGE_REPO="$OPTARG" + ;; + c) + GITHUB_WEBPAGE_TOKEN="$OPTARG" + ;; + n) + GIT_NAME="$OPTARG" + ;; + e) + GIT_EMAIL="$OPTARG" + ;; + \?) + set +x + echo "Invalid option: -$OPTARG" >&2 + usage + exit 1 + ;; + :) + set +x + echo "Option -$OPTARG requires an argument." >&2 + usage + exit 1 + ;; + esac +done + +if [ "${DEBUG:-}" == "1" ]; then + echo "[INFO] Debug Enabled" + set -x +fi + +set -e + +if [ "${VERSION}x" == "x" ]; then + echo "[ERROR] No version defined" + usage + exit 1 +fi + +if [ "${SRC_PAELLA_FOLDER}x" == "x" ]; then + echo "[ERROR] No source paella folder defined" + usage + exit 1 +fi + +if [ ! -d "${SRC_PAELLA_FOLDER}" ]; then + echo "[ERROR] Source paella folder does not exists" + exit 1 +fi + +if [ ! -d "${SRC_PAELLA_FOLDER}/build/player" ] ; then + echo "[ERROR] Paella is not built" + exit 1 +fi + +if [ "${GITHUB_WEBPAGE_REPO}x" == "x" ] ; then + echo "[ERROR] No git repo for webpage defined" + exit 1 +fi + +if [ "${GITHUB_WEBPAGE_TOKEN}x" == "x" ] ; then + echo "[ERROR] No git token defined" + exit 1 +fi + + + +echo "[INFO] Publishing paella player version=$VERSION to webpage" + +TMP_FOLDER=$(mktemp -d -t deploy-player.XXXXXX) +echo "[INFO] Using $TMP_FOLDER as temporal folder" + +git clone https://${GITHUB_WEBPAGE_TOKEN}@github.com/${GITHUB_WEBPAGE_REPO}.git --branch gh-pages $TMP_FOLDER +COMMIT_AUTHOR=$(git --no-pager show -s --format='%an <%ae>' ${TRAVIS_COMMIT}) + +pushd $TMP_FOLDER > /dev/null + + if [ -d "${TMP_FOLDER}/paella/player-${VERSION}" ] ; then + if [ "${FORCE}x" == "1x" ] ; then + echo "[INFO] player version ${VERSION} is already installed. Updating..." + git rm -r paella/player-${VERSION}/* + else + echo "[ERROR] player version ${VERSION} is already installed" + exit 1 + fi + fi + + cp -r ${SRC_PAELLA_FOLDER}/build/player ${TMP_FOLDER}/paella/player-${VERSION} + jq '.standalone.repository = "//repository.paellaplayer.upv.es/"' ${TMP_FOLDER}/paella/player-${VERSION}/config/config.json > ${TMP_FOLDER}/paella/player-${VERSION}/config/config.json.tmp + mv ${TMP_FOLDER}/paella/player-${VERSION}/config/config.json.tmp ${TMP_FOLDER}/paella/player-${VERSION}/config/config.json + + + echo "[INFO] Setup git name=$GIT_NAME email=$GIT_EMAIL" + git config --local user.email "$GIT_EMAIL" + git config --local user.name "$GIT_NAME" + + git add ./* + git status + GIT_COMMITTER_NAME="${GIT_NAME}" GIT_COMMITTER_EMAIL="${GIT_EMAIL}" git commit --author "${COMMIT_AUTHOR}" \ + -m "Update paella player ${VERSION}" \ + -m "Triggered by https://github.com/${TRAVIS_REPO_SLUG}/commit/${TRAVIS_COMMIT}" \ + || true + + + + + git push --tags https://${GITHUB_WEBPAGE_TOKEN}@github.com/${GITHUB_WEBPAGE_REPO}.git gh-pages || true +popd > /dev/null + +echo "[INFO] Removing temporal folder" +rm -rf $TMP_FOLDER +echo "[INFO] Done!" \ No newline at end of file diff --git a/node_modules/paellaplayer/.travis.yml b/node_modules/paellaplayer/.travis.yml new file mode 100644 index 000000000..934dccc7c --- /dev/null +++ b/node_modules/paellaplayer/.travis.yml @@ -0,0 +1,46 @@ +language: node_js + +node_js: + - "lts/*" + +install: + - npm ci + +jobs: + include: + - stage: tests + addons: + chrome: stable + before_install: + - google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost & + script: + - npm run markdownlint + + - stage: build and deploy + script: + - npm run build + before_deploy: + - export PRERELEASE=$(bash ./.publish_scripts/is_prerelease_version.sh ${TRAVIS_TAG}) + deploy: + - provider: script + script: ./.publish_scripts/publish_on_branch.sh -b ${TRAVIS_BRANCH} + skip_cleanup: true + on: + all_branches: true + condition: $TRAVIS_BRANCH =~ ^(([0-9]+\.[0-9]+\.x)|(develop))$ + - provider: script + script: ./.publish_scripts/publish_on_tag.sh -v ${TRAVIS_TAG} + skip_cleanup: true + on: + repo: polimediaupv/paella + tags: true + - provider: releases + skip_cleanup: true + api_key: + secure: UI6zIHGkhy7p/OtViLbi1yxuyYPteAoRGFO7D8xhc8N6YAkzxYFmlTHdUQgFj4Hgh+5gO6/jW9kpTkbkbATSIVLOLcuLyJEq6jDuorM2q8D2VInpc5ZpNddFjiQdKaIkZL8CeBnncKvmxCBZeHgE4MQPOGHtCQ900viROEVY0ak= + file: + - ${HOME}/prebuilt/paella-prebuilt-${TRAVIS_TAG}.tar.gz + prerelease: ${PRERELEASE} + on: + repo: polimediaupv/paella + tags: true diff --git a/node_modules/paellaplayer/.travis_scripts/prepate_deploy.sh b/node_modules/paellaplayer/.travis_scripts/prepate_deploy.sh new file mode 100755 index 000000000..7cc342000 --- /dev/null +++ b/node_modules/paellaplayer/.travis_scripts/prepate_deploy.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +if [ ! -z "${TRAVIS_TAG}" ]; then + mkdir ${HOME}/deploy + tar czf ~/deploy/paella-prebuilt-${TRAVIS_TAG}.tar.gz -C `pwd`/build/ . +fi \ No newline at end of file diff --git a/node_modules/paellaplayer/CHANGELOG b/node_modules/paellaplayer/CHANGELOG new file mode 100644 index 000000000..a2bc294b1 --- /dev/null +++ b/node_modules/paellaplayer/CHANGELOG @@ -0,0 +1,858 @@ + +CHANGELOG +========= + +* Paella 6.5.6 + + * The HLS plugin has been modified with features taken from `paella-core`, to improve playback of `m3u8` streams on bandwidth-limited connections. + * Other bug fixes. + * Breaking changes: + - The modifications in HLS plugin breaks some features on HLS plugin, such as the initial quality level. + +* Paella 6.5.5 + + * Improvements in HLS plugin. Please, ensure that the `isLiveStream` attribute is set correctly configured in the video manifest. + * Security bugs fixed. + * Other minor improvements. + +* Paella 6.5.4 + + * Removed RTMP support + * Fixed a bug when playing the video by clicking on the video container + * Other minor bug fixes + +* Paella 6.5.3 + + * New subtitle configuration options have been added. + * The log system has been improved. + * Fixed a bug in the parsing of subtitles in DFXP format. + +* Paella 6.5.2 + + * An accessibility bug has been fixed, which did not allow starting the video with screen readers. + * Fixed an issue with matomo media analytics. + +* Paella 6.5.1 + + * The subtitle plugin can now work with servers that require credentials. + +* Paella 6.5.0 + + * Improvements in HLS plugin + * Improvements in Matomo tracking plugin + * Dependencies have been updated + +* Paella 6.4.6 + + * Bug fixed in footprint plugin + +* Paella 6.4.5 + + * Improvements in dual stream video layout + +* Paella 6.4.4 + + * Bug fixes from 6.3.x branch. + +* Paella 6.4.3 + + * DFXP caption parse fix for jQuery 3.5.0 upgrade + * jQuery 3.5.1 upgrade + +* Paella 6.4.2 + + * Fixed a bug in HLS videos that occurs when the connection is slow. + +* Paella 6.4.1 + + * Bug fixed in iOS audio selector plugin. + +* Paella 6.4.0 + + * Playback bar canvas plugins: allows you to draw information in the playback bar area. + * Buffered video API added to streamProvider. + * Slide time marks moved to a playback bar canvas plugin. + * Buffered video playback bar canvas plugin added. + * New button plugin type: menu button. + * New multi audio API and HLS playlist multi audio compatibility. To use the new multi audio API: + - The new API is supported in HLS playlists. Configure your HLS server to provide the different audio streams in one (and only one) video stream. + - All other video streams must not contain any audio tracks. + - Set the property "role": "master" in the "data.json" manifest in the stream that contains the audio tracks. + * Breaking changes: + - Be sure to add the `es.upv.paella.timeMarksPlaybackCanvasPlugin` plugin settings so that the slide marks are drawn on the timeline. + - Note that the "audioTag" multi audio API is now deprecated, because it is not compatible with iOS devices. It will continue to work in the same way as it has so far, but will no longer be maintained due to incompatibility with iOS devices. + +* Paella 6.3.5 + + * Bug fixed in playback rate. + +* Paella 6.3.4 + + * webgl engine updated + +* Paella 6.3.3 + + * Bug fixes from the 6.2.x branch. + +* Paella 6.3.2 + + * Zoom plugin enhancements + * Bug fixes + +* Paella 6.3.1 + + * New video canvas: video360theta + +* Paella 6.3.0 + + * New feature: + + * video canvas. + * mute/unmute through paella.player.videoContainer, which retains the previous volume value. + * related videos: allows you to add links to two related videos, which appear at the end of the current video. + * related videos data delegate: by default, related video data is placed in the video manifest, but it is possible to customize this data with a new DataDelegate. + + * Improvements in video zoom UX: now it is necessary to press the ALT key to make the video zoom work. + * Other minor UX improvements. + +* 6.2.7 + + * Update Build Dependencies + * Update jQuery to 5.3.1 + * DFXP caption parse fix for jQuery 5.3.0 upgrade + +* Paella 6.2.6 + + * Fixed a bug with hiding videos in the profile manager + +* Paella 6.2.5 + + * Bug fixed in breaks plugin + + +* Paella 6.2.4 + + * Update dependencies + * Don't use the minimified version of lunr (olivernn/lunr.js#420, opencast/opencast#1131) + * The stream provider main audio player is now configured in the startVideoSync function. Fix #441 + +* Paella 6.2.3 + + * LazyLoad mode enhancements. + * Refactoring: play on screen icon. + +* Paella 6.2.2 + + * Fix a bug in the search service + +* Paella 6.2.1 + + * New setting added to configure the default audio tag to use. + * The video zoom is now enabled by default. + * Improvements in the processing of the video end event + * Other bug fixes + + +* Paella 6.2.0 + + * Lazy load: Paella Player will load the minimum resources requrired until the user press play. See the documentation for more information about how to enabler it. + * Preview improvements: it is possible to configure a preview image in the "metadata" section of the "data.json" file, independently of the preview of video streams. + * Breaking changes: + - Monostream profile APIs removed. This may break monostream videos if the streams + in `data.json` does not include the `content` attribute. + +* Paella 6.1.6 + + * Improved synchronization between video and audio streams + * Syncrhonous query functions added to video and audio elements + +* Paella 6.1.5 + + * Bug fixed and improvements in breaks plugin + +* Paella 6.1.4 + + * Some bug fixes and improvements in audo tags + +* Paella 6.1.3 + + * Some obsolete plugins removed + * Added an option to configure the maximum numbmer of simultaneous HLS streams. + * Bug fixed in trimmed videos. + +* Paella 6.1.2 + + * Support for n-streams implemented in arrow slide navigation plugin (Fix #406) + +* Paella 6.1.1 + + * Bug fixed in volume range plugin + +* Paella 6.1.0 + + * All the core classes migrated to ECMAScript 2015. + * Improvements in HLS plugin configuration. + * Improvements in accesibility. + * Improvements in usability: fold-out button plugin (see volume button plugin). + * Support for audio + images streams. + * Add support for video Picture-in-Picture in Chrome (#389) + * Add basque localization + * Add galician localization + * Breaking changes: + - The index.html file now includes paella_player_es2015.js. If you plan to support + Internet Explorer, you will need to modify the index.html file to add the legacy scripts. + - The button plugins now must implement the method getAriaLabel() to be included in the + tabindex. if you have a plugin that is relevant for screen readers, you must implement + this function in your plugin. + +* Paella 6.0.8 + + * Bug fixed in live streams videos + +* Paella 6.0.7 + + * Bug fixed when no "standalone" property exists in config.json + +* Paella 6.0.6 + + * Bug fixed setting video profile + +* Paella 6.0.5 + + * Improved video stability on slow networks. + * Bug fixed on first video layout load. + +* Paella 6.0.4 + + * Fix issues in stream video profiles + +* Paella 6.0.3 + + * Fix issues in errorContainer size + * Fixed bug in the zoom plugin visibility, when the control bar is hidden. + * Bug fixed in video factory selection method + +* Paella 6.0.2 + + * Fix some XSS security issues + +* Paella 6.0.1 + + * Better customization of video profile plugins + * Bug fixes + +* Paella 6.0.0 + + * Multiple video stream support + * Video profile plugins + * Dynamic video profiles + * Bug fixed in Elasticsearch plugin + * Full support for full screen on iPad, with iOS 12 + * Breaking changes: Check the following link to update your data.json files + to support the new multistream capabilities: + https://github.com/polimediaupv/paella/blob/develop/doc/adopter_doc/integrate_datajson.md + + + +* Paella 5.3.10 + + * Change width of PlaybackBar on resize (fixes #339) + * Return play and pause promise (fixes #341) + * Fix search when video is trimmed (fixes #351) + * Fix seek to incorrect caption and duplicated captions (fixes #353 and #354) + * Fix loop when seek throught a break in Safari for iOS (fixes #356) + * HLS plugin: handle nonfatal media errors + +* Paella 5.3.9 + + * Bug fixed in elasticsearch plugin + +* Paella 5.3.8 + + * HTML5 video factory now allows mp3 sources + * The VideoContainer.play() function now returns a rejected promise if the video can't be played + +* Paella 5.3.7 + + * Improvements on HLS plugin + * Add russian translation + * Track4k auto zoom fixes + * Improvements in video zoom + * Bug fixed in footprints plugin + +* Paella 5.3.6 + + * Improvements in legal info plugin + * Fixed issue in fullscreen plugin, in browsers that don't support autoplay + +* Paella 5.3.5 + + * Loader icon updated + * Bug fixed in arrow slides navigator plugin + * New plugin: legal information + +* Paella 5.3.4 + + * Fixes and improvements in live streaming videos + +* Paella 5.3.3 + + * UX bug fixed in paella.MessageBox + +* Paella 5.3.2 + + * Bug fixed in paella.MessageBox + * Bug fixed in travis scripts + * Added Matomo (org.opencast.usertracking.MatomoSaverPlugIn) plugin (thanks to @rrolf) + +* Paella 5.3.1 + + * Bug fixed in captions load + +* Paella 5.3.0 + + * New plugin registration system. + * Automatic zoom using track 4k + * Refactoring and bug fixes + * Use 16/9 aspect ratio for audio sources + * New plugin: Usertracking xAPI plugin (@dpeite) + * New plugin: Usertracking Piwik plugin + +* Paella 5.2.19 + + * Bug fixed in blackboard high resolution photo plugin + * Bug fixed in HTML 5 video element when the buffer is empty + +* Paella 5.2.18 + + * Full screen support on iPad iOS 12 + * Fix some XSS security issues + * Update NPM dependencies + +* Paella 5.2.17 + + * Bug fixed in elasticsearch plugin + +* Paella 5.2.16 + + * Improvements on HLS plugin + * Bug fixed in footprints plugin + +* Paella 5.2.15 + + * Legal info plugin improvements + +* Paella 5.2.14 + + * Legal info plugin added + +* Paella 5.2.13 + + * Fixed a bug when loading captions in an not supported format + +* Paella 5.2.12 + + * Changed function to build localization files + +* Paella 5.2.11 + + * Fix bug in embed code + +* Paella 5.2.10 + + * Fix publish scripts + +* Paella 5.2.9 + + * Bug fixed in arrow slide navigator plugin + * Added configUrl parameter to paella.load options + +* Paella 5.2.8 + + * Bug fixes and improvements + +* Paella 5.2.7 + + * Improvements and bug fixes in HLS. + +* Paella 5.2.6 + + * HLS streams in Safari for macOS now uses the native hls player. + +* Paella 5.2.5 + + * HLS streams limited to one simultaneous stream on iOS, to prevent memory problems on old iOS devices. + +* Paella 5.2.4 + + * Bug fixed in zoom plugin, in Safari 11 for macOS 10.13 + * Autoplay settings updated to take account of the upcoming browser restrictions in Safari 11 and Chrome 64 + * Bug fixed in zoom plugin, when some parameters in settings.json are missing. + * Bug fixed in captions plugin, that prevents to change the captions language in firefox. + +* Paella 5.2.3 + + * Now the video zoom button in toolbar shows the current zoom level. + +* Paella 5.2.2 + + * Bug fixed in breaks plugin. + * Now it's possible to configure the minimum window size to enable the video zoom. + * Deprecated plugins removed. + +* Paella 5.2.1 + + * Now it's possible to specify the video, preview and title using URL parameters. + * Visual improvements in breaks plugin. + +* Paella 5.2.0 + + * New video plugin: HLS player. + * Zoom on videos. + * Two new video zoom plugins. + * Video title plugin. + * Dual video playback in iOS 10.3 and above. + * Multiple audio stream selector (compatible with desktop browsers). + * WebVTT subtitle support. + * New multi language audio selector plugin. + * Refactoring, improvements and bug fixes. + +* Paella 5.1.14 + + * Fix error changing quality in mpeg dash streams. + +* Paella 5.1.13 + + * Bug fixed in window title plugin + +* Paella 5.1.12 + + * Fix some issues when changing profile (#249) + * Improvements in trimmed videos. + * Fix some warning on build (#255) + * Fix caption issues in trimmed videos (#260) + +* Paella 5.1.11 + + * Fix some issues playing live streams. + +* Paella 5.1.10 + + * Fix compilation error in blackboard profile selection. + +* Paella 5.1.9 + + * Fix #241: start-end params num protection in setTrimming (thanks to @karendolan). + * Fix bug in blackboard plugin. + +* Paella 5.1.8 + + * Fixed bug in volume control plugin initialization. + +* Paella 5.1.7 + + * Added translations to German (thanks to @underscoreabandit) + +* Paella 5.1.6 + + * Fixed bug setting attributes to video tag (iOS bug only) + * Fixed bug in footprints plugin duration returns promise) + * Fixed some bugs in javascript "strict mode" (thanks to @ppettit) + +* Paella 5.1.5 + + * Fixed bug in footprints plugin. + +* Paella 5.1.4 + + * Some events were not emited. + +* Paella 5.1.3 + + * WebGL video players are now compatible with mobile devices. + +* Paella 5.1.2 + + * Bug fix in es.upv.paella.arrowSlidesNavigatorPlugin + +* Paella 5.1.1 + + * Fix bugs in plugin: es.upv.paella.frameCaptionsSearchPlugin + * Fix bugs in plugin: es.upv.paella.searchPlugin + +* Paella 5.1.0 + + * Now using ECMAScript 6, with Traceur compiler. + * jQuery deferred changed to ECMAScript promises. + * Now it's possible to add audio streams as slave stream. + * New aspect ratios supported for single video streams. + * Video plugin: WebGL real time chroma video. + * Video plugin: Spheric 360º video. + * Video plugin: Ricoh Theta 360º camera raw video player. + * Captions added to video frame list. + * Now it's possible to hide pop up plugins on mouse out. + * New Apple Air Play plugin. + * New plugin to use the picture-in-picture mode in Safari for macOS. + * New plugin to rate videos. + * Improvements in mobile platforms. + * Search plugin updated to look into the frame list captions. + * Default skin changed. + * Refactoring, improvements and bug fixes. + * Changes in frameControl plugin. Show preview images over the player can be disabled and select the slides video(master/slave) + * New plugin 'es.upv.paella.arrowSlidesNavigatorPlugin': Allows slide navigation with next/prev arrows over the slide. + +* Paella 5.0.18 + + * Fix bug in RTMP plugin. + +* Paella 5.0.17 + + * Fix bug in captions plugin when there is only one caption + +* Paella 5.0.16 + + * Mute icon not showing on volume mute (Fix #219) + +* Paella 5.0.15 + + * Several bugs fixed in RTMP playback + +* Paella 5.0.14 + + * Bug fixed in video rectangle calculation, playing single stream videos + +* Paella 5.0.13 + + * Load error messages improved. + * Bug fix in captions plugin. + +* Paella 5.0.12 + + * Bug fix in RTMPVideo.setQuality(). + +* Paella 5.0.11 + + * Bug fix with volume initialization. + +* Paella 5.0.10 + + * Fixed some issues with the volume range plugin. + +* Paella 5.0.9 + + * Bug fixed with multiple video load in iOS. + +* Paella 5.0.8 + + * Fixed typo (Fix #207). + +* Paella 5.0.7 + + * Fixed several bugs with video factories in iOS platform. + +* Paella 5.0.6 + + * Fixed bug with dictionary loading. + +* Paella 5.0.5 + + * New automatic quality mode added to mpeg-dash video sources + * HLS support implemented for iOS devices + +* Paella 5.0.4 (07-06-2016) + + * Fixing PlayBackRate Plugin + +* Paella 5.0.3 (04-05-2016) + + * Bug fixed in translectures plugin + +* Paella 5.0.2 (04-05-2016) + + * Bug fixed in volumeRange plugin + +* Paella 5.0.1 (03-05-2016) + + * Bug fixed in visual annotations plugin + +* Paella 5.0.0 (25-04-2016) + + * Now the video query functions returns promises, and it isn't necessary to use events. + * New architecture implemented to provide a way to add new video type plugins. + * The RTMP video type has been moved to a plugin. + * New video plugin implemented to playback MPEG-DASH + * The editor has been moved to an external project (paella-editor). + * Refactoring on the video owner and permissions data APIs. + * New video plugin: youtube videos support. + +* Paella 4.2.0 (26-02-2016) + + * Add segment lines to the timeline + * Fix a bug when reload a video causing black screen blinks + * Resource pathes can be changed in config.json file (#168) + * Login functions implemented + * Microsoft Edge added to supported browser list + * Skins are now optional (#170) + * New Plugin: paella.plugins.WindowTitlePlugin + * Fix bug in captions plugin on Firefox (#177) + * Option to pass trim start & stop values as location arguments (#179) + +* Paella 4.1.13 (10-02-2016) + + * Fix bug in breakPlugins. Even if the configuration value 'neverShow' is 'true', the behaviour on the editor should remain before. + * Fix bug in editor: paella.breakPlugins: After changing its name, selecting a break will reset it (#189) + +* Paella 4.1.12 (27-01-2016) + + * Allow open the editor in an iframe using 'openEditorInIframe' parameter to true. + * Avoid negative trimming in trimming plugins. + * Added enableResetButton option using 'enableResetButton' parameter. + * Added config value 'neverShow' to the breaksPlayer plugin. + * Fixed editor not discarding changes on Breaks plugin + * Fixed editor not displaying saved changes on trimming. + +* Paella 4.1.11 (10-12-2015) + + * Microsoft Edge compatibility + +* Paella 4.1.10 (21-09-2015) + + * Fixed bug when there isn't a poster frame (#172) + +* Paella 4.1.9 (08-09-2015) + + * Fixed bug in Safari when the adblock plugin is installed. + +* Paella 4.1.8 (26-08-2015) + + * Fixed Bug on RTMP buffer time. + +* Paella 4.1.6 (29-07-2015) + + * Fixed Bug on Trimming Video using Slides preview on playbackbar. + +* Paella 4.1.5 (29-07-2015) + + * Fix bug in trimming feature. the setTrim event was not triggered. + +* Paella 4.1.4 (09-07-2015) + + * Fix bug when the video URL contains a '?' chararcter (#161). + +* Paella 4.1.3 (03-07-2015) + + * Fix bug in captions service. + +* Paella 4.1.2 (02-07-2015) + + * Fix bug in config.json file (es.upv.paella.multipleQualitiesPlugin was not enabled) + * Fixed bug in captions overlay showing captions on top + +* Paella 4.1.1 (30-06-2015) + + * Fix typo in config.json file + +* Paella 4.1.0 (30-06-2015) + + * Don't ignore vendor directories to make collaboration easier. + * Improvements to tools/layout_calculator. + * Changes in default audio configuration. + * Video resolution refactoring: class VideoQualityStrategy extracted, to create custom video resolution selection strategies. + * New plugin loading system implemented. + * Fixed bug in the image Preview (#98). + * Captions functionality moved into the paella core. + * The parameters of paella:resize event are now generated correctly (#102). + * Search service added to the core. + * New Plugin: es.upv.paella.searchPlugin + * userTracking logger added to the core. + * New DefaultVideoLoader added to Paella core + * New built in video loader + * Fixed bug with the volume when the video is reloaded + * New plugin added: es.upv.paella.translectures.CaptionsPlugIn + * New videoMode: blackboard + zoom images + * HLS support for iOS devices + +* Paella 4.0.24 (29-05-2015) + + * Fixed bug: Live stream with URLs containing a @ character doesn't work (#140) + +* Paella 4.0.23 (22-05-2015) + + * Fixed bug: Live stream volume control shows "muted" by default but audio is not muted (#143) + +* Paella 4.0.22 (20-05-2015) + + * Fixed bug causing video to mute when resolution switching (#142) + +* Paella 4.0.21 (18-05-2015) + + * Fixed bug in Multi-Qualities sort (#141) + +* Paella 4.0.20 (12-05-2015) + + * RTMP live streaming bug fixed + +* Paella 4.0.19 (04-05-2015) + + * MultiQuality selection change with single video fails at volumeRangePlugin storeVolume() (#137) + +* Paella 4.0.18 (20-4-2015) + + * Fixed bug in MultiQuality Sort order in Safari (#135) + +* Paella 4.0.17 (16-4-2015) + + * Fix bug in frameControl Plugin (#132) + +* Paella 4.0.16 (15-4-2015) + + * Fixed a bun in paella extended mode causing videos to be cropped in the video container (#94) + +* Paella 4.0.15 (10-4-2015) + + * Fixed bug with the volume when the video is reloaded + * Fixed bug with the "playing" when the video is reloaded + +* Paella 4.0.14 (10-4-2015) + + * Update VolumeRange when using KeyManager + +* Paella 4.0.13 (12-3-2015) + + * Flash video resize smooth + +* Paella 4.0.12 (19-2-2015) + + * Flash RTMP flv and mp4 improvements + +* Paella 4.0.11 (10-2-2015) + + * Flash RTMP live streaming bug fixed+ + +* Paella 4.0.10 (10-2-2015) + + * Flash RTMP streaming stability improved + +* Paella 4.0.9 (30-1-2015) + + * Volume Control bugs when the video reloads (#96) + +* Paella 4.0.8 (29-1-2015) + + * Internet Explorer fullscreen bug fixed + +* Paella 4.0.7 (29-1-2015) + + * Slide flickering bug fixed + +* Paella 4.0.6 (26-1-2015) + + * experimental autoplay mode in non-mobile devices + +* Paella 4.0.5 (22-12-2014) + + * multipleQualitiesPlugin updated. Ability to configure a minimum/maximum resolution to show in the available resolutions list. + * OSX/Firefox minimum version required only showed when playing mp4 files. + * Plugin ch.ethz.paella.multipleQualitiesPlugin removed. es.upv.paella.multipleQualitiesPlugin does that functionality. + +* Paella 4.0.4 (17-12-2014) + + * Fixed issues in multi quality plugin (list is not sorted (#83) and show only vertical resolition (#84) + * Change the OSX/Firefox error message to show it in Firefox 34 (#89) + * Fixed a bug in timeline-preview images (#85) + * When switching between resolutions no preview picture is showed (#87) + * Fix issues when trying to change from embed to fullscreen in IE11 (#88) + * New plugin added: ch.ethz.paella.multipleQualitiesPlugin + +* Paella 4.0.3 (09-12-2014) + + * Fix html5 videonode setDefaultVolume in firefox. (#78) + +* Paella 4.0.2 (04-12-2014) + + * Fix a bug that causes that time were not retained when switching resolutions. (#74) + +* Paella 4.0.1 (02-12-2014) + + * New event added on window resize. And Fixed a bug when resizing in extended mode. + +* Paella 4.0.0 (01-12-2014) + + * Better Video Quality management (Change video source to higher quality file seamlessly when switching to full screen. And switch to smaller file seamlessly when going back to embed). + * Video download bandwidth improved in multi resolution videos. + * Dual audio in dual track videos: Configurable option to mute one of the sources for desktop browsers. + * Pause video by clicking in the video area – and restart video by clicking there again. + * Don’t display the play icon in the video area after the video has started. + * Don’t display the control bar until the user has pressed the large play symbol (or hovered the mouse into the video area). + * Adaptive display for 4:3 videos. + * Multiple speed support in HTML5 mode. + * Better RTMP video playback. + * Improved Flash fallback for desktop browsers not able to play HTML5 video. + * Better Fullscreen management. + * Solved the issue that happened when calling the page, the video plays for half a second (with audio), then goes back to the pause and waits for user interaction; that shouldn’t happen. + * Icon redesign and cosmetic changes. + * Plugin activation and deactivation depending on the player state (displayed / not displayed only in embed / only in full screen). + * Change colour scheme: New skinning options. + * Removed the “zoom in” effect when player starts. + * Change symbol for full screen when in full screen: Invert arrows. + * iOS: Control bar now disappears automatically after x seconds. + * Internet Explorer: Control bar now hide automatically after x seconds. + * Slides now appear on top of the timeline on hovering. + * Now there is a configuration option that don’t allow a video to be larger than its real size. + * Preview release of the Blackboard zoom plugin. + * New layout calculator to create or modify the video layouts (thank's to Daniel Collins-Puro from Harvard for his contribution). + * The fullscreen plugin now opens the player in a new window, in those platforms that doesn't support HTML 5 fullscreen. + + +* Paella 3.1.0 (22-07-2014) + + * RTMP Live Streaming + * Multiple Language Captions + * Changes on the plugin management + * Bug fixes + +* Paella 3.0.0 (13-03.2014) + + * Redesign of the timeline + * New style of the slide list + * Auto hide buttons/features when they aren't relevant + * New still image video provider + * Android 4.x and iPad Support + * Multi-Quality video support + * New plugin: Download + * Improved accessibility for disabled users (Tooltips, ARIA roles and alerts) + * Enable/Disable plugins in the config file. + * Login/logout button for Matterhorn + * Integrated Video Editor with Soft Trimming and Soft Breaks + * Added the embed code in the share button). + * Fixed some bugs in Export Videos plugin + * Localization support + +* Paella 2.0.0 (21-06-2013) + + * Jump by clicking on the slide list + * High quality slides while seeking + * Can handle RTMP streaming servers + * Support of .flv files + * Embeddable + * Captions support + * Comments (experimental) + * Soft Editing features: Trimming and breaks + * Support of Chrome, Firefox, Safari and Internet Explorer 9 an 10 browsers + * Compatible with Opencast Matterhorn 1.4 + +* Paella 1.0 (Paella Engage Player) (28-05-2012) + + * Multi stream video player + * Completely based in HTML5 and Javascript + * Can play audio from any of the two videos, mute any of them or mix both + * Resize position/size of video windows while playing + * Play/Pause/30 seconds back controls + * Jump anywhere in the video keeping both tracks in sync + * Can handle progressive download and pseudostreaming servers + * Easily change the relative position of presenter and presentation windows + * Native Fullscreen version + * “Publish to” buttons for Facebook and Twitter + * Easy skinning + * Easy install. Just get the code, point to your server and run (if you have mp4/ogg videos available) + * Compatible with Opencast Matterhorn diff --git a/node_modules/paellaplayer/CHANGELOG-DEV b/node_modules/paellaplayer/CHANGELOG-DEV new file mode 100644 index 000000000..1c5539f4b --- /dev/null +++ b/node_modules/paellaplayer/CHANGELOG-DEV @@ -0,0 +1,6 @@ +CHANGELOG +========= + +* Paella WIP + + * Add support for HLS in non iOS devices (#223) \ No newline at end of file diff --git a/node_modules/paellaplayer/README.md b/node_modules/paellaplayer/README.md index 1389c837a..c5b026a96 100644 --- a/node_modules/paellaplayer/README.md +++ b/node_modules/paellaplayer/README.md @@ -1,25 +1,21 @@ -Paella Player (up to release 6.x) +About Paella Player 6.x ============= -The Paella (pronounced 'paeja') Player is an HTML 5 multistream player, developed by the [Universitat Politècnica de València](https://www.upv.es/). -It is specially designed for lecture recordings, like [Opencast](https://opencast.org) lectures or Polimedia pills. +Paella Player 7 has been rewritten from scratch using more current tools, to support technologies such as React or Svelte. For this reason, the development of Paella Player 6.x has been discontinued. No further updates of new features will be made. For the time being, updates of third-party dependency libraries and resolution of particularly serious bugs will continue, but it is recommended to migrate to version 7 as soon as possible. -Paella Player is capable of playing multiple audio and video streams synchronously and can be integrated into almost any video platform -using its powerful and easy to use plugin architecture. -You can find out more about Paella on the [Paella Player Web Page](https://paellaplayer.upv.es). +- [More information about Paella Player 7](https://github.com/polimediaupv/paella-core/blob/main/doc/paella_player_7_presentation.md) +- [Main Paella Player 7 github repository](https://github.com/polimediaupv/paella-player) -![Paella Player Logo](./config/profiles/resources/paella_logo_old.png) +Paella Player 7 repositories +---------------------------- +Paella Player version 7 has been developed following a different approach. The new player is divided into a base library (paella-core) and several plugin libraries developed by the Polytechnic University of Valencia (UPV) and other institutions. The main repository of Paella Player 7 is assembled from the libraries developed by the UPV. You can compile it to use it in your website, or to start from a code base to develop your own player. -Paella Player 7 and beyond ------------------ -In version 7, Paella is being rewritten from scratch, so we are using a different repo. - -Paella 7 is being developed in https://github.com/polimediaupv/paella-player +You can consult the official documentation in the [paella-core github repository](https://github.com/polimediaupv/paella-core/blob/main/doc/index.md) -Build and Install +Build and Install Paella Player 6 ----------------- To build Paella, run: @@ -31,5 +27,3 @@ To build Paella, run: ``` You can get more information about Paella and its development in the [documentation](https://paellaplayer.upv.es/docs/). - -[![Build Status](https://travis-ci.org/polimediaupv/paella.svg?branch=master)](https://travis-ci.org/polimediaupv/paella) diff --git a/node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js b/node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js deleted file mode 100644 index d57f56b70..000000000 --- a/node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js +++ /dev/null @@ -1,18403 +0,0 @@ - -const bg = {}; -bg.version = "1.3.32 - build: 87f16ac"; -bg.utils = {}; - -Reflect.defineProperty = Reflect.defineProperty || Object.defineProperty; - -(function(win) { - win.requestAnimFrame = (function() { - return window.requestAnimationFrame || - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - window.oRequestAnimationFrame || - window.msRequestAnimationFrame || - function(callback,element) { window.setTimeout(callback,1000/60); }; - })(); - - bg.utils.initWebGLContext = function(canvas) { - let context = { - gl:null, - supported:false, - experimental:false - } - try { - context.gl = canvas.getContext("webgl",{ preserveDrawingBuffer:true }); - context.supported = context.gl!=null; - } - catch (e) { - context.supported = false; - } - - if (!context.supported) { - try { - context.gl = canvas.getContext("experimental-webgl", { preserveDrawingBuffer:true }); - context.supported = context.gl!=null; - context.experimental = true; - } - catch(e) { - } - } - - if (context) { - context.gl.uuid = Symbol(context.gl); - } - return context; - }; - - bg.utils.isBigEndian = function() { - let arr32 = new Uint32Array(1); - var arr8 = new Uint8Array(arr32.buffer); - arr32[0] = 255; - return arr32[3]==255; - }; - - bg.utils.isLittleEndian = function() { - let arr32 = new Uint32Array(1); - var arr8 = new Uint8Array(arr32.buffer); - arr32[0] = 255; - return arr32[0]==255; - }; - - class UserAgent { - - constructor(userAgentString) { - this.system = {}; - this.browser = {}; - - if (!userAgentString) { - userAgentString = navigator.userAgent; - } - this.parseOperatingSystem(userAgentString); - this.parseBrowser(userAgentString); - } - - parseOperatingSystem(userAgentString) { - this.system.OSX = /Macintosh/.test(userAgentString); - this.system.Windows = /Windows/.test(userAgentString); - this.system.iPhone = /iPhone/.test(userAgentString); - this.system.iPodTouch = /iPod/.test(userAgentString); - this.system.iPad = /iPad/.test(userAgentString); - this.system.iOS = this.system.iPhone || this.system.iPad || this.system.iPodTouch; - this.system.Android = /Android/.test(userAgentString); - this.system.Linux = (this.system.Android) ? false:/Linux/.test(userAgentString); - - if (this.system.OSX) { - this.system.OSName = "OS X"; - this.parseOSXVersion(userAgentString); - } - else if (this.system.Windows) { - this.system.OSName = "Windows"; - this.parseWindowsVersion(userAgentString); - } - else if (this.system.Linux) { - this.system.OSName = "Linux"; - this.parseLinuxVersion(userAgentString); - } - else if (this.system.iOS) { - this.system.OSName = "iOS"; - this.parseIOSVersion(userAgentString); - } - else if (this.system.Android) { - this.system.OSName = "Android"; - this.parseAndroidVersion(userAgentString); - } - } - - parseBrowser(userAgentString) { - // Safari: Version/X.X.X Safari/XXX - // Chrome: Chrome/XX.X.XX.XX Safari/XXX - // Opera: Opera/X.XX - // Firefox: Gecko/XXXXXX Firefox/XX.XX.XX - // Explorer: MSIE X.X - this.browser.Version = {}; - this.browser.Safari = /Version\/([\d\.]+) Safari\//.test(userAgentString); - if (this.browser.Safari) { - this.browser.Name = "Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Chrome = /Chrome\/([\d\.]+) Safari\//.test(userAgentString); - if (this.browser.Chrome) { - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Opera = /Opera\/[\d\.]+/.test(userAgentString); - if (this.browser.Opera) { - this.browser.Name = "Opera"; - this.browser.Vendor = "Opera Software"; - var versionString = /Version\/([\d\.]+)/.test(userAgentString); - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Firefox = /Gecko\/[\d\.]+ Firefox\/([\d\.]+)/.test(userAgentString); - if (this.browser.Firefox) { - this.browser.Name = "Firefox"; - this.browser.Vendor = "Mozilla Foundation"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Edge = /Edge\/(.*)/.test(userAgentString); - if (this.browser.Edge) { - var result = /Edge\/(.*)/.exec(userAgentString); - this.browser.Name = "Edge"; - this.browser.Chrome = false; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = result[1]; - } - - this.browser.Explorer = /MSIE ([\d\.]+)/.test(userAgentString); - if (!this.browser.Explorer) { - var re = /\Mozilla\/5.0 \(([^)]+)\) like Gecko/ - var matches = re.exec(userAgentString); - if (matches) { - re = /rv:(.*)/ - var version = re.exec(matches[1]); - this.browser.Explorer = true; - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - if (version) { - this.browser.Version.versionString = version[1]; - } - else { - this.browser.Version.versionString = "unknown"; - } - } - } - else { - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = RegExp.$1; - } - - if (this.system.iOS) { - this.browser.IsMobileVersion = true; - this.browser.MobileSafari = /Version\/([\d\.]+) Mobile/.test(userAgentString); - if (this.browser.MobileSafari) { - this.browser.Name = "Mobile Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - this.browser.Android = false; - } - else if (this.system.Android) { - this.browser.IsMobileVersion = true; - this.browser.Android = /Version\/([\d\.]+) Mobile/.test(userAgentString); - if (this.browser.MobileSafari) { - this.browser.Name = "Android Browser"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - else { - this.browser.Chrome = /Chrome\/([\d\.]+)/.test(userAgentString); - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Safari = false; - } - else { - this.browser.IsMobileVersion = false; - } - - this.parseBrowserVersion(userAgentString); - } - - parseBrowserVersion(userAgentString) { - if (/([\d]+)\.([\d]+)\.*([\d]*)/.test(this.browser.Version.versionString)) { - this.browser.Version.major = Number(RegExp.$1); - this.browser.Version.minor = Number(RegExp.$2); - this.browser.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - } - } - - parseOSXVersion(userAgentString) { - var versionString = (/Mac OS X (\d+_\d+_*\d*)/.test(userAgentString)) ? RegExp.$1:''; - this.system.Version = {}; - // Safari/Chrome - if (versionString!='') { - if (/(\d+)_(\d+)_*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - } - } - // Firefox/Opera - else { - versionString = (/Mac OS X (\d+\.\d+\.*\d*)/.test(userAgentString)) ? RegExp.$1:'Unknown'; - if (/(\d+)\.(\d+)\.*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - } - } - if (!this.system.Version.major) { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - this.system.Version.stringValue = this.system.Version.major + '.' + this.system.Version.minor + '.' + this.system.Version.revision; - switch (this.system.Version.minor) { - case 0: - this.system.Version.name = "Cheetah"; - break; - case 1: - this.system.Version.name = "Puma"; - break; - case 2: - this.system.Version.name = "Jaguar"; - break; - case 3: - this.system.Version.name = "Panther"; - break; - case 4: - this.system.Version.name = "Tiger"; - break; - case 5: - this.system.Version.name = "Leopard"; - break; - case 6: - this.system.Version.name = "Snow Leopard"; - break; - case 7: - this.system.Version.name = "Lion"; - break; - case 8: - this.system.Version.name = "Mountain Lion"; - break; - } - } - - parseWindowsVersion(userAgentString) { - this.system.Version = {}; - if (/NT (\d+)\.(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = 0; // Solo por compatibilidad - this.system.Version.stringValue = "NT " + this.system.Version.major + "." + this.system.Version.minor; - var major = this.system.Version.major; - var minor = this.system.Version.minor; - var name = 'undefined'; - if (major==5) { - if (minor==0) this.system.Version.name = '2000'; - else this.system.Version.name = 'XP'; - } - else if (major==6) { - if (minor==0) this.system.Version.name = 'Vista'; - else if (minor==1) this.system.Version.name = '7'; - else if (minor==2) this.system.Version.name = '8'; - } - } - else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - parseLinuxVersion(userAgentString) { - this.system.Version = {}; - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - this.system.Version.name = ""; - this.system.Version.stringValue = "Unknown distribution"; - } - - parseIOSVersion(userAgentString) { - this.system.Version = {}; - if (/iPhone OS (\d+)_(\d+)_*(\d*)/i.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - this.system.Version.name = "iOS"; - } - else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - parseAndroidVersion(userAgentString) { - this.system.Version = {}; - if (/Android (\d+)\.(\d+)\.*(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } - else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - if (/Build\/([a-zA-Z]+)/.test(userAgentString)) { - this.system.Version.name = RegExp.$1; - } - else { - this.system.Version.name = "Unknown version"; - } - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } - - getInfoString() { - return navigator.userAgent; - } - } - - bg.utils.UserAgent = UserAgent; - bg.utils.userAgent = new UserAgent(); - - class Path { - get sep() { return "/"; } - - join(a,b) { - if (a.lastIndexOf(this.sep)!=a.length-1) { - return a + this.sep + b; - } - else { - return a + b; - } - } - - extension(path) { - return path.split(".").pop(); - } - - fileName(path) { - return path.split(this.sep).pop(); - } - - removeFileName(path) { - let result = path.split(this.sep); - result.pop(); - return result.join(this.sep); - } - } - - bg.utils.Path = Path; - bg.utils.path = new Path(); -})(window); - -(function() { - let s_preventImageDump = []; - let s_preventVideoDump = []; - - class ResourceProvider { - getRequest(url,onSuccess,onFail,onProgress) {} - loadImage(url,onSucces,onFail) {} - loadVideo(url,onSuccess,onFail) {} - } - - let g_videoLoaders = {}; - g_videoLoaders["mp4"] = function(url,onSuccess,onFail) { - var video = document.createElement('video'); - s_preventVideoDump.push(video); - video.crossOrigin = ""; - video.autoplay = true; - video.setAttribute("playsinline",null); - video.addEventListener('canplay',(evt) => { - let videoIndex = s_preventVideoDump.indexOf(evt.target); - if (videoIndex!=-1) { - s_preventVideoDump.splice(videoIndex,1); - } - onSuccess(event.target); - }); - video.addEventListener("error",(evt) => { - onFail(new Error(`Error loading video: ${url}`)); - }); - video.addEventListener("abort",(evt) => { - onFail(new Error(`Error loading video: ${url}`)); - }); - video.src = url; - } - g_videoLoaders["m4v"] = g_videoLoaders["mp4"]; - - class HTTPResourceProvider extends ResourceProvider { - static AddVideoLoader(type,callback) { - g_videoLoaders[type] = callback; - } - - static GetVideoLoaderForType(type) { - return g_videoLoaders[type]; - } - - static GetCompatibleVideoFormats() { - return Object.keys(g_videoLoaders); - } - - static IsVideoCompatible(videoUrl) { - let ext = Resource.GetExtension(videoUrl); - return bg.utils.HTTPResourceProvider.GetCompatibleVideoFormats().indexOf(ext)!=-1; - } - - getRequest(url,onSuccess,onFail,onProgress) { - var req = new XMLHttpRequest(); - if (!onProgress) { - onProgress = function(progress) { - console.log(`Loading ${ progress.file }: ${ progress.loaded / progress.total * 100 } %`); - } - } - req.open("GET",url,true); - req.addEventListener("load", function() { - if (req.status===200) { - onSuccess(req); - } - else { - onFail(new Error(`Error receiving data: ${req.status}, url: ${url}`)); - } - }, false); - req.addEventListener("error", function() { - onFail(new Error(`Cannot make AJAX request. Url: ${url}`)); - }, false); - req.addEventListener("progress", function(evt) { - onProgress({ file:url, loaded:evt.loaded, total:evt.total }); - }, false); - return req; - } - - loadImage(url,onSuccess,onFail) { - var img = new Image(); - s_preventImageDump.push(img); - img.crossOrigin = ""; - img.addEventListener("load",function(event) { - let imageIndex = s_preventImageDump.indexOf(event.target); - if (imageIndex!=-1) { - s_preventImageDump.splice(imageIndex,1); - } - onSuccess(event.target); - }); - img.addEventListener("error",function(event) { - onFail(new Error(`Error loading image: ${url}`)); - }); - img.addEventListener("abort",function(event) { - onFail(new Error(`Image load aborted: ${url}`)); - }); - img.src = url + '?' + bg.utils.generateUUID(); - } - - loadVideo(url,onSuccess,onFail) { - let ext = Resource.GetExtension(url); - let loader = bg.utils.HTTPResourceProvider.GetVideoLoaderForType(ext); - if (loader) { - loader.apply(this,[url,onSuccess,onFail]); - } - else { - onFail(new Error(`Could not find video loader for resource: ${ url }`)); - } - } - } - - bg.utils.ResourceProvider = ResourceProvider; - bg.utils.HTTPResourceProvider = HTTPResourceProvider; - - let g_resourceProvider = new HTTPResourceProvider(); - - class Resource { - static SetResourceProvider(provider) { - g_resourceProvider = provider; - } - - static GetResourceProvider() { - return g_resourceProvider; - } - - static GetExtension(url) { - let match = /\.([a-z0-9-_]*)(\?.*)?(\#.*)?$/i.exec(url); - return (match && match[1].toLowerCase()) || ""; - } - - static JoinUrl(url,path) { - if (url.length==0) return path; - if (path.length==0) return url; - return /\/$/.test(url) ? url + path : url + "/" + path; - } - - static IsFormat(url,formats) { - return formats.find(function(fmt) { - return fmt==this; - },Resource.GetExtension(url))!=null; - } - - static IsImage(url) { - return Resource.IsFormat(url,["jpg","jpeg","gif","png"]); - } - - static IsBinary(url,binaryFormats = ["vwglb","bg2"]) { - return Resource.IsFormat(url,binaryFormats); - } - - static IsVideo(url,videoFormats = ["mp4","m4v","ogg","ogv","m3u8","webm"]) { - return Resource.IsFormat(url,videoFormats); - } - - static LoadMultiple(urlArray,onProgress) { - let progressFiles = {} - - let progressFunc = function(progress) { - progressFiles[progress.file] = progress; - let total = 0; - let loaded = 0; - for (let key in progressFiles) { - let file = progressFiles[key]; - total += file.total; - loaded += file.loaded; - } - if (onProgress) { - onProgress({ fileList:urlArray, total:total, loaded:loaded }); - } - else { - console.log(`Loading ${ Object.keys(progressFiles).length } files: ${ loaded / total * 100}% completed`); - } - } - - let resources = []; - urlArray.forEach(function(url) { - resources.push(Resource.Load(url,progressFunc)); - }); - - let resolvingPromises = resources.map(function(promise) { - return new Promise(function(resolve) { - let payload = new Array(2); - promise.then(function(result) { - payload[0] = result; - }) - .catch(function(error) { - payload[1] = error; - }) - .then(function() { - resolve(payload); - }); - }); - }); - - let errors = []; - let results = []; - - return Promise.all(resolvingPromises) - .then(function(loadedData) { - let result = {}; - urlArray.forEach(function(url,index) { - let pl = loadedData[index]; - result[url] = pl[1] ? null : pl[0]; - }); - return result; - }); - } - - static Load(url,onProgress) { - let loader = null; - switch (true) { - case url.constructor===Array: - loader = Resource.LoadMultiple; - break; - case Resource.IsImage(url): - loader = Resource.LoadImage; - break; - case Resource.IsBinary(url): - loader = Resource.LoadBinary; - break; - case Resource.IsVideo(url): - loader = Resource.LoadVideo; - break; - case Resource.GetExtension(url)=='json': - loader = Resource.LoadJson; - break; - default: - loader = Resource.LoadText; - } - return loader(url,onProgress); - } - - static LoadText(url,onProgress) { - return new Promise(function(resolve,reject) { - g_resourceProvider.getRequest(url, - function(req) { - resolve(req.responseText); - }, - function(error) { - reject(error); - },onProgress).send(); - }); - } - - static LoadVideo(url,onProgress) { - return new Promise(function(resolve,reject) { - g_resourceProvider.loadVideo( - url, - (target) => { - resolve(target); - bg.emitImageLoadEvent(target); - }, - (err) => { - reject(err); - } - ); - }); - } - - static LoadBinary(url,onProgress) { - return new Promise(function(resolve,reject) { - var req = g_resourceProvider.getRequest(url, - function(req) { - resolve(req.response); - }, - function(error) { - reject(error); - },onProgress); - req.responseType = "arraybuffer"; - req.send(); - }); - } - - static LoadImage(url) { - return new Promise(function(resolve,reject) { - g_resourceProvider.loadImage( - url, - (target) => { - resolve(target); - bg.emitImageLoadEvent(target); - }, - (err) => { - reject(err); - } - ); - }); - } - - static LoadJson(url) { - return new Promise(function(resolve,reject) { - g_resourceProvider.getRequest(url, - function(req) { - try { - resolve(JSON.parse(req.responseText)); - } - catch(e) { - reject(new Error("Error parsing JSON data")); - } - }, - function(error) { - reject(error); - }).send(); - }); - } - } - - bg.utils.Resource = Resource; - - bg.utils.requireGlobal = function(src) { - let s = document.createElement('script'); - s.src = src; - s.type = "text/javascript"; - s.async = false; - document.getElementsByTagName('head')[0].appendChild(s); - } - -})(); -(function() { - let s_Engine = null; - - class Engine { - static Set(engine) { - s_Engine = engine; - } - - static Get() { - return s_Engine; - } - - get id() { return this._engineId; } - - get texture() { return this._texture; } - get pipeline() { return this._pipeline; } - get polyList() { return this._polyList; } - get shader() { return this._shader; } - get colorBuffer() { return this._colorBuffer; } - get textureBuffer() { return this._textureBuffer; } - get shaderSource() { return this._shaderSource; } - } - - bg.Engine = Engine; -})(); -(function() { - - class LifeCycle { - init() {} - frame(delta) {} - - displayGizmo(pipeline,matrixState) {} - - ////// Direct rendering methods: will be deprecated soon - willDisplay(pipeline,matrixState) {} - display(pipeline,matrixState,forceDraw=false) {} - didDisplay(pipeline,matrixState) {} - ////// End direct rendering methods - - ////// Render queue methods - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) {} - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) {} - didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) {} - ////// End render queue methods - - reshape(pipeline,matrixState,width,height) {} - keyDown(evt) {} - keyUp(evt) {} - mouseUp(evt) {} - mouseDown(evt) {} - mouseMove(evt) {} - mouseOut(evt) {} - mouseDrag(evt) {} - mouseWheel(evt) {} - touchStart(evt) {} - touchMove(evt) {} - touchEnd(evt) {} - - // Utility functions: do not override - // 4 frames to ensure that the reflections are fully updated - postRedisplay(frames=4) { - bg.app.MainLoop.singleton.postRedisplay(frames); - } - - postReshape() { - bg.app.MainLoop.singleton.postReshape(); - } - } - - bg.LifeCycle = LifeCycle; - -})(); -// https://github.com/xibre/FastMD5 -(function() { - !function(r){function n(r){for(var n="",t="",o=0,e=0,a=0,i=r.length;i>a;a++){var f=r.charCodeAt(a);128>f?e++:(t=2048>f?String.fromCharCode(f>>6|192,63&f|128):String.fromCharCode(f>>12|224,f>>6&63|128,63&f|128),e>o&&(n+=r.slice(o,e)),n+=t,o=e=a+1)}return e>o&&(n+=r.slice(o,i)),n}function t(r){var n,t;if(r+="",s=!1,v=w=r.length,w>63){for(o(r.substring(0,64)),i(A),s=!0,n=128;w>=n;n+=64)o(r.substring(n-64,n)),f(A);r=r.substring(n-64),w=r.length}for(d[0]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,n=0;w>n;n++)t=3&n,0===t?d[n>>2]=r.charCodeAt(n):d[n>>2]|=r.charCodeAt(n)<>2]|=h[3&n],n>55?(s?f(d):(i(d),s=!0),f([0,0,0,0,0,0,0,0,0,0,0,0,0,0,v<<3,0])):(d[14]=v<<3,void(s?f(d):i(d)))}function o(r){for(var n=16;n--;){var t=n<<2;A[n]=r.charCodeAt(t)+(r.charCodeAt(t+1)<<8)+(r.charCodeAt(t+2)<<16)+(r.charCodeAt(t+3)<<24)}}function e(r,o,e){t(o?r:n(r));var a=g[0];return u[1]=l[15&a],u[0]=l[15&(a>>=4)],u[3]=l[15&(a>>=4)],u[2]=l[15&(a>>=4)],u[5]=l[15&(a>>=4)],u[4]=l[15&(a>>=4)],u[7]=l[15&(a>>=4)],u[6]=l[15&(a>>=4)],a=g[1],u[9]=l[15&a],u[8]=l[15&(a>>=4)],u[11]=l[15&(a>>=4)],u[10]=l[15&(a>>=4)],u[13]=l[15&(a>>=4)],u[12]=l[15&(a>>=4)],u[15]=l[15&(a>>=4)],u[14]=l[15&(a>>=4)],a=g[2],u[17]=l[15&a],u[16]=l[15&(a>>=4)],u[19]=l[15&(a>>=4)],u[18]=l[15&(a>>=4)],u[21]=l[15&(a>>=4)],u[20]=l[15&(a>>=4)],u[23]=l[15&(a>>=4)],u[22]=l[15&(a>>=4)],a=g[3],u[25]=l[15&a],u[24]=l[15&(a>>=4)],u[27]=l[15&(a>>=4)],u[26]=l[15&(a>>=4)],u[29]=l[15&(a>>=4)],u[28]=l[15&(a>>=4)],u[31]=l[15&(a>>=4)],u[30]=l[15&(a>>=4)],e?u:u.join("")}function a(r,n,t,o,e,a,i){return n+=r+o+i,(n<>>a)+t<<0}function i(r){c(0,0,0,0,r),g[0]=y[0]+1732584193<<0,g[1]=y[1]-271733879<<0,g[2]=y[2]-1732584194<<0,g[3]=y[3]+271733878<<0}function f(r){c(g[0],g[1],g[2],g[3],r),g[0]=y[0]+g[0]<<0,g[1]=y[1]+g[1]<<0,g[2]=y[2]+g[2]<<0,g[3]=y[3]+g[3]<<0}function c(r,n,t,o,e){var i,f;s?(r=a((t^o)&n^o,r,n,e[0],7,25,-680876936),o=a((n^t)&r^t,o,r,e[1],12,20,-389564586),t=a((r^n)&o^n,t,o,e[2],17,15,606105819),n=a((o^r)&t^r,n,t,e[3],22,10,-1044525330)):(r=e[0]-680876937,r=(r<<7|r>>>25)-271733879<<0,o=e[1]-117830708+(2004318071&r^-1732584194),o=(o<<12|o>>>20)+r<<0,t=e[2]-1126478375+((-271733879^r)&o^-271733879),t=(t<<17|t>>>15)+o<<0,n=e[3]-1316259209+((o^r)&t^r),n=(n<<22|n>>>10)+t<<0),r=a((t^o)&n^o,r,n,e[4],7,25,-176418897),o=a((n^t)&r^t,o,r,e[5],12,20,1200080426),t=a((r^n)&o^n,t,o,e[6],17,15,-1473231341),n=a((o^r)&t^r,n,t,e[7],22,10,-45705983),r=a((t^o)&n^o,r,n,e[8],7,25,1770035416),o=a((n^t)&r^t,o,r,e[9],12,20,-1958414417),t=a((r^n)&o^n,t,o,e[10],17,15,-42063),n=a((o^r)&t^r,n,t,e[11],22,10,-1990404162),r=a((t^o)&n^o,r,n,e[12],7,25,1804603682),o=a((n^t)&r^t,o,r,e[13],12,20,-40341101),t=a((r^n)&o^n,t,o,e[14],17,15,-1502002290),n=a((o^r)&t^r,n,t,e[15],22,10,1236535329),r=a((n^t)&o^t,r,n,e[1],5,27,-165796510),o=a((r^n)&t^n,o,r,e[6],9,23,-1069501632),t=a((o^r)&n^r,t,o,e[11],14,18,643717713),n=a((t^o)&r^o,n,t,e[0],20,12,-373897302),r=a((n^t)&o^t,r,n,e[5],5,27,-701558691),o=a((r^n)&t^n,o,r,e[10],9,23,38016083),t=a((o^r)&n^r,t,o,e[15],14,18,-660478335),n=a((t^o)&r^o,n,t,e[4],20,12,-405537848),r=a((n^t)&o^t,r,n,e[9],5,27,568446438),o=a((r^n)&t^n,o,r,e[14],9,23,-1019803690),t=a((o^r)&n^r,t,o,e[3],14,18,-187363961),n=a((t^o)&r^o,n,t,e[8],20,12,1163531501),r=a((n^t)&o^t,r,n,e[13],5,27,-1444681467),o=a((r^n)&t^n,o,r,e[2],9,23,-51403784),t=a((o^r)&n^r,t,o,e[7],14,18,1735328473),n=a((t^o)&r^o,n,t,e[12],20,12,-1926607734),i=n^t,r=a(i^o,r,n,e[5],4,28,-378558),o=a(i^r,o,r,e[8],11,21,-2022574463),f=o^r,t=a(f^n,t,o,e[11],16,16,1839030562),n=a(f^t,n,t,e[14],23,9,-35309556),i=n^t,r=a(i^o,r,n,e[1],4,28,-1530992060),o=a(i^r,o,r,e[4],11,21,1272893353),f=o^r,t=a(f^n,t,o,e[7],16,16,-155497632),n=a(f^t,n,t,e[10],23,9,-1094730640),i=n^t,r=a(i^o,r,n,e[13],4,28,681279174),o=a(i^r,o,r,e[0],11,21,-358537222),f=o^r,t=a(f^n,t,o,e[3],16,16,-722521979),n=a(f^t,n,t,e[6],23,9,76029189),i=n^t,r=a(i^o,r,n,e[9],4,28,-640364487),o=a(i^r,o,r,e[12],11,21,-421815835),f=o^r,t=a(f^n,t,o,e[15],16,16,530742520),n=a(f^t,n,t,e[2],23,9,-995338651),r=a(t^(n|~o),r,n,e[0],6,26,-198630844),o=a(n^(r|~t),o,r,e[7],10,22,1126891415),t=a(r^(o|~n),t,o,e[14],15,17,-1416354905),n=a(o^(t|~r),n,t,e[5],21,11,-57434055),r=a(t^(n|~o),r,n,e[12],6,26,1700485571),o=a(n^(r|~t),o,r,e[3],10,22,-1894986606),t=a(r^(o|~n),t,o,e[10],15,17,-1051523),n=a(o^(t|~r),n,t,e[1],21,11,-2054922799),r=a(t^(n|~o),r,n,e[8],6,26,1873313359),o=a(n^(r|~t),o,r,e[15],10,22,-30611744),t=a(r^(o|~n),t,o,e[6],15,17,-1560198380),n=a(o^(t|~r),n,t,e[13],21,11,1309151649),r=a(t^(n|~o),r,n,e[4],6,26,-145523070),o=a(n^(r|~t),o,r,e[11],10,22,-1120210379),t=a(r^(o|~n),t,o,e[2],15,17,718787259),n=a(o^(t|~r),n,t,e[9],21,11,-343485551),y[0]=r,y[1]=n,y[2]=t,y[3]=o}var u=[],d=[],A=[],h=[],l="0123456789abcdef".split(""),C=[],g=[],s=!1,v=0,w=0,y=[];if(r.Int32Array)d=new Int32Array(16),A=new Int32Array(16),h=new Int32Array(4),C=new Int32Array(4),g=new Int32Array(4),y=new Int32Array(4);else{var I;for(I=0;16>I;I++)d[I]=A[I]=0;for(I=0;4>I;I++)h[I]=C[I]=g[I]=y[I]=0}h[0]=128,h[1]=32768,h[2]=8388608,h[3]=-2147483648,C[0]=0,C[1]=8,C[2]=16,C[3]=24,r.md5=r.md5||e}("undefined"==typeof global?window:global); - - bg.utils.md5 = md5; -})(); - -(function() { - function generateUUID () { // Public Domain/MIT - var d = new Date().getTime(); - if (typeof performance !== 'undefined' && typeof performance.now === 'function'){ - d += performance.now(); //use high-precision timer if available - } - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = (d + Math.random() * 16) % 16 | 0; - d = Math.floor(d / 16); - return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); - }); - } - - bg.utils.generateUUID = generateUUID; -})(); -bg.app = {}; -(function() { - - class Canvas { - constructor(domElem) { - let initContext = () => { - this._context = bg.utils.initWebGLContext(domElem); - return this._context.supported; - } - - - // Attributes - this._domElem = domElem; - this._domElem.style.MozUserSelect = 'none'; - this._domElem.style.WebkitUserSelect = 'none'; - this._domElem.setAttribute("onselectstart","return false"); - - this._multisample = 1.0; - - // Initialization - if (!initContext()) { - throw new Error("Sorry, your browser does not support WebGL."); - } - } - - get multisample() { - return this._multisample; - } - - set multisample(ms) { - this._multisample = ms; - } - - get context() { - return this._context; - } - - get domElement() { - return this._domElem; - } - - get width() { - return this._domElem.clientWidth; - } - - get height() { - return this._domElem.clientHeight; - } - - screenshot(format, width, height) { - let canvasStyle = ""; - let prevSize = {} - if (width) { - height = height ? height:width; - canvasStyle = this.domElement.style.cssText; - prevSize.width = this.domElement.width; - prevSize.height = this.domElement.height; - - this.domElement.style.cssText = "top:auto;left:auto;bottom:auto;right:auto;width:" + width + "px;height:" + height + "px;"; - this.domElement.width = width; - this.domElement.height = height; - bg.app.MainLoop.singleton.windowController.reshape(width,height); - bg.app.MainLoop.singleton.windowController.postRedisplay(); - bg.app.MainLoop.singleton.windowController.display(); - } - var data = this.domElement.toDataURL(format); - if (width) { - this.domElement.style.cssText = canvasStyle; - this.domElement.width = prevSize.width; - this.domElement.height = prevSize.height; - bg.app.MainLoop.singleton.windowController.reshape(prevSize.width,prevSize.height); - bg.app.MainLoop.singleton.windowController.postRedisplay(); - bg.app.MainLoop.singleton.windowController.display(); - } - return data; - } - - } - - bg.app.Canvas = Canvas; - - class ContextObject { - constructor(context) { - this._context = context; - } - - get context() { return this._context; } - set context(c) { this._context = c; } - } - - bg.app.ContextObject = ContextObject; -})(); -(function() { - bg.app.SpecialKey = { - BACKSPACE: "Backspace", - TAB: "Tab", - ENTER: "Enter", - SHIFT: "Shift", - SHIFT_LEFT: "ShiftLeft", - SHIFT_RIGHT: "ShiftRight", - CTRL: "Control", - CTRL_LEFT: "ControlLeft", - CTRL_LEFT: "ControlRight", - ALT: "Alt", - ALT_LEFT: "AltLeft", - ALT_RIGHT: "AltRight", - PAUSE: "Pause", - CAPS_LOCK: "CapsLock", - ESCAPE: "Escape", - PAGE_UP: "PageUp", - PAGEDOWN: "PageDown", - END: "End", - HOME: "Home", - LEFT_ARROW: "ArrowLeft", - UP_ARROW: "ArrowUp", - RIGHT_ARROW: "ArrowRight", - DOWN_ARROW: "ArrowDown", - INSERT: "Insert", - DELETE: "Delete" - }; - - class EventBase { - constructor() { - this._executeDefault = false; - } - - get executeDefault() { return this._executeDefault; } - set executeDefault(d) { this._executeDefault = d; } - } - bg.app.EventBase = EventBase; - - class KeyboardEvent extends EventBase { - static IsSpecialKey(event) { - return bg.app.SpecialKey[event.code]!=null; - } - - constructor(key,event) { - super(); - this.key = key; - this.event = event; - } - - isSpecialKey() { - return KeyboardEvent.IsSpecialKey(this.event); - } - } - - bg.app.KeyboardEvent = KeyboardEvent; - - bg.app.MouseButton = { - LEFT: 0, - MIDDLE: 1, - RIGHT: 2, - NONE: -1 - }; - - class MouseEvent extends EventBase { - - constructor(button = bg.app.MouseButton.NONE, x=-1, y=-1, delta=0,event=null) { - super(); - - this.button = button; - this.x = x; - this.y = y; - this.delta = delta; - this.event = event; - } - } - - bg.app.MouseEvent = MouseEvent; - - class TouchEvent extends EventBase { - constructor(touches,event) { - super(); - this.touches = touches; - this.event = event; - } - } - - bg.app.TouchEvent = TouchEvent; - -})(); -(function() { - let s_mainLoop = null; - let s_mouseStatus = { - leftButton:false, - middleButton:false, - rightButton:false, - pos: { - x:-1, - y:-1 - } - } - Object.defineProperty(s_mouseStatus, "anyButton", { - get: function() { - return this.leftButton || this.middleButton || this.rightButton; - } - }); - let s_delta = -1; - - class Mouse { - static LeftButton() { return s_mouseStatus.leftButton; } - static MiddleButton() { return s_mouseStatus.middleButton; } - static RightButton() { return s_mouseStatus.rightButton; } - static Position() { return s_mouseStatus.pos; } - } - - bg.app.Mouse = Mouse; - - bg.app.FrameUpdate = { - AUTO: 0, - MANUAL: 1 - }; - - class MainLoop { - constructor() { - this._canvas = null; - this._windowController = null; - this._updateMode = bg.app.FrameUpdate.AUTO; - this._redisplayFrames = 1; - bg.bindImageLoadEvent(() => { - this.postRedisplay(); - }); - } - - get canvas() { return this._canvas; } - set canvas(c) { - this._canvas = new bg.app.Canvas(c); - } - get windowController() { return this._windowController; } - get updateMode() { return this._updateMode; } - set updateMode(m) { - this._updateMode = m; - if (this._updateMode==bg.app.FrameUpdate.AUTO) { - this._redisplayFrames = 1; - } - } - get redisplay() { return this._redisplayFrames>0; } - get mouseButtonStatus() { return s_mouseStatus; } - - run(windowController) { - this._windowController = windowController; - this.postRedisplay(); - this.windowController.init(); - initEvents(); - animationLoop(); - } - - // 4 frames to ensure that the reflections are fully updated - postRedisplay(frames=4) { - this._redisplayFrames = frames; - } - - postReshape() { - onResize(); - } - } - - let lastTime = 0; - function animationLoop(totalTime) { - totalTime = totalTime || 0; - requestAnimFrame(animationLoop); - let elapsed = totalTime - lastTime; - lastTime = totalTime; - onUpdate(elapsed); - } - - function initEvents() { - onResize(); - - window.addEventListener("resize", function(evt) { onResize(); }); - - if (s_mainLoop.canvas) { - let c = s_mainLoop.canvas.domElement; - c.addEventListener("mousedown", function(evt) { - if (!onMouseDown(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mousemove", function(evt) { - if (!onMouseMove(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mouseout", function(evt) { - if (!onMouseOut(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mouseover", function(evt) { - if (!onMouseOver(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mouseup", function(evt) { - if (!onMouseUp(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - - c.addEventListener("touchstart", function(evt) { - if (!onTouchStart(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("touchmove", function(evt) { - if (!onTouchMove(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("touchend", function(evt) { - if (!onTouchEnd(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - - var mouseWheelEvt = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel"; - c.addEventListener(mouseWheelEvt, function(evt) { - if (!onMouseWheel(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - - window.addEventListener("keydown", function(evt) { onKeyDown(evt); }); - window.addEventListener("keyup", function(evt) { onKeyUp(evt); }); - - c.oncontextmenu = function(e) { return false; }; - } - else { - throw new Error("Configuration error in MainLoop: no canvas defined"); - } - } - - function onResize() { - if (s_mainLoop.canvas && s_mainLoop.windowController) { - let multisample = s_mainLoop.canvas.multisample; - s_mainLoop.canvas.domElement.width = s_mainLoop.canvas.width * multisample; - s_mainLoop.canvas.domElement.height = s_mainLoop.canvas.height * multisample; - s_mainLoop.windowController.reshape(s_mainLoop.canvas.width * multisample, s_mainLoop.canvas.height * multisample); - } - } - - function onUpdate(elapsedTime) { - if (s_mainLoop.redisplay) { - //if (s_delta==-1) s_delta = Date.now(); - //s_mainLoop.windowController.frame((Date.now() - s_delta) * 2); - //s_delta = Date.now(); - s_mainLoop.windowController.frame(elapsedTime); - if (s_mainLoop.updateMode==bg.app.FrameUpdate.AUTO) { - s_mainLoop._redisplayFrames = 1; - } - else { - s_mainLoop._redisplayFrames--; - } - s_mainLoop.windowController.display(); - } - } - - function onMouseDown(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - switch (event.button) { - case bg.app.MouseButton.LEFT: - s_mouseStatus.leftButton = true; - break; - case bg.app.MouseButton.MIDDLE: - s_mouseStatus.middleButton = true; - break; - case bg.app.MouseButton.RIGHT: - s_mouseStatus.rightButton = true; - break; - } - - let bgEvent = new bg.app.MouseEvent(event.button,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,event); - s_mainLoop.windowController.mouseDown(bgEvent); - return bgEvent; - } - - function onMouseMove(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - let evt = new bg.app.MouseEvent(bg.app.MouseButton.NONE, - s_mouseStatus.pos.x, - s_mouseStatus.pos.y, - 0, - event); - s_mainLoop.windowController.mouseMove(evt); - if (s_mouseStatus.anyButton) { - s_mainLoop.windowController.mouseDrag(evt); - } - return evt; - } - - function onMouseOut() { - let bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.NONE,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseOut(bgEvt); - if (s_mouseStatus.leftButton) { - s_mouseStatus.leftButton = false; - bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.LEFT,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseUp(bgEvt); - } - if (s_mouseStatus.middleButton) { - s_mouseStatus.middleButton = false; - bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.MIDDLE,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseUp(bgEvt); - } - if (s_mouseStatus.rightButton) { - bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.RIGHT,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseUp(bgEvt); - s_mouseStatus.rightButton = false; - } - return bgEvt; - } - - function onMouseOver(event) { - return onMouseMove(event); - } - - function onMouseUp(event) { - switch (event.button) { - case bg.app.MouseButton.LEFT: - s_mouseStatus.leftButton = false; - break; - case bg.app.MouseButton.MIDDLE: - s_mouseStatus.middleButton = false; - break; - case bg.app.MouseButton.RIGHT: - s_mouseStatus.rightButton = false; - break; - } - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - let bgEvt = new bg.app.MouseEvent(event.button,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,event) - s_mainLoop.windowController.mouseUp(bgEvt); - return bgEvt; - } - - function onMouseWheel(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - let delta = event.wheelDelta ? event.wheelDelta * -1:event.detail * 10; - let bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.NONE,s_mouseStatus.pos.x,s_mouseStatus.pos.y,delta,event) - s_mainLoop.windowController.mouseWheel(bgEvt); - return bgEvt; - } - - function getTouchEvent(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let touches = []; - for (let i=0; i { - source.params.forEach((param) => { - if (param) { - if (param.role=="buffer") { - this._inputVars[param.target] = param.name; - inputAttribs.push(param.name); - } - else if (param.role=="value") { - inputVars.push(param.name); - } - } - }); - - this._shader.addShaderSource(source.type,source.toString()); - }); - this._shader.link(); - if (!this._shader.status) { - bg.log(this._shader.compileError); - if (this._shader.compileErrorSource) { - bg.log("Shader source:"); - bg.log(this._shader.compileErrorSource); - } - bg.log(this._shader.linkError); - } - else { - this._shader.initVars(inputAttribs,inputVars); - } - } - - // This function is used to setup shader variables that are the same for all - // scene object, such as lights or color correction - beginDraw() { - - } - - // This function is called before draw each polyList. The material properties will be - // set in this.material - setupVars() { - // pass the input vars values to this.shader - } - - setActive() { - this.shader.setActive(); - this.beginDraw(); - } - - clearActive() { - this.shader.clearActive(); - } - - bindPolyList(plist) { - var s = this.shader; - if (this.inputVars.vertex) { - s.setInputBuffer(this.inputVars.vertex, plist.vertexBuffer, 3); - } - if (this.inputVars.normal) { - s.setInputBuffer(this.inputVars.normal, plist.normalBuffer, 3); - } - if (this.inputVars.tex0) { - s.setInputBuffer(this.inputVars.tex0, plist.texCoord0Buffer, 2); - } - if (this.inputVars.tex1) { - s.setInputBuffer(this.inputVars.tex1, plist.texCoord1Buffer, 2); - } - if (this.inputVars.tex2) { - s.setInputBuffer(this.inputVars.tex2, plist.texCoord2Buffer, 2); - } - if (this.inputVars.color) { - s.setInputBuffer(this.inputVars.color, plist.colorBuffer, 4); - } - if (this.inputVars.tangent) { - s.setInputBuffer(this.inputVars.tangent, plist.tangentBuffer, 3); - } - this.setupVars(); - } - - unbind() { - var s = this.shader; - if (this.inputVars.vertex) { - s.disableInputBuffer(this.inputVars.vertex); - } - if (this.inputVars.normal) { - s.disableInputBuffer(this.inputVars.normal); - } - if (this.inputVars.tex0) { - s.disableInputBuffer(this.inputVars.tex0); - } - if (this.inputVars.tex1) { - s.disableInputBuffer(this.inputVars.tex1); - } - if (this.inputVars.tex2) { - s.disableInputBuffer(this.inputVars.tex2); - } - if (this.inputVars.color) { - s.disableInputBuffer(this.inputVars.color); - } - if (this.inputVars.tangent) { - s.disableInputBuffer(this.inputVars.tangent); - } - } - } - - bg.base.Effect = Effect; - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class TextureEffect extends Effect { - constructor(context) { - super(context); - - this._frame = new bg.base.PolyList(context); - - this._frame.vertex = [ 1, 1, 0, -1, 1, 0, -1,-1, 0,1,-1, 0 ]; - this._frame.texCoord0 = [ 1, 1, 0, 1, 0, 0, 1, 0 ]; - this._frame.index = [ 0, 1, 2, 2, 3, 0 ]; - - this._frame.build(); - - this.rebuildShaders(); - } - - rebuildShaders() { - this.setupShaderSource([ - this.vertexShaderSource, - this.fragmentShaderSource - ]); - } - - get vertexShaderSource() { - if (!this._vertexShaderSource) { - this._vertexShaderSource = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - this._vertexShaderSource.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - this._vertexShaderSource.setMainBody(` - gl_Position = vec4(inVertex,1.0); - fsTexCoord = inTex0;`); - } - } - return this._vertexShaderSource; - } - - get fragmentShaderSource() { - if (!this._fragmentShaderSource) { - this._fragmentShaderSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - this._fragmentShaderSource.addParameter( - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ); - - if (bg.Engine.Get().id=="webgl1") { - this._fragmentShaderSource.setMainBody(` - gl_FragColor = vec4(1.0,0.0,0.0,1.0);`); - } - } - return this._fragmentShaderSource; - } - - //setupVars() { - // this._surface contains the surface passed to drawSurface - //} - - drawSurface(surface) { - this.setActive(); - this._surface = surface; - this.bindPolyList(this._frame); - this._frame.draw(); - this.unbind(); - this.clearActive(); - } - - } - - bg.base.TextureEffect = TextureEffect; - -})(); -(function() { - - class LoaderPlugin { - - acceptType(url,data) { return false; } - load(context,url,data) { - return new Promise((resolve,reject) => { - reject(new Error("Not implemented")); - }); - } - - } - - bg.base.LoaderPlugin = LoaderPlugin; - - let s_loaderPlugins = []; - - function loadUrl(context,url,onProgress = null,extraData = null) { - return new Promise((accept,reject) => { - bg.utils.Resource.Load(url,onProgress) - .then(function(data) { - return Loader.LoadData(context,url,data,extraData); - }) - - .then((result,extendedData) => { - accept(result,extendedData); - }) - - .catch(function(err) { - reject(err); - }); - }); - } - - function loadUrlArray(context,url,onProgress = null,extraData = null) { - return new Promise((accept,reject) => { - bg.utils.Resource.LoadMultiple(url,onProgress) - .then((result) => { - let promises = []; - - for (let itemUrl in result) { - let data = result[itemUrl]; - promises.push(loadData(context,itemUrl,data,extraData)); - } - - return Promise.all(promises); - }) - .then((loadedResults) => { - let resolvedData = {} - url.forEach((itemUrl,index) => { - resolvedData[itemUrl] = loadedResults[index]; - }) - accept(resolvedData); - }) - .catch((err) => { - reject(err); - }) - }) - } - - function loadData(context,url,data,extraData = null) { - return new Promise((accept,reject) => { - let selectedPlugin = null; - s_loaderPlugins.some((plugin) => { - if (plugin.acceptType(url,data)) { - selectedPlugin = plugin; - return true; - } - }) - - if (selectedPlugin) { - if (!extraData) { - extraData = {}; - } - accept(selectedPlugin.load(context,url,data,extraData)); - } - else { - return reject(new Error("No suitable plugin found for load " + url)); - } - }); - } - - class Loader { - static RegisterPlugin(p) { s_loaderPlugins.push(p); } - - static Load(context,url,onProgress = null,extraData = null) { - if (Array.isArray(url)) { - return loadUrlArray(context,url,onProgress,extraData); - } - else { - return loadUrl(context,url,onProgress,extraData); - } - } - - static LoadData(context,url,data,extraData = null) { - return loadData(context,url,data,extraData); - } - } - - bg.base.Loader = Loader; - -})(); -(function() { - // NOTE: All the writer functions and classes are intended to be used - // only in an Electron.js application - if (!bg.isElectronApp) { - return false; - } - - class WriterPlugin { - acceptType(url,data) { return false; } - write(url,data) {} - } - - bg.base.WriterPlugin = WriterPlugin; - - let s_writerPlugins = []; - - class Writer { - static RegisterPlugin(p) { s_writerPlugins.push(p); } - - static Write(url,data) { - return new Promise((resolve,reject) => { - let selectedPlugin = null; - s_writerPlugins.some((plugin) => { - if (plugin.acceptType(url,data)) { - selectedPlugin = plugin; - return true; - } - }); - - if (selectedPlugin) { - resolve(selectedPlugin.write(url,data)); - } - else { - reject(new Error("No suitable plugin found for write " + url)); - } - }) - } - - static PrepareDirectory(dir) { - let targetDir = Writer.ToSystemPath(dir); - const fs = require('fs'); - const path = require('path'); - const sep = path.sep; - const initDir = path.isAbsolute(targetDir) ? sep : ''; - targetDir.split(sep).reduce((parentDir,childDir) => { - const curDir = path.resolve(parentDir, childDir); - if (!fs.existsSync(curDir)) { - fs.mkdirSync(curDir); - } - return curDir; - }, initDir); - } - - static StandarizePath(inPath) { - return inPath.replace(/\\/g,'/'); - } - - static ToSystemPath(inPath) { - const path = require('path'); - const sep = path.sep; - return inPath.replace(/\\/g,sep).replace(/\//g,sep); - } - - static CopyFile(source,target) { - return new Promise((resolve,reject) => { - const fs = require("fs"); - const path = require("path"); - let cbCalled = false; - - source = Writer.StandarizePath(path.resolve(source)); - target = Writer.StandarizePath(path.resolve(target)); - - if (source==target) { - resolve(); - } - else { - let rd = fs.createReadStream(source); - rd.on("error", function(err) { - done(err); - }); - let wr = fs.createWriteStream(target); - wr.on("error", function(err) { - done(err); - }); - wr.on("close", function(ex) { - done(); - }); - rd.pipe(wr); - - function done(err) { - if (!cbCalled) { - err ? reject(err) : resolve(); - cbCalled = true; - } - } - } - }) - } - } - - bg.base.Writer = Writer; -})(); -(function() { - // NOTE: this plugin is intended to be used only in an Electron.js app - if (!bg.isElectronApp) { - return false; - } - - let fs = require('fs'); - let path = require('path'); - - function writeTexture(texture,fileData) { - if (texture) { - let dstPath = bg.base.Writer.StandarizePath(fileData.path).split("/"); - dstPath.pop(); - let paths = { - src: bg.base.Writer.StandarizePath(texture.fileName), - dst: null - }; - - let srcFileName = paths.src.split("/").pop(); - dstPath.push(srcFileName); - dstPath = dstPath.join("/"); - paths.dst = dstPath; - - if (paths.src!=paths.dst) { - fileData.copyFiles.push(paths); - } - return srcFileName; - } - else { - return ""; - } - } - function getMaterialString(fileData) { - let mat = []; - fileData.node.drawable.forEach((plist,material) => { - mat.push({ - "name": plist.name, - "class": "GenericMaterial", - - "diffuseR": material.diffuse.r, - "diffuseG": material.diffuse.g, - "diffuseB": material.diffuse.b, - "diffuseA": material.diffuse.a, - - "specularR": material.specular.r, - "specularG": material.specular.g, - "specularB": material.specular.b, - "specularA": material.specular.a, - - "shininess": material.shininess, - "refractionAmount": material.refractionAmount, - "reflectionAmount": material.reflectionAmount, - "lightEmission": material.lightEmission, - - "textureOffsetX": material.textureOffset.x, - "textureOffsetY": material.textureOffset.y, - "textureScaleX": material.textureScale.x, - "textureScaleY": material.textureScale.y, - - "lightmapOffsetX": material.lightmapOffset.x, - "lightmapOffsetY": material.lightmapOffset.y, - "lightmapScaleX": material.lightmapScale.x, - "lightmapScaleY": material.lightmapScale.y, - - "normalMapOffsetX": material.normalMapOffset.x, - "normalMapOffsetY": material.normalMapOffset.y, - "normalMapScaleX": material.normalMapScale.x, - "normalMapScaleY": material.normalMapScale.y, - - "castShadows": material.castShadows, - "receiveShadows": material.receiveShadows, - - "alphaCutoff": material.alphaCutoff, - - "shininessMaskChannel": material.shininessMaskChannel, - "invertShininessMask": material.shininessMaskInvert, - "lightEmissionMaskChannel": material.lightEmissionMaskChannel, - "invertLightEmissionMask": material.lightEmissionMaskInvert, - - "displacementFactor": 0, - "displacementUV": 0, - "tessDistanceFarthest": 40.0, - "tessDistanceFar": 30.0, - "tessDistanceNear": 15.0, - "tessDistanceNearest": 8.0, - "tessFarthestLevel": 1, - "tessFarLevel": 1, - "tessNearLevel": 1, - "tessNearestLevel": 1, - - "reflectionMaskChannel": material.reflectionMaskChannel, - "invertReflectionMask": material.reflectionMaskInvert, - - "roughness": material.roughness, - "roughnessMaskChannel": material.roughnessMaskChannel, - "invertRoughnessMask": material.roughnessMaskInvert, - - "cullFace": material.cullFace, - - "unlit": material.unlit, - - "texture": writeTexture(material.texture,fileData), - "lightmap": writeTexture(material.lightmap,fileData), - "normalMap": writeTexture(material.normalMap,fileData), - "shininessMask": writeTexture(material.shininessMask,fileData), - "lightEmissionMask": writeTexture(material.lightEmissionMask,fileData), - "displacementMap": "", - "reflectionMask": writeTexture(material.reflectionMask,fileData), - "roughnessMask": writeTexture(material.roughnessMask,fileData), - "visible": plist.visible, - "visibleToShadows": plist.visibleToShadows, - "groupName": plist.groupName - }); - }); - return JSON.stringify(mat); - } - - function getJointString(fileData) { - let joints = {}; - let inJoint = fileData.node.component("bg.scene.InputChainJoint"); - let outJoint = fileData.node.component("bg.scene.OutputChainJoint"); - if (inJoint) { - joints.input = { - "type":"LinkJoint", - "offset":[ - inJoint.joint.offset.x, - inJoint.joint.offset.y, - inJoint.joint.offset.z - ], - "pitch": inJoint.joint.pitch, - "roll": inJoint.joint.roll, - "yaw": inJoint.joint.yaw - }; - } - if (outJoint) { - joints.output = [{ - "type":"LinkJoint", - "offset":[ - outJoint.joint.offset.x, - outJoint.joint.offset.y, - outJoint.joint.offset.z - ], - "pitch": outJoint.joint.pitch, - "roll": outJoint.joint.roll, - "yaw": outJoint.joint.yaw - }]; - } - return JSON.stringify(joints); - } - - function ensurePolyListName(fileData) { - let plistNames = []; - let plIndex = 0; - fileData.node.drawable.forEach((plist,matName) => { - let plName = plist.name; - if (!plName || plistNames.indexOf(plName)!=-1) { - do { - plName = "polyList_" + plIndex; - ++plIndex; - } - while (plistNames.indexOf(plName)!=-1); - plist.name = plName; - } - plistNames.push(plName); - }); - } - - class FileData { - constructor(path,node) { - this._path = path; - this._node = node; - this._copyFiles = []; - this._stream = fs.createWriteStream(path); - } - - get path() { return this._path; } - get node() { return this._node; } - get copyFiles() { return this._copyFiles; } - - get stream() { return this._stream; } - - writeUInt(number) { - let buffer = Buffer.alloc(4); - buffer.writeUInt32BE(number,0); - this.stream.write(buffer); - } - - writeBlock(blockName) { - this.stream.write(Buffer.from(blockName,"utf-8")); - } - - writeString(stringData) { - this.writeUInt(stringData.length); - this.stream.write(Buffer.from(stringData,"utf-8")); - } - - writeBuffer(name,arrayBuffer) { - this.writeBlock(name); - this.writeUInt(arrayBuffer.length); - let buffer = Buffer.alloc(4 * arrayBuffer.length); - if (name=="indx") { - arrayBuffer.forEach((d,i) => buffer.writeUInt32BE(d,i * 4)); - } - else { - arrayBuffer.forEach((d,i) => buffer.writeFloatBE(d,i * 4)); - } - this.stream.write(buffer); - } - - writeTextures() { - let promises = []; - this.copyFiles.forEach((copyData) => { - promises.push(new Promise((resolve,reject) => { - let rd = fs.createReadStream(copyData.src); - rd.on('error',rejectCleanup); - let wr = fs.createWriteStream(copyData.dst); - wr.on('error',rejectCleanup); - function rejectCleanup(err) { - rd.destroy(); - wr.end(); - reject(err); - } - wr.on('finish',resolve); - rd.pipe(wr); - })) - }); - return Promise.all(promises); - } - } - - function writeHeader(fileData) { - let buffer = Buffer.alloc(4); - [ - 0, // big endian - 1, // major version - 2, // minor version - 0 // review - ].forEach((d,i) => buffer.writeInt8(d,i)); - fileData.stream.write(buffer); - - // Header - fileData.writeBlock("hedr"); - - // Ensure that all poly list have name and material name - ensurePolyListName(fileData); - - // Number of polyLists - let drw = fileData.node.drawable; - let plistItems = 0; - drw.forEach(() => plistItems++); - fileData.writeUInt(plistItems); - - // Material header - fileData.writeBlock("mtrl"); - fileData.writeString(getMaterialString(fileData)); - - // Joints header - fileData.writeBlock("join"); - fileData.writeString(getJointString(fileData)); - } - - function writePolyList(fileData,plist,material,trx) { - //let buffer = Buffer.alloc(4); - //fileData.stream.write(Buffer.from("plst","utf-8")); // poly list - fileData.writeBlock("plst"); - - // Poly list name - fileData.writeBlock("pnam"); - fileData.writeString(plist.name); - - // Material name, the same as plist name in version 1.2.0 - fileData.writeBlock("mnam"); - fileData.writeString(plist.name); - - fileData.writeBuffer("varr",plist.vertex); - fileData.writeBuffer("narr",plist.normal); - fileData.writeBuffer("t0ar",plist.texCoord0); - fileData.writeBuffer("t1ar",plist.texCoord1); - fileData.writeBuffer("indx",plist.index); - } - - function writeNode(fileData) { - writeHeader(fileData); - fileData.node.drawable.forEach((plist,mat,trx) => { - writePolyList(fileData,plist,mat,trx); - }); - fileData.writeBlock("endf"); - fileData.stream.end(); - } - - class Bg2WriterPlugin extends bg.base.WriterPlugin { - acceptType(url,data) { - let ext = url.split(".").pop(); - return /bg2/i.test(ext) || /vwglb/i.test(ext); - } - - write(url,data) { - return new Promise((resolve,reject) => { - if (!data || !data instanceof bg.scene.Node || !data.drawable) { - reject(new Error("Invalid data format. Expecting scene node.")); - } - let fileData = new FileData(url,data); - - try { - writeNode(fileData); - fileData.writeTextures() - .then(() => resolve()) - .catch((err) => reject(err)); - } - catch (err) { - reject(err); - } - }) - } - } - - bg.base.Bg2WriterPlugin = Bg2WriterPlugin; -})(); -(function() { - - class Bg2matLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - return bg.utils.Resource.GetExtension(url)=="bg2mat"; - } - - load(context,url,data) { - return new Promise((resolve,reject) => { - if (data) { - try { - if (typeof(data)=="string") { - data = JSON.parse(data); - } - let promises = []; - let basePath = url.substring(0,url.lastIndexOf('/')+1); - - data.forEach((matData) => { - promises.push(bg.base.Material.FromMaterialDefinition(context,matData,basePath)); - }); - - Promise.all(promises) - .then((result) => { - resolve(result); - }); - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading material. Data is null.")); - } - }); - } - } - - bg.base.Bg2matLoaderPlugin = Bg2matLoaderPlugin; - -})(); -(function() { - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class DrawTextureEffect extends bg.base.TextureEffect { - constructor(context) { - super(context); - - let vertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - let fragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - vertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - fragment.addParameter([ - lib().inputs.material.texture, - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - vertex.setMainBody(` - gl_Position = vec4(inVertex,1.0); - fsTexCoord = inTex0;`); - fragment.setMainBody("gl_FragColor = texture2D(inTexture,fsTexCoord);"); - } - - this.setupShaderSource([ - vertex, - fragment - ]); - } - - setupVars() { - let texture = null; - if (this._surface instanceof bg.base.Texture) { - texture = this._surface; - } - else if (this._surface instanceof bg.base.RenderSurface) { - texture = this._surface.getTexture(0); - } - - if (texture) { - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - } - } - } - - bg.base.DrawTextureEffect = DrawTextureEffect; -})(); -(function() { - let shaders = {}; - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - let s_vertexSource = null; - let s_fragmentSource = null; - - function vertexShaderSource() { - if (!s_vertexSource) { - s_vertexSource = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_vertexSource.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.normal, - lib().inputs.buffers.tangent, - lib().inputs.buffers.tex0, - lib().inputs.buffers.tex1 - ]); - - s_vertexSource.addParameter(lib().inputs.matrix.all); - - s_vertexSource.addParameter([ - { name:"inLightProjectionMatrix", dataType:"mat4", role:"value" }, - { name:"inLightViewMatrix", dataType:"mat4", role:"value" }, - ]); - - s_vertexSource.addParameter([ - { name:"fsPosition", dataType:"vec3", role:"out" }, - { name:"fsTex0Coord", dataType:"vec2", role:"out" }, - { name:"fsTex1Coord", dataType:"vec2", role:"out" }, - { name:"fsNormal", dataType:"vec3", role:"out" }, - { name:"fsTangent", dataType:"vec3", role:"out" }, - { name:"fsBitangent", dataType:"vec3", role:"out" }, - { name:"fsSurfaceToView", dataType:"vec3", role:"out" }, - - { name:"fsVertexPosFromLight", dataType:"vec4", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_vertexSource.setMainBody(` - mat4 ScaleMatrix = mat4(0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0); - - vec4 viewPos = inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - gl_Position = inProjectionMatrix * viewPos; - - fsNormal = normalize((inNormalMatrix * vec4(inNormal,1.0)).xyz); - fsTangent = normalize((inNormalMatrix * vec4(inTangent,1.0)).xyz); - fsBitangent = cross(fsNormal,fsTangent); - - fsVertexPosFromLight = ScaleMatrix * inLightProjectionMatrix * inLightViewMatrix * inModelMatrix * vec4(inVertex,1.0); - - fsTex0Coord = inTex0; - fsTex1Coord = inTex1; - fsPosition = viewPos.xyz;`); - } - } - return s_vertexSource; - } - - function fragmentShaderSource() { - if (!s_fragmentSource) { - s_fragmentSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - s_fragmentSource.addParameter(lib().inputs.material.all); - s_fragmentSource.addParameter(lib().inputs.lightingForward.all); - s_fragmentSource.addParameter(lib().inputs.shadows.all); - s_fragmentSource.addParameter(lib().inputs.colorCorrection.all); - s_fragmentSource.addParameter([ - { name:"fsPosition", dataType:"vec3", role:"in" }, - { name:"fsTex0Coord", dataType:"vec2", role:"in" }, - { name:"fsTex1Coord", dataType:"vec2", role:"in" }, - { name:"fsNormal", dataType:"vec3", role:"in" }, - { name:"fsTangent", dataType:"vec3", role:"in" }, - { name:"fsBitangent", dataType:"vec3", role:"in" }, - { name:"fsSurfaceToView", dataType:"vec3", role:"in" }, - - { name:"fsVertexPosFromLight", dataType:"vec4", role:"in" }, - - { name:"inCubeMap", dataType:"samplerCube", role:"value" }, - { name:"inLightEmissionFactor", dataType:"float", role:"value" } - ]); - - s_fragmentSource.addFunction(lib().functions.materials.all); - s_fragmentSource.addFunction(lib().functions.colorCorrection.all); - s_fragmentSource.addFunction(lib().functions.utils.unpack); - s_fragmentSource.addFunction(lib().functions.utils.random); - s_fragmentSource.addFunction(lib().functions.lighting.all); - s_fragmentSource.addFunction(lib().functions.blur.blurCube); - - if (bg.Engine.Get().id=="webgl1") { - s_fragmentSource.setMainBody(` - vec4 diffuseColor = samplerColor(inTexture,fsTex0Coord,inTextureOffset,inTextureScale); - vec4 lightmapColor = samplerColor(inLightMap,fsTex1Coord,inLightMapOffset,inLightMapScale); - - if (inUnlit && diffuseColor.a>=inAlphaCutoff) { - gl_FragColor = diffuseColor * lightmapColor; - } - else if (diffuseColor.a>=inAlphaCutoff) { - vec3 normalMap = samplerNormal(inNormalMap,fsTex0Coord,inNormalMapOffset,inNormalMapScale); - // This doesn't work on many Mac Intel GPUs - // vec3 frontFacingNormal = fsNormal; - // if (!gl_FrontFacing) { - // frontFacingNormal *= -1.0; - // } - normalMap = combineNormalWithMap(fsNormal,fsTangent,fsBitangent,normalMap); - vec4 shadowColor = vec4(1.0); - if (inReceiveShadows) { - shadowColor = getShadowColor(fsVertexPosFromLight,inShadowMap,inShadowMapSize,inShadowType,inShadowStrength,inShadowBias,inShadowColor); - } - - vec4 specular = specularColor(inSpecularColor,inShininessMask,fsTex0Coord,inTextureOffset,inTextureScale, - inShininessMaskChannel,inShininessMaskInvert); - float lightEmission = applyTextureMask(inLightEmission, - inLightEmissionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inLightEmissionMaskChannel,inLightEmissionMaskInvert); - diffuseColor = diffuseColor * inDiffuseColor * lightmapColor; - - vec4 light = vec4(0.0,0.0,0.0,1.0); - vec4 specularColor = vec4(0.0,0.0,0.0,1.0); - // This doesn't work on A11 and A12 chips on Apple devices. - // for (int i=0; i<${ bg.base.MAX_FORWARD_LIGHTS}; ++i) { - // if (i>=inNumLights) break; - // light.rgb += getLight( - // inLightType[i], - // inLightAmbient[i], inLightDiffuse[i], inLightSpecular[i],inShininess, - // inLightPosition[i],inLightDirection[i], - // inLightAttenuation[i].x,inLightAttenuation[i].y,inLightAttenuation[i].z, - // inSpotCutoff[i],inSpotExponent[i],inLightCutoffDistance[i], - // fsPosition,normalMap, - // diffuseColor,specular,shadowColor, - // specularColor - // ).rgb; - // light.rgb += specularColor.rgb; - // } - - // Workaround for A11 and A12 chips - if (inNumLights>0) { - light.rgb += getLight( - inLightType[0], - inLightAmbient[0], inLightDiffuse[0], inLightSpecular[0],inShininess, - inLightPosition[0],inLightDirection[0], - inLightAttenuation[0].x,inLightAttenuation[0].y,inLightAttenuation[0].z, - inSpotCutoff[0],inSpotExponent[0],inLightCutoffDistance[0], - fsPosition,normalMap, - diffuseColor,specular,shadowColor, - specularColor - ).rgb; - light.rgb += specularColor.rgb; - } - if (inNumLights>1) { - light.rgb += getLight( - inLightType[1], - inLightAmbient[1], inLightDiffuse[1], inLightSpecular[1],inShininess, - inLightPosition[1],inLightDirection[1], - inLightAttenuation[1].x,inLightAttenuation[1].y,inLightAttenuation[1].z, - inSpotCutoff[0],inSpotExponent[1],inLightCutoffDistance[1], - fsPosition,normalMap, - diffuseColor,specular,shadowColor, - specularColor - ).rgb; - light.rgb += specularColor.rgb; - } - - vec3 cameraPos = vec3(0.0); - vec3 cameraVector = fsPosition - cameraPos; - vec3 lookup = reflect(cameraVector,normalMap); - - // Roughness using gaussian blur has been deactivated because it is very inefficient - //float dist = distance(fsPosition,cameraPos); - //float maxRough = 50.0; - //float rough = max(inRoughness * 10.0,1.0); - //rough = max(rough*dist,rough); - //float blur = min(rough,maxRough); - //vec3 cubemapColor = blurCube(inCubeMap,lookup,int(blur),vec2(10),dist).rgb; - - vec3 cubemapColor = textureCube(inCubeMap,lookup).rgb; - - float reflectionAmount = applyTextureMask(inReflection, - inReflectionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inReflectionMaskChannel,inReflectionMaskInvert); - - light.rgb = clamp(light.rgb + (lightEmission * diffuseColor.rgb * 10.0), vec3(0.0), vec3(1.0)); - - - gl_FragColor = vec4(light.rgb * (1.0 - reflectionAmount) + cubemapColor * reflectionAmount * diffuseColor.rgb, diffuseColor.a); - } - else { - discard; - }` - ); - } - } - return s_fragmentSource; - } - - class ColorCorrectionSettings { - constructor() { - this._hue = 1; - this._saturation = 1; - this._lightness = 1; - this._brightness = 0.5; - this._contrast = 0.5; - } - - set hue(h) { this._hue = h; } - get hue() { return this._hue; } - set saturation(s) { this._saturation = s; } - get saturation() { return this._saturation; } - set lightness(l) { this._lightness = l; } - get lightness() { return this._lightness; } - set brightness(b) { this._brightness = b; } - get brightness() { return this._brightness; } - set contrast(c) { this._contrast = c; } - get contrast() { return this._contrast; } - - apply(shader,varNames={ hue:'inHue', - saturation:'inSaturation', - lightness:'inLightness', - brightness:'inBrightness', - contrast:'inContrast' }) - { - shader.setValueFloat(varNames['hue'], this._hue); - shader.setValueFloat(varNames['saturation'], this._saturation); - shader.setValueFloat(varNames['lightness'], this._lightness); - shader.setValueFloat(varNames['brightness'], this._brightness); - shader.setValueFloat(varNames['contrast'], this._contrast); - } - } - - bg.base.ColorCorrectionSettings = ColorCorrectionSettings; - - class ForwardEffect extends bg.base.Effect { - constructor(context) { - super(context); - this._material = null; - this._light = null; - this._lightTransform = bg.Matrix4.Identity(); - - this._lightArray = new bg.base.LightArray(); - - this._shadowMap = null; - - let sources = [ - vertexShaderSource(), - fragmentShaderSource() - ]; - this.setupShaderSource(sources); - this._colorCorrection = new bg.base.ColorCorrectionSettings(); - } - - get material() { return this._material; } - set material(m) { this._material = m; } - - // Individual light mode - get light() { return this._light; } - set light(l) { this._light = l; this._lightArray.reset(); } - get lightTransform() { return this._lightTransform; } - set lightTransform(trx) { this._lightTransform = trx; this._lightArray.reset();} - - // Multiple light mode: use light arrays - get lightArray() { return this._lightArray; } - - set shadowMap(sm) { this._shadowMap = sm; } - get shadowMap() { return this._shadowMap; } - - get colorCorrection() { return this._colorCorrection; } - set colorCorrection(cc) { this._colorCorrection = cc; } - - beginDraw() { - if (this._light) { - // Individual mode: initialize light array - this.lightArray.reset(); - this.lightArray.push(this.light,this.lightTransform); - } - - if (this.lightArray.numLights) { - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - - // Update lights positions and directions using the current view matrix - this.lightArray.updatePositionAndDirection(viewMatrix); - - // Forward render only supports one shadow map - let lightTransform = this.shadowMap ? this.shadowMap.viewMatrix : this.lightArray.shadowLightTransform; - this.shader.setMatrix4("inLightProjectionMatrix", this.shadowMap ? this.shadowMap.projection : this.lightArray.shadowLight.projection); - let shadowColor = this.shadowMap ? this.shadowMap.shadowColor : bg.Color.Transparent(); - - let blackTex = bg.base.TextureCache.BlackTexture(this.context); - this.shader.setMatrix4("inLightViewMatrix",lightTransform); - this.shader.setValueInt("inShadowType",this._shadowMap ? this._shadowMap.shadowType : 0); - this.shader.setTexture("inShadowMap",this._shadowMap ? this._shadowMap.texture : blackTex,bg.base.TextureUnit.TEXTURE_5); - this.shader.setVector2("inShadowMapSize",this._shadowMap ? this._shadowMap.size : new bg.Vector2(32,32)); - this.shader.setValueFloat("inShadowStrength",this.lightArray.shadowLight.shadowStrength); - this.shader.setVector4("inShadowColor",shadowColor); - this.shader.setValueFloat("inShadowBias",this.lightArray.shadowLight.shadowBias); - this.shader.setValueInt("inCastShadows",this.lightArray.shadowLight.castShadows); - - this.shader.setVector4Ptr('inLightAmbient',this.lightArray.ambient); - this.shader.setVector4Ptr('inLightDiffuse',this.lightArray.diffuse); - this.shader.setVector4Ptr('inLightSpecular',this.lightArray.specular); - this.shader.setValueIntPtr('inLightType',this.lightArray.type); - this.shader.setVector3Ptr('inLightAttenuation',this.lightArray.attenuation); - this.shader.setValueFloatPtr('inLightCutoffDistance',this.lightArray.cutoffDistance); - - // TODO: promote this value to a variable - let lightEmissionFactor = 10; - this.shader.setValueFloat('inLightEmissionFactor',lightEmissionFactor); - - this.shader.setTexture('inCubeMap',bg.scene.Cubemap.Current(this.context),bg.base.TextureUnit.TEXTURE_6); - - this.shader.setVector3Ptr('inLightDirection',this.lightArray.direction); - this.shader.setVector3Ptr('inLightPosition',this.lightArray.position); - this.shader.setValueFloatPtr('inSpotCutoff',this.lightArray.spotCutoff); - this.shader.setValueFloatPtr('inSpotExponent',this.lightArray.spotExponent); - - this.shader.setValueInt('inNumLights',this.lightArray.numLights); - } - else { - let BLACK = bg.Color.Black(); - this.shader.setVector4Ptr('inLightAmbient',BLACK.toArray()); - this.shader.setVector4Ptr('inLightDiffuse',BLACK.toArray()); - this.shader.setVector4Ptr('inLightSpecular',BLACK.toArray()); - this.shader.setVector3Ptr('inLightDirection',(new bg.Vector3(0,0,0)).toArray()); - this.shader.setValueInt('inNumLights',0); - } - - this.colorCorrection.apply(this.shader); - } - - setupVars() { - if (this.material) { - // Matrix state - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - this.shader.setMatrix4('inModelMatrix',matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',viewMatrix); - this.shader.setMatrix4('inProjectionMatrix',matrixState.projectionMatrixStack.matrixConst); - this.shader.setMatrix4('inNormalMatrix',matrixState.normalMatrix); - this.shader.setMatrix4('inViewMatrixInv',matrixState.viewMatrixInvert); - - // Material - // Prepare textures - let whiteTex = bg.base.TextureCache.WhiteTexture(this.context); - let blackTex = bg.base.TextureCache.BlackTexture(this.context); - let normalTex = bg.base.TextureCache.NormalTexture(this.context); - let texture = this.material.texture || whiteTex; - let lightMap = this.material.lightmap || whiteTex; - let normalMap = this.material.normalMap || normalTex; - let shininessMask = this.material.shininessMask || whiteTex; - let lightEmissionMask = this.material.lightEmissionMask || whiteTex; - - this.shader.setVector4('inDiffuseColor',this.material.diffuse); - this.shader.setVector4('inSpecularColor',this.material.specular); - this.shader.setValueFloat('inShininess',this.material.shininess); - this.shader.setTexture('inShininessMask',shininessMask,bg.base.TextureUnit.TEXTURE_3); - this.shader.setVector4('inShininessMaskChannel',this.material.shininessMaskChannelVector); - this.shader.setValueInt('inShininessMaskInvert',this.material.shininessMaskInvert); - this.shader.setValueFloat('inLightEmission',this.material.lightEmission); - this.shader.setTexture('inLightEmissionMask',lightEmissionMask,bg.base.TextureUnit.TEXTURE_4); - this.shader.setVector4('inLightEmissionMaskChannel',this.material.lightEmissionMaskChannelVector); - this.shader.setValueInt('inLightEmissionMaskInvert',this.material.lightEmissionMaskInvert); - this.shader.setValueFloat('inAlphaCutoff',this.material.alphaCutoff); - - this.shader.setTexture('inTexture',texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2('inTextureOffset',this.material.textureOffset); - this.shader.setVector2('inTextureScale',this.material.textureScale); - - this.shader.setTexture('inLightMap',lightMap,bg.base.TextureUnit.TEXTURE_1); - this.shader.setVector2('inLightMapOffset',this.material.lightmapOffset); - this.shader.setVector2('inLightMapScale',this.material.lightmapScale); - - this.shader.setTexture('inNormalMap',normalMap,bg.base.TextureUnit.TEXTURE_2); - this.shader.setVector2('inNormalMapScale',this.material.normalMapScale); - this.shader.setVector2('inNormalMapOffset',this.material.normalMapOffset); - - this.shader.setValueInt('inReceiveShadows',this.material.receiveShadows); - - let reflectionMask = this.material.reflectionMask || whiteTex; - this.shader.setValueFloat('inReflection',this.material.reflectionAmount); - this.shader.setTexture('inReflectionMask',reflectionMask,bg.base.TextureUnit.TEXTURE_7); - this.shader.setVector4('inReflectionMaskChannel',this.material.reflectionMaskChannelVector); - this.shader.setValueInt('inReflectionMaskInvert',this.material.reflectionMaskInvert); - - let roughnessMask = this.material.roughnessMask || whiteTex; - this.shader.setValueFloat('inRoughness',this.material.roughness); - if (this.context.getParameter(this.context.MAX_TEXTURE_IMAGE_UNITS)<9) { - this.shader.setTexture('inRoughnessMask',roughnessMask,bg.base.TextureUnit.TEXTURE_7); - } - else { - this.shader.setTexture('inRoughnessMask',roughnessMask,bg.base.TextureUnit.TEXTURE_8); - } - this.shader.setVector4('inRoughnessMaskChannel',this.material.roughnessMaskChannelVector); - this.shader.setValueInt('inRoughnessMaskInvert',this.material.roughnessMaskInvert); - - // Other settings - this.shader.setValueInt('inSelectMode',false); - - this.shader.setValueInt('inUnlit',this.material.unlit); - } - } - - } - - bg.base.ForwardEffect = ForwardEffect; - - // Define the maximum number of lights that can be used in forward render - bg.base.MAX_FORWARD_LIGHTS = 4; - -})(); - -(function() { - - bg.base.LightType = { - DIRECTIONAL: 4, - SPOT: 1, - POINT: 5, - DISABLED: 10 - }; - - class Light extends bg.app.ContextObject { - constructor(context) { - super(context); - - this._enabled = true; - - this._type = bg.base.LightType.DIRECTIONAL; - - this._direction = new bg.Vector3(0,0,-1); - - this._ambient = new bg.Color(0.2,0.2,0.2,1); - this._diffuse = new bg.Color(0.9,0.9,0.9,1); - this._specular = bg.Color.White(); - this._attenuation = new bg.Vector3(1,0.5,0.1); - this._spotCutoff = 20; - this._spotExponent = 30; - this._shadowStrength = 0.7; - this._cutoffDistance = -1; - this._castShadows = true; - this._shadowBias = 0.00002; - - this._projection = bg.Matrix4.Ortho(-10,10,-10,10,0.5,300.0); - } - - // If context is null, it will be used the same context as this light - clone(context) { - let newLight = new bg.base.Light(context || this.context); - newLight.assign(this); - return newLight; - } - - assign(other) { - this.enabled = other.enabled; - this.type = other.type; - this.direction.assign(other.direction); - this.ambient.assign(other.ambient); - this.diffuse.assign(other.diffuse); - this.specular.assign(other.specular); - this._attenuation.assign(other._attenuation); - this.spotCutoff = other.spotCutoff; - this.spotExponent = other.spotExponent; - this.shadowStrength = other.shadowStrength; - this.cutoffDistance = other.cutoffDistance; - this.castShadows = other.castShadows; - this.shadowBias = other.shadowBias; - } - - get enabled() { return this._enabled; } - set enabled(v) { this._enabled = v; } - - get type() { return this._type; } - set type(t) { this._type = t; } - - get direction() { return this._direction; } - set direction(d) { this._direction = d; } - - get ambient() { return this._ambient; } - set ambient(a) { this._ambient = a; } - get diffuse() { return this._diffuse; } - set diffuse(d) { this._diffuse = d; } - get specular() { return this._specular; } - set specular(s) { this._specular = s; } - - get attenuationVector() { return this._attenuation; } - get constantAttenuation() { return this._attenuation.x; } - get linearAttenuation() { return this._attenuation.y; } - get quadraticAttenuation() { return this._attenuation.z; } - set attenuationVector(a) { this._attenuation = a; } - set constantAttenuation(a) { this._attenuation.x = a; } - set linearAttenuation(a) { this._attenuation.y = a; } - set quadraticAttenuation(a) { this._attenuation.z = a; } - - get cutoffDistance() { return this._cutoffDistance; } - set cutoffDistance(c) { this._cutoffDistance = c; } - - get spotCutoff() { return this._spotCutoff; } - set spotCutoff(c) { this._spotCutoff = c; } - get spotExponent() { return this._spotExponent; } - set spotExponent(e) { this._spotExponent = e; } - - get shadowStrength() { return this._shadowStrength; } - set shadowStrength(s) { this._shadowStrength = s; } - get castShadows() { return this._castShadows; } - set castShadows(s) { this._castShadows = s; } - get shadowBias() { return this._shadowBias; } - set shadowBias(s) { this._shadowBias = s; } - - get projection() { return this._projection; } - set projection(p) { this._projection = p; } - - deserialize(sceneData) { - switch (sceneData.lightType) { - case 'kTypeDirectional': - this._type = bg.base.LightType.DIRECTIONAL; - // Use the predefined shadow bias for directional lights - //this._shadowBias = sceneData.shadowBias; - break; - case 'kTypeSpot': - this._type = bg.base.LightType.SPOT; - this._shadowBias = sceneData.shadowBias; - break; - case 'kTypePoint': - this._type = bg.base.LightType.POINT; - break; - } - - this._ambient = new bg.Color(sceneData.ambient); - this._diffuse = new bg.Color(sceneData.diffuse); - this._specular = new bg.Color(sceneData.specular); - this._attenuation = new bg.Vector3( - sceneData.constantAtt, - sceneData.linearAtt, - sceneData.expAtt - ); - this._spotCutoff = sceneData.spotCutoff || 20; - this._spotExponent = sceneData.spotExponent || 30; - this._shadowStrength = sceneData.shadowStrength; - this._cutoffDistance = sceneData.cutoffDistance; - this._projection = new bg.Matrix4(sceneData.projection); - this._castShadows = sceneData.castShadows; - } - - serialize(sceneData) { - let lightTypes = []; - lightTypes[bg.base.LightType.DIRECTIONAL] = "kTypeDirectional"; - lightTypes[bg.base.LightType.SPOT] = "kTypeSpot"; - lightTypes[bg.base.LightType.POINT] = "kTypePoint"; - sceneData.lightType = lightTypes[this._type]; - sceneData.ambient = this._ambient.toArray(); - sceneData.diffuse = this._diffuse.toArray(); - sceneData.specular = this._specular.toArray(); - sceneData.intensity = 1; - sceneData.constantAtt = this._attenuation.x; - sceneData.linearAtt = this._attenuation.y; - sceneData.expAtt = this._attenuation.z; - sceneData.spotCutoff = this._spotCutoff || 20; - sceneData.spotExponent = this._spotExponent || 30; - sceneData.shadowStrength = this._shadowStrength; - sceneData.cutoffDistance = this._cutoffDistance; - sceneData.projection = this._projection.toArray(); - sceneData.castShadows = this._castShadows; - sceneData.shadowBias = this._shadowBias || 0.0029; - } - } - - bg.base.Light = Light; - - // Store a light array, optimized to be used as shader input - class LightArray { - constructor() { - this.reset(); - } - - get type() { return this._type; } - get ambient() { return this._ambient; } - get diffuse() { return this._diffuse; } - get specular() { return this._specular; } - get position() { return this._position; } - get direction() { return this._direction; } - get rawDirection() { return this._rawDirection; } - get attenuation() { return this._attenuation; } - get spotCutoff() { return this._spotCutoff; } - get spotExponent() { return this._spotExponent; } - get shadowStrength() { return this._shadowStrength; } - get cutoffDistance() { return this._cutoffDistance; } - get numLights() { return this._numLights; } - - get lightTransform() { return this._lightTransform; } - - get shadowLight() { return this._shadowLight || { - shadowStrength: 0, - shadowColor: bg.Color.Black(), - shadowBias: 0, - castShadows: false, - projection: bg.Matrix4.Identity() - }} - get shadowLightTransform() { return this._shadowLightTransform || bg.Matrix4.Identity(); } - get shadowLightIndex() { return this._shadowLightIndex; } - - reset() { - this._type = []; - this._ambient = []; - this._diffuse = []; - this._specular = []; - this._position = []; - this._direction = []; - this._rawDirection = []; - this._attenuation = []; - this._spotCutoff = []; - this._spotExponent = []; - this._shadowStrength = []; - this._cutoffDistance = []; - this._numLights = 0; - this._lightTransform = []; - - // Forward render only supports one shadow map, so will only store - // one projection - this._shadowLightTransform = null; - this._shadowLightIndex = -1; - this._shadowLight = null; - } - - push(light,lightTransform) { - if (this._numLights==bg.base.MAX_FORWARD_LIGHTS) { - return false; - } - else { - if (this._shadowLightIndex==-1 && light.type!=bg.base.LightType.POINT && light.castShadows) { - this._shadowLightTransform = lightTransform; - this._shadowLight = light; - this._shadowLightIndex = this._numLights; - } - this._type.push(light.type); - this._ambient.push(...(light.ambient.toArray())); - this._diffuse.push(...(light.diffuse.toArray())); - this._specular.push(...(light.specular.toArray())); - this._rawDirection.push(light.direction); - this._attenuation.push(light.constantAttenuation); - this._attenuation.push(light.linearAttenuation); - this._attenuation.push(light.quadraticAttenuation); - this._spotCutoff.push(light.spotCutoff); - this._spotExponent.push(light.spotExponent); - this._shadowStrength.push(light.shadowStrength); - this._cutoffDistance.push(light.cutoffDistance); - - this._numLights++; - this._lightTransform.push(lightTransform); - return true; - } - } - - updatePositionAndDirection(viewMatrix) { - this._direction = []; - this._position = []; - for (let i=0; i { - if (!texData) { - resolve(); - } - else if (/data\:image\/[a-z]+\;base64\,/.test(texData)) { - let hash = bg.utils.md5(texData); - if (g_base64Images[hash]) { - mat[property] = g_base64Images[hash]; - } - else { - mat[property] = bg.base.Texture.FromBase64Image(context,texData); - g_base64Images[hash] = mat[property]; - } - resolve(mat[property]); - } -// else if (/data\:md5/.test(texData)) { - -// } - else { - let fullPath = basePath + texData; // TODO: add full path - bg.base.Loader.Load(context,fullPath) - .then(function(tex) { - mat[property] = tex; - resolve(tex); - }); - } - }); - } - - class Material { - // Create and initialize a material from the json material definition - static FromMaterialDefinition(context,def,basePath="") { - return new Promise((resolve,reject) => { - let mat = new Material(); - - mat.diffuse = readVector(def.diffuse) || bg.Color.White(); - mat.specular = readVector(def.specular) || bg.Color.White(); - mat.shininess = def.shininess || 0; - mat.shininessMaskChannel = def.shininessMaskChannel || 0; - mat.shininessMaskInvert = def.shininessMaskInvert || false; - mat.lightEmission = def.lightEmission || 0; - mat.lightEmissionMaskChannel = def.lightEmissionMaskChannel || 0; - mat.lightEmissionMaskInvert = def.lightEmissionMaskInvert || false; - mat.refractionAmount = def.refractionAmount || 0; - mat.reflectionAmount = def.reflectionAmount || 0; - mat.reflectionMaskChannel = def.reflectionMaskChannel || 0; - mat.reflectionMaskInvert = def.reflectionMaskInvert || false; - mat.textureOffset = readVector(def.textureOffset) || new bg.Vector2(0,0); - mat.textureScale = readVector(def.textureScale) || new bg.Vector2(1,1); - mat.normalMapOffset = readVector(def.normalMapOffset) || new bg.Vector2(0,0); - mat.normalMapScale = readVector(def.normalMapScale) || new bg.Vector2(1,1); - mat.cullFace = def.cullFace===undefined ? true : def.cullFace; - mat.castShadows = def.castShadows===undefined ? true : def.castShadows; - mat.receiveShadows = def.receiveShadows===undefined ? true : def.receiveShadows; - mat.alphaCutoff = def.alphaCutoff===undefined ? 0.5 : def.alphaCutoff; - mat.name = def.name; - mat.description = def.description; - mat.roughness = def.roughness || 0; - mat.roughnessMaskChannel = def.roughnessMaskChannel || 0; - mat.roughnessMaskInvert = def.roughnessMaskInvert || false; - mat.unlit = def.unlit || false; - - let texPromises = []; - texPromises.push(readTexture(context,basePath,def.shininessMask,mat,"shininessMask")); - texPromises.push(readTexture(context,basePath,def.lightEmissionMask,mat,"lightEmissionMask")); - texPromises.push(readTexture(context,basePath,def.reflectionMask,mat,"reflectionMask")); - texPromises.push(readTexture(context,basePath,def.texture,mat,"texture")); - texPromises.push(readTexture(context,basePath,def.normalMap,mat,"normalMap")); - texPromises.push(readTexture(context,basePath,def.roughnessMask,mat,"roughnessMask")); - - Promise.all(texPromises) - .then(() => { - resolve(mat); - }); - }); - } - - constructor() { - this._diffuse = bg.Color.White(); - this._specular = bg.Color.White(); - this._shininess = 0; - this._lightEmission = 0; - this._refractionAmount = 0; - this._reflectionAmount = 0; - this._texture = null; - this._lightmap = null; - this._normalMap = null; - this._textureOffset = new bg.Vector2(); - this._textureScale = new bg.Vector2(1); - this._lightmapOffset = new bg.Vector2(); - this._lightmapScale = new bg.Vector2(1); - this._normalMapOffset = new bg.Vector2(); - this._normalMapScale = new bg.Vector2(1); - this._castShadows = true; - this._receiveShadows = true; - this._alphaCutoff = 0.5; - this._shininessMask = null; - this._shininessMaskChannel = 0; - this._shininessMaskInvert = false; - this._lightEmissionMask = null; - this._lightEmissionMaskChannel = 0; - this._lightEmissionMaskInvert = false; - this._reflectionMask = null; - this._reflectionMaskChannel = 0; - this._reflectionMaskInvert = false; - this._cullFace = true; - this._roughness = 0; - this._roughnessMask = null; - this._roughnessMaskChannel = 0; - this._roughnessMaskInvert = false; - this._unlit = false; - - this._selectMode = false; - } - - clone() { - let copy = new Material(); - copy.assign(this); - return copy; - } - - assign(other) { - this._diffuse = new bg.Color(other.diffuse); - this._specular = new bg.Color(other.specular); - this._shininess = other.shininess; - this._lightEmission = other.lightEmission; - this._refractionAmount = other.refractionAmount; - this._reflectionAmount = other.reflectionAmount; - this._texture = other.texture; - this._lightmap = other.lightmap; - this._normalMap = other.normalMap; - this._textureOffset = new bg.Vector2(other.textureOffset); - this._textureScale = new bg.Vector2(other.textureScale); - this._lightmapOffset = new bg.Vector2(other.ligthmapOffset); - this._lightmapScale = new bg.Vector2(other.lightmapScale); - this._normalMapOffset = new bg.Vector2(other.normalMapOffset); - this._normalMapScale = new bg.Vector2(other.normalMapScale); - this._castShadows = other.castShadows; - this._receiveShadows = other.receiveShadows; - this._alphaCutoff = other.alphaCutoff; - this._shininessMask = other.shininessMask; - this._shininessMaskChannel = other.shininessMaskChannel; - this._shininessMaskInvert = other.shininessMaskInvert; - this._lightEmissionMask = other.lightEmissionMask; - this._lightEmissionMaskChannel = other.lightEmissionMaskChannel; - this._lightEmissionMaskInvert = other.lightEmissionMaskInvert; - this._reflectionMask = other.reflectionMask; - this._reflectionMaskChannel = other.reflectionMaskChannel; - this._reflectionMaskInvert = other.reflectionMaskInvert; - this._cullFace = other.cullFace; - this._roughness = other.roughness; - this._roughnessMask = other.roughnessMask; - this._roughnessMaskChannel = other.roughnessMaskChannel; - this._roughnessMaskInvert = other.roughnessMaskInvert; - this._unlit = other.unlit; - } - - get isTransparent() { - return this._diffuse.a<1; - } - - get diffuse() { return this._diffuse; } - get specular() { return this._specular; } - get shininess() { return this._shininess; } - get lightEmission() { return this._lightEmission; } - get refractionAmount() { return this._refractionAmount; } - get reflectionAmount() { return this._reflectionAmount; } - get texture() { return this._texture; } - get lightmap() { return this._lightmap; } - get normalMap() { return this._normalMap; } - get textureOffset() { return this._textureOffset; } - get textureScale() { return this._textureScale; } - get lightmapOffset() { return this._lightmapOffset; } - get lightmapScale() { return this._lightmapScale; } - get normalMapOffset() { return this._normalMapOffset; } - get normalMapScale() { return this._normalMapScale; } - get castShadows() { return this._castShadows; } - get receiveShadows() { return this._receiveShadows; } - get alphaCutoff() { return this._alphaCutoff; } - get shininessMask() { return this._shininessMask; } - get shininessMaskChannel() { return this._shininessMaskChannel; } - get shininessMaskInvert() { return this._shininessMaskInvert; } - get lightEmissionMask() { return this._lightEmissionMask; } - get lightEmissionMaskChannel() { return this._lightEmissionMaskChannel; } - get lightEmissionMaskInvert() { return this._lightEmissionMaskInvert; } - get reflectionMask() { return this._reflectionMask; } - get reflectionMaskChannel() { return this._reflectionMaskChannel; } - get reflectionMaskInvert() { return this._reflectionMaskInvert; } - get cullFace() { return this._cullFace; } - get roughness() { return this._roughness; } - get roughnessMask() { return this._roughnessMask; } - get roughnessMaskChannel() { return this._roughnessMaskChannel; } - get roughnessMaskInvert() { return this._roughnessMaskInvert; } - get unlit() { return this._unlit; } - - - set diffuse(newVal) { this._diffuse = newVal; } - set specular(newVal) { this._specular = newVal; } - set shininess(newVal) { if (!isNaN(newVal)) this._shininess = newVal; } - set lightEmission(newVal) { if (!isNaN(newVal)) this._lightEmission = newVal; } - set refractionAmount(newVal) { this._refractionAmount = newVal; } - set reflectionAmount(newVal) { this._reflectionAmount = newVal; } - set texture(newVal) { this._texture = newVal; } - set lightmap(newVal) { this._lightmap = newVal; } - set normalMap(newVal) { this._normalMap = newVal; } - set textureOffset(newVal) { this._textureOffset = newVal; } - set textureScale(newVal) { this._textureScale = newVal; } - set lightmapOffset(newVal) { this._lightmapOffset = newVal; } - set lightmapScale(newVal) { this._lightmapScale = newVal; } - set normalMapOffset(newVal) { this._normalMapOffset = newVal; } - set normalMapScale(newVal) { this._normalMapScale = newVal; } - set castShadows(newVal) { this._castShadows = newVal; } - set receiveShadows(newVal) { this._receiveShadows = newVal; } - set alphaCutoff(newVal) { if (!isNaN(newVal)) this._alphaCutoff = newVal; } - set shininessMask(newVal) { this._shininessMask = newVal; } - set shininessMaskChannel(newVal) { this._shininessMaskChannel = newVal; } - set shininessMaskInvert(newVal) { this._shininessMaskInvert = newVal; } - set lightEmissionMask(newVal) { this._lightEmissionMask = newVal; } - set lightEmissionMaskChannel(newVal) { this._lightEmissionMaskChannel = newVal; } - set lightEmissionMaskInvert(newVal) { this._lightEmissionMaskInvert = newVal; } - set reflectionMask(newVal) { this._reflectionMask = newVal; } - set reflectionMaskChannel(newVal) { this._reflectionMaskChannel = newVal; } - set reflectionMaskInvert(newVal) { this._reflectionMaskInvert = newVal; } - set cullFace(newVal) { this._cullFace = newVal; } - set roughness(newVal) { this._roughness = newVal; } - set roughnessMask(newVal) { this._roughnessMask = newVal; } - set roughnessMaskChannel(newVal) { this._roughnessMaskChannel = newVal; } - set roughnessMaskInvert(newVal) { this._roughnessMaskInvert = newVal; } - - get unlit() { return this._unlit; } - set unlit(u) { this._unlit = u; } - - get selectMode() { return this._selectMode; } - set selectMode(s) { this._selectMode = s; } - - // Mask channel vectors: used to pass the mask channel to a shader - get lightEmissionMaskChannelVector() { - return channelVector(this.lightEmissionMaskChannel) - } - - get shininessMaskChannelVector() { - return channelVector(this.shininessMaskChannel); - } - - get reflectionMaskChannelVector() { - return channelVector(this.reflectionMaskChannel); - } - - get roughnessMaskChannelVector() { - return channelVector(this.roughnessMaskChannel); - } - - // Returns an array of the external resources used by this material, for example, - // the paths to the textures. If the "resources" parameter (array) is passed, the resources - // will be added to this array, and the parameter will be modified to include the new - // resources. If a resource exists in the "resources" parameter, it will not be added - getExternalResources(resources=[]) { - function tryadd(texture) { - if (texture && texture.fileName && texture.fileName!="" && resources.indexOf(texture.fileName)==-1) { - resources.push(texture.fileName); - } - } - tryadd(this.texture); - tryadd(this.lightmap); - tryadd(this.normalMap); - tryadd(this.shininessMask); - tryadd(this.lightEmissionMask); - tryadd(this.reflectionMask); - tryadd(this.roughnessMask); - return resources; - } - - copyMaterialSettings(mat,mask) { - if ( mask & bg.base.MaterialFlag.DIFFUSE) { - mat.diffuse = this.diffuse; - } - if ( mask & bg.base.MaterialFlag.SPECULAR) { - mat.specular = this.specular; - } - if ( mask & bg.base.MaterialFlag.SHININESS) { - mat.shininess = this.shininess; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION) { - mat.lightEmission = this.lightEmission; - } - if ( mask & bg.base.MaterialFlag.REFRACTION_AMOUNT) { - mat.refractionAmount = this.refractionAmount; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_AMOUNT) { - mat.reflectionAmount = this.reflectionAmount; - } - if ( mask & bg.base.MaterialFlag.TEXTURE) { - mat.texture = this.texture; - } - if ( mask & bg.base.MaterialFlag.LIGHT_MAP) { - mat.lightmap = this.lightmap; - } - if ( mask & bg.base.MaterialFlag.NORMAL_MAP) { - mat.normalMap = this.normalMap; - } - if ( mask & bg.base.MaterialFlag.TEXTURE_OFFSET) { - mat.textureOffset = this.textureOffset; - } - if ( mask & bg.base.MaterialFlag.TEXTURE_SCALE) { - mat.textureScale = this.textureScale; - } - if ( mask & bg.base.MaterialFlag.LIGHT_MAP_OFFSET) { - mat.lightmapOffset = this.lightmapOffset; - } - if ( mask & bg.base.MaterialFlag.LIGHT_MAP_SCALE) { - mat.lightmapScale = this.lightmapScale; - } - if ( mask & bg.base.MaterialFlag.NORMAL_MAP_OFFSET) { - mat.normalMapOffset = this.normalMapOffset; - } - if ( mask & bg.base.MaterialFlag.NORMAL_MAP_SCALE) { - mat.normalMapScale = this.normalMapScale; - } - if ( mask & bg.base.MaterialFlag.CAST_SHADOWS) { - mat.castShadows = this.castShadows; - } - if ( mask & bg.base.MaterialFlag.RECEIVE_SHADOWS) { - mat.receiveShadows = this.receiveShadows; - } - if ( mask & bg.base.MaterialFlag.ALPHA_CUTOFF) { - mat.alphaCutoff = this.alphaCutoff; - } - if ( mask & bg.base.MaterialFlag.SHININESS_MASK) { - mat.shininessMask = this.shininessMask; - } - if ( mask & bg.base.MaterialFlag.SHININESS_MASK_CHANNEL) { - mat.shininessMaskChannel = this.shininessMaskChannel; - } - if ( mask & bg.base.MaterialFlag.SHININESS_MASK_INVERT) { - mat.shininessMaskInvert = this.shininessMaskInvert; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION_MASK) { - mat.lightEmissionMask = this.lightEmissionMask; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION_MASK_CHANNEL) { - mat.lightEmissionMaskChannel = this.lightEmissionMaskChannel; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION_MASK_INVERT) { - mat.lightEmissionMaskInvert = this.lightEmissionMaskInvert; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_MASK) { - mat.reflectionMask = this.reflectionMask; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_MASK_CHANNEL) { - mat.reflectionMaskChannel = this.reflectionMaskChannel; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_MASK_INVERT) { - mat.reflectionMaskInvert = this.reflectionMaskInvert; - } - if ( mask & bg.base.MaterialFlag.CULL_FACE) { - mat.cullFace = this.cullFace; - } - - // All the roughness attributes are copied together using this flag. In - // the future, the *_MASK, *_MASK_CHANNEL and *_MASK_INVERT for shininess, - // light emission and reflection, will be deprecated and will work in the - // same way as ROUGHNESS here - if ( mask & bg.base.MaterialFlag.ROUGHNESS) { - mat.reflectionAmount = this.reflectionAmount; - mat.reflectionMask = this.reflectionMask; - mat.reflectionMaskChannel = this.reflectionMaskChannel; - mat.reflectionMaskInvert = this.reflectionMaskInvert; - } - - if (mask & bg.base.MaterialFlag.UNLIT) { - mat.unlit = this.unlit; - } - } - - applyModifier(context, mod, resourcePath) { - if (mod.isEnabled(bg.base.MaterialFlag.DIFFUSE)) { - this.diffuse = mod.diffuse; - } - if (mod.isEnabled(bg.base.MaterialFlag.SPECULAR)) { - this.specular = mod.specular; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS)) { - this.shininess = mod.shininess; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION)) { - this.lightEmission = mod.lightEmission; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFRACTION_AMOUNT)) { - this.refractionAmount = mod.refractionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_AMOUNT)) { - this.reflectionAmount = mod.reflectionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE)) { - this.texture = getTexture(context,mod.texture,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP)) { - this.lightmap = getTexture(context,mod.lightmap,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP)) { - this.normalMap = getTexture(context,mod.normalMap,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_OFFSET)) { - this.textureOffset = mod.textureOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_SCALE)) { - this.textureScale = mod.textureScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_OFFSET)) { - this.lightmapOffset = mod.lightmapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_SCALE)) { - this.lightmapScale = mod.lightmapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_OFFSET)) { - this.normalMapOffset = mod.normalMapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_SCALE)) { - this.normalMapScale = mod.normalMapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.CAST_SHADOWS)) { - this.castShadows = mod.castShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.RECEIVE_SHADOWS)) { - this.receiveShadows = mod.receiveShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.ALPHA_CUTOFF)) { - this.alphaCutoff = mod.alphaCutoff; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK)) { - this.shininessMask = getTexture(context,mod.shininessMask,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_CHANNEL)) { - this.shininessMaskChannel = mod.shininessMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_INVERT)) { - this.shininessMaskInvert = mod.shininessMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK)) { - this.lightEmissionMask = getTexture(context,mod.lightEmissionMask,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_CHANNEL)) { - this.lightEmissionMaskChannel = mod.lightEmissionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_INVERT)) { - this.lightEmissionMaskInvert = mod.lightEmissionMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK)) { - this.reflectionMask = getTexture(context,mod.reflectionMask,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_CHANNEL)) { - this.reflectionMaskChannel = mod.reflectionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_INVERT)) { - this.reflectionMaskInvert = mod.reflectionMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.CULL_FACE)) { - this.cullFace = mod.cullFace; - } - - // See above note for ROUGHNESS flags - if (mod.isEnabled(bg.base.MaterialFlag.ROUGHNESS)) { - this.roughness = mod.roughness; - this.roughnessMask = getTexture(context,mod.roughnessMask,resourcePath); - this.roughnessMaskChannel = mod.roughnessMaskChannel; - this.roughnessMaskInvert = mod.roughnessMaskInvert; - } - - if (mod.isEnabled(bg.base.MaterialFlag.UNLIT)) { - this.unlit = mod.unlit; - } - } - - getModifierWithMask(modifierMask) { - var mod = new MaterialModifier(); - - mod.modifierFlags = modifierMask; - - if (mod.isEnabled(bg.base.MaterialFlag.DIFFUSE)) { - mod.diffuse = this.diffuse; - } - if (mod.isEnabled(bg.base.MaterialFlag.SPECULAR)) { - mod.specular = this.specular; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS)) { - mod.shininess = this.shininess; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION)) { - mod.lightEmission = this.lightEmission; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFRACTION_AMOUNT)) { - mod.refractionAmount = this.refractionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_AMOUNT)) { - mod.reflectionAmount = this.reflectionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE)) { - mod.texture = getPath(this.texture); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP)) { - mod.lightmap = getPath(this.lightmap); - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP)) { - mod.normalMap = getPath(this.normalMap); - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_OFFSET)) { - mod.textureOffset = this.textureOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_SCALE)) { - mod.textureScale = this.textureScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_OFFSET)) { - mod.lightmapOffset = this.lightmapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_SCALE)) { - mod.lightmapScale = this.lightmapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_OFFSET)) { - mod.normalMapOffset = this.normalMapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_SCALE)) { - mod.normalMapScale = this.normalMapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.CAST_SHADOWS)) { - mod.castShadows = this.castShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.RECEIVE_SHADOWS)) { - mod.receiveShadows = this.receiveShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.ALPHA_CUTOFF)) { - mod.alphaCutoff = this.alphaCutoff; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK)) { - mod.shininessMask = getPath(this.shininessMask); - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_CHANNEL)) { - mod.shininessMaskChannel = this.shininessMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_INVERT)) { - mod.shininessMaskInvert = this.shininessMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK)) { - mod.lightEmissionMask = getPath(this.lightEmissionMask); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_CHANNEL)) { - mod.lightEmissionMaskChannel = this.lightEmissionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_INVERT)) { - mod.lightEmissionMaskInver = this.lightEmissionMaskInver; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK)) { - mod.reflectionMask = getPath(this.reflectionMask); - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_CHANNEL)) { - mod.reflectionMaskChannel = this.reflectionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_INVERT)) { - mod.reflectionMaskInvert = this.reflectionMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.CULL_FACE)) { - mod.cullFace = this.cullFace; - } - - // See above note about ROUGHNESS flag - if (mod.isEnabled(bg.base.MaterialFlag.ROUGHNESS)) { - mod.roughness = this.roughness; - mod.roughnessMask = getPath(this.roughnessMask); - mod.roughnessMaskChannel = this.roughnessMaskChannel; - mod.roughnessMaskInvert = this.roughnessMaskInvert; - } - - if (mod.isEnabled(bg.base.MaterialFlag.UNLIT)) { - mod.unlit = this.unlit; - } - - return mod; - } - - static GetMaterialWithJson(context,data,path) { - let material = new Material(); - if (data.cullFace===undefined) { - data.cullFace = true; - } - - material.diffuse.set(data.diffuseR,data.diffuseG,data.diffuseB,data.diffuseA); - material.specular.set(data.specularR,data.specularG,data.specularB,data.specularA); - material.shininess = data.shininess; - material.lightEmission = data.lightEmission; - - material.refractionAmount = data.refractionAmount; - material.reflectionAmount = data.reflectionAmount; - - material.textureOffset.set(data.textureOffsetX,data.textureOffsetY); - material.textureScale.set(data.textureScaleX,data.textureScaleY); - - material.lightmapOffset.set(data.lightmapOffsetX,data.lightmapOffsetY); - material.lightmapScale.set(data.lightmapScaleX,data.lightmapScaleY); - - material.normalMapOffset.set(data.normalMapOffsetX,data.normalMapOffsetY); - material.normalMapScale.set(data.normalMapScaleX,data.normalMapScaleY); - - material.alphaCutoff = data.alphaCutoff; - material.castShadows = data.castShadows; - material.receiveShadows = data.receiveShadows; - - material.shininessMaskChannel = data.shininessMaskChannel; - material.shininessMaskInvert = data.invertShininessMask; - - material.lightEmissionMaskChannel = data.lightEmissionMaskChannel; - material.lightEmissionMaskInvert = data.invertLightEmissionMask; - - material.reflectionMaskChannel = data.reflectionMaskChannel; - material.reflectionMaskInvert = data.invertReflectionMask; - - material.roughness = data.roughness; - material.roughnessMaskChannel = data.roughnessMaskChannel; - material.roughnessMaskInvert = data.invertRoughnessMask; - - material.cullFace = data.cullFace; - - material.unlit = data.unlit; - - if (path && path[path.length-1]!='/') { - path += '/'; - } - - function mergePath(path,file) { - if (!file) return null; - return path ? path + file:file; - } - - data.texture = mergePath(path,data.texture); - data.lightmap = mergePath(path,data.lightmap); - data.normalMap = mergePath(path,data.normalMap); - data.shininessMask = mergePath(path,data.shininessMask); - data.lightEmissionMask = mergePath(path,data.lightEmissionMask); - data.reflectionMask = mergePath(path,data.reflectionMask); - data.roughnessMask = mergePath(path,data.roughnessMask); - - return new Promise((accept,reject) => { - let textures = []; - - if (data.texture) { - textures.push(data.texture); - } - if (data.lightmap && textures.indexOf(data.lightmap)==-1) { - textures.push(data.lightmap); - } - if (data.normalMap && textures.indexOf(data.normalMap)==-1) { - textures.push(data.normalMap); - } - if (data.shininessMask && textures.indexOf(data.shininessMask)==-1) { - textures.push(data.shininessMask); - } - if (data.lightEmissionMask && textures.indexOf(data.lightEmissionMask)==-1) { - textures.push(data.lightEmissionMask); - } - if (data.reflectionMask && textures.indexOf(data.reflectionMask)==-1) { - textures.push(data.reflectionMask); - } - if (data.roughnessMask && textures.indexOf(data.roughnessMask)==-1) { - textures.push(data.roughnessMask); - } - - bg.utils.Resource.Load(textures) - .then(function(images) { - material.texture = loadTexture(context,images[data.texture],data.texture); - material.lightmap = loadTexture(context,images[data.lightmap],data.lightmap); - material.normalMap = loadTexture(context,images[data.normalMap],data.normalMap); - material.shininessMask = loadTexture(context,images[data.shininessMask],data.shininessMask); - material.lightEmissionMask = loadTexture(context,images[data.lightEmissionMask],data.lightEmissionMask); - material.reflectionMask = loadTexture(context,images[data.reflectionMask],data.reflectionMask); - material.roughnessMask = loadTexture(context,images[data.roughnessMask],data.roughnessMask); - accept(material); - }); - }); - } - } - - bg.base.Material = Material; -})(); - -(function() { - class MatrixStack { - constructor() { - this._matrix = bg.Matrix4.Identity(); - this._stack = []; - this._changed = true; - } - - get changed() { return this._changed; } - set changed(c) { this._changed = c; } - - push() { - this._stack.push(new bg.Matrix4(this._matrix)); - } - - set(m) { - this._matrix.assign(m); - this._changed = true; - return this; - } - - mult(m) { - this._matrix.mult(m); - this._changed = true; - return this; - } - - identity() { - this._matrix.identity(); - this._changed = true; - return this; - } - - translate(x, y, z) { - this._matrix.translate(x, y, z); - this._changed = true; - return this; - } - - rotate(alpha, x, y, z) { - this._matrix.rotate(alpha, x, y, z); - this._changed = true; - return this; - } - - scale(x, y, z) { - this._matrix.scale(x, y, z); - this._changed = true; - return this; - } - - setScale(x, y, z) { - this._matrix.setScale(x,y,z); - this._changed = true; - return this; - } - - perspective(fov,aspect,near,far) { - this._matrix - .identity() - .perspective(fov,aspect,near,far); - this._changed = true; - return this; - } - - frustum(left, right, bottom, top, nearPlane, farPlane) { - this._matrix - .identity() - .frustum(left,right,bottom,top,nearPlane,farPlane); - this._changed = true; - return this; - } - - ortho(left, right, bottom, top, nearPlane, farPlane) { - this._matrix - .identity() - .ortho(left,right,bottom,top,nearPlane,farPlane); - this._changed = true; - return this; - } - - invert() { - this._matrix.invert(); - this._changed = true; - return this; - } - - get matrix() { - this._changed = true; - return this._matrix; - } - - // This accessor will return the current matrix without mark the internal state - // to changed. There isn't any way in JavaScript to ensure that the returned matrix - // will not be changed, therefore use this accessor carefully. It's recommended to use this - // accessor ONLY to retrieve the matrix and pass it to the shaders. - get matrixConst() { - return this._matrix; - } - - pop() { - if (this._stack.length) { - this._matrix.assign(this._stack.pop()); - this._changed = true; - } - return this._matrix; - } - } - - bg.base.MatrixStack = MatrixStack; - - let s_MatrixState = null; - - class MatrixState { - static Current() { - if (!s_MatrixState) { - s_MatrixState = new MatrixState(); - } - return s_MatrixState; - } - - static SetCurrent(s) { - s_MatrixState = s; - return s_MatrixState; - } - - constructor() { - // Matrixes - this._modelMatrixStack = new MatrixStack(); - this._viewMatrixStack = new MatrixStack(); - this._projectionMatrixStack = new MatrixStack(); - this._modelViewMatrix = bg.Matrix4.Identity(); - this._normalMatrix = bg.Matrix4.Identity(); - this._cameraDistanceScale = null; - } - - get modelMatrixStack() { - return this._modelMatrixStack; - } - - get viewMatrixStack() { - return this._viewMatrixStack; - } - - get projectionMatrixStack() { - return this._projectionMatrixStack; - } - - get modelViewMatrix() { - if (!this._modelViewMatrix || this._modelMatrixStack.changed || this._viewMatrixStack.changed) { - this._modelViewMatrix = new bg.Matrix4(this._viewMatrixStack._matrix); - this._modelViewMatrix.mult(this._modelMatrixStack._matrix); - this._modelMatrixStack.changed = false; - this._viewMatrixStack.changed = false; - } - return this._modelViewMatrix; - } - - get normalMatrix() { - if (!this._normalMatrix || this._modelMatrixStack.changed || this._viewMatrixStack.changed) { - this._normalMatrix = new bg.Matrix4(this.modelViewMatrix); - this._normalMatrix.invert(); - this._normalMatrix.traspose(); - this._modelMatrixStack.changed = false; - } - return this._normalMatrix; - } - - get viewMatrixInvert() { - if (!this._viewMatrixInvert || this._viewMatrixStack.changed) { - this._viewMatrixInvert = new bg.Matrix4(this.viewMatrixStack.matrixConst); - this._viewMatrixInvert.invert(); - } - return this._viewMatrixInvert; - } - - // This function returns a number that represents the - // distance from the camera to the model. - get cameraDistanceScale() { - return this._cameraDistanceScale = this._viewMatrixStack.matrix.position.magnitude(); - } - } - - bg.base.MatrixState = MatrixState; -})(); -(function() { - - bg.base.ClearBuffers = { - COLOR:null, - DEPTH:null, - COLOR_DEPTH:null - }; - - bg.base.BlendMode = { - NORMAL: 1, // It works as the Photoshop layers does GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA, GL_FUNC_ADD - MULTIPLY: 2, // GL_ZERO GL_SRC_COLOR, GL_FUNC_ADD - ADD: 3, // GL_ONE GL_ONE, GL_FUNC_ADD - SUBTRACT: 4, // GL_ONE GL_ONE, GL_FUNC_SUBTRACT - ALPHA_ADD: 5, // GL_SRC_ALPHA GL_DST_ALPHA, GL_FUNC_ADD - ALPHA_SUBTRACT: 6 // GL_SRC_ALPHA GL_DST_ALPHA, GL_FUNC_SUBTRACT - }; - - bg.base.OpacityLayer = { - TRANSPARENT: 0b1, - OPAQUE: 0b10, - GIZMOS: 0b100, - SELECTION: 0b1000, - GIZMOS_SELECTION: 0b10000, - ALL: 0b1111, - NONE: 0 - }; - - class PipelineImpl { - constructor(context) { - this.initFlags(context); - bg.base.ClearBuffers.COLOR_DEPTH = bg.base.ClearBuffers.COLOR | bg.base.ClearBuffers.DEPTH; - } - - initFlags(context) {} - - setViewport(context,vp) {} - clearBuffers(context,color,buffers) {} - setDepthTestEnabled(context,e) {} - setBlendEnabled(context,e) {} - setBlendMode(context,m) {} - setCullFace(context,e) {} - } - - bg.base.PipelineImpl = PipelineImpl; - - let s_currentPipeline = null; - - function enablePipeline(pipeline) { - if (pipeline._effect) { - pipeline._effect.setActive(); - } - pipeline.renderSurface.setActive(); - - bg.Engine.Get().pipeline.setViewport(pipeline.context,pipeline._viewport); - bg.Engine.Get().pipeline.setDepthTestEnabled(pipeline.context,pipeline._depthTest); - bg.Engine.Get().pipeline.setCullFace(pipeline.context,pipeline._cullFace); - bg.Engine.Get().pipeline.setBlendEnabled(pipeline.context,pipeline._blend); - bg.Engine.Get().pipeline.setBlendMode(pipeline.context,pipeline._blendMode); - } - - class Pipeline extends bg.app.ContextObject { - static SetCurrent(p) { - s_currentPipeline = p; - if (s_currentPipeline) { - enablePipeline(s_currentPipeline); - } - } - - static Current() { return s_currentPipeline; } - - constructor(context) { - super(context); - - // Opacity layer - this._opacityLayer = bg.base.OpacityLayer.ALL; - - // Viewport - this._viewport = new bg.Viewport(0,0,200,200); - - // Clear buffer - this._clearColor = bg.Color.Black(); - - // Effect (used with draw method) - this._effect = null; - - // Texture effect (used with drawTexture method) - this._textureEffect = null; - - - // Other flags - this._depthTest = true; - this._cullFace = true; - - // Render surface - this._renderSurface = null; - - // Blending - this._blend = false; - this._blendMode = bg.base.BlendMode.NORMAL; - - this._buffersToClear = bg.base.ClearBuffers.COLOR_DEPTH; - } - - get isCurrent() { return s_currentPipeline==this; } - - set opacityLayer(l) { this._opacityLayer = l; } - get opacityLayer() { return this._opacityLayer; } - shouldDraw(material) { - return material && - ((material.isTransparent && (this._opacityLayer & bg.base.OpacityLayer.TRANSPARENT)!=0) || - (!material.isTransparent && (this._opacityLayer & bg.base.OpacityLayer.OPAQUE)!=0)); - } - - get effect() { return this._effect; } - set effect(m) { - this._effect = m; - if (this._effect && this.isCurrent) { - this._effect.setActive(); - } - } - - get textureEffect() { - if (!this._textureEffect) { - this._textureEffect = new bg.base.DrawTextureEffect(this.context); - } - return this._textureEffect; - } - - set textureEffect(t) { - this._textureEffect = t; - } - - set buffersToClear(b) { this._buffersToClear = b; } - get buffersToClear() { return this._buffersToClear; } - - get renderSurface() { - if (!this._renderSurface) { - this._renderSurface = new bg.base.ColorSurface(this.context); - this._renderSurface.setActive(); - } - return this._renderSurface; - } - - set renderSurface(r) { - this._renderSurface = r; - if (this.isCurrent) { - this._renderSurface.setActive(); - } - } - - draw(polyList) { - if (this._effect && polyList && this.isCurrent) { - let cf = this.cullFace; - this._effect.bindPolyList(polyList); - if (this._effect.material) { - - this.cullFace = this._effect.material.cullFace; - } - polyList.draw(); - this._effect.unbind(); - this.cullFace = cf; - } - } - - drawTexture(texture) { - let depthTest = this.depthTest; - this.depthTest = false; - this.textureEffect.drawSurface(texture); - this.depthTest = depthTest; - } - - get blend() { return this._blend; } - set blend(b) { - this._blend = b; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setBlendEnabled(this.context,this._blend); - } - } - - get blendMode() { return this._blendMode; } - set blendMode(b) { - this._blendMode = b; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setBlendMode(this.context,this._blendMode); - } - } - - get viewport() { return this._viewport; } - set viewport(vp) { - this._viewport = vp; - if (this.renderSurface.resizeOnViewportChanged) { - this.renderSurface.size = new bg.Vector2(vp.width,vp.height); - } - if (this.isCurrent) { - bg.Engine.Get().pipeline.setViewport(this.context,this._viewport); - } - } - - clearBuffers(buffers) { - if (this.isCurrent) { - buffers = buffers!==undefined ? buffers : this._buffersToClear; - bg.Engine.Get().pipeline.clearBuffers(this.context,this._clearColor,buffers); - } - } - - get clearColor() { return this._clearColor; } - set clearColor(c) { this._clearColor = c; } - - get depthTest() { return this._depthTest; } - set depthTest(e) { - this._depthTest = e; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setDepthTestEnabled(this.context,this._depthTest); - } - } - - get cullFace() { return this._cullFace; } - set cullFace(c) { - this._cullFace = c; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setCullFace(this.context,this._cullFace); - } - } - } - - bg.base.Pipeline = Pipeline; -})(); -(function() { - - bg.base.BufferType = { - VERTEX: 1 << 0, - NORMAL: 1 << 1, - TEX_COORD_0: 1 << 2, - TEX_COORD_1: 1 << 3, - TEX_COORD_2: 1 << 4, - COLOR: 1 << 5, - TANGENT: 1 << 6, - INDEX: 1 << 7 - }; - - class PolyListImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) {} - create(context) {} - build(context,plist,vert,norm,t0,t1,t2,col,tan,index) { return false; } - draw(context,plist,drawMode,numberOfIndex) {} - destroy(context,plist) {} - - // NOTE: the new buffer data must have the same size as the old one - update(context,plist,bufferType,newData) {} - } - - function createTangents(plist) { - if (!plist.texCoord0 || !plist.vertex) return; - plist._tangent = []; - - let result = []; - let generatedIndexes = {}; - let invalidUV = false; - if (plist.index.length%3==0) { - for (let i=0; i0 && this.normal.length!=this.vertex.length) - throw new Error("Unexpected number of normal coordinates found in polyList"); - - for (let i=0;i { - return a.cameraDistance > b.cameraDistance; - }); - } - - get opaqueQueue() { - return this._opaqueQueue; - } - - get transparentQueue() { - return this._transparentQueue; - } - - - } - - bg.base.RenderQueue = RenderQueue; -})(); -(function() { - - class RenderSurfaceBufferImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) {} - - create(context,attachments) {} - setActive(context,renderSurface) {} - readBuffer(context,renderSurface,rectangle) {} - resize(context,renderSurface,size) {} - destroy(context,renderSurface) {} - supportType(type) {} - supportFormat(format) {} - maxColorAttachments() {} - } - - bg.base.RenderSurfaceBufferImpl = RenderSurfaceBufferImpl; - - class RenderSurface extends bg.app.ContextObject { - static DefaultAttachments() { - return [ - { type:bg.base.RenderSurfaceType.RGBA, format:bg.base.RenderSurfaceFormat.UNSIGNED_BYTE }, - { type:bg.base.RenderSurfaceType.DEPTH, format:bg.base.RenderSurfaceFormat.RENDERBUFFER } - ]; - } - static SupportFormat(format) { - return bg.Engine.Get().colorBuffer.supportFormat(format); - } - - static SupportType(type) { - return bg.Engine.Get().colorBuffer.supportType(type); - } - - static MaxColorAttachments() { - return bg.Engine.Get().textureBuffer.maxColorAttachments; - } - - constructor(context) { - super(context); - - this._size = new bg.Vector2(256); - this._renderSurface = null; - this._resizeOnViewportChanged = true; - } - - get size() { return this._size; } - set size(s) { - if (this._size.x!=s.x || this._size.y!=s.y) { - this._size = s; - this.surfaceImpl.resize(this.context,this._renderSurface,s); - } - } - - get surfaceImpl() { return null; } - - get resizeOnViewportChanged() { return this._resizeOnViewportChanged; } - set resizeOnViewportChanged(r) { this._resizeOnViewportChanged = r; } - - create(attachments) { - if (!attachments) { - attachments = RenderSurface.DefaultAttachments(); - } - this._renderSurface = this.surfaceImpl.create(this.context,attachments); - } - - setActive() { - this.surfaceImpl.setActive(this.context,this._renderSurface); - } - - readBuffer(rectangle) { - return this.surfaceImpl.readBuffer(this.context,this._renderSurface,rectangle,this.size); - } - - destroy() { - this.surfaceImpl.destroy(this.context,this._renderSurface); - this._renderSurface = null; - } - } - - bg.base.RenderSurface = RenderSurface; - - bg.base.RenderSurfaceType = { - RGBA:null, - DEPTH:null - }; - - bg.base.RenderSurfaceFormat = { - UNSIGNED_BYTE:null, - UNSIGNED_SHORT:null, - FLOAT:null, - RENDERBUFFER:null - }; - - class ColorSurface extends RenderSurface { - static MaxColorAttachments() { - return bg.Engine.Get().colorBuffer.maxColorAttachments; - } - - get surfaceImpl() { return bg.Engine.Get().colorBuffer; } - } - - bg.base.ColorSurface = ColorSurface; - - class TextureSurface extends RenderSurface { - static MaxColorAttachments() { - return bg.Engine.Get().textureBuffer.maxColorAttachments; - } - - get surfaceImpl() { return bg.Engine.Get().textureBuffer; } - - getTexture(attachment = 0) { - return this._renderSurface.attachments[attachment] && - this._renderSurface.attachments[attachment].texture; - } - } - - bg.base.TextureSurface = TextureSurface; - -})(); - -(function() { - if (!bg.isElectronApp) { - return false; - } - - const fs = require('fs'); - const path = require('path'); - - class SaveSceneHelper { - save(filePath,sceneRoot) { - filePath = bg.base.Writer.StandarizePath(filePath); - return new Promise((resolve,reject) => { - this._url = {}; - this._url.path = filePath.split('/'); - this._url.fileName = this._url.path.pop(); - this._url.path = this._url.path.join('/'); - this._sceneData = { - fileType:"vwgl::scene", - version:{ - major:2, - minor:0, - rev:0 - }, - scene:[] - } - this._promises = []; - bg.base.Writer.PrepareDirectory(this._url.path); - - let rootNode = {}; - this._sceneData.scene.push(rootNode); - this.buildSceneNode(sceneRoot,rootNode); - - fs.writeFileSync(path.join(this._url.path,this._url.fileName),JSON.stringify(this._sceneData,"","\t"),"utf-8"); - - Promise.all(this._promises) - .then(() => resolve()) - .catch((err) => reject(err)); - }); - } - - buildSceneNode(node,sceneData) { - sceneData.type = "Node"; - sceneData.name = node.name; - sceneData.enabled = node.enabled; - sceneData.steady = node.steady; - sceneData.children = []; - sceneData.components = []; - node.forEachComponent((component) => { - if (component.shouldSerialize) { - let componentData = {}; - component.serialize(componentData,this._promises,this._url); - sceneData.components.push(componentData) - } - }); - node.children.forEach((child) => { - let childData = {} - this.buildSceneNode(child,childData); - sceneData.children.push(childData); - }) - } - }; - - class SceneWriterPlugin extends bg.base.WriterPlugin { - acceptType(url,data) { - let ext = url.split(".").pop("."); - return /vitscnj/i.test(ext) && data instanceof bg.scene.Node; - } - - write(url,data) { - let saveSceneHelper = new SaveSceneHelper(); - return saveSceneHelper.save(url,data); - } - } - - bg.base.SceneWriterPlugin = SceneWriterPlugin; -})(); -(function() { - - let s_shaderLibrary = null; - - function defineAll(obj) { - Reflect.defineProperty(obj,"all", { - get() { - if (!this._all) { - this._all = []; - for (let key in obj) { - if (typeof(obj[key])=="object" && obj[key].name) { - this._all.push(obj[key]); - } - } - } - return this._all; - } - }); - } - - class ShaderLibrary { - static Get() { - if (!s_shaderLibrary) { - s_shaderLibrary = new ShaderLibrary(); - } - return s_shaderLibrary; - } - - constructor() { - let library = bg[bg.Engine.Get().id].shaderLibrary; - - for (let key in library) { - this[key] = library[key]; - } - - defineAll(this.inputs.matrix); - Object.defineProperty(this.inputs.matrix,"modelViewProjection",{ - get() { - return [ - this.model, - this.view, - this.projection - ] - } - }); - defineAll(this.inputs.material); - defineAll(this.inputs.lighting); - defineAll(this.inputs.lightingForward); - defineAll(this.inputs.shadows); - defineAll(this.inputs.colorCorrection); - defineAll(this.functions.materials); - defineAll(this.functions.colorCorrection); - defineAll(this.functions.lighting); - defineAll(this.functions.utils); - } - } - - bg.base.ShaderLibrary = ShaderLibrary; - - class ShaderSourceImpl { - header(shaderType) { return ""; } - parameter(shaderType,paramData) { return paramData.name; } - func(shaderType,funcData) { return funcData.name; } - } - - bg.base.ShaderSourceImpl = ShaderSourceImpl; - - class ShaderSource { - static FormatSource(src) { - let result = ""; - let lines = src.replace(/^\n*/,"").replace(/\n*$/,"").split("\n"); - let minTabs = 100; - lines.forEach((line) => { - let tabsInLine = /(\t*)/.exec(line)[0].length; - if (minTabs>tabsInLine) { - minTabs = tabsInLine; - } - }); - - lines.forEach((line) => { - let tabsInLine = /(\t*)/.exec(line)[0].length; - let diff = tabsInLine - minTabs; - result += line.slice(tabsInLine - diff,line.length) + "\n"; - }); - - return result.replace(/^\n*/,"").replace(/\n*$/,""); - } - - constructor(type) { - this._type = type; - this._params = []; - this._functions = []; - this._requiredExtensions = []; - this._header = ""; - } - - get type() { return this._type; } - get params() { return this._params; } - get header() { return this._header; } - get functions() { return this._functions; } - - addParameter(param) { - if (param instanceof Array) { - this._params = [...this._params, ...param]; - } - else { - this._params.push(param); - } - this._params.push(null); // This will be translated into a new line character - } - - addFunction(func) { - if (func instanceof Array) { - this._functions = [...this._functions, ...func]; - } - else { - this._functions.push(func); - } - } - - setMainBody(body) { - this.addFunction({ - returnType:"void", name:"main", params:{}, body:body - }); - } - - appendHeader(src) { - this._header += src + "\n"; - } - - toString() { - let impl = bg.Engine.Get().shaderSource; - // Build header - let src = impl.header(this.type) + "\n" + this._header + "\n\n"; - - this.params.forEach((p) => { - src += impl.parameter(this.type,p) + "\n"; - }); - - this.functions.forEach((f) => { - src += "\n" + impl.func(this.type,f) + "\n"; - }) - return src; - } - } - - bg.base.ShaderSource = ShaderSource; -})(); -(function() { - - class ShaderImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) {} - setActive(context,shaderProgram) {} - create(context) {} - addShaderSource(context,shaderProgram,shaderType,source) {} - link(context,shaderProgram) {} - initVars(context,shader,inputBufferVars,valueVars) {} - setInputBuffer(context,shader,varName,vertexBuffer,itemSize) {} - setValueInt(context,shader,name,v) {} - setValueIntPtr(context,shader,name,v) {} - setValueFloat(context,shader,name,v) {} - setValueFloatPtr(context,shader,name,v) {} - setValueVector2(context,shader,name,v) {} - setValueVector3(context,shader,name,v) {} - setValueVector4(context,shader,name,v) {} - setValueVector2v(context,shader,name,v) {} - setValueVector3v(context,shader,name,v) {} - setValueVector4v(context,shader,name,v) {} - setValueMatrix3(context,shader,name,traspose,v) {} - setValueMatrix4(context,shader,name,traspose,v) {} - setTexture(context,shader,name,texture,textureUnit) {} - } - - bg.base.ShaderImpl = ShaderImpl; - - bg.base.ShaderType = { - VERTEX: null, - FRAGMENT: null - }; - - function addLineNumbers(source) { - let result = ""; - source.split("\n").forEach((line,index) => { - ++index; - let prefix = index<10 ? "00":index<100 ? "0":""; - result += prefix + index + " | " + line + "\n"; - }); - return result; - } - - class Shader extends bg.app.ContextObject { - static ClearActive(context) { bg.Engine.Get().shader.setActive(context,null); } - - constructor(context) { - super(context); - - this._shader = bg.Engine.Get().shader.create(context); - this._linked = false; - - this._compileError = null; - this._linkError = null; - } - - get shader() { return this._shader; } - get compileError() { return this._compileError; } - get compileErrorSource() { return this._compileErrorSource; } - get linkError() { return this._linkError; } - get status() { return this._compileError==null && this._linkError==null; } - - addShaderSource(shaderType, shaderSource) { - if (this._linked) { - this._compileError = "Tying to attach a shader to a linked program"; - } - else if (!this._compileError) { - this._compileError = bg.Engine.Get().shader.addShaderSource( - this.context, - this._shader, - shaderType,shaderSource); - if (this._compileError) { - this._compileErrorSource = addLineNumbers(shaderSource); - } - } - return this._compileError==null; - } - - link() { - this._linkError = null; - if (this._linked) { - this._linkError = "Shader already linked"; - } - else { - this._linkError = bg.Engine.Get().shader.link(this.context,this._shader); - this._linked = this._linkError==null; - } - return this._linked; - } - - setActive() { - bg.Engine.Get().shader.setActive(this.context,this._shader); - } - - clearActive() { - Shader.ClearActive(this.context); - } - - initVars(inputBufferVars,valueVars) { - bg.Engine.Get().shader.initVars(this.context,this._shader,inputBufferVars,valueVars); - } - - setInputBuffer(name,vbo,itemSize) { - bg.Engine.Get().shader - .setInputBuffer(this.context,this._shader,name,vbo,itemSize); - } - - disableInputBuffer(name) { - bg.Engine.Get().shader - .disableInputBuffer(this.context,this._shader,name); - } - - setValueInt(name,v) { - bg.Engine.Get().shader - .setValueInt(this.context,this._shader,name,v); - } - - setValueIntPtr(name,v) { - bg.Engine.Get().shader - .setValueIntPtr(this.context,this._shader,name,v); - } - - setValueFloat(name,v) { - bg.Engine.Get().shader - .setValueFloat(this.context,this._shader,name,v); - } - - setValueFloatPtr(name,v) { - bg.Engine.Get().shader - .setValueFloatPtr(this.context,this._shader,name,v); - } - - setVector2(name,v) { - bg.Engine.Get().shader - .setValueVector2(this.context,this._shader,name,v); - } - - setVector3(name,v) { - bg.Engine.Get().shader - .setValueVector3(this.context,this._shader,name,v); - } - - setVector4(name,v) { - bg.Engine.Get().shader - .setValueVector4(this.context,this._shader,name,v); - } - - setVector2Ptr(name,v) { - bg.Engine.Get().shader - .setValueVector2v(this.context,this._shader,name,v); - } - - setVector3Ptr(name,v) { - bg.Engine.Get().shader - .setValueVector3v(this.context,this._shader,name,v); - } - - setVector4Ptr(name,v) { - bg.Engine.Get().shader - .setValueVector4v(this.context,this._shader,name,v); - } - - setMatrix3(name,v,traspose=false) { - bg.Engine.Get().shader - .setValueMatrix3(this.context,this._shader,name,traspose,v); - } - - setMatrix4(name,v,traspose=false) { - bg.Engine.Get().shader - .setValueMatrix4(this.context,this._shader,name,traspose,v); - } - - setTexture(name,texture,textureUnit) { - bg.Engine.Get().shader - .setTexture(this.context,this._shader,name,texture,textureUnit); - } - } - - bg.base.Shader = Shader; -})(); -(function() { - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - let s_vertexSource = null; - let s_fragmentSource = null; - - function vertexShaderSource() { - if (!s_vertexSource) { - s_vertexSource = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_vertexSource.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - null, - lib().inputs.matrix.model, - lib().inputs.matrix.view, - lib().inputs.matrix.projection, - null, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_vertexSource.setMainBody(` - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - fsTexCoord = inTex0; - `); - } - } - return s_vertexSource; - } - - function fragmentShaderSource() { - if (!s_fragmentSource) { - s_fragmentSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - s_fragmentSource.addParameter([ - lib().inputs.material.castShadows, - lib().inputs.material.texture, - lib().inputs.material.textureOffset, - lib().inputs.material.textureScale, - lib().inputs.material.alphaCutoff, - null, - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ]); - - s_fragmentSource.addFunction(lib().functions.utils.pack); - s_fragmentSource.addFunction(lib().functions.materials.samplerColor); - - if (bg.Engine.Get().id=="webgl1") { - s_fragmentSource.setMainBody(` - - float alpha = samplerColor(inTexture,fsTexCoord,inTextureOffset,inTextureScale).a; - if (inCastShadows && alpha>inAlphaCutoff) { - gl_FragColor = pack(gl_FragCoord.z); - } - else { - discard; - }`); - } - } - return s_fragmentSource; - } - - class ShadowMapEffect extends bg.base.Effect { - constructor(context) { - super(context); - - this._material = null; - this._light = null; - this._lightTransform = null; - - this.setupShaderSource([ - vertexShaderSource(), - fragmentShaderSource() - ]); - } - - get material() { return this._material; } - set material(m) { this._material = m; } - - get light() { return this._light; } - set light(l) { this._light = l; } - - get lightTransform() { return this._lightTransform; } - set lightTransform(t) { this._lightTransform = t; } - - setupVars() { - if (this.material && this.light && this.lightTransform) { - let matrixState = bg.base.MatrixState.Current(); - this.shader.setMatrix4("inModelMatrix",matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4("inViewMatrix",this.lightTransform); - this.shader.setMatrix4("inProjectionMatrix",this.light.projection); - - this.shader.setValueInt("inCastShadows",this.material.castShadows); - let texture = this.material.texture || bg.base.TextureCache.WhiteTexture(this.context); - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2("inTextureOffset",this.material.textureOffset); - this.shader.setVector2("inTextureScale",this.material.textureScale); - this.shader.setValueFloat("inAlphaCutoff",this.material.alphaCutoff); - } - } - } - - bg.base.ShadowMapEffect = ShadowMapEffect; - - bg.base.ShadowType = { - HARD: 0, - SOFT: 1, - STRATIFIED: 2 - }; - - bg.base.ShadowCascade = { - NEAR: 0, - FAR: 1, - MID: 2 - } - - function updateDirectional(scene,camera,light,lightTransform,cascade) { - let ms = bg.base.MatrixState.Current(); - bg.base.MatrixState.SetCurrent(this._matrixState); - this._pipeline.effect.light = light; - this._viewMatrix = new bg.Matrix4(lightTransform); - - let rotation = this._viewMatrix.rotation; - let cameraTransform = camera.transform ? new bg.Matrix4(camera.transform.matrix) : bg.Matrix4.Identity(); - let cameraPos = cameraTransform.position; - let target = cameraPos.add(cameraTransform.forwardVector.scale(-camera.focus)) - - this._viewMatrix - .identity() - .translate(target) - .mult(rotation) - .translate(0,0,10) - .invert(); - - this._pipeline.effect.lightTransform = this._viewMatrix; - - bg.base.Pipeline.SetCurrent(this._pipeline); - this._pipeline.clearBuffers(bg.base.ClearBuffers.COLOR_DEPTH); - - let mult = 1; - // Far cascade - if (cascade==bg.base.ShadowCascade.FAR) { - mult = 20; - light.shadowBias = 0.0001; - } - // Near cascade - else if (cascade==bg.base.ShadowCascade.NEAR) { - mult = 2; - light.shadowBias = 0.00002; - } - else if (cascade==bg.base.ShadowCascade.MID) { - mult = 4; - light.shadowBias = 0.0001; - } - light.projection = bg.Matrix4.Ortho(-camera.focus * mult ,camera.focus * mult,-camera.focus * mult,camera.focus * mult,1,300*camera.focus); - this._projection = light.projection; - scene.accept(this._drawVisitor); - - bg.base.MatrixState.SetCurrent(ms); - } - - function updateSpot(scene,camera,light,lightTransform) { - let ms = bg.base.MatrixState.Current(); - bg.base.MatrixState.SetCurrent(this._matrixState); - this._pipeline.effect.light = light; - this._viewMatrix = new bg.Matrix4(lightTransform); - - let cutoff = light.spotCutoff; - light.projection = bg.Matrix4.Perspective(cutoff * 2,1,0.1,200.0); - light.shadowBias = 0.0005; - this._viewMatrix.invert(); - - this._projection = light.projection; - this._pipeline.effect.lightTransform = this._viewMatrix; - - bg.base.Pipeline.SetCurrent(this._pipeline); - this._pipeline.clearBuffers(bg.base.ClearBuffers.COLOR_DEPTH); - - scene.accept(this._drawVisitor); - bg.base.MatrixState.SetCurrent(ms); - } - - class ShadowMap extends bg.app.ContextObject { - constructor(context) { - super(context); - - this._pipeline = new bg.base.Pipeline(context); - this._pipeline.renderSurface = new bg.base.TextureSurface(context); - this._pipeline.renderSurface.create(); - this._pipeline.effect = new bg.base.ShadowMapEffect(context); - - this._matrixState = new bg.base.MatrixState(); - this._drawVisitor = new bg.scene.DrawVisitor(this._pipeline,this._matrixState); - - this._shadowMapSize = new bg.Vector2(2048); - this._pipeline.viewport = new bg.Viewport(0,0,this._shadowMapSize.width,this._shadowMapSize.height); - - this._shadowType = bg.base.ShadowType.SOFT; - - this._projection = bg.Matrix4.Ortho(-15,15,-15,15,1,50); - this._viewMatrix = bg.Matrix4.Identity(); - - this._shadowColor = bg.Color.Black(); - } - - get size() { return this._shadowMapSize; } - set size(s) { - this._shadowMapSize = s; - this._pipeline.viewport = new bg.Viewport(0,0,s.width,s.height); - } - - get shadowType() { return this._shadowType; } - set shadowType(t) { this._shadowType = t; } - - get shadowColor() { return this._shadowColor; } - set shadowColor(c) { this._shadowColor = c; } - - get viewMatrix() { return this._viewMatrix; } - get projection() { return this._projection; } - - get texture() { return this._pipeline.renderSurface.getTexture(0); } - - // it's important that the camera has set the focus to calculate the projection of the directional lights - update(scene,camera,light,lightTransform,cascade=bg.base.ShadowCascade.NEAR) { - if (light.type==bg.base.LightType.DIRECTIONAL) { - updateDirectional.apply(this,[scene,camera,light,lightTransform,cascade]); - } - else if (light.type==bg.base.LightType.SPOT) { - updateSpot.apply(this,[scene,camera,light,lightTransform]); - } - } - } - - bg.base.ShadowMap = ShadowMap; - -})(); -(function() { - - class TextProperties { - - constructor() { - this._font = "Verdana"; - this._size = 30; - this._color = "#FFFFFF"; - this._background = "transparent"; - this._align = "start"; - this._bold = false; - this._italic = false; - - this._dirty = true; - } - - clone() { - let newInstance = new TextProperties(); - - newInstance._font = this._font; - newInstance._size = this._size; - newInstance._color = this._color; - newInstance._background = this._background; - newInstance._align = this._align; - newInstance._bold = this._bold; - newInstance._italic = this._italic; - - return newInstance; - } - - get font() { return this._font; } - set font(v) { this._dirty = true; this._font = v; } - get size() { return this._size; } - set size(v) { this._dirty = true; this._size = v; } - get color() { return this._color; } - set color(v) { this._dirty = true; this._color = v; } - get background() { return this._background; } - set background(v) { this._dirty = true; this._background = v; } - get align() { return this._align; } - set align(v) { this._dirty = true; this._align = v; } - get bold() { return this._bold; } - set bold(v) { this._dirty = true; this._bold = v; } - get italic() { return this._italic; } - set italic(v) { this._dirty = true; this._italic = v; } - - - // this property is set to true every time some property is changed - set dirty(d) { this._dirty = d; } - get dirty() { return this._dirty; } - - serialize(jsonData) { - jsonData.font = this.font; - jsonData.size = this.size; - jsonData.color = this.color; - jsonData.background = this.background; - jsonData.align = this.align; - jsonData.bold = this.bold; - jsonData.italic = this.italic; - } - - deserialize(jsonData) { - this.font = jsonData.font; - this.size = jsonData.size; - this.color = jsonData.color; - this.background = jsonData.background; - this.align = jsonData.align; - this.bold = jsonData.bold; - this.italic = jsonData.italic; - this._dirty = true; - } - } - - bg.base.TextProperties = TextProperties; -})(); -(function() { - let s_textureCache = {}; - - let COLOR_TEXTURE_SIZE = 8; - - let s_whiteTexture = "static-white-color-texture"; - let s_blackTexture = "static-black-color-texture"; - let s_normalTexture = "static-normal-color-texture"; - let s_randomTexture = "static-random-color-texture"; - let s_whiteCubemap = "static-white-cubemap-texture"; - - class TextureCache { - static SetColorTextureSize(size) { COLOR_TEXTURE_SIZE = size; } - static GetColorTextureSize() { return COLOR_TEXTURE_SIZE; } - - static WhiteCubemap(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_whiteCubemap); - - if (!tex) { - tex = bg.base.Texture.WhiteCubemap(context); - cache.register(s_whiteCubemap,tex); - } - return tex; - } - - static WhiteTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_whiteTexture); - - if (!tex) { - tex = bg.base.Texture.WhiteTexture(context,new bg.Vector2(COLOR_TEXTURE_SIZE)); - cache.register(s_whiteTexture,tex); - } - - return tex; - } - - static BlackTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_blackTexture); - - if (!tex) { - tex = bg.base.Texture.BlackTexture(context,new bg.Vector2(COLOR_TEXTURE_SIZE)); - cache.register(s_blackTexture,tex); - } - - return tex; - } - - static NormalTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_normalTexture); - - if (!tex) { - tex = bg.base.Texture.NormalTexture(context,new bg.Vector2(COLOR_TEXTURE_SIZE)); - cache.register(s_normalTexture,tex); - } - - return tex; - } - - static RandomTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_randomTexture); - - if (!tex) { - tex = bg.base.Texture.RandomTexture(context,new bg.Vector2(64)); - cache.register(s_randomTexture,tex); - } - - return tex; - } - - static Get(context) { - if (!s_textureCache[context.uuid]) { - s_textureCache[context.uuid] = new TextureCache(context); - } - return s_textureCache[context.uuid]; - } - - constructor(context) { - this._context = context; - this._textures = {}; - } - - find(url) { - return this._textures[url]; - } - - register(url,texture) { - if (texture instanceof bg.base.Texture) { - this._textures[url] = texture; - } - } - - unregister(url) { - if (this._textures[url]) { - delete this._textures[url]; - } - } - - clear() { - this._textures = {}; - } - } - - bg.base.TextureCache = TextureCache; - - let g_wrapX = null; - let g_wrapY = null; - let g_minFilter = null; - let g_magFilter = null; - - /* Extra data: - * wrapX - * wrapY - * minFilter - * magFilter - */ - class TextureLoaderPlugin extends bg.base.LoaderPlugin { - static GetWrapX() { - return g_wrapX || bg.base.TextureWrap.REPEAT; - } - - static GetWrapY() { - return g_wrapY || bg.base.TextureWrap.REPEAT; - } - - static GetMinFilter() { - return g_minFilter || bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST; - } - - static GetMagFilter() { - return g_magFilter || bg.base.TextureFilter.LINEAR; - } - - static SetMinFilter(f) { - g_minFilter = f; - } - - static SetMagFilter(f) { - g_magFilter = f; - } - - static SetWrapX(w) { - g_wrapX = w; - } - - static SetWrapY(w) { - g_wrapY = w; - } - - acceptType(url,data) { - return bg.utils.Resource.IsImage(url); - } - - load(context,url,data,extraData) { - return new Promise((accept,reject) => { - if (data) { - let texture = bg.base.TextureCache.Get(context).find(url); - if (!texture) { - bg.log(`Texture ${url} not found. Loading texture`); - texture = new bg.base.Texture(context); - texture.create(); - texture.bind(); - texture.wrapX = extraData.wrapX || TextureLoaderPlugin.GetWrapX(); - texture.wrapY = extraData.wrapY || TextureLoaderPlugin.GetWrapY(); - texture.minFilter = extraData.minFilter || TextureLoaderPlugin.GetMinFilter(); - texture.magFilter = extraData.magFilter || TextureLoaderPlugin.GetMagFilter(); - texture.setImage(data); - texture.fileName = url; - bg.base.TextureCache.Get(context).register(url,texture); - } - accept(texture); - } - else { - reject(new Error("Error loading texture image data")); - } - }); - } - } - - bg.base.TextureLoaderPlugin = TextureLoaderPlugin; - - class VideoTextureLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - return bg.utils.Resource.IsVideo(url); - } - - load(context,url,video) { - return new Promise((accept,reject) => { - if (video) { - let texture = new bg.base.Texture(context); - texture.create(); - texture.bind(); - texture.setVideo(video); - texture.fileName = url; - accept(texture); - } - else { - reject(new Error("Error loading video texture data")); - } - }); - } - } - - bg.base.VideoTextureLoaderPlugin = VideoTextureLoaderPlugin; -})(); -(function() { - - bg.base.TextureUnit = { - TEXTURE_0: 0, - TEXTURE_1: 1, - TEXTURE_2: 2, - TEXTURE_3: 3, - TEXTURE_4: 4, - TEXTURE_5: 5, - TEXTURE_6: 6, - TEXTURE_7: 7, - TEXTURE_8: 8, - TEXTURE_9: 9, - TEXTURE_10: 10, - TEXTURE_11: 11, - TEXTURE_12: 12, - TEXTURE_13: 13, - TEXTURE_14: 14, - TEXTURE_15: 15, - TEXTURE_16: 16, - TEXTURE_17: 17, - TEXTURE_18: 18, - TEXTURE_19: 19, - TEXTURE_20: 20, - TEXTURE_21: 21, - TEXTURE_22: 22, - TEXTURE_23: 23, - TEXTURE_24: 24, - TEXTURE_25: 25, - TEXTURE_26: 26, - TEXTURE_27: 27, - TEXTURE_28: 28, - TEXTURE_29: 29, - TEXTURE_30: 30 - }; - - bg.base.TextureWrap = { - REPEAT: null, - CLAMP: null, - MIRRORED_REPEAT: null - }; - - bg.base.TextureFilter = { - NEAREST_MIPMAP_NEAREST: null, - LINEAR_MIPMAP_NEAREST: null, - NEAREST_MIPMAP_LINEAR: null, - LINEAR_MIPMAP_LINEAR: null, - NEAREST: null, - LINEAR: null - }; - - bg.base.TextureTarget = { - TEXTURE_2D: null, - CUBE_MAP: null, - POSITIVE_X_FACE: null, - NEGATIVE_X_FACE: null, - POSITIVE_Y_FACE: null, - NEGATIVE_Y_FACE: null, - POSITIVE_Z_FACE: null, - NEGATIVE_Z_FACE: null - }; - - class TextureImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) { - console.log("TextureImpl: initFlags() method not implemented"); - } - - create(context) { - console.log("TextureImpl: create() method not implemented"); - return null; - } - - setActive(context,texUnit) { - console.log("TextureImpl: setActive() method not implemented"); - } - - bind(context,target,texture) { - console.log("TextureImpl: bind() method not implemented"); - } - - unbind(context,target) { - console.log("TextureImpl: unbind() method not implemented"); - } - - setTextureWrapX(context,target,texture,wrap) { - console.log("TextureImpl: setTextureWrapX() method not implemented"); - } - - setTextureWrapY(context,target,texture,wrap) { - console.log("TextureImpl: setTextureWrapY() method not implemented"); - } - - setImage(context,target,minFilter,magFilter,texture,img,flipY) { - console.log("TextureImpl: setImage() method not implemented"); - } - - setImageRaw(context,target,minFilter,magFilter,texture,width,height,data) { - console.log("TextureImpl: setImageRaw() method not implemented"); - } - - setTextureFilter(context,target,minFilter,magFilter) { - console.log("TextureImpl: setTextureFilter() method not implemented"); - } - - setCubemapImage(context,face,image) { - console.log("TextureImpl: setCubemapImage() method not implemented"); - } - - setCubemapRaw(context,face,rawImage,w,h) { - console.log("TextureImpl: setCubemapRaw() method not implemented"); - } - - setVideo(context,target,texture,video,flipY) { - console.log("TextureImpl: setVideo() method not implemented"); - } - - updateVideoData(context,target,texture,video) { - console.log("TextureImpl: updateVideoData() method not implemented"); - } - - destroy(context,texture) { - console.log("TextureImpl: destroy() method not implemented"); - } - } - - bg.base.TextureImpl = TextureImpl; - - bg.base.TextureDataType = { - NONE: 0, - IMAGE: 1, - IMAGE_DATA: 2, - CUBEMAP: 3, - CUBEMAP_DATA: 4, - VIDEO: 5 - }; - - let g_base64TexturePreventRemove = []; - - class Texture extends bg.app.ContextObject { - static IsPowerOfTwoImage(image) { - return bg.Math.checkPowerOfTwo(image.width) && bg.Math.checkPowerOfTwo(image.height); - } - - static FromCanvas(context,canvas2d) { - return Texture.FromBase64Image(context,canvas2d.toDataURL("image/png")); - } - - static UpdateCanvasImage(texture,canvas2d) { - if (!texture.valid) { - return false; - } - let imageData = canvas2d.toDataURL("image/png"); - let recreate = false; - if (texture.img.width!=imageData.width || texture.img.height!=imageData.height) { - recreate = true; - } - texture.img = new Image(); - g_base64TexturePreventRemove.push(texture); - //tex.onload = function(evt,img) { - // Check this: use onload or setTimeout? - // onload seems to not work in all situations - setTimeout(() => { - texture.bind(); - if (Texture.IsPowerOfTwoImage(texture.img)) { - texture.minFilter = bg.base.TextureLoaderPlugin.GetMinFilter(); - texture.magFilter = bg.base.TextureLoaderPlugin.GetMagFilter(); - } - else { - texture.minFilter = bg.base.TextureFilter.NEAREST; - texture.magFilter = bg.base.TextureFilter.NEAREST; - texture.wrapX = bg.base.TextureWrap.CLAMP; - texture.wrapY = bg.base.TextureWrap.CLAMP; - } - texture.setImage(texture.img,true); - texture.unbind(); - let index = g_base64TexturePreventRemove.indexOf(texture); - if (index!=-1) { - g_base64TexturePreventRemove.splice(index,1); - } - bg.emitImageLoadEvent(); - //} - },10); - texture.img.src = imageData; - - return texture; - } - - static FromBase64Image(context,imgData) { - let tex = new bg.base.Texture(context); - tex.img = new Image(); - g_base64TexturePreventRemove.push(tex); - //tex.onload = function(evt,img) { - // Check this: use onload or setTimeout? - // onload seems to not work in all situations - setTimeout(() => { - tex.create(); - tex.bind(); - if (Texture.IsPowerOfTwoImage(tex.img)) { - tex.minFilter = bg.base.TextureLoaderPlugin.GetMinFilter(); - tex.magFilter = bg.base.TextureLoaderPlugin.GetMagFilter(); - } - else { - tex.minFilter = bg.base.TextureFilter.NEAREST; - tex.magFilter = bg.base.TextureFilter.NEAREST; - tex.wrapX = bg.base.TextureWrap.CLAMP; - tex.wrapY = bg.base.TextureWrap.CLAMP; - } - tex.setImage(tex.img,false); // Check this: flip base64 image? - tex.unbind(); - let index = g_base64TexturePreventRemove.indexOf(tex); - if (index!=-1) { - g_base64TexturePreventRemove.splice(index,1); - } - bg.emitImageLoadEvent(); - //} - },10); - tex.img.src = imgData; - - return tex; - } - - static ColorTexture(context,color,size) { - let colorTexture = new bg.base.Texture(context); - colorTexture.create(); - colorTexture.bind(); - - var dataSize = size.width * size.height * 4; - var textureData = []; - for (var i = 0; i < dataSize; i+=4) { - textureData[i] = color.r * 255; - textureData[i+1] = color.g * 255; - textureData[i+2] = color.b * 255; - textureData[i+3] = color.a * 255; - } - - textureData = new Uint8Array(textureData); - - colorTexture.minFilter = bg.base.TextureFilter.NEAREST; - colorTexture.magFilter = bg.base.TextureFilter.NEAREST; - colorTexture.setImageRaw(size.width,size.height,textureData); - colorTexture.unbind(); - - return colorTexture; - } - - static WhiteTexture(context,size) { - return Texture.ColorTexture(context,bg.Color.White(),size); - } - - static WhiteCubemap(context) { - return Texture.ColorCubemap(context, bg.Color.White()); - } - - static BlackCubemap(context) { - return Texture.ColorCubemap(context, bg.Color.Black()); - } - - static ColorCubemap(context,color) { - let cm = new bg.base.Texture(context); - cm.target = bg.base.TextureTarget.CUBE_MAP; - cm.create(); - cm.bind(); - - let dataSize = 32 * 32 * 4; - let textureData = []; - for (let i = 0; i-this.EPSILON && v=2) { - vec = vec._v; - } - let x=vec[0]; - let y=vec[1]; - let z=1.0; - - return new bg.Vector3( this._m[0]*x + this._m[3]*y + this._m[6]*z, - this._m[1]*x + this._m[4]*y + this._m[7]*z, - this._m[2]*x + this._m[5]*y + this._m[8]*z); - } - - isNan() { - return !Math.isNaN(_m[0]) && !Math.isNaN(_m[1]) && !Math.isNaN(_m[2]) && - !Math.isNaN(_m[3]) && !Math.isNaN(_m[4]) && !Math.isNaN(_m[5]) && - !Math.isNaN(_m[6]) && !Math.isNaN(_m[7]) && !Math.isNaN(_m[8]); - } - - toString() { - return "[" + this._m[0] + ", " + this._m[1] + ", " + this._m[2] + "]\n" + - " [" + this._m[3] + ", " + this._m[4] + ", " + this._m[5] + "]\n" + - " [" + this._m[6] + ", " + this._m[7] + ", " + this._m[8] + "]"; - } -} - -bg.Matrix3 = Matrix3; - -class Matrix4 { - static Unproject(x, y, depth, mvMat, pMat, viewport) { - let mvp = new bg.Matrix4(pMat); - mvp.mult(mvMat); - mvp.invert(); - - let vin = new bg.Vector4(((x - viewport.y) / viewport.width) * 2.0 - 1.0, - ((y - viewport.x) / viewport.height) * 2.0 - 1.0, - depth * 2.0 - 1.0, - 1.0); - - let result = new bg.Vector4(mvp.multVector(vin)); - if (result.z==0) { - result.set(0); - } - else { - result.set( result.x/result.w, - result.y/result.w, - result.z/result.w, - result.w/result.w); - } - - return result; - } - - static Identity() { - return new bg.Matrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); - } - - static Perspective(fovy, aspect, nearPlane, farPlane) { - let fovy2 = bg.Math.tan(fovy * bg.Math.PI / 360.0) * nearPlane; - let fovy2aspect = fovy2 * aspect; - - return bg.Matrix4.Frustum(-fovy2aspect,fovy2aspect,-fovy2,fovy2,nearPlane,farPlane); - } - - static Frustum(left, right, bottom, top, nearPlane, farPlane) { - let res = new bg.Matrix4(); - let A = right-left; - let B = top-bottom; - let C = farPlane-nearPlane; - - res.setRow(0, new bg.Vector4(nearPlane*2.0/A, 0.0, 0.0, 0.0)); - res.setRow(1, new bg.Vector4(0.0, nearPlane*2.0/B, 0.0, 0.0)); - res.setRow(2, new bg.Vector4((right+left)/A, (top+bottom)/B, -(farPlane+nearPlane)/C, -1.0)); - res.setRow(3, new bg.Vector4(0.0, 0.0, -(farPlane*nearPlane*2.0)/C, 0.0)); - - return res; - } - - static Ortho(left, right, bottom, top, nearPlane, farPlane) { - let p = new bg.Matrix4(); - - let m = right-left; - let l = top-bottom; - let k = farPlane-nearPlane;; - - p._m[0] = 2/m; p._m[1] = 0; p._m[2] = 0; p._m[3] = 0; - p._m[4] = 0; p._m[5] = 2/l; p._m[6] = 0; p._m[7] = 0; - p._m[8] = 0; p._m[9] = 0; p._m[10] = -2/k; p._m[11]= 0; - p._m[12]=-(left+right)/m; p._m[13] = -(top+bottom)/l; p._m[14] = -(farPlane+nearPlane)/k; p._m[15]=1; - - return p; - } - - static LookAt(p_eye, p_center, p_up) { - let result = new bg.Matrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); - let forward = new bg.Vector3(p_center); - forward.sub(p_eye); - let up = new bg.Vector3(p_up); - - forward.normalize(); - - let side = new bg.Vector3(forward); - side.cross(up); - up.assign(side); - up.cross(forward); - - result.set00(side.x); result.set10(side.y); result.set20(side.z); - result.set01(up.x); result.set11(up.y); result.set21(up.z); - result.set02(-forward.x); result.set12(-forward.y); result.set22(-forward.z); - result.setRow(3, new vwgl.Vector4(-p_eye.x,-p_eye.y,-p_eye.z,1.0)); - - return result; - } - - static Translation(x, y, z) { - if (typeof(x)=='object' && x._v && x._v.length>=3) { - y = x._v[1]; - z = x._v[2]; - x = x._v[0]; - } - return new bg.Matrix4( - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - x, y, z, 1.0 - ); - } - - static Rotation(alpha, x, y, z) { - let axis = new bg.Vector3(x,y,z); - axis.normalize(); - let rot = new bg.Matrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); - - var cosAlpha = bg.Math.cos(alpha); - var acosAlpha = 1.0 - cosAlpha; - var sinAlpha = bg.Math.sin(alpha); - - return new bg.Matrix4( - axis.x * axis.x * acosAlpha + cosAlpha, axis.x * axis.y * acosAlpha + axis.z * sinAlpha, axis.x * axis.z * acosAlpha - axis.y * sinAlpha, 0, - axis.y * axis.x * acosAlpha - axis.z * sinAlpha, axis.y * axis.y * acosAlpha + cosAlpha, axis.y * axis.z * acosAlpha + axis.x * sinAlpha, 0, - axis.z * axis.x * acosAlpha + axis.y * sinAlpha, axis.z * axis.y * acosAlpha - axis.x * sinAlpha, axis.z * axis.z * acosAlpha + cosAlpha, 0, - 0,0,0,1 - ); - } - - static Scale(x, y, z) { - if (typeof(x)=='object' && x._v && x._v.length>=3) { - x = x._v[0]; - y = x._v[1]; - z = x._v[2]; - } - return new bg.Matrix4( - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - ) - } - - constructor(m00=0,m01=0,m02=0,m03=0, m10=0,m11=0,m12=0,m13=0, m20=0,m21=0,m22=0,m23=0, m30=0,m31=0,m32=0,m33=0) { - this._m = new bg.Math.Array(16); - if (Array.isArray(m00)) { - this._m[ 0] = m00[0]; this._m[ 1] = m00[1]; this._m[ 2] = m00[2]; this._m[ 3] = m00[3]; - this._m[ 4] = m00[4]; this._m[ 5] = m00[5]; this._m[ 6] = m00[6]; this._m[ 7] = m00[7]; - this._m[ 8] = m00[8]; this._m[ 9] = m00[9]; this._m[10] = m00[10]; this._m[11] = m00[11]; - this._m[12] = m00[12]; this._m[13] = m00[13]; this._m[14] = m00[14]; this._m[15] = m00[15]; - } - else if (typeof(m00)=="number") { - this._m[ 0] = m00; this._m[ 1] = m01; this._m[ 2] = m02; this._m[ 3] = m03; - this._m[ 4] = m10; this._m[ 5] = m11; this._m[ 6] = m12; this._m[ 7] = m13; - this._m[ 8] = m20; this._m[ 9] = m21; this._m[10] = m22; this._m[11] = m23; - this._m[12] = m30; this._m[13] = m31; this._m[14] = m32; this._m[15] = m33; - } - else { - this.assign(m00); - } - } - - get m() { return this._m; } - - toArray() { - return [ - this._m[ 0], this._m[ 1], this._m[ 2], this._m[ 3], - this._m[ 4], this._m[ 5], this._m[ 6], this._m[ 7], - this._m[ 8], this._m[ 9], this._m[10], this._m[11], - this._m[12], this._m[13], this._m[14], this._m[15] - ] - } - - get m00() { return this._m[0]; } - get m01() { return this._m[1]; } - get m02() { return this._m[2]; } - get m03() { return this._m[3]; } - get m10() { return this._m[4]; } - get m11() { return this._m[5]; } - get m12() { return this._m[6]; } - get m13() { return this._m[7]; } - get m20() { return this._m[8]; } - get m21() { return this._m[9]; } - get m22() { return this._m[10]; } - get m23() { return this._m[11]; } - get m30() { return this._m[12]; } - get m31() { return this._m[13]; } - get m32() { return this._m[14]; } - get m33() { return this._m[15]; } - - set m00(v) { this._m[0] = v; } - set m01(v) { this._m[1] = v; } - set m02(v) { this._m[2] = v; } - set m03(v) { this._m[3] = v; } - set m10(v) { this._m[4] = v; } - set m11(v) { this._m[5] = v; } - set m12(v) { this._m[6] = v; } - set m13(v) { this._m[7] = v; } - set m20(v) { this._m[8] = v; } - set m21(v) { this._m[9] = v; } - set m22(v) { this._m[10] = v; } - set m23(v) { this._m[11] = v; } - set m30(v) { this._m[12] = v; } - set m31(v) { this._m[13] = v; } - set m32(v) { this._m[14] = v; } - set m33(v) { this._m[15] = v; } - - - zero() { - this._m[ 0] = 0; this._m[ 1] = 0; this._m[ 2] = 0; this._m[ 3] = 0; - this._m[ 4] = 0; this._m[ 5] = 0; this._m[ 6] = 0; this._m[ 7] = 0; - this._m[ 8] = 0; this._m[ 9] = 0; this._m[10] = 0; this._m[11] = 0; - this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 0; - return this; - } - - identity() { - this._m[ 0] = 1; this._m[ 1] = 0; this._m[ 2] = 0; this._m[ 3] = 0; - this._m[ 4] = 0; this._m[ 5] = 1; this._m[ 6] = 0; this._m[ 7] = 0; - this._m[ 8] = 0; this._m[ 9] = 0; this._m[10] = 1; this._m[11] = 0; - this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 1; - return this; - } - - isZero() { - return this._m[ 0]==0 && this._m[ 1]==0 && this._m[ 2]==0 && this._m[ 3]==0 && - this._m[ 4]==0 && this._m[ 5]==0 && this._m[ 6]==0 && this._m[ 7]==0 && - this._m[ 8]==0 && this._m[ 9]==0 && this._m[10]==0 && this._m[11]==0 && - this._m[12]==0 && this._m[13]==0 && this._m[14]==0 && this._m[15]==0; - } - - isIdentity() { - return this._m[ 0]==1 && this._m[ 1]==0 && this._m[ 2]==0 && this._m[ 3]==0 && - this._m[ 4]==0 && this._m[ 5]==1 && this._m[ 6]==0 && this._m[ 7]==0 && - this._m[ 8]==0 && this._m[ 9]==0 && this._m[10]==1 && this._m[11]==0 && - this._m[12]==0 && this._m[13]==0 && this._m[14]==0 && this._m[15]==1; - } - - row(i) { return new bg.Vector4(this._m[i*4],this._m[i*4 + 1],this._m[i*4 + 2],this._m[i*4 + 3]); } - setRow(i, row) { this._m[i*4]=row._v[0]; this._m[i*4 + 1]=row._v[1]; this._m[i*4 + 2]=row._v[2]; this._m[i*4 + 3]=row._v[3]; return this; } - setScale(x,y,z) { - let rx = new bg.Vector3(this._m[0], this._m[4], this._m[8]).normalize().scale(x); - let ry = new bg.Vector3(this._m[1], this._m[5], this._m[9]).normalize().scale(y); - let rz = new bg.Vector3(this._m[2], this._m[6], this._m[10]).normalize().scale(z); - this._m[0] = rx.x; this._m[4] = rx.y; this._m[8] = rx.z; - this._m[1] = ry.x; this._m[5] = ry.y; this._m[9] = ry.z; - this._m[2] = rz.x; this._m[6] = rz.y; this._m[10] = rz.z; - return this; - } - getScale() { - return new bg.Vector3( - new bg.Vector3(this._m[0], this._m[4], this._m[8]).module, - new bg.Vector3(this._m[1], this._m[5], this._m[9]).module, - new bg.Vector3(this._m[2], this._m[6], this._m[10]).module - ); - } - - setPosition(pos,y,z) { - if (typeof(pos)=="number") { - this._m[12] = pos; - this._m[13] = y; - this._m[14] = z; - } - else { - this._m[12] = pos.x; - this._m[13] = pos.y; - this._m[14] = pos.z; - } - return this; - } - - get rotation() { - let scale = this.getScale(); - return new bg.Matrix4( - this._m[0]/scale.x, this._m[1]/scale.y, this._m[ 2]/scale.z, 0, - this._m[4]/scale.x, this._m[5]/scale.y, this._m[ 6]/scale.z, 0, - this._m[8]/scale.x, this._m[9]/scale.y, this._m[10]/scale.z, 0, - 0, 0, 0, 1 - ); - } - - get position() { - return new bg.Vector3(this._m[12], this._m[13], this._m[14]); - } - - get length() { return this._m.length; } - - getMatrix3() { - return new bg.Matrix3(this._m[0], this._m[1], this._m[ 2], - this._m[4], this._m[5], this._m[ 6], - this._m[8], this._m[9], this._m[10]); - } - - perspective(fovy, aspect, nearPlane, farPlane) { - this.assign(bg.Matrix4.Perspective(fovy, aspect, nearPlane, farPlane)); - return this; - } - - frustum(left, right, bottom, top, nearPlane, farPlane) { - this.assign(bg.Matrix4.Frustum(left, right, bottom, top, nearPlane, farPlane)); - return this; - } - - ortho(left, right, bottom, top, nearPlane, farPlane) { - this.assign(bg.Matrix4.Ortho(left, right, bottom, top, nearPlane, farPlane)); - return this; - } - - lookAt(origin, target, up) { - this.assign(bg.Matrix4.LookAt(origin,target,up)); - return this; - } - - translate(x, y, z) { - this.mult(bg.Matrix4.Translation(x, y, z)); - return this; - } - - rotate(alpha, x, y, z) { - this.mult(bg.Matrix4.Rotation(alpha, x, y, z)); - return this; - } - - scale(x, y, z) { - this.mult(bg.Matrix4.Scale(x, y, z)); - return this; - } - - elemAtIndex(i) { return this._m[i]; } - - assign(a) { - if (a.length==9) { - this._m[0] = a._m[0]; this._m[1] = a._m[1]; this._m[2] = a._m[2]; this._m[3] = 0; - this._m[4] = a._m[3]; this._m[5] = a._m[4]; this._m[6] = a._m[5]; this._m[7] = 0; - this._m[8] = a._m[6]; this._m[9] = a._m[7]; this._m[10] = a._m[8]; this._m[11] = 0; - this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 1; - } - else if (a.length==16) { - this._m[0] = a._m[0]; this._m[1] = a._m[1]; this._m[2] = a._m[2]; this._m[3] = a._m[3]; - this._m[4] = a._m[4]; this._m[5] = a._m[5]; this._m[6] = a._m[6]; this._m[7] = a._m[7]; - this._m[8] = a._m[8]; this._m[9] = a._m[9]; this._m[10] = a._m[10]; this._m[11] = a._m[11]; - this._m[12] = a._m[12]; this._m[13] = a._m[13]; this._m[14] = a._m[14]; this._m[15] = a._m[15]; - } - return this; - } - - equals(m) { - return this._m[ 0]==m._m[ 0] && this._m[ 1]==m._m[ 1] && this._m[ 2]==m._m[ 2] && this._m[ 3]==m._m[ 3] && - this._m[ 4]==m._m[ 4] && this._m[ 5]==m._m[ 5] && this._m[ 6]==m._m[ 6] && this._m[ 7]==m._m[ 7] && - this._m[ 8]==m._m[ 8] && this._m[ 9]==m._m[ 9] && this._m[10]==m._m[10] && this._m[11]==m._m[11] && - this._m[12]==m._m[12] && this._m[13]==m._m[13] && this._m[14]==m._m[14] && this._m[15]==m._m[15]; - } - - notEquals(m) { - return this._m[ 0]!=m._m[ 0] || this._m[ 1]!=m._m[ 1] || this._m[ 2]!=m._m[ 2] || this._m[ 3]!=m._m[ 3] || - this._m[ 4]!=m._m[ 4] || this._m[ 5]!=m._m[ 5] || this._m[ 6]!=m._m[ 6] || this._m[ 7]!=m._m[ 7] || - this._m[ 8]!=m._m[ 8] || this._m[ 9]!=m._m[ 9] || this._m[10]!=m._m[10] || this._m[11]!=m._m[11] || - this._m[12]!=m._m[12] || this._m[13]!=m._m[13] || this._m[14]!=m._m[14] || this._m[15]!=m._m[15]; - } - - mult(a) { - if (typeof(a)=='number') { - this._m[ 0] *= a; this._m[ 1] *= a; this._m[ 2] *= a; this._m[ 3] *= a; - this._m[ 4] *= a; this._m[ 5] *= a; this._m[ 6] *= a; this._m[ 7] *= a; - this._m[ 8] *= a; this._m[ 9] *= a; this._m[10] *= a; this._m[11] *= a; - this._m[12] *= a; this._m[13] *= a; this._m[14] *= a; this._m[15] *= a; - return this; - } - - var rm = this._m; - var lm = a._m; - var res = new bg.Math.Array(16); - - res[0] = lm[ 0] * rm[ 0] + lm[ 1] * rm[ 4] + lm[ 2] * rm[ 8] + lm[ 3] * rm[12]; - res[1] = lm[ 0] * rm[ 1] + lm[ 1] * rm[ 5] + lm[ 2] * rm[ 9] + lm[ 3] * rm[13]; - res[2] = lm[ 0] * rm[ 2] + lm[ 1] * rm[ 6] + lm[ 2] * rm[10] + lm[ 3] * rm[14]; - res[3] = lm[ 0] * rm[ 3] + lm[ 1] * rm[ 7] + lm[ 2] * rm[11] + lm[ 3] * rm[15]; - - res[4] = lm[ 4] * rm[ 0] + lm[ 5] * rm[ 4] + lm[ 6] * rm[ 8] + lm[ 7] * rm[12]; - res[5] = lm[ 4] * rm[ 1] + lm[ 5] * rm[ 5] + lm[ 6] * rm[ 9] + lm[ 7] * rm[13]; - res[6] = lm[ 4] * rm[ 2] + lm[ 5] * rm[ 6] + lm[ 6] * rm[10] + lm[ 7] * rm[14]; - res[7] = lm[ 4] * rm[ 3] + lm[ 5] * rm[ 7] + lm[ 6] * rm[11] + lm[ 7] * rm[15]; - - res[8] = lm[ 8] * rm[ 0] + lm[ 9] * rm[ 4] + lm[10] * rm[ 8] + lm[11] * rm[12]; - res[9] = lm[ 8] * rm[ 1] + lm[ 9] * rm[ 5] + lm[10] * rm[ 9] + lm[11] * rm[13]; - res[10] = lm[ 8] * rm[ 2] + lm[ 9] * rm[ 6] + lm[10] * rm[10] + lm[11] * rm[14]; - res[11] = lm[ 8] * rm[ 3] + lm[ 9] * rm[ 7] + lm[10] * rm[11] + lm[11] * rm[15]; - - res[12] = lm[12] * rm[ 0] + lm[13] * rm[ 4] + lm[14] * rm[ 8] + lm[15] * rm[12]; - res[13] = lm[12] * rm[ 1] + lm[13] * rm[ 5] + lm[14] * rm[ 9] + lm[15] * rm[13]; - res[14] = lm[12] * rm[ 2] + lm[13] * rm[ 6] + lm[14] * rm[10] + lm[15] * rm[14]; - res[15] = lm[12] * rm[ 3] + lm[13] * rm[ 7] + lm[14] * rm[11] + lm[15] * rm[15]; - - this._m = res; - return this; - } - - multVector(vec) { - if (typeof(vec)=='object' && vec._v && vec._v.length>=3) { - vec = vec._v; - } - let x=vec[0]; - let y=vec[1]; - let z=vec[2]; - let w=1.0; - - return new bg.Vector4(this._m[0]*x + this._m[4]*y + this._m[ 8]*z + this._m[12]*w, - this._m[1]*x + this._m[5]*y + this._m[ 9]*z + this._m[13]*w, - this._m[2]*x + this._m[6]*y + this._m[10]*z + this._m[14]*w, - this._m[3]*x + this._m[7]*y + this._m[11]*z + this._m[15]*w); - } - - invert() { - let a00 = this._m[0], a01 = this._m[1], a02 = this._m[2], a03 = this._m[3], - a10 = this._m[4], a11 = this._m[5], a12 = this._m[6], a13 = this._m[7], - a20 = this._m[8], a21 = this._m[9], a22 = this._m[10], a23 = this._m[11], - a30 = this._m[12], a31 = this._m[13], a32 = this._m[14], a33 = this._m[15]; - - let b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32; - - let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) { - this.zero(); - return this; - } - else { - det = 1.0 / det; - - this._m[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - this._m[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - this._m[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - this._m[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - this._m[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - this._m[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - this._m[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - this._m[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - this._m[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - this._m[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - this._m[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - this._m[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - this._m[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - this._m[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - this._m[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - this._m[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return this; - } - } - - traspose() { - let r0 = new bg.Vector4(this._m[0], this._m[4], this._m[ 8], this._m[12]); - let r1 = new bg.Vector4(this._m[1], this._m[5], this._m[ 9], this._m[13]); - let r2 = new bg.Vector4(this._m[2], this._m[6], this._m[10], this._m[14]); - let r3 = new bg.Vector4(this._m[3], this._m[7], this._m[11], this._m[15]); - - this.setRow(0, r0); - this.setRow(1, r1); - this.setRow(2, r2); - this.setRow(3, r3); - return this; - } - - transformDirection(/* Vector3 */ dir) { - let direction = new bg.Vector3(dir); - let trx = new bg.Matrix4(this); - trx.setRow(3, new bg.Vector4(0.0, 0.0, 0.0, 1.0)); - direction.assign(trx.multVector(direction).xyz); - direction.normalize(); - return direction; - } - - get forwardVector() { - return this.transformDirection(new bg.Vector3(0.0, 0.0, 1.0)); - } - - get rightVector() { - return this.transformDirection(new bg.Vector3(1.0, 0.0, 0.0)); - } - - get upVector() { - return this.transformDirection(new bg.Vector3(0.0, 1.0, 0.0)); - } - - get backwardVector() { - return this.transformDirection(new bg.Vector3(0.0, 0.0, -1.0)); - } - - get leftVector() { - return this.transformDirection(new bg.Vector3(-1.0, 0.0, 0.0)); - } - - get downVector() { - return this.transformDirection(new bg.Vector3(0.0, -1.0, 0.0)); - } - - isNan() { - return Number.isNaN(this._m[ 0]) || Number.isNaN(this._m[ 1]) || Number.isNaN(this._m[ 2]) || Number.isNaN(this._m[ 3]) || - Number.isNaN(this._m[ 4]) || Number.isNaN(this._m[ 5]) || Number.isNaN(this._m[ 6]) || Number.isNaN(this._m[ 7]) || - Number.isNaN(this._m[ 8]) || Number.isNaN(this._m[ 9]) || Number.isNaN(this._m[10]) || Number.isNaN(this._m[11]) || - Number.isNaN(this._m[12]) || Number.isNaN(this._m[13]) || Number.isNaN(this._m[14]) || Number.isNaN(this._m[15]); - } - - getOrthoValues() { - return [ (1+get23())/get22(), - -(1-get23())/get22(), - (1-get13())/get11(), - -(1+get13())/get11(), - -(1+get03())/get00(), - (1-get03())/get00() ]; - } - - getPerspectiveValues() { - return [ get23()/(get22()-1), - get23()/(get22()+1), - near * (get12()-1)/get11(), - near * (get12()+1)/get11(), - near * (get02()-1)/get00(), - near * (get02()+1)/get00() ]; - } - - toString() { - return "[" + this._m[ 0] + ", " + this._m[ 1] + ", " + this._m[ 2] + ", " + this._m[ 3] + "]\n" + - " [" + this._m[ 4] + ", " + this._m[ 5] + ", " + this._m[ 6] + ", " + this._m[ 7] + "]\n" + - " [" + this._m[ 8] + ", " + this._m[ 9] + ", " + this._m[10] + ", " + this._m[11] + "]\n" + - " [" + this._m[12] + ", " + this._m[13] + ", " + this._m[14] + ", " + this._m[15] + "]"; - } -} - -bg.Matrix4 = Matrix4; - -})(); - -(function() { - class Vector { - static MinComponents(v1,v2) { - let length = Math.min(v1.length, v2.length); - let result = null; - switch (length) { - case 2: - result = new bg.Vector2(); - break; - case 3: - result = new bg.Vector3(); - break; - case 4: - result = new bg.Vector4(); - break; - } - - for (let i=0; iv2._v[i] ? v1._v[i] : v2._v[i]; - } - return result; - } - - constructor(v) { - this._v = v; - } - - get v() { return this._v; } - - get length() { return this._v.length; } - - get x() { return this._v[0]; } - set x(v) { this._v[0] = v; } - get y() { return this._v[1]; } - set y(v) { this._v[1] = v; } - - get module() { return this.magnitude(); } - - toArray() { - let result = []; - for (let i=0; i=2) { - this._v[0] = x[0]; - this._v[1] = x[1]; - } - else { - if (y===undefined) y=x; - this._v[0] = x; - this._v[1] = y; - } - } - - distance(other) { - let v3 = new bg.Vector2(this._v[0] - other._v[0], - this._v[1] - other._v[1]); - return v3.magnitude(); - } - - normalize() { - let m = this.magnitude(); - this._v[0] = this._v[0]/m; this._v[1]=this._v[1]/m; - return this; - } - - add(v2) { - this._v[0] += v2._v[0]; - this._v[1] += v2._v[1]; - return this; - } - - sub(v2) { - this._v[0] -= v2._v[0]; - this._v[1] -= v2._v[1]; - return this; - } - - dot(v2) { - return this._v[0] * v2._v[0] + this._v[1] * v2._v[1]; - } - - scale(scale) { - this._v[0] *= scale; this._v[1] *= scale; - return this; - } - - magnitude() { - return Math.sqrt( - this._v[0] * this._v[0] + - this._v[1] * this._v[1] - ) - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; } - - set(x, y) { - if (y===undefined) y = x; - this._v[0] = x; this._v[1] = y; - } - - get width() { return this._v[0]; } - get height() { return this._v[1]; } - set width(v) { this._v[0] = v; } - set height(v) { this._v[1] = v; } - - get aspectRatio() { return this._v[0]/this._v[1]; } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]); } - - toString() { - return "[" + this._v + "]"; - } - } - - bg.Vector2 = Vector2; - - class Vector3 extends Vector { - static Add(v1,v2) { - return new Vector3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); - } - - static Sub(v1,v2) { - return new Vector3(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); - } - - constructor(x = 0, y = 0, z = 0) { - super(new bg.Math.ArrayHighP(3)); - if (x instanceof Vector2) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = y; - } - else if (x instanceof Vector3) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = x._v[2]; - } - else if (Array.isArray(x) && x.length>=3) { - this._v[0] = x[0]; - this._v[1] = x[1]; - this._v[2] = x[2]; - } - else { - if (y===undefined) y=x; - if (z===undefined) z=y; - this._v[0] = x; - this._v[1] = y; - this._v[2] = z; - } - } - - get z() { return this._v[2]; } - set z(v) { this._v[2] = v; } - - magnitude() { - return Math.sqrt( - this._v[0] * this._v[0] + - this._v[1] * this._v[1] + - this._v[2] * this._v[2] - ); - } - - normalize() { - let m = this.magnitude(); - this._v[0] = this._v[0]/m; this._v[1]=this._v[1]/m; this._v[2]=this._v[2]/m; - return this; - } - - distance(other) { - let v3 = new bg.Vector3(this._v[0] - other._v[0], - this._v[1] - other._v[1], - this._v[2] - other._v[2]); - return v3.magnitude(); - } - - add(v2) { - this._v[0] += v2._v[0]; - this._v[1] += v2._v[1]; - this._v[2] += v2._v[2]; - return this; - } - - sub(v2) { - this._v[0] -= v2._v[0]; - this._v[1] -= v2._v[1]; - this._v[2] -= v2._v[2]; - return this; - } - - dot(v2) { - return this._v[0] * v2._v[0] + this._v[1] * v2._v[1] + this._v[2] * v2._v[2]; - } - - scale(scale) { - this._v[0] *= scale; this._v[1] *= scale; this._v[2] *= scale; - return this; - } - - cross(/* Vector3 */ v2) { - let x = this._v[1] * v2._v[2] - this._v[2] * v2._v[1]; - let y = this._v[2] * v2._v[0] - this._v[0] * v2._v[2]; - let z = this._v[0] * v2._v[1] - this._v[1] * v2._v[0]; - this._v[0]=x; this._v[1]=y; this._v[2]=z; - return this; - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1] && this._v[2]==v._v[2]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1] || this._v[2]!=v._v[2]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; if (v._v.length>=3) this._v[2]=v._v[2]; } - - set(x, y, z) { - this._v[0] = x; - this._v[1] = (y===undefined) ? x:y; - this._v[2] = (y===undefined) ? x:(z===undefined ? y:z); - } - - get width() { return this._v[0]; } - get height() { return this._v[1]; } - get depth() { return this._v[2]; } - - set width(v) { this._v[0] = v; } - set height(v) { this._v[1] = v; } - set depth(v) { this._v[2] = v; } - - get xy() { return new bg.Vector2(this._v[0],this._v[1]); } - get yz() { return new bg.Vector2(this._v[1],this._v[2]); } - get xz() { return new bg.Vector2(this._v[0],this._v[2]); } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]) || isNaN(this._v[2]); } - - toString() { - return "[" + this._v + "]"; - } - } - - bg.Vector3 = Vector3; - - class Vector4 extends Vector { - static Add(v1,v2) { - return new Vector4(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z, v1.w + v2.w); - } - - static Sub(v1,v2) { - return new Vector4(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z, v1.w - v2.w); - } - - static Yellow() { return new bg.Vector4(1.0,1.0,0.0,1.0); } - static Orange() { return new bg.Vector4(1.0,0.5,0.0,1.0); } - static Red() { return new bg.Vector4(1.0,0.0,0.0,1.0); } - static Violet() { return new bg.Vector4(0.5,0.0,1.0,1.0); } - static Blue() { return new bg.Vector4(0.0,0.0,1.0,1.0); } - static Green() { return new bg.Vector4(0.0,1.0,0.0,1.0); } - static White() { return new bg.Vector4(1.0,1.0,1.0,1.0); } - static LightGray() { return new bg.Vector4(0.8,0.8,0.8,1.0); } - static Gray() { return new bg.Vector4(0.5,0.5,0.5,1.0); } - static DarkGray() { return new bg.Vector4(0.2,0.2,0.2,1.0); } - static Black() { return new bg.Vector4(0.0,0.0,0.0,1.0); } - static Brown() { return new bg.Vector4(0.4,0.2,0.0,1.0); } - static Transparent() { return new bg.Vector4(0,0,0,0); } - - constructor(x = 0, y = 0, z = 0, w = 0) { - super(new bg.Math.ArrayHighP(4)); - if (x instanceof Vector2) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = y - this._v[3] = z; - } - else if (x instanceof Vector3) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = x._v[2]; - this._v[3] = y; - } - else if (x instanceof Vector4) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = x._v[2]; - this._v[3] = x._v[3]; - } - else if (Array.isArray(x) && x.length>=4) { - this._v[0] = x[0]; - this._v[1] = x[1]; - this._v[2] = x[2]; - this._v[3] = x[3]; - } - else { - if (y===undefined) y=x; - if (z===undefined) z=y; - if (w===undefined) w=z; - this._v[0] = x; - this._v[1] = y; - this._v[2] = z; - this._v[3] = w; - } - } - - get z() { return this._v[2]; } - set z(v) { this._v[2] = v; } - get w() { return this._v[3]; } - set w(v) { this._v[3] = v; } - - magnitude() { - return Math.sqrt( - this._v[0] * this._v[0] + - this._v[1] * this._v[1] + - this._v[2] * this._v[2] + - this._v[3] * this._v[3] - ); - } - - normalize() { - let m = this.magnitude(); - this._v[0] = this._v[0]/m; - this._v[1]=this._v[1]/m; - this._v[2]=this._v[2]/m; - this._v[3]=this._v[3]/m; - return this; - } - - distance(other) { - let v3 = new bg.Vector4(this._v[0] - other._v[0], - this._v[1] - other._v[1], - this._v[2] - other._v[2], - this._v[3] - other._v[3]); - return v3.magnitude(); - } - - add(v2) { - this._v[0] += v2._v[0]; - this._v[1] += v2._v[1]; - this._v[2] += v2._v[2]; - this._v[3] += v2._v[3]; - return this; - } - - sub(v2) { - this._v[0] -= v2._v[0]; - this._v[1] -= v2._v[1]; - this._v[2] -= v2._v[2]; - this._v[3] -= v2._v[3]; - return this; - } - - dot(v2) { - return this._v[0] * v2._v[0] + this._v[1] * v2._v[1] + this._v[2] * v2._v[2] + this._v[3] * v2._v[3]; - } - - scale(scale) { - this._v[0] *= scale; this._v[1] *= scale; this._v[2] *= scale; this._v[3] *= scale; - return this; - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1] && this._v[2]==v._v[2] && this._v[3]==v._v[3]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1] || this._v[2]!=v._v[2] || this._v[3]!=v._v[3]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; if (v._v.length>=3) this._v[2]=v._v[2]; if (v._v.length==4) this._v[3]=v._v[3]; } - - set(x, y, z, w) { - this._v[0] = x; - this._v[1] = (y===undefined) ? x:y; - this._v[2] = (y===undefined) ? x:(z===undefined ? y:z); - this._v[3] = (y===undefined) ? x:(z===undefined ? y:(w===undefined ? z:w)); - } - - get r() { return this._v[0]; } - get g() { return this._v[1]; } - get b() { return this._v[2]; } - get a() { return this._v[3]; } - - set r(v) { this._v[0] = v; } - set g(v) { this._v[1] = v; } - set b(v) { this._v[2] = v; } - set a(v) { this._v[3] = v; } - - get xy() { return new bg.Vector2(this._v[0],this._v[1]); } - get yz() { return new bg.Vector2(this._v[1],this._v[2]); } - get xz() { return new bg.Vector2(this._v[0],this._v[2]); } - get xyz() { return new bg.Vector3(this._v[0],this._v[1],this._v[2]); } - - get width() { return this._v[2]; } - get height() { return this._v[3]; } - - set width(v) { this._v[2] = v; } - set height(v) { this._v[3] = v; } - - get aspectRatio() { return this._v[3]!=0 ? this._v[2]/this._v[3]:1.0; } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]) || isNaN(this._v[2]) || isNaN(this._v[3]); } - - toString() { - return "[" + this._v + "]"; - } - } - - bg.Vector4 = Vector4; - - bg.Size2D = Vector2; - bg.Size3D = Vector3; - bg.Position2D = Vector2; - bg.Viewport = Vector4; - bg.Color = Vector4; - - class Bounds extends Vector { - constructor(a=0,b=0,c=0,d=0,e=0,f=0) { - super(new bg.Math.Array(6)); - this._v[0] = a; - this._v[1] = b; - this._v[2] = c; - this._v[3] = d; - this._v[4] = e; - this._v[5] = f; - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1] && this._v[2]==v._v[2] && this._v[3]==v._v[3] && this._v[4]==v._v[4] && this._v[5]==v._v[5]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1] || this._v[2]!=v._v[2] || this._v[3]!=v._v[3] || this._v[4]!=v._v[4] || this._v[5]!=v._v[5]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; this._v[2]=v._v[2]; this._v[3]=v._v[3]; this._v[4]=v._v[4]; this._v[5]=v._v[5]; } - - set(left, right, bottom, top, back, front) { - this._v[0] = left; - this._v[1] = (right===undefined) ? left:right; - this._v[2] = (right===undefined) ? left:bottom; - this._v[3] = (right===undefined) ? left:top; - this._v[4] = (right===undefined) ? left:back; - this._v[5] = (right===undefined) ? left:front; - } - - get left() { return this._v[0]; } - get right() { return this._v[1]; } - get bottom() { return this._v[2]; } - get top() { return this._v[3]; } - get back() { return this._v[4]; } - get front() { return this._v[5]; } - - set left(v) { this._v[0] = v; } - set right(v) { this._v[1] = v; } - set bottom(v) { this._v[2] = v; } - set top(v) { this._v[3] = v; } - set back(v) { this._v[4] = v; } - set front(v) { this._v[5] = v; } - - get width() { return Math.abs(this._v[1] - this._v[0]); } - get height() { return Math.abs(this._v[3] - this._v[2]); } - get depth() { return Math.abs(this._v[5] - this._v[4]); } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]) || isNaN(this._v[2]) || isNaN(this._v[3]) || isNaN(this._v[4]) || isNaN(this._v[5]); } - - toString() { - return "[" + this._v + "]"; - } - - isInBounds(/* vwgl.Vector3*/ v) { - return v.x>=this._v[0] && v.x<=this._v[1] && - v.y>=this._v[2] && v.y<=this._v[3] && - v.z>=this._v[4] && v.z<=this._v[5]; - } - } - - bg.Bounds = Bounds; - - class Quaternion extends Vector4 { - static MakeWithMatrix(m) { - return new Quaternion(m); - } - - constructor(a,b,c,d) { - super(); - if (a===undefined) this.zero(); - else if (b===undefined) { - if (a._v && a._v.lenght>=4) this.clone(a); - else if(a._m && a._m.length==9) this.initWithMatrix3(a); - else if(a._m && a._m.length==16) this.initWithMatrix4(a); - else this.zero(); - } - else if (a!==undefined && b!==undefined && c!==undefined && d!==undefined) { - this.initWithValues(a,b,c,d); - } - else { - this.zero(); - } - } - - initWithValues(alpha,x,y,z) { - this._v[0] = x * bg.Math.sin(alpha/2); - this._v[1] = y * bg.Math.sin(alpha/2); - this._v[2] = z * bg.Math.sin(alpha/2); - this._v[3] = bg.Math.cos(alpha/2); - return this; - } - - clone(q) { - this._v[0] = q._v[0]; - this._v[1] = q._v[1]; - this._v[2] = q._v[2]; - this._v[3] = q._v[3]; - } - - initWithMatrix3(m) { - let w = bg.Math.sqrt(1.0 + m._m[0] + m._m[4] + m._m[8]) / 2.0; - let w4 = 4.0 * w; - - this._v[0] = (m._m[7] - m._m[5]) / w; - this._v[1] = (m._m[2] - m._m[6]) / w4; - this._v[2] = (m._m[3] - m._m[1]) / w4; - this._v[3] = w; - } - - initWithMatrix4(m) { - let w = bg.Math.sqrt(1.0 + m._m[0] + m._m[5] + m._m[10]) / 2.0; - let w4 = 4.0 * w; - - this._v[0] = (m._m[9] - m._m[6]) / w; - this._v[1] = (m._m[2] - m._m[8]) / w4; - this._v[2] = (m._m[4] - m._m[1]) / w4; - this._v[3] = w; - } - - getMatrix4() { - let m = bg.Matrix4.Identity(); - let _v = this._v; - m.setRow(0, new bg.Vector4(1.0 - 2.0*_v[1]*_v[1] - 2.0*_v[2]*_v[2], 2.0*_v[0]*_v[1] - 2.0*_v[2]*_v[3], 2.0*_v[0]*_v[2] + 2.0*_v[1]*_v[3], 0.0)); - m.setRow(1, new bg.Vector4(2.0*_v[0]*_v[1] + 2.0*_v[2]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[2]*_v[2], 2.0*_v[1]*_v[2] - 2.0*_v[0]*_v[3], 0.0)); - m.setRow(2, new bg.Vector4(2.0*_v[0]*_v[2] - 2.0*_v[1]*_v[3], 2.0*_v[1]*_v[2] + 2.0*_v[0]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[1]*_v[1], 0.0)); - return m; - } - - getMatrix3() { - let m = bg.Matrix3.Identity(); - let _v = this._v; - - m.setRow(0, new bg.Vector3(1.0 - 2.0*_v[1]*_v[1] - 2.0*_v[2]*_v[2], 2.0*_v[0]*_v[1] - 2.0*_v[2]*_v[3], 2.0*_v[0]*_v[2] + 2.0*_v[1]*_v[3])); - m.setRow(1, new bg.Vector3(2.0*_v[0]*_v[1] + 2.0*_v[2]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[2]*_v[2], 2.0*_v[1]*_v[2] - 2.0*_v[0]*_v[3])); - m.setRow(2, new bg.Vector3(2.0*_v[0]*_v[2] - 2.0*_v[1]*_v[3], 2.0*_v[1]*_v[2] + 2.0*_v[0]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[1]*_v[1])); - return m; - } - } - - bg.Quaternion = Quaternion; - -})(); - -bg.physics = {}; -(function() { - - bg.physics.IntersectionType = { - NONE:0, - POINT:1, - LLINE:2 - }; - - class Intersection { - - static RayToPlane(ray,plane) { - return new bg.physics.RayToPlaneIntersection(ray,plane); - } - - constructor() { - this._type = null; - this._p0 = null; - this._p1 = null; - } - - get type() { return this._type; } - get point() { return this._p0; } - get endPoint() { return this._p1; } - - intersects() { return false; } - } - - bg.physics.Intersection = Intersection; - - class RayToPlaneIntersection extends bg.physics.Intersection { - constructor(ray,plane) { - super(); - this._ray = null; - this._p0 = null; - - this._type = bg.physics.IntersectionType.POINT; - let p0 = new bg.Vector3(plane.origin); - let n = new bg.Vector3(plane.normal); - let l0 = new bg.Vector3(ray.start); - let l = new bg.Vector3(ray.vector); - let num = p0.sub(l0).dot(n); - let den = l.dot(n); - - if (den==0) return; - let d = num/den; - if (d>ray.magnitude) return; - - this._ray = bg.physics.Ray.RayWithVector(ray.vector,ray.start,d); - this._p0 = this._ray.end; - } - - get ray() { - return this._ray; - } - - intersects() { - return (this._ray!=null && this._p0!=null); - } - } - - bg.physics.RayToPlaneIntersection = RayToPlaneIntersection; - - -})(); -(function() { - - class Joint { - static Factory(linkData) { - switch (linkData.type) { - case 'LinkJoint': - return LinkJoint.Factory(linkData); - break; - } - return null; - } - - constructor() { - this._transform = bg.Matrix4.Identity(); - } - - get transform() { return this._transform; } - set transform(t) { this._transform = t; } - - applyTransform(matrix) { - - } - - calculateTransform() { - - } - } - - bg.physics.Joint = Joint; - - bg.physics.LinkTransformOrder = { - TRANSLATE_ROTATE:1, - ROTATE_TRANSLATE:0 - } - - class LinkJoint extends Joint { - static Factory(data) { - let result = new LinkJoint(); - result.offset = new bg.Vector3( - data.offset[0] || 0, - data.offset[1] || 0, - data.offset[2] || 0 - ); - result.yaw = data.yaw || 0; - result.pitch = data.pitch || 0; - result.roll = data.roll || 0; - result.order = data.order || 1; - return result; - } - - constructor() { - super(); - this._offset = new bg.Vector3(); - this._eulerRotation = new bg.Vector3(); - - this._transformOrder = bg.physics.LinkTransformOrder.TRANSLATE_ROTATE; - } - - applyTransform(matrix) { - matrix.mult(this.transform); - } - - assign(j) { - this.yaw = j.yaw; - this.pitch = j.pitch; - this.roll = j.roll; - this.offset.assign(j.offset); - this.transformOrder = j.transformOrder; - } - - get offset() { return this._offset; } - set offset(o) { this._offset = o; this.calculateTransform(); } - - get eulerRotation() { return this._eulerRotation; } - set eulerRotation(r) { this._eulerRotation = r; this.calculateTransform(); } - - get yaw() { return this._eulerRotation.x; } - get pitch() { return this._eulerRotation.y; } - get roll() { return this._eulerRotation.z; } - - set yaw(y) { this._eulerRotation.x = y; this.calculateTransform(); } - set pitch(p) { this._eulerRotation.y = p; this.calculateTransform(); } - set roll(r) { this._eulerRotation.z = r; this.calculateTransform(); } - - get transformOrder() { return this._transformOrder; } - set transformOrder(o) { this._transformOrder = o; this.calculateTransform(); } - - multTransform(dst) { - let offset = this.offset; - switch (this.transformOrder) { - case bg.physics.LinkTransformOrder.TRANSLATE_ROTATE: - dst.translate(offset.x,offset.y,offset.z); - this.multRotation(dst); - break; - case bg.physics.LinkTransformOrder.ROTATE_TRANSLATE: - this.multRotation(dst); - dst.translate(offset.x,offset.y,offset.z); - break; - } - } - - multRotation(dst) { - dst.rotate(this.eulerRotation.z, 0,0,1) - .rotate(this.eulerRotation.y, 0,1,0) - .rotate(this.eulerRotation.x, 1,0,0); - } - - calculateTransform() { - this.transform.identity(); - this.multTransform(this.transform); - } - - serialize(data) { - data.type = "LinkJoint"; - data.offset = [ - this.offset.x, - this.offset.y, - this.offset.z - ]; - data.yaw = this.yaw; - data.pitch = this.pitch; - data.roll = this.roll; - data.order = this.order; - } - } - - bg.physics.LinkJoint = LinkJoint; -})(); -(function() { - - class Plane { - // a = normal: create a plane with origin=(0,0,0) and normal=a - // a = normal, b = origin: create a plane with origin=b and normal=a - // a = p1, b = p2, c = p3: create a plane that contains the points p1, p2 and p3 - constructor(a, b, c) { - a = a instanceof bg.Vector3 && a; - b = b instanceof bg.Vector3 && b; - c = c instanceof bg.Vector3 && c; - if (a && !b) { - this._normal = new bg.Vector3(a); - this._origin = new bg.Vector3(0); - } - else if (a && b && !c) { - this._normal = new bg.Vector3(a); - this._origin = new bg.Vector3(b); - } - else if (a && b && c) { - var vec1 = new bg.Vector3(a); vec1.sub(b); - var vec2 = new bg.Vector3(c); vec2.sub(a); - this._origin = new bg.Vector3(p1); - this._normal = new bg.Vector3(vec1); - this._normal.cross(vec2).normalize(); - } - else { - this._origin = new bg.Vector3(0); - this._normal = new bg.Vector3(0,1,0); - } - } - - get normal() { return this._normal; } - set normal(n) { this._normal.assign(n); } - - get origin() { return this._origin; } - set origin(o) { this._origin.assign(o); } - - toString() { - return `P0: ${this._origin.toString()}, normal:${this._normal.toString()}`; - } - - valid() { return !this._origin.isNan() && !this._normal.isNan(); } - - assign(p) { - this._origin.assign(p._origin); - this._normal.assign(p._normal); - return this; - } - - equals(p) { - return this._origin.equals(p._origin) && this._normal.equals(p._normal); - } - } - - bg.physics.Plane = Plane; - -})(); -(function() { - - function calculateVector(ray) { - ray._vector = new bg.Vector3(ray._end); - ray._vector.sub(ray._start); - ray._magnitude = ray._vector.magnitude(); - ray._vector.normalize(); - } - - class Ray { - static RayWithPoints(start,end) { - return new Ray(start,end); - } - - static RayWithVector(vec,origin,maxDepth) { - let r = new Ray(); - r.setWithVector(vec,origin,maxDepth); - return r; - } - - static RayWithScreenPoint(screenPoint,projMatrix,viewMatrix,viewport) { - let r = new Ray(); - r.setWithScreenPoint(screenPoint,projMatrix,viewMatrix,viewport); - return r; - } - - - constructor(start,end) { - this._start = start || new bg.Vector3(); - this._end = end || new bg.Vector3(1); - calculateVector(this); - } - - setWithPoints(start,end) { - this._start.assign(start); - this._end.assign(end); - calculateVector(); - return this; - } - - setWithVector(vec,origin,maxDepth) { - this._start.assign(origin); - this._end.assign(origin); - let vector = new bg.Vector3(vec); - vector.normalize().scale(maxDepth); - this._end.add(vector); - calculateVector(this); - return this; - } - - setWithScreenPoint(screenPoint,projMatrix,viewMatrix,viewport) { - let start = bg.Matrix4.Unproject(screenPoint.x, screenPoint.y, 0, viewMatrix, projMatrix, viewport); - let end = bg.Matrix4.Unproject(screenPoint.x, screenPoint.y, 1, viewMatrix, projMatrix, viewport); - this._start = start.xyz; - this._end = end.xyz; - calculateVector(this); - return this; - } - - assign(r) { - this._start.assign(r.start); - this._end.assign(r.end); - this._vector.assign(r.vector); - this._magnitude.assign(r.magnitude); - } - - get start() { return this._start; } - set start(s) { this._start.assign(s); calculateVector(this); } - - get end() { return this._end; } - set end(e) { this._end.assign(e); } - - get vector() { return this._vector; } - - get magnitude() { return this._magnitude; } - - toString() { - return `start: ${this.start.toString()}, end: ${this.end.toString()}`; - } - } - - bg.physics.Ray = Ray; - -})() - -bg.scene = {}; - -(function() { - - let s_componentRegister = {}; - - class Component extends bg.LifeCycle { - static Factory(context,componentData,node,url) { - let Constructor = s_componentRegister[componentData.type]; - if (Constructor) { - let instance = new Constructor(); - node.addComponent(instance); - return instance.deserialize(context,componentData,url); - } - else { - return Promise.resolve(); - } - - } - - constructor() { - super(); - - this._node = null; - - this._drawGizmo = true; - } - - clone() { - bg.log(`WARNING: Component with typeid ${this.typeId} does not implmement the clone() method.`); - return null; - } - - destroy() { - - } - - get node() { return this._node; } - - get typeId() { return this._typeId; } - - get draw3DGizmo() { return this._drawGizmo; } - set draw3DGizmo(d) { this._drawGizmo = d; } - - removedFromNode(node) {} - addedToNode(node) {} - - // Override this to prevent serialize this component - get shouldSerialize() { return true; } - - deserialize(context,sceneData,url) { - return Promise.resolve(this); - } - - // componentData: the current json object corresponding to the parent node - // promises: array of promises. If the component needs to execute asynchronous - // actions, it can push one or more promises into this array - // url: the destination scene url, composed by: - // { - // path: "scene path, using / as separator even on Windows", - // fileName: "scene file name" - // } - serialize(componentData,promises,url) { - componentData.type = this.typeId.split(".").pop(); - } - - // The following functions are implemented in the SceneComponent class, in the C++ API - component(typeId) { return this._node && this._node.component(typeId); } - - get camera() { return this.component("bg.scene.Camera"); } - get chain() { return this.component("bg.scene.Chain"); } - get drawable() { return this.component("bg.scene.Drawable"); } - get inputChainJoint() { return this.component("bg.scene.InputChainJoint"); } - get outputChainJoint() { return this.component("bg.scene.OutputChainJoint"); } - get light() { return this.component("bg.scene.Light"); } - get transform() { return this.component("bg.scene.Transform"); } - } - - bg.scene.Component = Component; - - bg.scene.registerComponent = function(namespace,componentClass,identifier) { - let result = /function (.+)\(/.exec(componentClass.toString()); - if (!result) { - result = /class ([a-zA-Z0-9_]+) /.exec(componentClass.toString()); - } - let funcName = (result && result.length>1) ? result[1] : ""; - - namespace[funcName] = componentClass; - componentClass.prototype._typeId = identifier || funcName; - - - s_componentRegister[funcName] = componentClass; - } - -})(); -(function() { - class SceneObjectLifeCycle extends bg.LifeCycle { - // This class reimplements the bg.app.ContextObject due to the lack - // in JavaScript of multiple ihneritance - - constructor(context) { - super(context); - - this._context = context; - } - - get context() { return this._context; } - set context(c) { this._context = c; } - } - - function updateComponentsArray() { - this._componentsArray = []; - for (let key in this._components) { - this._components[key] && this._componentsArray.push(this._components[key]); - } - } - - class SceneObject extends SceneObjectLifeCycle { - - constructor(context,name="") { - super(context); - - this._name = name; - this._enabled = true; - this._steady = false; - - this._components = {}; - this._componentsArray = []; - } - - toString() { - return " scene object: " + this._name; - } - - // Create a new instance of this node, with a copy of all it's components - cloneComponents() { - let newNode = new bg.scene.Node(this.context,this.name ? `copy of ${this.name}`:""); - newNode.enabled = this.enabled; - this.forEachComponent((comp) => { - newNode.addComponent(comp.clone()); - }); - return newNode; - } - - get name() { return this._name; } - set name(n) { this._name = n; } - - get enabled() { return this._enabled; } - set enabled(e) { this._enabled = e; } - - get steady() { return this._steady; } - set steady(s) { this._steady = s; } - - addComponent(c) { - if (c._node) { - c._node.removeComponent(c); - } - c._node = this; - this._components[c.typeId] = c; - c.addedToNode(this); - updateComponentsArray.apply(this); - } - - // It's possible to remove a component by typeId or by the specific object. - // - typeId: if the scene object contains a component of this type, will be removed - // - specific object: if the scene object contains the specified object, will be removed - removeComponent(findComponent) { - let typeId = ""; - let comp = null; - if (typeof(findComponent)=="string") { - typeId = findComponent - comp = this.component(findComponent); - } - else if (findComponent instanceof bg.scene.Component) { - comp = findComponent; - typeId = findComponent.typeId; - } - - let status = false; - if (this._components[typeId]==comp && comp!=null) { - delete this._components[typeId]; - comp.removedFromNode(this); - status = true; - } - - updateComponentsArray.apply(this); - return status; - } - - component(typeId) { - return this._components[typeId]; - } - - // Most common components - get camera() { return this.component("bg.scene.Camera"); } - get chain() { return this.component("bg.scene.Chain"); } - get drawable() { return this.component("bg.scene.Drawable"); } - get inputJoint() { return this.component("bg.scene.InputJoint"); } - get outputJoint() { return this.component("bg.scene.OutputJoint"); } - get light() { return this.component("bg.scene.Light"); } - get transform() { return this.component("bg.scene.Transform"); } - - forEachComponent(callback) { - this._componentsArray.forEach(callback); - } - - someComponent(callback) { - return this._componentsArray.some(callback); - } - - everyComponent(callback) { - return this._componentsArray.every(callback); - } - - destroy() { - this.forEachComponent((comp) => { - comp.removedFromNode(this); - }); - - this._components = {}; - this._componentsArray = []; - } - - init() { - this._componentsArray.forEach((comp) => { - comp.init(); - }); - } - - frame(delta) { - this._componentsArray.forEach((comp) => { - if (!comp._initialized_) { - comp.init(); - comp._initialized_ = true; - } - comp.frame(delta); - }); - } - - displayGizmo(pipeline,matrixState) { - this._componentsArray.forEach((comp) => { - if (comp.draw3DGizmo) comp.displayGizmo(pipeline,matrixState); - }); - } - - /////// Direct rendering methods: will be deprecated soon - willDisplay(pipeline,matrixState) { - this._componentsArray.forEach((comp) => { - comp.willDisplay(pipeline,matrixState); - }); - } - - display(pipeline,matrixState,forceDraw=false) { - this._componentsArray.forEach((comp) => { - comp.display(pipeline,matrixState,forceDraw); - }); - } - - - didDisplay(pipeline,matrixState) { - this._componentsArray.forEach((comp) => { - comp.didDisplay(pipeline,matrixState); - }); - } - //////// End direct rendering methods - - - ////// Render queue methods - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - this._componentsArray.forEach((comp) => { - comp.willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack); - }); - } - - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - this._componentsArray.forEach((comp) => { - comp.draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack); - }); - } - - didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - this._componentsArray.forEach((comp) => { - comp.didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack); - }); - } - ////// End render queue methods - - - reshape(pipeline,matrixState,width,height) { - this._componentsArray.forEach((comp) => { - comp.reshape(width,height); - }); - } - - keyDown(evt) { - this._componentsArray.forEach((comp) => { - comp.keyDown(evt); - }); - } - - keyUp(evt) { - this._componentsArray.forEach((comp) => { - comp.keyUp(evt); - }); - } - - mouseUp(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseUp(evt); - }); - } - - mouseDown(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseDown(evt); - }); - } - - mouseMove(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseMove(evt); - }); - } - - mouseOut(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseOut(evt); - }); - } - - mouseDrag(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseDrag(evt); - }); - } - - mouseWheel(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseWheel(evt); - }); - } - - touchStart(evt) { - this._componentsArray.forEach((comp) => { - comp.touchStart(evt); - }); - } - - touchMove(evt) { - this._componentsArray.forEach((comp) => { - comp.touchMove(evt); - }); - } - - touchEnd(evt) { - this._componentsArray.forEach((comp) => { - comp.touchEnd(evt); - }); - } - } - - bg.scene.SceneObject = SceneObject; - -})(); -(function() { - - function isNodeAncient(node, ancient) { - if (!node || !ancient) { - return false; - } - else if (node._parent==ancient) { - return true; - } - else { - return isNodeAncient(node._parent, ancient); - } - } - - function cleanupNode(sceneNode) { - let components = []; - let children = []; - sceneNode.forEachComponent((c) => components.push(c)); - sceneNode.children.forEach((child) => children.push(child)); - components.forEach((c) => sceneNode.removeComponent(c)); - children.forEach((child) => { - sceneNode.removeChild(child); - cleanupNode(child); - }); - } - - class Node extends bg.scene.SceneObject { - // IMPORTANT: call this function to clean all the resources of - // a node if you don't want to use it anymore. - static CleanupNode(node) { - cleanupNode(node); - } - - constructor(context,name="") { - super(context,name); - - this._children = []; - this._parent = null; - } - - toString() { - return super.toString() + " (" + this._children.length + " children and " + Object.keys(this._components).length + " components)"; - } - - addChild(child) { - if (child && !this.isAncientOf(child) && child!=this) { - if (child.parent) { - child.parent.removeChild(child); - } - this._children.push(child); - child._parent = this; - } - } - - removeChild(node) { - let index = this._children.indexOf(node); - if (index>=0) { - this._children.splice(index,1); - } - } - - get children() { return this._children; } - - get parent() { return this._parent; } - - get sceneRoot() { - if (this._parent) { - return this._parent.sceneRoot(); - } - return this; - } - - haveChild(node) { - return this._children.indexOf(node)!=-1; - } - - isAncientOf(node) { - isNodeAncient(this,node); - } - - accept(nodeVisitor) { - if (!nodeVisitor.ignoreDisabled || this.enabled) { - nodeVisitor.visit(this); - this._children.forEach((child) => { - child.accept(nodeVisitor); - }); - nodeVisitor.didVisit(this); - } - } - - acceptReverse(nodeVisitor) { - if (!nodeVisitor.ignoreDisabled || this.enabled) { - if (this._parent) { - this._parent.acceptReverse(nodeVisitor); - } - nodeVisitor.visit(this); - } - } - - destroy() { - super.destroy(); - this._children.forEach((child) => { - child.destroy(); - }); - this._children = []; - } - - } - - bg.scene.Node = Node; - - class NodeVisitor { - constructor() { - this._ignoreDisabled = true; - } - - get ignoreDisabled() { return this._ignoreDisabled; } - - set ignoreDisabled(v) { this._ignoreDisabled = v; } - - visit(node) {} - didVisit(node) {} - } - - bg.scene.NodeVisitor = NodeVisitor; -})(); -(function() { - - class ProjectionStrategy extends bg.MatrixStrategy { - static Factory(jsonData) { - let result = null; - if (jsonData) { - if (jsonData.type=="PerspectiveProjectionMethod") { - result = new PerspectiveProjectionStrategy(); - } - else if (jsonData.type=="OpticalProjectionMethod") { - result = new OpticalProjectionStrategy(); - } - else if (jsonData.type=="OrthographicProjectionStrategy") { - result = new OrthographicProjectionStrategy(); - } - - if (result) { - result.deserialize(jsonData); - } - } - return result; - } - - constructor(target) { - super(target); - - this._near = 0.1; - this._far = 100.0; - this._viewport = new bg.Viewport(0,0,512,512); - } - - clone() { console.log("WARNING: ProjectionStrategy::clone() method not implemented by child class."); } - - get near() { return this._near; } - set near(n) { this._near = n; } - get far() { return this._far; } - set far(f) { this._far = f; } - get viewport() { return this._viewport; } - set viewport(vp) { this._viewport = vp; } - - get fov() { return 0; } - - serialize(jsonData) { - jsonData.near = this.near; - jsonData.far = this.far; - } - } - - bg.scene.ProjectionStrategy = ProjectionStrategy; - - class PerspectiveProjectionStrategy extends ProjectionStrategy { - constructor(target) { - super(target); - this._fov = 60; - } - - clone() { - let result = new PerspectiveProjectionStrategy(); - result.near = this.near; - result.far = this.far; - result.viewport = this.viewport; - result.fov = this.fov; - return result; - } - - get fov() { return this._fov; } - set fov(f) { this._fov = f; } - - apply() { - if (this.target) { - this.target.perspective(this.fov, this.viewport.aspectRatio, this.near, this.far); - } - } - - deserialize(jsonData) { - this.near = jsonData.near; - this.far = jsonData.far; - this.fov = jsonData.fov; - } - - serialize(jsonData) { - jsonData.type = "PerspectiveProjectionMethod"; - jsonData.fov = this.fov; - super.serialize(jsonData); - } - } - - bg.scene.PerspectiveProjectionStrategy = PerspectiveProjectionStrategy; - - class OpticalProjectionStrategy extends ProjectionStrategy { - constructor(target) { - super(target); - this._focalLength = 50; - this._frameSize = 35; - } - - clone() { - let result = new OpticalProjectionStrategy(); - result.near = this.near; - result.far = this.far; - result.viewport = this.viewport; - result.focalLength = this.focalLength; - result.frameSize = this.frameSize; - return result; - } - - get focalLength() { return this._focalLength; } - set focalLength(fl) { this._focalLength = fl; } - get frameSize() { return this._frameSize; } - set frameSize(s) { this._frameSize = s; } - - get fov() { - return 2 * bg.Math.atan(this.frameSize / (this.focalLength / 2)); - } - - apply() { - if (this.target) { - let fov = this.fov; - fov = bg.Math.radiansToDegrees(fov); - this.target.perspective(fov, this.viewport.aspectRatio, this.near, this.far); - } - } - - deserialize(jsonData) { - this.frameSize = jsonData.frameSize; - this.focalLength = jsonData.focalLength; - this.near = jsonData.near; - this.far = jsonData.far; - } - - serialize(jsonData) { - jsonData.type = "OpticalProjectionMethod"; - jsonData.frameSize = this.frameSize; - jsonData.focalLength = this.focalLength; - super.serialize(jsonData); - } - } - - bg.scene.OpticalProjectionStrategy = OpticalProjectionStrategy; - - class OrthographicProjectionStrategy extends ProjectionStrategy { - constructor(target) { - super(target); - this._viewWidth = 100; - } - - clone() { - let result = new OrthographicProjectionStrategy(); - result.near = this.near; - result.far = this.far; - result.viewWidth = this.viewWidth; - return result; - } - - get viewWidth() { return this._viewWidth; } - set viewWidth(w) { this._viewWidth = w; } - - apply() { - if (this.target) { - let ratio = this.viewport.aspectRatio; - let height = this.viewWidth / ratio; - let x = this.viewWidth / 2; - let y = height / 2; - this.target.ortho(-x, x, -y, y, -this._far, this._far); - } - } - - deserialize(jsonData) { - this.viewWidth = jsonData.viewWidth; - this.near = jsonData.near; - this.far = jsonData.far; - } - - serialize(jsonData) { - jsonData.type = "OrthographicProjectionStrategy"; - jsonData.viewWidth = this.viewWidth; - jsonData.near = this.near; - jsonData.far = this.far; - super.serialize(jsonData); - } - } - - bg.scene.OrthographicProjectionStrategy = OrthographicProjectionStrategy; - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i clearMain(child)); - } - - class Camera extends bg.scene.Component { - - static SetAsMainCamera(mainCamera,sceneRoot) { - clearMain(sceneRoot); - if (mainCamera instanceof Camera) { - mainCamera.isMain = true; - } - else if (mainCamera instanceof bg.scene.Node && mainCamera.camera) { - mainCamera.camera.isMain = true; - } - else { - throw new Error("Error setting main camera: invalid camera node."); - } - } - - constructor() { - super(); - - this._projection = bg.Matrix4.Perspective(60,1,0.1,100.0); - this._viewport = new bg.Viewport(0,0,512,512); - - this._visitor = new bg.scene.TransformVisitor(); - this._rebuildTransform = true; - - this._position = new bg.Vector3(0); - this._rebuildPosition = true; - - this._clearBuffers = bg.base.ClearBuffers.COLOR_DEPTH; - - this._focus = 5; // default 5 meters - - this._projectionStrategy = null; - - this._isMain = false; - } - - clone() { - let newCamera = new bg.scene.Camera(); - newCamera._projection = new bg.Matrix4(this._projection); - newCamera._viewport = new bg.Matrix4(this._viewport); - newCamera._projectionStrategy = this._projectionStrategy ? this._projectionStrategy.clone() : null; - return newCamera; - } - - get projection() { return this._projection; } - set projection(p) { - if (!this._projectionStrategy) { - this._projection = p; - } - } - - get viewport() { return this._viewport; } - set viewport(v) { - this._viewport = v; - if (this._projectionStrategy) { - this._projectionStrategy.viewport = v; - this._projectionStrategy.apply(); - } - } - - get focus() { return this._focus; } - set focus(f) { this._focus = f; this.recalculateGizmo() } - - get isMain() { return this._isMain; } - set isMain(m) { - this._isMain = m; - } - - get projectionStrategy() { return this._projectionStrategy; } - set projectionStrategy(ps) { - this._projectionStrategy = ps; - if (this._projectionStrategy) { - this._projectionStrategy.target = this._projection; - } - this.recalculateGizmo() - } - - get clearBuffers() { return this._clearBuffers; } - set clearBuffers(c) { this._clearBuffers = c; } - - get modelMatrix() { - if (this._rebuildTransform && this.node) { - this._visitor.matrix.identity(); - this.node.acceptReverse(this._visitor); - this._rebuildTransform = false; - } - return this._visitor.matrix; - } - - get viewMatrix() { - if (!this._viewMatrix || this._rebuildTransform) { - this._viewMatrix = new bg.Matrix4(this.modelMatrix); - this._viewMatrix.invert(); - } - return this._viewMatrix; - } - - get worldPosition() { - if (this._rebuildPosition) { - this._position = this.modelMatrix.multVector(new bg.Vector3(0)).xyz - this._rebuildPosition = false; - this._rebuildTransform = true; - } - return this._position; - } - - recalculateGizmo() { - if (this._gizmo) { - this._gizmo.destroy(); - this._gizmo = null; - } - } - - frame(delta) { - this._rebuildPosition = true; - this._rebuildTransform = true; - } - - displayGizmo(pipeline,matrixState) { - if (this.isMain) return; // Do not render the main camera plist - let plist = getGizmo.apply(this); - if (plist) { - pipeline.draw(plist); - } - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.isMain = this.isMain; - if (this.projectionStrategy) { - let projMethod = {}; - componentData.projectionMethod = projMethod; - this.projectionStrategy.serialize(projMethod); - } - } - - deserialize(context,sceneData,url) { - sceneData.isMain = sceneData.isMain || false; - this.projectionStrategy = ProjectionStrategy.Factory(sceneData.projectionMethod || {}); - } - } - - bg.scene.registerComponent(bg.scene,Camera,"bg.scene.Camera"); -})(); -(function() { - - let GizmoType = { - IN_JOINT: 0, - OUT_JOINT: 1 - } - - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i { - let trx = child.component("bg.scene.Transform"); - let inJoint = child.component("bg.scene.InputChainJoint"); - let outJoint = child.component("bg.scene.OutputChainJoint"); - - if (index>0 && inJoint) { - inJoint.joint.applyTransform(matrix); - } - else { - matrix.identity(); - } - - if (trx) { - trx.matrix.assign(matrix); - } - - if (outJoint) { - outJoint.joint.applyTransform(matrix); - } - }); - } - } - - class Chain extends bg.scene.Component { - constructor() { - super(); - } - - clone() { - return new bg.scene.Chain(); - } - - - ////// Direct rendering functions: will be deprecated soon - willDisplay(pipeline,matrixState,projectionMatrixStack) { - updateJointTransforms.apply(this); - } - - ////// Render queue functions - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - updateJointTransforms.apply(this); - } - } - - bg.scene.registerComponent(bg.scene,Chain,"bg.scene.Chain"); - - class ChainJoint extends bg.scene.Component { - constructor() { - super(); - - this._joint = new bg.physics.LinkJoint(); - } - - get joint() { return this._joint; } - set joint(j) { this._joint = j; } - - deserialize(context,sceneData,url) { - if (sceneData.joint) { - this.joint = bg.physics.Joint.Factory(sceneData.joint); - } - } - } - - bg.scene.ChainJoint = ChainJoint; - - class InputChainJoint extends ChainJoint { - constructor(joint) { - super(); - if (joint) { - this.joint = joint; - } - else { - this.joint.transformOrder = bg.physics.LinkTransformOrder.ROTATE_TRANSLATE; - } - } - - clone() { - let newJoint = new bg.scene.InputChainJoint(); - newJoint.joint.assign(this.joint); - return newJoint; - } - - displayGizmo(pipeline,matrixState) { - let plist = getGizmo.apply(this,[0]); - if (plist) { - matrixState.modelMatrixStack.push(); - let mat = new bg.Matrix4(this.joint.transform); - mat.invert(); - matrixState.modelMatrixStack.mult(mat); - pipeline.draw(plist); - matrixState.modelMatrixStack.pop(); - } - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.joint = {}; - this.joint.serialize(componentData.joint); - } - } - - bg.scene.registerComponent(bg.scene,InputChainJoint,"bg.scene.InputChainJoint"); - - - class OutputChainJoint extends ChainJoint { - constructor(joint) { - super(); - if (joint) { - this.joint = joint; - } - else { - this.joint.transformOrder = bg.physics.LinkTransformOrder.TRANSLATE_ROTATE; - } - } - - clone() { - let newJoint = new bg.scene.OutputChainJoint(); - newJoint.joint.assign(this.joint); - return newJoint; - } - - displayGizmo(pipeline,matrixState) { - let plist = getGizmo.apply(this,[1]); - if (plist) { - matrixState.modelMatrixStack.push(); - let mat = new bg.Matrix4(this.joint.transform); - matrixState.modelMatrixStack.mult(mat); - pipeline.draw(plist); - matrixState.modelMatrixStack.pop(); - } - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.joint = {}; - this.joint.serialize(componentData.joint); - } - } - - bg.scene.registerComponent(bg.scene,OutputChainJoint,"bg.scene.OutputChainJoint"); - -})(); -(function() { - bg.scene.CubemapImage = { - POSITIVE_X: 0, - NEGATIVE_X: 1, - POSITIVE_Y: 2, - NEGATIVE_Y: 3, - POSITIVE_Z: 4, - NEGATIVE_Z: 5, - }; - - let g_currentCubemap = null; - - function copyCubemapImage(componentData,cubemapImage,dstPath) { - let path = require("path"); - let src = bg.base.Writer.StandarizePath(this.getImageUrl(cubemapImage)); - let file = src.split('/').pop(); - let dst = bg.base.Writer.StandarizePath(path.join(dstPath,file)); - switch (cubemapImage) { - case bg.scene.CubemapImage.POSITIVE_X: - componentData.positiveX = file; - break; - case bg.scene.CubemapImage.NEGATIVE_X: - componentData.negativeX = file; - break; - case bg.scene.CubemapImage.POSITIVE_Y: - componentData.positiveY = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Y: - componentData.negativeY = file; - break; - case bg.scene.CubemapImage.POSITIVE_Z: - componentData.positiveZ = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Z: - componentData.negativeZ = file; - break; - } - return bg.base.Writer.CopyFile(src,dst); - } - - class Cubemap extends bg.scene.Component { - static Current(context) { - if (!g_currentCubemap) { - g_currentCubemap = bg.base.TextureCache.WhiteCubemap(context); - } - return g_currentCubemap; - } - - constructor() { - super(); - this._images = [null, null, null, null, null, null]; - this._texture = null; - } - - setImageUrl(imgCode,texture) { - this._images[imgCode] = texture; - } - - getImageUrl(imgCode) { - return this._images[imgCode]; - } - - get texture() { - return this._texture; - } - - loadCubemap(context) { - context = context || this.node && this.node.context; - return new Promise((resolve,reject) => { - bg.utils.Resource.LoadMultiple(this._images) - .then((result) => { - this._texture = new bg.base.Texture(context); - this._texture.target = bg.base.TextureTarget.CUBE_MAP; - this._texture.create(); - this._texture.bind(); - - this._texture.setCubemap( - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Z)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Z)] - ); - - g_currentCubemap = this._texture; - bg.emitImageLoadEvent(result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)]); - resolve(this); - }) - - .catch((err) => { - reject(err); - }); - }); - } - - clone() { - let cubemap = new Cubemap(); - for (let code in this._images) { - cubemap._images[code] = this._images[code]; - }; - cubemap._texture = this._texture; - return cubemap; - } - - deserialize(context,sceneData,url) { - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["positiveX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["negativeX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["positiveY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["negativeY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["positiveZ"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["negativeZ"]) - ); - return this.loadCubemap(context); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - if (!bg.isElectronApp) return; - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Z,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Z,url.path])); - } - } - - bg.scene.registerComponent(bg.scene,Cubemap,"bg.scene.Cubemap"); -})(); -(function() { - - function escapePathCharacters(name) { - if (!name) { - return bg.utils.generateUUID(); - } - else { - var illegalRe = /[\/\?<>\\:\*\|":\[\]\(\)\{\}]/g; - var controlRe = /[\x00-\x1f\x80-\x9f]/g; - var reservedRe = /^\.+$/; - var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; - var windowsTrailingRe = /[\. ]+$/; - - function sanitize(input, replacement) { - var sanitized = input - .replace(illegalRe, replacement) - .replace(controlRe, replacement) - .replace(reservedRe, replacement) - .replace(windowsReservedRe, replacement) - .replace(windowsTrailingRe, replacement); - return sanitized; - } - - return sanitize(name,'-'); - } - } - class Drawable extends bg.scene.Component { - - // It creates a copy of the node with all its components, except the drawable - // component, that will be an instance (share the same polyList instances) - static InstanceNode(node) { - let newNode = new bg.scene.Node(node.context,node.name ? `copy of ${node.name}`:""); - newNode.enabled = node.enabled; - node.forEachComponent((comp) => { - let newComp = null; - if (comp instanceof Drawable) { - newComp = comp.instance(); - } - else { - newComp = comp.clone(); - } - newNode.addComponent(newComp); - }); - return newNode; - } - - constructor(name="") { - super(); - - this._name = name; - this._items = []; // { polyList:p, material:m, transform:t } - } - - get name() { return this._name; } - set name(n) { this._name = n; } - - clone(newName) { - let newInstance = new bg.scene.Drawable(); - newInstance.name = newName || `copy of ${this.name}`; - this.forEach((plist,material,trx) => { - newInstance.addPolyList(plist.clone(), material.clone(), trx ? new bg.Matrix4(trx):null); - }); - return newInstance; - } - - destroy() { - this.forEach((plist) => { - plist.destroy(); - }); - this._name = ""; - this._items = []; - } - - // It works as clone(), but it doesn't duplicate the polyList - instance(newName) { - let newInstance = new bg.scene.Drawable(); - newInstance.name = newName || `copy of ${this.name}`; - this.forEach((plist,material,trx) => { - newInstance.addPolyList(plist, material.clone(), trx ? new bg.Matrix4(trx):null); - }); - return newInstance; - } - - addPolyList(plist,mat,trx=null) { - if (plist && this.indexOf(plist)==-1) { - mat = mat || new bg.base.Material(); - - this._items.push({ - polyList:plist, - material:mat, - transform:trx - }); - return true; - } - return false; - } - - getExternalResources(resources = []) { - this.forEach((plist,material) => { - material.getExternalResources(resources) - }); - return resources; - } - - // Apply a material definition object to the polyLists - applyMaterialDefinition(materialDefinitions,resourcesUrl) { - let promises = []; - this.forEach((plist,mat) => { - let definition = materialDefinitions[plist.name]; - if (definition) { - promises.push(new Promise((resolve,reject) => { - let modifier = new bg.base.MaterialModifier(definition); - mat.applyModifier(plist.context,modifier,resourcesUrl); - resolve(); - })); - } - }); - return Promise.all(promises); - } - - removePolyList(plist) { - let index = -1; - this._items.some((item, i) => { - if (plist==item.polyList) { - index = i; - } - }) - if (index>=0) { - this._items.splice(index,1); - } - } - - indexOf(plist) { - let index = -1; - this._items.some((item,i) => { - if (item.polyList==plist) { - index = i; - return true; - } - }); - return index; - } - - replacePolyList(index,plist) { - if (index>=0 && index=0 && index=0 && index=0 && index=0 && index=0 && index { - if ((!isShadowMap && plist.visible) || (isShadowMap && plist.visibleToShadows) || forceDraw) { - let currMaterial = pipeline.effect.material; - if (trx) { - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.mult(trx); - } - - if (pipeline.shouldDraw(mat)) { - pipeline.effect.material = mat; - pipeline.draw(plist); - } - - if (trx) { - matrixState.modelMatrixStack.pop(); - } - pipeline.effect.material = currMaterial; - } - }); - } - } - - //// Render queue method - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (!this.node.enabled) { - return; - } - - this.forEach((plist,mat,trx) => { - if (!plist.visible) { - return; - } - if (trx) { - modelMatrixStack.push(); - modelMatrixStack.mult(trx); - } - - if (mat.isTransparent) { - renderQueue.renderTransparent(plist,mat,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - else { - renderQueue.renderOpaque(plist,mat,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - - if (trx) { - modelMatrixStack.pop(trx); - } - }); - } - - setGroupVisible(groupName,visibility=true) { - this.forEach((plist) => { - if (plist.groupName==groupName) { - plist.visible = visibility; - } - }); - } - - hideGroup(groupName) { this.setGroupVisible(groupName,false); } - - showGroup(groupName) { this.setGroupVisible(groupName,true); } - - setVisibleByName(name,visibility=true) { - this.some((plist) => { - if (plist.name==name) { - plist.visible = visibility; - return true; - } - }); - } - - showByName(name) { - this.setVisibleByName(name,true); - } - - hideByName(name) { - this.setVisibleByName(name,false); - } - - deserialize(context,sceneData,url) { - return new Promise((resolve,reject) => { - let modelUrl = bg.utils.Resource.JoinUrl(url,sceneData.name + '.vwglb'); - bg.base.Loader.Load(context,modelUrl) - .then((node) => { - let drw = node.component("bg.scene.Drawable"); - this._name = sceneData.name; - this._items = drw._items; - resolve(this); - }); - }); - } - - serialize(componentData,promises,url) { - if (!bg.isElectronApp) { - return; - } - super.serialize(componentData,promises,url); - this.name = escapePathCharacters(this.name); - - componentData.name = this.name; - const path = require('path'); - let dst = path.join(url.path,componentData.name + ".vwglb"); - promises.push(new Promise((resolve,reject) => { - bg.base.Writer.Write(dst,this.node) - .then(() => resolve()) - .catch((err) => reject(err)); - })); - } - } - - bg.scene.registerComponent(bg.scene,Drawable,"bg.scene.Drawable"); - -})(); -(function() { - - let s_lightRegister = []; - - function registerLight(l) { - s_lightRegister.push(l); - } - - function unregisterLight(l) { - let i = s_lightRegister.indexOf(l); - if (i!=-1) { - s_lightRegister.splice(i,1); - } - } - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i { - this._light = new bg.base.Light(context); - this._light.deserialize(sceneData); - resolve(this); - }); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - this.light.serialize(componentData); - } - } - - bg.scene.registerComponent(bg.scene,Light,"bg.scene.Light"); -})(); -(function() { - function parseMTL_n(line) { - let res = /newmtl\s+(.*)/.exec(line); - if (res) { - this._jsonData[res[1]] = JSON.parse(JSON.stringify(s_matInit)); - this._currentMat = this._jsonData[res[1]]; - } - } - - function parseMTL_N(line) { - let res = /Ns\s+([\d\.]+)/.exec(line); - if (res) { // Specular - this._currentMat.shininess = Number(res[1]); - } - //else if ( (res=/Ni\s+([\d\.]+)/.exec(line)) ) { - //} - } - - function vectorFromRE(re) { - return [ - Number(re[1]), - Number(re[2]), - Number(re[3]), - re[4] ? Number(re[4]) : 1.0 - ] - } - - function parseMTL_K(line) { - let res = /Kd\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s*([\d\.]*)/.exec(line); - if (res) { - // Diffuse - let d = vectorFromRE(res); - this._currentMat.diffuseR = d[0]; - this._currentMat.diffuseG = d[1]; - this._currentMat.diffuseB = d[2]; - this._currentMat.diffuseA = d[3]; - } - else if ( (res = /Ks\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s*([\d\.]*)/.exec(line)) ) { - // Specular - let s = vectorFromRE(res); - this._currentMat.specularR = s[0]; - this._currentMat.specularG = s[1]; - this._currentMat.specularB = s[2]; - this._currentMat.specularA = s[3]; - } - } - - function parseMTL_m(line) { - let res = /map_Kd\s+(.*)/.exec(line); - if (res) { - let path = res[1]; - path = path.replace(/\\/g,'/'); - let slashIndex = path.lastIndexOf('/'); - if (slashIndex>=0) { - path = path.substring(slashIndex + 1); - } - this._currentMat.texture = path; - } - } - - let s_matInit = { - diffuseR: 1.0, - diffuseG:1.0, - diffuseB:1.0, - diffuseA:1.0, - - specularR:1.0, - specularG:1.0, - specularB:1.0, - specularA:1.0, - - shininess: 0, - lightEmission: 0, - - refractionAmount: 0, - reflectionAmount: 0, - - textureOffsetX: 0, - textureOffsetY: 0, - textureScaleX: 1, - textureScaleY: 1, - - lightmapOffsetX: 0, - lightmapOffsetY: 0, - lightmapScaleX: 1, - lightmapScaleY: 1, - - normalMapOffsetX: 0, - normalMapOffsetY: 0, - normalMapScaleX: 1, - normalMapScaleY: 1, - - alphaCutoff: 0.5, - castShadows: true, - receiveShadows: true, - - shininessMaskChannel: 0, - shininessMaskInvert: false, - lightEmissionMaskChannel: 0, - lightEmissionMaskInvert: false, - - reflectionMaskChannel: 0, - reflectionMaskInvert: false, - - cullFace: true, - - texture: "", - lightmap: "", - normalMap: "", - shininessMask: "", - lightEmissionMask: "", - reflectionMask: "" - }; - - class MTLParser { - constructor(mtlData) { - this._jsonData = {} - this._currentMat = JSON.parse(JSON.stringify(s_matInit)); - let lines = mtlData.split('\n'); - - lines.forEach((line) => { - // First optimization: parse the first character and string lenght - line = line.trim(); - if (line.length>1 && line[0]!='#') { - // Second optimization: parse by the first character - switch (line[0]) { - case 'n': - parseMTL_n.apply(this,[line]); - break; - case 'N': - parseMTL_N.apply(this,[line]); - break; - case 'm': - parseMTL_m.apply(this,[line]); - break; - case 'd': - break; - case 'T': - break; - case 'K': - parseMTL_K.apply(this,[line]); - break; - case 'i': - break; - case 'o': - break; - } - } - }); - } - - get jsonData() { return this._jsonData; } - } - - function parseM(line) { - // mtllib - let res = /mtllib\s+(.*)/.exec(line); - if (res) { - this._mtlLib = res[1]; - } - } - - function parseG(line) { - // g - let res = /g\s+(.*)/.exec(line); - if (res) { - this._currentPlist.name = res[1]; - } - } - - function parseU(line) { - // usemtl - let res = /usemtl\s+(.*)/.exec(line); - if (res) { - this._currentPlist._matName = res[1]; - if (this._currentPlist.name=="") { - this._currentPlist.name = res[1]; - } - } - } - - function parseS(line) { - // s - let res = /s\s+(.*)/.exec(line); - if (res) { - // TODO: Do something with smoothing groups - } - } - - function addPoint(pointData) { - this._currentPlist.vertex.push(pointData.vertex[0],pointData.vertex[1],pointData.vertex[2]); - if (pointData.normal) { - this._currentPlist.normal.push(pointData.normal[0],pointData.normal[1],pointData.normal[2]); - } - if (pointData.tex) { - this._currentPlist.texCoord0.push(pointData.tex[0],pointData.tex[1]); - } - this._currentPlist.index.push(this._currentPlist.index.length); - } - - function isValid(point) { - return point && point.vertex && point.tex && point.normal; - } - - function addPolygon(polygonData) { - let currentVertex = 0; - let sides = polygonData.length; - if (sides<3) return; - while (currentVertex { - let name = this.url.replace(/[\\\/]/ig,'-'); - let drawable = new bg.scene.Drawable(name); - let lines = data.split('\n'); - - let multiLine = ""; - lines.forEach((line) => { - line = line.trim(); - - // This section controls the break line character \ - // to concatenate this line with the next one - if (multiLine) { - line = multiLine + line; - } - if (line[line.length-1]=='\\') { - line = line.substring(0,line.length-1); - multiLine += line; - return; - } - else { - multiLine = ""; - } - - // First optimization: parse the first character and string lenght - if (line.length>1 && line[0]!='#') { - // Second optimization: parse by the first character - switch (line[0]) { - case 'v': - let res = /v\s+([\d\.\-e]+)\s+([\d\.\-e]+)\s+([\d\.\-e]+)/.exec(line); - if (res) { - this._vertexArray.push( - [ Number(res[1]), Number(res[2]), Number(res[3]) ] - ); - } - else if ( (res = /vn\s+([\d\.\-e]+)\s+([\d\.\-e]+)\s+([\d\.\-e]+)/.exec(line)) ) { - this._normalArray.push( - [ Number(res[1]), Number(res[2]), Number(res[3]) ] - ); - } - else if ( (res = /vt\s+([\d\.\-e]+)\s+([\d\.\-e]+)/.exec(line)) ) { - this._texCoordArray.push( - [ Number(res[1]), Number(res[2]) ] - ); - } - else { - console.warn("Error parsing line " + line); - } - break; - case 'm': - checkAddPlist.apply(this); - parseM.apply(this,[line]); - break; - case 'g': - checkAddPlist.apply(this); - parseG.apply(this,[line]); - break; - case 'u': - checkAddPlist.apply(this); - parseU.apply(this,[line]); - break; - case 's': - //checkAddPlist.apply(this); - parseS.apply(this,[line]); - break; - case 'f': - parseF.apply(this,[line]); - break; - case 'o': - checkAddPlist.apply(this); - parseO.apply(this,[line]); - break; - } - } - }); - - if (this._currentPlist && this._addPlist) { - this._currentPlist.build(); - this._plistArray.push(this._currentPlist); - } - - function buildDrawable(plistArray,materials) { - plistArray.forEach((plist) => { - let mat = new bg.base.Material(); - let matData = materials[plist._matName]; - if (matData) { - let url = this.url.substring(0,this.url.lastIndexOf('/') + 1); - bg.base.Material.GetMaterialWithJson(this.context,matData,url) - .then((material) => { - drawable.addPolyList(plist,material); - }) - } - else { - drawable.addPolyList(plist,mat); - } - }); - } - - if (this._mtlLib) { - let locationUrl = this.url.substring(0,this.url.lastIndexOf("/")); - if (locationUrl.length>0 && locationUrl!='/') locationUrl += "/"; - bg.utils.Resource.Load(locationUrl + this._mtlLib) - .then((data) => { - buildDrawable.apply(this,[this._plistArray,parseMTL(data)]); - resolve(drawable); - }) - .catch(() => { - bg.log("Warning: no such material library file for obj model " + this.url); - buildDrawable.apply(this,[this._plistArray,{}]); - resolve(drawable); - }); - } - else { - buildDrawable.apply(this,[this._plistArray,{}]); - resolve(drawable); - } - }); - } - } - - class OBJLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - return bg.utils.Resource.GetExtension(url)=="obj"; - } - - load(context,url,data) { - return new Promise((resolve,reject) => { - if (data) { - try { - let parser = new OBJParser(context,url); - let resultNode = null; - let basePath = url.split("/"); - basePath.pop(); - basePath = basePath.join("/") + '/'; - let matUrl = url.split("."); - matUrl.pop(); - matUrl.push("bg2mat"); - matUrl = matUrl.join("."); - parser.loadDrawable(data) - .then((drawable) => { - let node = new bg.scene.Node(context,drawable.name); - node.addComponent(drawable); - resultNode = node; - return bg.utils.Resource.LoadJson(matUrl); - }) - - .then((matData) => { - let promises = []; - try { - let drw = resultNode.component("bg.scene.Drawable"); - drw.forEach((plist,mat)=> { - let matDef = null; - matData.some((defItem) => { - if (defItem.name==plist.name) { - matDef = defItem; - return true; - } - }); - - if (matDef) { - let p = bg.base.Material.FromMaterialDefinition(context,matDef,basePath); - promises.push(p) - p.then((newMat) => { - mat.assign(newMat); - }); - } - }); - } - catch(err) { - - } - return Promise.all(promises); - }) - - .then(() => { - resolve(resultNode); - }) - - .catch(() => { - // bg2mat file not found - resolve(resultNode) - }) - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading drawable. Data is null.")); - } - }); - } - } - - bg.base.OBJLoaderPlugin = OBJLoaderPlugin; -})(); -(function() { - - function createCube(context,w,h,d) { - let plist = new bg.base.PolyList(context); - - let x = w/2; - let y = h/2; - let z = d/2; - - plist.vertex = [ - x,-y,-z, -x,-y,-z, -x, y,-z, x, y,-z, // back face - x,-y, z, x,-y,-z, x, y,-z, x, y, z, // right face - -x,-y, z, x,-y, z, x, y, z, -x, y, z, // front face - -x,-y,-z, -x,-y, z, -x, y, z, -x, y,-z, // left face - -x, y, z, x, y, z, x, y,-z, -x, y,-z, // top face - x,-y, z, -x,-y, z, -x,-y,-z, x,-y,-z // bottom face - ]; - - plist.normal = [ - 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, // back face - 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // right face - 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // front face - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // left face - 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // top face - 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0 // bottom face - ]; - - plist.texCoord0 = [ - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1 - ]; - - plist.index = [ - 0, 1, 2, 2, 3, 0, - 4, 5, 6, 6, 7, 4, - 8, 9,10, 10,11, 8, - 12,13,14, 14,15,12, - 16,17,18, 18,19,16, - 20,21,22, 22,23,20 - ]; - - plist.texCoord1 = bg.tools.UVMap.atlas(plist.vertex,plist.index,0.03); - - plist.build(); - return plist; - } - - function createPlane(context,w,d,plane='y') { - let x = w / 2.0; - let y = d / 2.0; - - let plist = new bg.base.PolyList(context); - - switch (plane.toLowerCase()) { - case 'x': - plist.vertex =[ 0.000000,-x,-y, - 0.000000, x,-y, - 0.000000, x, y, - 0.000000, x, y, - 0.000000,-x, y, - 0.000000,-x,-y]; - - plist.normal = [1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000]; - - plist.texCoord0 = [ 0.000000,0.000000, - 1.000000,0.000000, - 1.000000,1.000000, - 1.000000,1.000000, - 0.000000,1.000000, - 0.000000,0.000000]; - - - plist.index = [2,1,0,5,4,3]; - break; - case 'y': - plist.vertex =[ -x,0.000000,-y, - x,0.000000,-y, - x,0.000000, y, - x,0.000000, y, - -x,0.000000, y, - -x,0.000000,-y]; - - plist.normal = [0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000]; - - plist.texCoord0 = [ 0.000000,0.000000, - 1.000000,0.000000, - 1.000000,1.000000, - 1.000000,1.000000, - 0.000000,1.000000, - 0.000000,0.000000]; - - - plist.index = [2,1,0,5,4,3]; - break; - case 'z': - plist.vertex =[-x, y,0.000000, - -x,-y,0.000000, - x,-y,0.000000, - x,-y,0.000000, - x, y,0.000000, - -x, y,0.000000]; - - plist.normal = [0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000]; - - plist.texCoord0 = [ - 0.000000,1.000000, - 0.000000,0.000000, - 1.000000,0.000000, - 1.000000,0.000000, - 1.000000,1.000000, - 0.000000,1.000000]; - - plist.index = [0,1,2,3,4,5]; - break; - } - - - plist.texCoord1 = [ - 0.00,0.95, - 0.00,0.00, - 0.95,0.00, - 0.95,0.00, - 0.95,0.95, - 0.00,0.95 - ]; - - - - plist.build(); - return plist; - } - - function createSphere(context,radius,slices,stacks) { - let plist = new bg.base.PolyList(context); - - ++slices; - const R = 1/(stacks-1); - const S = 1/(slices-1); - let r, s; - - let vertex = []; - let normal = []; - let texCoord = []; - let index = []; - - for(r = 0; r < stacks; r++) for(s = 0; s < slices; s++) { - const y = bg.Math.sin( -bg.Math.PI_2 + bg.Math.PI * r * R ); - const x = bg.Math.cos(2*bg.Math.PI * s * S) * bg.Math.sin(bg.Math.PI * r * R); - const z = bg.Math.sin(2*bg.Math.PI * s * S) * bg.Math.sin(bg.Math.PI * r * R); - texCoord.push(s * S); texCoord.push(r * R); - normal.push(x,y,z); - vertex.push(x * radius, y * radius, z * radius); - } - - for(r = 0; r < stacks - 1; r++) for(s = 0; s < slices - 1; s++) { - let i1 = r * slices + s; - let i2 = r * slices + (s + 1); - let i3 = (r + 1) * slices + (s + 1); - let i4 = (r + 1) * slices + s; - index.push(i1); index.push(i4); index.push(i3); - index.push(i3); index.push(i2); index.push(i1); - } - - plist.vertex = vertex; - plist.normal = normal; - plist.texCoord0 = texCoord; - - plist.texCoord1 = bg.tools.UVMap.atlas(vertex,index,0.03); - plist.index = index; - - plist.build(); - - return plist; - } - - function createDrawable(plist,name) { - let drawable = new bg.scene.Drawable(name); - drawable.addPolyList(plist); - return drawable; - } - - class PrimitiveFactory { - static CubePolyList(context,w=1,h,d) { - h = h || w; - d = d || w; - return createCube(context,w,h,d); - } - - static PlanePolyList(context,w=1,d,plane='y') { - d = d || w; - return createPlane(context,w,d,plane); - } - - static SpherePolyList(context,r=1,slices=20,stacks) { - stacks = stacks || slices; - return createSphere(context,r,slices,stacks); - } - - static Cube(context,w=1,h,d) { - h = h || w; - d = d || w; - return createDrawable(createCube(context,w,h,d),"Cube"); - } - - static Plane(context,w=1,d,plane='y') { - d = d || w; - return createDrawable(createPlane(context,w,d,plane),"Plane"); - } - - static Sphere(context,r=1,slices=20,stacks) { - stacks = stacks || slices; - return createDrawable(createSphere(context,r,slices,stacks),"Sphere"); - } - } - - bg.scene.PrimitiveFactory = PrimitiveFactory; - -})(); -(function() { - function fooScene(context) { - let root = new bg.scene.Node(context, "Scene Root"); - - bg.base.Loader.Load(context,"../data/test-shape.vwglb") - .then((node) => { - root.addChild(node); - node.addComponent(new bg.scene.Transform(bg.Matrix4.Translation(-1.4,0.25,0).scale(0.5,0.5,0.5))); - }) - - .catch(function(err) { - alert(err.message); - }); - - let sphereNode = new bg.scene.Node(context,"Sphere"); - sphereNode.addComponent(new bg.scene.Transform(bg.Matrix4.Translation(-1.3,0.1,1.3))); - sphereNode.addComponent(bg.scene.PrimitiveFactory.Sphere(context,0.1)); - sphereNode.component("bg.scene.Drawable").getMaterial(0).diffuse.a = 0.8; - sphereNode.component("bg.scene.Drawable").getMaterial(0).reflectionAmount = 0.4; - root.addChild(sphereNode); - - let floorNode = new bg.scene.Node(context,"Floor"); - floorNode.addComponent(new bg.scene.Transform(bg.Matrix4.Translation(0,0,0))); - floorNode.addComponent(bg.scene.PrimitiveFactory.Plane(context,10,10)); - floorNode.component("bg.scene.Drawable").getMaterial(0).shininess = 50; - floorNode.component("bg.scene.Drawable").getMaterial(0).reflectionAmount = 0.3; - floorNode.component("bg.scene.Drawable").getMaterial(0).normalMapScale = new bg.Vector2(10,10); - floorNode.component("bg.scene.Drawable").getMaterial(0).textureScale = new bg.Vector2(10,10); - floorNode.component("bg.scene.Drawable").getMaterial(0).reflectionMaskInvert = true; - floorNode.component("bg.scene.Drawable").getMaterial(0).shininessMaskInvert = true; - root.addChild(floorNode); - - bg.base.Loader.Load(context,"../data/bricks_nm.png") - .then((tex) => { - floorNode.component("bg.scene.Drawable").getMaterial(0).normalMap = tex; - }); - - bg.base.Loader.Load(context,"../data/bricks.jpg") - .then((tex) => { - floorNode.component("bg.scene.Drawable").getMaterial(0).texture = tex; - }); - - bg.base.Loader.Load(context,"../data/bricks_shin.jpg") - .then((tex) => { - floorNode.component("bg.scene.Drawable").getMaterial(0).reflectionMask = tex; - floorNode.component("bg.scene.Drawable").getMaterial(0).shininessMask = tex; - }); - - let lightNode = new bg.scene.Node(context,"Light"); - lightNode.addComponent(new bg.scene.Light(new bg.base.Light(context))); - lightNode.addComponent(new bg.scene.Transform(bg.Matrix4.Identity() - .rotate(bg.Math.degreesToRadians(30),0,1,0) - .rotate(bg.Math.degreesToRadians(35),-1,0,0))); - root.addChild(lightNode); - - let camera = new bg.scene.Camera(); - camera.isMain = true; - let cameraNode = new bg.scene.Node("Camera"); - cameraNode.addComponent(camera); - cameraNode.addComponent(new bg.scene.Transform()); - cameraNode.addComponent(new bg.manipulation.OrbitCameraController()); - let camCtrl = cameraNode.component("bg.manipulation.OrbitCameraController"); - camCtrl.minPitch = -45; - root.addChild(cameraNode); - - return root; - } - - class SceneFileParser { - constructor(url,jsonData) { - this.url = url.substring(0,url.lastIndexOf('/')); - this.jsonData = jsonData; - } - - loadNode(context,jsonData,parent,promises) { - // jsonData: object, input. Json data for the node - // parent: scene node, input. The parent node to which we must to add the new scene node. - // promises: array, output. Add promises from component.deserialize() - let node = new bg.scene.Node(context,jsonData.name); - node.enabled = jsonData.enabled; - node.steady = jsonData.steady || false; - parent.addChild(node); - jsonData.components.forEach((compData) => { - promises.push(bg.scene.Component.Factory(context,compData,node,this.url)); - }); - jsonData.children.forEach((child) => { - this.loadNode(context,child,node,promises); - }); - } - - loadScene(context) { - let promises = []; - let sceneRoot = new bg.scene.Node(context,"scene-root"); - - this.jsonData.scene.forEach((nodeData) => { - this.loadNode(context,nodeData,sceneRoot,promises); - }); - - return new Promise((resolve,reject) => { - Promise.all(promises) - .then(() => { - let findVisitor = new bg.scene.FindComponentVisitor("bg.scene.Camera"); - sceneRoot.accept(findVisitor); - - let cameraNode = null; - let firstCamera = null; - findVisitor.result.some((cn) => { - if (!firstCamera) { - firstCamera = cn; - } - if (cn.camera.isMain) { - cameraNode = cn; - return true; - } - }); - cameraNode = cameraNode || firstCamera; - if (!cameraNode) { - cameraNode = new bg.scene.Node(context,"Camera"); - cameraNode.addComponent(new bg.scene.Camera()); - let trx = bg.Matrix4.Rotation(0.52,-1,0,0); - trx.translate(0,0,5); - cameraNode.addComponent(new bg.scene.Transform(trx)); - sceneRoot.addChild(cameraNode); - } - - // Ensure that cameraNode is the only camera marked as main - bg.scene.Camera.SetAsMainCamera(cameraNode,sceneRoot); - resolve({ sceneRoot:sceneRoot, cameraNode:cameraNode }); - }); - }); - } - - } - - class SceneLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - let ext = bg.utils.Resource.GetExtension(url); - return ext=="vitscnj"; - } - - load(context,url,data) { - return new Promise((resolve,reject) => { - if (data) { - try { - if (typeof(data)=="string") { - // Prevent a bug in the C++ API version 2.0, that inserts a comma after the last - // element of some arrays and objects - data = data.replace(/,[\s\r\n]*\]/g,']'); - data = data.replace(/,[\s\r\n]*\}/g,'}'); - data = JSON.parse(data); - } - let parser = new SceneFileParser(url,data); - parser.loadScene(context) - .then((result) => { - resolve(result); - }); - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading scene. Data is null")); - } - }); - } - } - - bg.base.SceneLoaderPlugin = SceneLoaderPlugin; - -})(); -(function() { - - function copyCubemapImage(componentData,cubemapImage,dstPath) { - let path = require("path"); - let src = bg.base.Writer.StandarizePath(this.getImageUrl(cubemapImage)); - let file = src.split('/').pop(); - let dst = bg.base.Writer.StandarizePath(path.join(dstPath,file)); - switch (cubemapImage) { - case bg.scene.CubemapImage.POSITIVE_X: - componentData.positiveX = file; - break; - case bg.scene.CubemapImage.NEGATIVE_X: - componentData.negativeX = file; - break; - case bg.scene.CubemapImage.POSITIVE_Y: - componentData.positiveY = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Y: - componentData.negativeY = file; - break; - case bg.scene.CubemapImage.POSITIVE_Z: - componentData.positiveZ = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Z: - componentData.negativeZ = file; - break; - } - return bg.base.Writer.CopyFile(src,dst); - } - - let g_backFace = [ 0.5,-0.5,-0.5, -0.5,-0.5,-0.5, -0.5, 0.5,-0.5, 0.5, 0.5,-0.5 ]; - let g_rightFace = [ 0.5,-0.5, 0.5, 0.5,-0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5 ]; - let g_frontFace = [ -0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5 ]; - let g_leftFace = [ -0.5,-0.5,-0.5, -0.5,-0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5,-0.5 ]; - let g_topFace = [ -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,-0.5, -0.5, 0.5,-0.5 ]; - let g_bottomFace = [ 0.5,-0.5, 0.5, -0.5,-0.5, 0.5, -0.5,-0.5,-0.5, 0.5,-0.5,-0.5 ]; - - let g_backFaceNorm = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 ]; - let g_rightFaceNorm = [-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0 ]; - let g_frontFaceNorm = [ 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ]; - let g_leftFaceNorm = [ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 ]; - let g_topFaceNorm = [ 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0 ]; - let g_bottomFaceNorm = [ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]; - - let uv0 = 0; - let uv1 = 1; - let g_backFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_rightFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_frontFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_leftFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_topFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_bottomFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - - let g_index = [ 2,1,0, 0,3,2 ]; - - class Skybox extends bg.scene.Component { - constructor() { - super(); - this._images = [null, null, null, null, null, null]; - this._textures = []; - this._plist = []; - this._material = null; - } - - clone(context) { - let result = new Skybox(); - result._images = [ - this._images[0], - this._images[1], - this._images[2], - this._images[3], - this._images[4], - this._images[5] - ]; - context = context || this.node && this.node.context; - if (context) { - result.loadSkybox(context); - } - return result; - } - - setImageUrl(imgCode,texture) { - this._images[imgCode] = texture; - } - - getImageUrl(imgCode) { - return this._images[imgCode]; - } - - getTexture(imgCode) { - return this._textures[imgCode]; - } - - loadSkybox(context = null,onProgress = null) { - context = context || this.node && this.node.context; - - let backPlist = new bg.base.PolyList(context); - let rightPlist = new bg.base.PolyList(context); - let frontPlist = new bg.base.PolyList(context); - let leftPlist = new bg.base.PolyList(context); - let topPlist = new bg.base.PolyList(context); - let bottomPlist = new bg.base.PolyList(context); - - backPlist.vertex = g_backFace; backPlist.normal = g_backFaceNorm; backPlist.texCoord0 = g_backFaceUV; backPlist.texCoord1 = g_backFaceUV; backPlist.index = g_index; - backPlist.build(); - - rightPlist.vertex = g_rightFace; rightPlist.normal = g_rightFaceNorm; rightPlist.texCoord0 = g_rightFaceUV; rightPlist.texCoord1 = g_rightFaceUV; rightPlist.index = g_index; - rightPlist.build(); - - frontPlist.vertex = g_frontFace; frontPlist.normal = g_frontFaceNorm; frontPlist.texCoord0 = g_frontFaceUV; frontPlist.texCoord1 = g_frontFaceUV; frontPlist.index = g_index; - frontPlist.build(); - - leftPlist.vertex = g_leftFace; leftPlist.normal = g_leftFaceNorm; leftPlist.texCoord0 = g_leftFaceUV; leftPlist.texCoord1 = g_leftFaceUV; leftPlist.index = g_index; - leftPlist.build(); - - topPlist.vertex = g_topFace; topPlist.normal = g_topFaceNorm; topPlist.texCoord0 = g_topFaceUV; topPlist.texCoord1 = g_topFaceUV; topPlist.index = g_index; - topPlist.build(); - - bottomPlist.vertex = g_bottomFace; bottomPlist.normal = g_bottomFaceNorm; bottomPlist.texCoord0 = g_bottomFaceUV; bottomPlist.texCoord1 = g_bottomFaceUV; bottomPlist.index = g_index; - bottomPlist.build(); - - this._plist = [leftPlist,rightPlist,topPlist,bottomPlist,frontPlist,backPlist]; - this._material = new bg.base.Material(); - this._material.receiveShadows = false; - this._material.castShadows = false; - this._material.unlit = true; - - - return new Promise((resolve,reject) => { - bg.base.Loader.Load(context,this._images,onProgress, { - wrapX:bg.base.TextureWrap.MIRRORED_REPEAT, - wrapY:bg.base.TextureWrap.MIRRORED_REPEAT - }) - .then((result) => { - this._textures = [ - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Z)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Z)] - ]; - this._textures.forEach((tex) => { - tex.wrapX = bg.base.TextureWrap.CLAMP; - tex.wrapY = bg.base.TextureWrap.CLAMP; - }); - bg.emitImageLoadEvent(result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)]); - resolve(); - }) - .catch((err) => { - reject(err); - }); - }) - } - - display(pipeline,matrixState) { - // TODO: extract far clip plane from projection matrix and use it to scale the cube before draw it - if (!pipeline.effect) { - throw new Error("Could not draw skybox: invalid effect"); - } - if (!this.node.enabled) { - return; - } - else if (this._textures.length==6) { - let curMaterial = pipeline.effect.material; - pipeline.effect.material = this._material; - matrixState.viewMatrixStack.push(); - matrixState.modelMatrixStack.push(); - matrixState.viewMatrixStack.matrix.setPosition(0,0,0); - - let projectionMatrix = matrixState.projectionMatrixStack.matrix; - let m22 = -projectionMatrix.m22; - let m32 = -projectionMatrix.m32; - let far = (2.0*m32)/(2.0*m22-2.0); - - let offset = 1; - let scale = bg.Math.sin(bg.Math.PI_4) * far - offset; - matrixState.modelMatrixStack.scale(scale,scale,scale); - - if (pipeline.shouldDraw(this._material)) { - this._plist.forEach((pl,index) => { - this._material.texture = this._textures[index]; - pipeline.draw(pl); - }); - } - - matrixState.modelMatrixStack.pop(); - matrixState.viewMatrixStack.pop(); - pipeline.effect.material = curMaterial; - } - } - - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this._textures.length==6) { - viewMatrixStack.push(); - modelMatrixStack.push(); - - viewMatrixStack.matrix.setPosition(0,0,0); - - let projectionMatrix = projectionMatrixStack.matrix; - let m22 = -projectionMatrix.m22; - let m32 = -projectionMatrix.m32; - let far = (2.0*m32)/(2.0*m22-2.0); - - let offset = 1; - let scale = bg.Math.sin(bg.Math.PI_4) * far - offset; - modelMatrixStack.scale(scale,scale,scale); - - this._plist.forEach((pl,index) => { - this._material.texture = this._textures[index]; - renderQueue.renderOpaque(pl,this._material.clone(),modelMatrixStack.matrix,viewMatrixStack.matrix); - }) - - viewMatrixStack.pop(); - modelMatrixStack.pop(); - } - } - - removedFromNode() { - this._plist.forEach((pl) => { - pl.destroy(); - }); - } - - deserialize(context,sceneData,url) { - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["positiveX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["negativeX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["positiveY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["negativeY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["positiveZ"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["negativeZ"]) - ); - return this.loadSkybox(context); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - if (!bg.isElectronApp) return; - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Z,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Z,url.path])); - } - } - - bg.scene.registerComponent(bg.scene,Skybox,"bg.scene.Skybox"); -})(); -(function() { - class TextRect extends bg.scene.Component { - constructor(rectSize = new bg.Vector2(1,1),textureSize = new bg.Vector2(1000,1000)) { - super(); - - this._rectSize = rectSize; - this._textureSize = textureSize; - - this._textProperties = new bg.base.TextProperties(); - this._doubleSided = true; - this._unlit = false; - this._text = "Hello, World!"; - - this._sprite = null; - this._material = null; - - this._sizeMatrix = bg.Matrix4.Scale(this._rectSize.x,this._rectSize.y,1); - - this._canvasTexture = null; - this._dirty = true; - } - - clone() { - let newInstance = new bg.scene.TextRect(); - newInstance._text = this._text; - newInstance._sprite = this._sprite && this._sprite.clone(); - newInstance._material = this._material && this._material.clone(); - - // TODO: Clone other properties - return newInstance; - } - - get textProperties() { return this._textProperties; } - get text() { return this._text; } - set text(t) { this._dirty = true; this._text = t; } - get doubleSided() { return this._doubleSided; } - set doubleSided(ds) { this._dirty = true; this._doubleSided = ds; } - get unlit() { return this._unlit; } - set unlit(ul) { this._dirty = true; this._unlit = ul; } - get rectSize() { return this._rectSize; } - set rectSize(s) { - this._sizeMatrix.identity().scale(s.x,s.y,1); - this._rectSize = s; - } - - // TODO: update texture size - get textureSize() { return this._textureSize; } - set textureSize(t) { - this._dirty = true; - this._canvasTexture.resize(t.x,t.y); - this._textureSize = t; - } - - get material() { return this._material; } - - init() { - if (!this._sprite && this.node && this.node.context) { - this._sprite = bg.scene.PrimitiveFactory.PlanePolyList(this.node.context,1,1,'z'); - this._material = new bg.base.Material(); - this._material.alphaCutoff = 0.9; - this._dirty = true; - } - if (!this._canvasTexture && this.node && this.node.context) { - this._canvasTexture = new bg.tools.CanvasTexture(this.node.context,this._textureSize.x,this._textureSize.y, - (ctx,w,h) => { - ctx.clearRect(0,0,w,h); - if (this._textProperties.background!="transparent") { - ctx.fillStyle = this._textProperties.background; - ctx.fillRect(0,0,w,h); - } - ctx.fillStyle = this._textProperties.color; - let textSize = this._textProperties.size; - let font = this._textProperties.font; - let padding = 0; - let italic = this._textProperties.italic ? "italic" : ""; - let bold = this._textProperties.bold ? "bold" : ""; - ctx.textAlign = this._textProperties.align; - ctx.font = `${ italic } ${ bold } ${ textSize }px ${ font }`; // TODO: Font and size - let textWidth = ctx.measureText(this._text); - let x = 0; - let y = 0; - switch (ctx.textAlign) { - case "center": - x = w / 2; - y = textSize + padding; - break; - case "right": - x = w; - y = textSize + padding; - break; - default: - x = padding; - y = textSize + padding; - } - let textLines = this._text.split("\n"); - textLines.forEach((line) => { - ctx.fillText(line,x, y); - y += textSize; - }); - } - ); - this._dirty = true; - } - } - - frame(delta) { - if ((this._dirty || this._textProperties.dirty) && this._material && this._canvasTexture) { - this._canvasTexture.update(); - this._material.texture = this._canvasTexture.texture; - this._material.unlit = this._unlit; - this._material.cullFace = !this._doubleSided; - this._dirty = false; - this.textProperties.dirty = false; - } - } - - ////// Direct rendering functions: will be deprecated soon - display(pipeline,matrixState) { - if (!pipeline.effect) { - throw new Error("Could not draw TextRect: invalid effect"); - } - if (!this.node.enabled) { - return; - } - else if (this._sprite && this._material) { - if (this._sprite.visible) { - let curMaterial = pipeline.effect.material; - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.mult(this._sizeMatrix); - - if (pipeline.shouldDraw(this._material)) { - pipeline.effect.material = this._material; - pipeline.draw(this._sprite); - } - - matrixState.modelMatrixStack.pop(); - pipeline.effect.material = curMaterial; - } - } - } - - ///// Render queue functions - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this._sprite && this._material) { - modelMatrixStack.push(); - modelMatrixStack.mult(this._sizeMatrix); - - if (this._material.isTransparent) { - renderQueue.renderTransparent(this._sprite,this._material,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - else { - renderQueue.renderOpaque(this._sprite,this._material,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - - modelMatrixStack.pop(); - } - } - - serialize(componentData,promises,url) { - componentData.textProperties = {}; - this.textProperties.serialize(componentData.textProperties); - componentData.text = this.text; - componentData.doubleSided = this.doubleSided; - componentData.unlit = this.unlit; - componentData.textureSize = this.textureSize.toArray(); - componentData.rectSize = this.rectSize.toArray(); - } - - deserialize(context,sceneData,url) { - this.textProperties.deserialize(sceneData.textProperties); - this.text = sceneData.text; - this.doubleSided = sceneData.doubleSided; - this.unlit = sceneData.unlit; - this.textureSize = new bg.Vector2(sceneData.textureSize); - this.rectSize = new bg.Vector2(sceneData.rectSize); - } - } - - bg.scene.registerComponent(bg.scene,TextRect,"bg.scene.TextRect"); -})(); -(function() { - - class Transform extends bg.scene.Component { - constructor(matrix) { - super(); - - this._matrix = matrix || bg.Matrix4.Identity(); - this._globalMatrixValid = false; - this._transformVisitor = new bg.scene.TransformVisitor(); - } - - clone() { - let newTrx = new bg.scene.Transform(); - newTrx.matrix = new bg.Matrix4(this.matrix); - return newTrx; - } - - get matrix() { return this._matrix; } - set matrix(m) { this._matrix = m; } - - get globalMatrix() { - if (!this._globalMatrixValid) { - this._transformVisitor.clear(); - this.node.acceptReverse(this._transformVisitor); - this._globalMatrix = this._transformVisitor.matrix; - } - return this._globalMatrix; - } - - deserialize(context,sceneData,url) { - return new Promise((resolve,reject) => { - if (sceneData.transformStrategy) { - let str = sceneData.transformStrategy; - if (str.type=="TRSTransformStrategy") { - this._matrix - .identity() - .translate(str.translate[0],str.translate[1],str.translate[2]); - switch (str.rotationOrder) { - case "kOrderXYZ": - this._matrix - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateZ,0,0,1); - break; - case "kOrderXZY": - this._matrix - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateY,0,1,0); - break; - case "kOrderYXZ": - this._matrix - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateZ,0,0,1); - break; - case "kOrderYZX": - this._matrix - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateX,1,0,0); - break; - case "kOrderZYX": - this._matrix - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateX,1,0,0); - break; - case "kOrderZXY": - this._matrix - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateY,0,1,0); - break; - } - this._matrix.scale(str.scale[0],str.scale[1],str.scale[2]) - } - } - else if (sceneData.transformMatrix) { - this._matrix = new bg.Matrix4(sceneData.transformMatrix); - } - resolve(this); - }); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.transformMatrix = this._matrix.toArray(); - } - - // The direct render methods will be deprecated soon - ////// Direct render methods - willDisplay(pipeline,matrixState) { - if (this.node && this.node.enabled) { - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.mult(this.matrix); - } - } - - didDisplay(pipeline,matrixState) { - if (this.node && this.node.enabled) { - matrixState.modelMatrixStack.pop(); - } - this._globalMatrixValid = false; - } - ////// End direct render methods - - - ////// Render queue methods - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this.node && this.node.enabled) { - modelMatrixStack.push(); - modelMatrixStack.mult(this.matrix); - } - } - - didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this.node && this.node.enabled) { - modelMatrixStack.pop(); - } - this._globalMatrixValid = false; - } - ////// End render queue methods - - } - - bg.scene.registerComponent(bg.scene,Transform,"bg.scene.Transform"); - -})(); -(function() { - - class DrawVisitor extends bg.scene.NodeVisitor { - constructor(pipeline,matrixState) { - super(); - this._pipeline = pipeline || bg.base.Pipeline.Current(); - this._matrixState = matrixState || bg.base.MatrixState.Current(); - this._forceDraw = false; - } - - get forceDraw() { return this._forceDraw; } - set forceDraw(f) { this._forceDraw = f; } - - get pipeline() { return this._pipeline; } - get matrixState() { return this._matrixState; } - - visit(node) { - node.willDisplay(this.pipeline,this.matrixState); - node.display(this.pipeline,this.matrixState,this.forceDraw); - } - - didVisit(node) { - node.didDisplay(this.pipeline,this.matrixState); - } - } - - bg.scene.DrawVisitor = DrawVisitor; - - class RenderQueueVisitor extends bg.scene.NodeVisitor { - constructor(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - super(); - this._modelMatrixStack = modelMatrixStack || new bg.base.MatrixStack(); - this._viewMatrixStack = viewMatrixStack || new bg.base.MatrixStack(); - this._projectionMatrixStack = projectionMatrixStack || new bg.base.MatrixStack(); - this._renderQueue = new bg.base.RenderQueue(); - } - - get modelMatrixStack() { return this._modelMatrixStack; } - set modelMatrixStack(m) { this._modelMatrixStack = m; } - - get viewMatrixStack() { return this._viewMatrixStack; } - set viewMatrixStack(m) { this._viewMatrixStack = m; } - - get projectionMatrixStack() { return this._projectionMatrixStack } - set projectionMatrixStack(m) { this._projectionMatrixStack = m; } - - get renderQueue() { return this._renderQueue; } - - visit(node) { - node.willUpdate(this._modelMatrixStack); - node.draw(this._renderQueue,this._modelMatrixStack, this._viewMatrixStack, this._projectionMatrixStack); - } - - didVisit(node) { - node.didUpdate(this._modelMatrixStack, this._viewMatrixStack, this._projectionMatrixStack); - } - } - - bg.scene.RenderQueueVisitor = RenderQueueVisitor; - - class FrameVisitor extends bg.scene.NodeVisitor { - constructor() { - super(); - this._delta = 0; - } - - get delta() { return this._delta; } - set delta(d) { this._delta = d; } - - visit(node) { - node.frame(this.delta); - } - } - - bg.scene.FrameVisitor = FrameVisitor; - - class TransformVisitor extends bg.scene.NodeVisitor { - constructor() { - super(); - this._matrix = bg.Matrix4.Identity(); - } - - get matrix() { return this._matrix; } - - clear() { - this._matrix = bg.Matrix4.Identity(); - } - - visit(node) { - let trx = node.component("bg.scene.Transform"); - if (trx) { - this._matrix.mult(trx.matrix); - } - } - } - - bg.scene.TransformVisitor = TransformVisitor; - - class InputVisitor extends bg.scene.NodeVisitor { - - visit(node) { - if (this._operation) { - node[this._operation](this._event); - } - } - - keyDown(scene,evt) { - this._operation = "keyDown"; - this._event = evt; - scene.accept(this); - } - - keyUp(scene,evt) { - this._operation = "keyUp"; - this._event = evt; - scene.accept(this); - } - - mouseUp(scene,evt) { - this._operation = "mouseUp"; - this._event = evt; - scene.accept(this); - } - - mouseDown(scene,evt) { - this._operation = "mouseDown"; - this._event = evt; - scene.accept(this); - } - - mouseMove(scene,evt) { - this._operation = "mouseMove"; - this._event = evt; - scene.accept(this); - } - - mouseOut(scene,evt) { - this._operation = "mouseOut"; - this._event = evt; - scene.accept(this); - } - - mouseDrag(scene,evt) { - this._operation = "mouseDrag"; - this._event = evt; - scene.accept(this); - } - - mouseWheel(scene,evt) { - this._operation = "mouseWheel"; - this._event = evt; - scene.accept(this); - } - - touchStart(scene,evt) { - this._operation = "touchStart"; - this._event = evt; - scene.accept(this); - } - - touchMove(scene,evt) { - this._operation = "touchMove"; - this._event = evt; - scene.accept(this); - } - - touchEnd(scene,evt) { - this._operation = "touchEnd"; - this._event = evt; - scene.accept(this); - } - } - - bg.scene.InputVisitor = InputVisitor; - - class BoundingBoxVisitor extends bg.scene.NodeVisitor { - constructor() { - super(); - this.clear(); - } - - get min() { - return this._min; - } - - get max() { - return this._max; - } - - get size() { - return this._size; - } - - clear() { - // left, right, bottom, top, back, front - this._min = new bg.Vector3(bg.Math.FLOAT_MAX,bg.Math.FLOAT_MAX,bg.Math.FLOAT_MAX); - this._max = new bg.Vector3(-bg.Math.FLOAT_MAX,-bg.Math.FLOAT_MAX,-bg.Math.FLOAT_MAX); - this._size = new bg.Vector3(0,0,0); - } - - visit(node) { - let trx = bg.Matrix4.Identity(); - if (node.component("bg.scene.Transform")) { - trx = node.component("bg.scene.Transform").globalMatrix; - } - if (node.component("bg.scene.Drawable")) { - let bb = new bg.tools.BoundingBox(node.component("bg.scene.Drawable"),new bg.Matrix4(trx)); - this._min = bg.Vector.MinComponents(this._min,bb.min); - this._max = bg.Vector.MaxComponents(this._max,bb.max); - this._size = bg.Vector3.Sub(this._max, this._min); - } - } - } - - bg.scene.BoundingBoxVisitor = BoundingBoxVisitor; - - - class FindComponentVisitor extends bg.scene.NodeVisitor { - constructor(componentId) { - super(); - this.componentId = componentId; - this.clear(); - } - - get result() { - return this._result; - } - - clear() { - this._result = []; - } - - visit(node) { - if (node.component(this.componentId)) { - this._result.push(node); - } - } - } - - bg.scene.FindComponentVisitor = FindComponentVisitor; -})(); -(function() { - - function readBlock(arrayBuffer,offset) { - var block = new Uint8Array(arrayBuffer,offset,4); - block = String.fromCharCode(block[0]) + String.fromCharCode(block[1]) + String.fromCharCode(block[2]) + String.fromCharCode(block[3]); - return block; - } - - function readInt(arrayBuffer,offset) { - var dataView = new DataView(arrayBuffer,offset,4); - return dataView.getInt32(0); - } - - function readFloat(arrayBuffer,offset) { - var dataView = new DataView(arrayBuffer,offset,4); - return dataView.getFloat32(0); - } - - function readMatrix4(arrayBuffer,offset) { - var response = {offset:0,data:[]} - var size = 16; - var dataView = new DataView(arrayBuffer,offset, size*4); - var littleEndian = false; - for (var i=0;i=data.byteLength) { - done = true; - } - - let plistData = { - name:plistName, - matName:matName, - vertices:vArray, - normal:nArray, - texcoord0:t0Array, - texcoord1:t1Array, - texcoord2:t2Array, - indices:iArray - } - polyLists.push(plistData) - plistName = ""; - matName = ""; - vArray = null; - nArray = null; - t0Array = null; - t1Array = null; - t2Array = null; - iArray = null; - break; - default: - throw "File format exception. Unexpected poly list member found"; - } - } - - var parsedData = { - version:version, - polyList:polyLists, - materials: {} - } - this._componentData = components; - materials.forEach((matData) => { - parsedData.materials[matData.name] = matData; - }); - return parsedData; - } - - createDrawable(data,path) { - let drawable = new bg.scene.Drawable(this.context); - drawable._version = data.version; - let promises = []; - - data.polyList.forEach((plistData) => { - let materialData = data.materials[plistData.matName]; - - let polyList = new bg.base.PolyList(this._context); - polyList.name = plistData.name; - polyList.vertex = plistData.vertices || polyList.vertex; - polyList.normal = plistData.normal || polyList.normal; - polyList.texCoord0 = plistData.texcoord0 || polyList.texCoord0; - polyList.texCoord1 = plistData.texcoord1 || polyList.texCoord1; - polyList.texCoord2 = plistData.texcoord2 || polyList.texCoord2; - polyList.index = plistData.indices || polyList.index; - - polyList.groupName = materialData.groupName; - polyList.visible = materialData.visible; - polyList.visibleToShadows = materialData.visibleToShadows!==undefined ? materialData.visibleToShadows : true; - - polyList.build(); - - promises.push(bg.base.Material.GetMaterialWithJson(this._context,materialData,path) - .then(function(material) { - drawable.addPolyList(polyList,material); - })); - }); - - return Promise.all(promises) - .then(() => { - return drawable; - }); - } - - addComponents(node,url) { - if (this._jointData) { - let i = null; - let o = null; - if (this._jointData.input) { - i = this._jointData.input; - } - if (this._jointData.output && this._jointData.output.length) { - o = this._jointData.output[0]; - } - - if (i) addJoint(node,"InputChainJoint",i); - if (o) addJoint(node,"OutputChainJoint",o); - } - - if (this._componentData) { - console.log("Component data found"); - let baseUrl = url; - if (bg.isElectronApp) { - baseUrl = bg.base.Writer.StandarizePath(url); - } - baseUrl = baseUrl.split("/"); - baseUrl.pop(); - baseUrl = baseUrl.join("/"); - this._componentData.forEach((cmpData) => { - bg.scene.Component.Factory(this.context,cmpData,node,baseUrl) - }) - } - } - } - - class VWGLBLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - let ext = bg.utils.Resource.GetExtension(url); - return ext=="vwglb" || ext=="bg2"; - } - - load(context,url,data) { - return new Promise((accept,reject) => { - if (data) { - try { - let parser = new VWGLBParser(context,data); - let path = url.substr(0,url.lastIndexOf("/")); - parser.loadDrawable(data,path) - .then((drawable) => { - let node = new bg.scene.Node(context,drawable.name); - node.addComponent(drawable); - parser.addComponents(node,url); - accept(node); - }); - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading drawable. Data is null")); - } - }); - } - } - - // This plugin load vwglb and bg2 files, but will also try to load the associated bg2mat file - class Bg2LoaderPlugin extends VWGLBLoaderPlugin { - load(context,url,data) { - let promise = super.load(context,url,data); - return new Promise((resolve,reject) => { - promise - .then((node) => { - let basePath = url.split("/"); - basePath.pop(); - basePath = basePath.join("/") + '/'; - let matUrl = url.split("."); - matUrl.pop(); - matUrl.push("bg2mat"); - matUrl = matUrl.join("."); - bg.utils.Resource.LoadJson(matUrl) - .then((matData) => { - let promises = []; - try { - let drw = node.component("bg.scene.Drawable"); - drw.forEach((plist,mat)=> { - let matDef = null; - matData.some((defItem) => { - if (defItem.name==plist.name) { - matDef = defItem; - return true; - } - }); - - if (matDef) { - let p = bg.base.Material.FromMaterialDefinition(context,matDef,basePath); - promises.push(p) - p.then((newMat) => { - mat.assign(newMat); - }); - } - }); - } - catch(err) { - - } - return Promise.all(promises); - }) - .then(() => { - resolve(node); - }) - .catch(() => { // bg2mat file not found - resolve(node); - }); - }) - .catch((err) => { - reject(err); - }); - }); - } - } - - bg.base.VWGLBLoaderPlugin = VWGLBLoaderPlugin; - bg.base.Bg2LoaderPlugin = Bg2LoaderPlugin; - -})(); -bg.manipulation = {}; -(function() { - - class DrawGizmoVisitor extends bg.scene.DrawVisitor { - constructor(pipeline,matrixState) { - super(pipeline,matrixState); - this._sprite = bg.scene.PrimitiveFactory.PlanePolyList(pipeline.context,1,1,"z"); - - this._gizmoScale = 1; - - this._gizmoIcons = []; - - this._show3dGizmos = true; - } - - get gizmoScale() { return this._gizmoScale; } - set gizmoScale(s) { this._gizmoScale = s; } - - get show3dGizmos() { return this._show3dGizmos; } - set show3dGizmos(g) { this._show3dGizmos = g; } - - clearGizmoIcons() { this._gizmoIcons = []; } - addGizmoIcon(type,icon,visible=true) { this._gizmoIcons.push({ type:type, icon:icon, visible:visible }); } - setGizmoIconVisibility(type,visible) { - this._gizmoIcons.some((iconData) => { - if (iconData.type==type) { - iconData.visible = visible; - } - }) - } - - get gizmoIcons() { return this._gizmoIcons; } - - getGizmoIcon(node) { - let icon = null; - this._gizmoIcons.some((iconData) => { - if (node.component(iconData.type) && iconData.visible) { - icon = iconData.icon; - return true; - } - }); - return icon; - } - - visit(node) { - super.visit(node); - - let icon = this.getGizmoIcon(node); - let gizmoOpacity = this.pipeline.effect.gizmoOpacity; - let gizmoColor = this.pipeline.effect.color; - this.pipeline.effect.color = bg.Color.White(); - let dt = this.pipeline.depthTest; - this.pipeline.depthTest = false; - if (icon) { - this.pipeline.effect.texture = icon; - this.pipeline.effect.gizmoOpacity = 1; - this.matrixState.viewMatrixStack.push(); - this.matrixState.modelMatrixStack.push(); - this.matrixState.viewMatrixStack.mult(this.matrixState.modelMatrixStack.matrix); - this.matrixState.modelMatrixStack.identity(); - this.matrixState.viewMatrixStack.matrix.setRow(0,new bg.Vector4(1,0,0,0)); - this.matrixState.viewMatrixStack.matrix.setRow(1,new bg.Vector4(0,1,0,0)); - this.matrixState.viewMatrixStack.matrix.setRow(2,new bg.Vector4(0,0,1,0)); - let s = this.matrixState.cameraDistanceScale * 0.05 * this._gizmoScale; - this.matrixState.viewMatrixStack.scale(s,s,s); - this.pipeline.draw(this._sprite); - - this.matrixState.viewMatrixStack.pop(); - this.matrixState.modelMatrixStack.pop(); - this.pipeline.effect.gizmoOpacity = gizmoOpacity; - this.pipeline.effect.texture = null; - } - if (this._show3dGizmos) { - node.displayGizmo(this.pipeline,this.matrixState); - } - this.pipeline.effect.color = gizmoColor; - this.pipeline.depthTest = dt; - } - - } - - bg.manipulation = bg.manipulation || {}; - bg.manipulation.DrawGizmoVisitor = DrawGizmoVisitor; -})(); -(function() { - - class GizmoManager extends bg.app.ContextObject { - - constructor(context) { - super(context); - this._gizmoOpacity = 0.9; - } - - get pipeline() { - if (!this._pipeline) { - this._pipeline = new bg.base.Pipeline(this.context); - this._pipeline.blendMode = bg.base.BlendMode.NORMAL; - this._pipeline.effect = new bg.manipulation.GizmoEffect(this.context); - } - return this._pipeline; - } - - get matrixState() { - if (!this._matrixState) { - this._matrixState = new bg.base.MatrixState(); - } - return this._matrixState; - } - - get drawVisitor() { - if (!this._drawVisitor) { - this._drawVisitor = new bg.manipulation.DrawGizmoVisitor(this.pipeline,this.matrixState); - } - return this._drawVisitor; - } - - get gizmoOpacity() { return this._gizmoOpacity; } - set gizmoOpacity(o) { this._gizmoOpacity = o; } - - get show3dGizmos() { return this.drawVisitor.show3dGizmos; } - set show3dGizmos(g) { this.drawVisitor.show3dGizmos = g; } - - get working() { return this._working; } - - // Load icon textures manually - // addGizmoIcon("bg.scene.Camera",cameraTexture) - addGizmoIcon(type,iconTexture) { - this.drawVisitor.addGizmoIcon(type,iconTexture); - } - - get gizmoIconScale() { return this.drawVisitor.gizmoScale; } - set gizmoIconScale(s) { this.drawVisitor.gizmoScale = s; } - - setGizmoIconVisibility(type,visible) { this.drawVisitor.setGizmoIconVisibility(type,visible); } - hideGizmoIcon(type) { this.drawVisitor.setGizmoIconVisibility(type,false); } - showGizmoIcon(type) { this.drawVisitor.setGizmoIconVisibility(type,true); } - - get gizmoIcons() { return this.drawVisitor.gizmoIcons; } - - /* - * Receives an array with the icon data, ordered by priority (only one component - * icon will be shown). - * iconData: [ - * { type:"bg.scene.Camera", icon:"../data/camera_gizmo.png" }, - * { type:"bg.scene.Light", icon:"../data/light_gizmo.png" }, - * { type:"bg.scene.Transform", icon:"../data/transform_gizmo.png" }, - * { type:"bg.scene.Drawable", icon:"../data/drawable_gizmo.png" }, - * ], - * basePath: if specified, this path will be prepended to the icon paths - */ - loadGizmoIcons(iconData, basePath="",onProgress) { - return new Promise((resolve,reject) => { - let urls = []; - let iconDataResult = []; - iconData.forEach((data) => { - let itemData = { type:data.type, iconTexture:null }; - itemData.path = bg.utils.path.join(basePath,data.icon); - urls.push(itemData.path); - iconDataResult.push(itemData); - }); - bg.base.Loader.Load(this.context,urls,onProgress) - .then((result) => { - iconDataResult.forEach((dataItem) => { - dataItem.iconTexture = result[dataItem.path]; - this.addGizmoIcon(dataItem.type,dataItem.iconTexture); - }) - resolve(iconDataResult); - }) - .catch((err) => { - reject(err); - }); - }); - } - - clearGizmoIcons() { - this.drawVisitor.clearGizmoIcons(); - } - - startAction(gizmoPickData,pos) { - this._working = true; - this._startPoint = pos; - this._currentGizmoData = gizmoPickData; - if (this._currentGizmoData && this._currentGizmoData.node) { - let gizmo = this._currentGizmoData.node.component("bg.manipulation.Gizmo"); - if (gizmo) { - gizmo.beginDrag(this._currentGizmoData.action,pos); - } - } - } - - move(pos,camera) { - if (this._currentGizmoData && this._currentGizmoData.node) { - let gizmo = this._currentGizmoData.node.component("bg.manipulation.Gizmo"); - if (gizmo) { - pos.y = camera.viewport.height - pos.y; // Convert to viewport coords - gizmo.drag(this._currentGizmoData.action,this._startPoint,pos,camera); - } - this._startPoint = pos; - } - } - - endAction() { - if (this._currentGizmoData && this._currentGizmoData.node) { - let gizmo = this._currentGizmoData.node.component("bg.manipulation.Gizmo"); - if (gizmo) { - gizmo.endDrag(this._currentGizmoData.action); - } - } - this._working = false; - this._startPoint = null; - this._currentGizmoData = null; - } - - drawGizmos(sceneRoot,camera,clearDepth=true) { - let restorePipeline = bg.base.Pipeline.Current(); - let restoreMatrixState = bg.base.MatrixState.Current(); - bg.base.Pipeline.SetCurrent(this.pipeline); - bg.base.MatrixState.SetCurrent(this.matrixState); - this.pipeline.viewport = camera.viewport; - this.pipeline.effect.matrixState = this.matrixState; - - if (clearDepth) { - this.pipeline.clearBuffers(bg.base.ClearBuffers.DEPTH); - } - - this.matrixState.projectionMatrixStack.set(camera.projection); - this.matrixState.viewMatrixStack.set(camera.viewMatrix); - - let opacityLayer = this.pipeline.opacityLayer; - this.pipeline.opacityLayer = bg.base.OpacityLayer.NONE; - - this.pipeline.blend = true; - this.pipeline.effect.gizmoOpacity = this.gizmoOpacity; - sceneRoot.accept(this.drawVisitor); - this.pipeline.blend = false; - - this.pipeline.opacityLayer = opacityLayer; - - if (restorePipeline) { - bg.base.Pipeline.SetCurrent(restorePipeline); - } - if (restoreMatrixState) { - bg.base.MatrixState.SetCurrent(restoreMatrixState); - } - } - } - - bg.manipulation.GizmoManager = GizmoManager; - -})(); - -(function() { - - let shaders = {}; - - function initShaders() { - shaders[bg.webgl1.EngineId] = { - vertex: ` - attribute vec3 inVertex; - attribute vec2 inTexCoord; - attribute vec4 inVertexColor; - - uniform mat4 inModelMatrix; - uniform mat4 inViewMatrix; - uniform mat4 inProjectionMatrix; - - varying vec2 fsTexCoord; - varying vec4 fsColor; - - void main() { - fsTexCoord = inTexCoord; - fsColor = inVertexColor; - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - } - `, - - fragment:` - precision highp float; - - uniform vec4 inColor; - uniform sampler2D inTexture; - uniform float inOpacity; - - varying vec2 fsTexCoord; - varying vec4 fsColor; - - void main() { - vec4 tex = texture2D(inTexture,fsTexCoord); - gl_FragColor = vec4(fsColor.rgb * tex.rgb * inColor.rgb,inOpacity * tex.a); - } - ` - }; - } - - class GizmoEffect extends bg.base.Effect { - constructor(context) { - super(context); - initShaders(); - this._gizmoOpacity = 1; - this._color = bg.Color.White(); - } - - get inputVars() { - return { - vertex:'inVertex', - color:'inVertexColor', - tex0:'inTexCoord' - } - } - - set matrixState(m) { this._matrixState = m; } - get matrixState() { - return this._matrixState; - } - - set texture(t) { this._texture = t; } - get texture() { return this._texture; } - - set color(c) { this._color = c; } - get color() { return this._color; } - - set gizmoOpacity(o) { this._gizmoOpacity = o; } - get gizmoOpacity() { return this._gizmoOpacity; } - - get shader() { - if (!this._shader) { - this._shader = new bg.base.Shader(this.context); - this._shader.addShaderSource(bg.base.ShaderType.VERTEX, shaders[bg.webgl1.EngineId].vertex); - this._shader.addShaderSource(bg.base.ShaderType.FRAGMENT, shaders[bg.webgl1.EngineId].fragment); - this._shader.link(); - if (!this._shader.status) { - console.log(this._shader.compileError); - console.log(this._shader.linkError); - } - else { - this._shader.initVars([ - 'inVertex', - 'inVertexColor', - 'inTexCoord' - ],[ - 'inModelMatrix', - 'inViewMatrix', - 'inProjectionMatrix', - 'inColor', - 'inTexture', - 'inOpacity' - ]); - } - } - return this._shader - } - - setupVars() { - let whiteTexture = bg.base.TextureCache.WhiteTexture(this.context); - this.shader.setMatrix4('inModelMatrix',this.matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',new bg.Matrix4(this.matrixState.viewMatrixStack.matrixConst)); - this.shader.setMatrix4('inProjectionMatrix',this.matrixState.projectionMatrixStack.matrixConst); - this.shader.setVector4('inColor',this.color); - this.shader.setTexture('inTexture', this.texture ? this.texture : whiteTexture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setValueFloat('inOpacity',this.gizmoOpacity); - } - - } - - bg.manipulation.GizmoEffect = GizmoEffect; - - bg.manipulation.GizmoAction = { - TRANSLATE: 1, - ROTATE: 2, - ROTATE_FINE: 3, - SCALE: 4, - TRANSLATE_X: 5, - TRANSLATE_Y: 6, - TRANSLATE_Z: 7, - ROTATE_X: 8, - ROTATE_Y: 9, - ROTATE_Z: 10, - SCALE_X: 11, - SCALE_Y: 12, - SCALE_Z: 13, - - NONE: 99 - }; - - function getAction(plist) { - if (/rotate.*fine/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_FINE; - } - if (/rotate.*x/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_X; - } - if (/rotate.*y/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_Y; - } - if (/rotate.*z/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_Z; - } - else if (/rotate/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE; - } - else if (/translate.*x/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE_X; - } - else if (/translate.*y/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE_Y; - } - else if (/translate.*z/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE_Z; - } - else if (/translate/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE; - } - else if (/scale.*x/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE_X; - } - else if (/scale.*y/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE_Y; - } - else if (/scale.*z/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE_Z; - } - else if (/scale/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE; - } - } - - let s_gizmoCache = {} - - class GizmoCache { - static Get(context) { - if (!s_gizmoCache[context.uuid]) { - s_gizmoCache[context.uuid] = new GizmoCache(context); - } - return s_gizmoCache[context.uuid]; - } - - constructor(context) { - this._context = context; - this._gizmos = {}; - } - - find(url) { - return this._gizmos[url]; - } - - register(url,gizmoItems) { - this._gizmos[url] = gizmoItems; - } - - unregister(url) { - if (this._gizmos[url]) { - delete this._gizmos[url]; - } - } - - clear() { - this._gizmos = {} - } - } - - bg.manipulation.GizmoCache = GizmoCache; - - function loadGizmo(context,gizmoUrl,gizmoNode) { - return new Promise(function(accept,reject) { - if (!gizmoUrl) { - accept([]); - return; - } - bg.base.Loader.Load(context,gizmoUrl) - .then(function (node) { - let drw = node.component("bg.scene.Drawable"); - let gizmoItems = []; - if (drw) { - drw.forEach(function (plist,material) { - gizmoItems.push({ - id:bg.manipulation.Selectable.GetIdentifier(), - type:bg.manipulation.SelectableType.GIZMO, - plist:plist, - material:material, - action:getAction(plist), - node:gizmoNode - }) - }); - } - - accept(gizmoItems); - }) - - .catch(function(err) { - reject(err); - }); - }); - } - - function rotationBetweenPoints(axis,p1,p2,origin,inc) { - if (!inc) inc = 0; - let v1 = new bg.Vector3(p2); - v1.sub(origin).normalize(); - let v2 = new bg.Vector3(p1); - v2.sub(origin).normalize(); - let dot = v1.dot(v2); - - let alpha = Math.acos(dot); - if (alpha>=inc || inc==0) { - if (inc!=0) { - alpha = (alpha>=2*inc) ? 2*inc:inc; - } - let sign = axis.dot(v1.cross(v2)); - if (sign<0) alpha *= -1.0; - let q = new bg.Quaternion(alpha,axis.x,axis.y,axis.z); - q.normalize(); - - if (!isNaN(q.x)) { - return q; - } - } - return new bg.Quaternion(0,0,1,0); - } - - class Gizmo extends bg.scene.Component { - constructor(gizmoPath,visible=true) { - super(); - this._gizmoPath = gizmoPath; - this._offset = new bg.Vector3(0); - this._visible = visible; - this._gizmoTransform = bg.Matrix4.Identity(); - this._gizmoP = bg.Matrix4.Identity(); - this._scale = 5; - this._minSize = 0.5; - } - - clone() { - let newGizmo = new Gizmo(this._gizmoPath); - newGizmo.offset.assign(this._offset); - newGizmo.visible = this._visible; - return newGizmo; - } - - get offset() { return this._offset; } - set offset(v) { this._offset = v; } - - get visible() { return this._visible; } - set visible(v) { this._visible = v; } - - get gizmoTransform() { - return this._gizmoTransform; - } - - beginDrag(action,pos) {} - - drag(action,startPos,endPos,camera) {} - - endDrag(action) {} - - findId(id) { - let result = null; - if (this._gizmoItems) { - this._gizmoItems.some((item) => { - if (item.id.r==id.r && item.id.g==id.g && item.id.b==id.b && item.id.a==id.a) { - result = item; - return true; - } - }); - } - return result; - } - - init() { - if (!this._error) { - this._gizmoItems = []; - loadGizmo(this.node.context,this._gizmoPath,this.node) - .then((gizmoItems) => { - this._gizmoItems = gizmoItems; - }) - - .catch((err) => { - this._error = true; - throw err; - }) - } - } - - frame(delta) { - - } - - display(pipeline,matrixState) { - if (!this._gizmoItems || !this.visible) return; - matrixState.modelMatrixStack.push(); - let modelview = new bg.Matrix4(matrixState.viewMatrixStack.matrix); - modelview.mult(matrixState.modelMatrixStack.matrix); - let s = modelview.position.magnitude() / this._scale; - matrixState.modelMatrixStack.matrix.setScale(s,s,s); - if (pipeline.effect instanceof bg.manipulation.ColorPickEffect && - (pipeline.opacityLayer & bg.base.OpacityLayer.GIZMOS || - pipeline.opacityLayer & bg.base.OpacityLayer.GIZMOS_SELECTION)) - { - let dt = pipeline.depthTest; - if (pipeline.opacityLayer & bg.base.OpacityLayer.GIZMOS_SELECTION) { // drawing gizmos in selection mode - pipeline.depthTest = true; - } - else { - pipeline.depthTest = false; - } - this._gizmoItems.forEach((item) => { - // The RGBA values are inverted because the alpha channel must be major than zero to - // produce any output in the framebuffer - if (item.plist.visible) { - pipeline.effect.pickId = new bg.Color(item.id.a/255,item.id.b/255,item.id.g/255,item.id.r/255); - pipeline.draw(item.plist); - } - }); - pipeline.depthTest = dt; - } - else if (pipeline.effect instanceof bg.manipulation.GizmoEffect) { - // Draw gizmo - this._gizmoItems.forEach((item) => { - if (item.plist.visible) { - pipeline.effect.texture = item.material.texture; - pipeline.effect.color = item.material.diffuse; - pipeline.draw(item.plist); - } - }) - } - matrixState.modelMatrixStack.pop(); - } - } - - function translateMatrix(gizmo,intersection) { - let matrix = new bg.Matrix4(gizmo.transform.matrix); - let rotation = matrix.rotation; - let origin = matrix.position; - - if (!gizmo._lastPickPoint) { - gizmo._lastPickPoint = intersection.ray.end; - gizmo._translateOffset = new bg.Vector3(origin); - gizmo._translateOffset.sub(intersection.ray.end); - } - - switch (Math.abs(gizmo.plane)) { - case bg.Axis.X: - matrix = bg.Matrix4.Translation(origin.x, - intersection.point.y + gizmo._translateOffset.y, - intersection.point.z + gizmo._translateOffset.z); - break; - case bg.Axis.Y: - matrix = bg.Matrix4.Translation(intersection.point.x + gizmo._translateOffset.x, - origin.y, - intersection.point.z + gizmo._translateOffset.z); - break; - case bg.Axis.Z: - matrix = bg.Matrix4.Translation(intersection.point.x + gizmo._translateOffset.x, - intersection.point.y + gizmo._translateOffset.y, - origin.z); - break; - } - - matrix.mult(rotation); - gizmo._lastPickPoint = intersection.point; - - return matrix; - } - - function rotateMatrix(gizmo,intersection,fine) { - let matrix = new bg.Matrix4(gizmo.transform.matrix); - let rotation = matrix.rotation; - let origin = matrix.position; - - if (!gizmo._lastPickPoint) { - gizmo._lastPickPoint = intersection.ray.end; - gizmo._translateOffset = new bg.Vector3(origin); - gizmo._translateOffset.sub(intersection.ray.end); - } - - if (!fine) { - let prevRotation = new bg.Matrix4(rotation); - rotation = rotationBetweenPoints(gizmo.planeAxis,gizmo._lastPickPoint,intersection.point,origin,bg.Math.degreesToRadians(22.5)); - if (rotation.x!=0 || rotation.y!=0 || rotation.z!=0 || rotation.w!=1) { - matrix = bg.Matrix4.Translation(origin) - .mult(rotation.getMatrix4()) - .mult(prevRotation); - gizmo._lastPickPoint = intersection.point; - } - } - else { - let prevRotation = new bg.Matrix4(rotation); - rotation = rotationBetweenPoints(gizmo.planeAxis,gizmo._lastPickPoint,intersection.point,origin); - if (rotation.x!=0 || rotation.y!=0 || rotation.z!=0 || rotation.w!=1) { - matrix = bg.Matrix4.Translation(origin) - .mult(rotation.getMatrix4()) - .mult(prevRotation); - gizmo._lastPickPoint = intersection.point; - } - } - - return matrix; - } - - function calculateClosestPlane(gizmo,matrixState) { - let cameraForward = matrixState.viewMatrixStack.matrix.forwardVector; - let upVector = matrixState.viewMatrixStack.matrix.upVector; - let xVector = new bg.Vector3(1,0,0); - let yVector = new bg.Vector3(0,1,0); - let zVector = new bg.Vector3(0,0,1); - let xVectorInv = new bg.Vector3(-1,0,0); - let yVectorInv = new bg.Vector3(0,-1,0); - let zVectorInv = new bg.Vector3(0,0,-1); - - let upAlpha = Math.acos(upVector.dot(yVector)); - if (upAlpha>0.9) { - gizmo.plane = bg.Axis.Y; - } - else { - let angles = [ - Math.acos(cameraForward.dot(xVector)), // x - Math.acos(cameraForward.dot(yVector)), // y - Math.acos(cameraForward.dot(zVector)), // z - Math.acos(cameraForward.dot(xVectorInv)), // -x - Math.acos(cameraForward.dot(yVectorInv)), // -y - Math.acos(cameraForward.dot(zVectorInv)) // -z - ]; - let min = angles[0]; - let planeIndex = 0; - angles.reduce(function(prev,v,index) { - if (v { - // The RGBA values are inverted because the alpha channel must be major than zero to - // produce any output in the framebuffer - if (item.plist.visible) { - pipeline.effect.pickId = new bg.Color(item.id.a/255,item.id.b/255,item.id.g/255,item.id.r/255); - pipeline.draw(item.plist); - } - }); - pipeline.depthTest = dt; - } - else if (pipeline.effect instanceof bg.manipulation.GizmoEffect) { - // Draw gizmo - this._gizmoItems.forEach((item) => { - if (item.plist.visible) { - pipeline.effect.texture = item.material.texture; - pipeline.effect.color = item.material.diffuse; - pipeline.draw(item.plist); - } - }) - } - matrixState.modelMatrixStack.pop(); - } - - beginDrag(action,pos) { - this._lastPickPoint = null; - } - - drag(action,startPos,endPos,camera) { - if (this.transform) { - let plane = new bg.physics.Plane(this.planeAxis); - let ray = bg.physics.Ray.RayWithScreenPoint(endPos,camera.projection,camera.viewMatrix,camera.viewport); - let intersection = bg.physics.Intersection.RayToPlane(ray,plane); - - if (intersection.intersects()) { - let matrix = new bg.Matrix4(this.transform.matrix); - this._gizmoP = bg.Matrix4.Translation(this.transform.matrix.position); - - switch (action) { - case bg.manipulation.GizmoAction.TRANSLATE: - matrix = translateMatrix(this,intersection); - break; - case bg.manipulation.GizmoAction.ROTATE: - matrix = rotateMatrix(this,intersection,false); - break; - case bg.manipulation.GizmoAction.ROTATE_FINE: - matrix = rotateMatrix(this,intersection,true); - break; - } - - this.transform.matrix = matrix; - } - } - } - - endDrag(action) { - this._lastPickPoint = null; - } - } - - class UnifiedGizmo extends Gizmo { - constructor(path,visible=true) { - super(path,visible); - this._translateSpeed = 0.005; - this._rotateSpeed = 0.005; - this._scaleSpeed = 0.001; - this._gizmoTransform = bg.Matrix4.Identity(); - } - - get gizmoTransform() { - return this._gizmoTransform; - } - - get translateSpeed() { return this._translateSpeed; } - set translateSpeed(s) { this._translateSpeed = s; } - - get rotateSpeed() { return this._rotateSpeed; } - set rotateSpeed(s) { this._rotateSpeed = s; } - - get scaleSpeed() { return this._scaleSpeed; } - set scaleSpeed(s) { this._scaleSpeed = s; } - - clone() { - let newGizmo = new PlaneGizmo(this._gizmoPath); - newGizmo.offset.assign(this._offset); - newGizmo.visible = this._visible; - return newGizmo; - } - - init() { - super.init(); - this._gizmoP = bg.Matrix4.Translation(this.transform.matrix.position); - this._gizmoTransform = this.transform.matrix.rotation; - } - - display(pipeline,matrixState) { - if (!this._gizmoItems || !this.visible) return; - super.display(pipeline,matrixState); - } - - beginDrag(action,pos) { - this._lastPickPoint = null; - } - - drag(action,startPos,endPos,camera) { - if (this.transform) { - if (!this._lastPickPoint) { - this._lastPickPoint = endPos; - } - - let matrix = new bg.Matrix4(this.transform.matrix); - this._gizmoP = bg.Matrix4.Translation(this.transform.matrix.position); - let diff = new bg.Vector2(this._lastPickPoint); - diff.sub(endPos); - - let matrixState = bg.base.MatrixState.Current(); - let modelview = new bg.Matrix4(matrixState.viewMatrixStack.matrix); - modelview.mult(matrixState.modelMatrixStack.matrix); - let s = modelview.position.magnitude() / this._scale; - s = s { - this._gizmoItems = gizmoItems; - bg.emitImageLoadEvent(); - }) - - .catch((err) => { - this._error = true; - throw err; - }) - } - } - } - - // All gizmo types share the same typeId, because a node can only contain one gizmo - bg.scene.registerComponent(bg.manipulation,Gizmo,"bg.manipulation.Gizmo"); - bg.scene.registerComponent(bg.manipulation,PlaneGizmo,"bg.manipulation.Gizmo"); - bg.scene.registerComponent(bg.manipulation,UnifiedGizmo,"bg.manipulation.Gizmo"); - bg.scene.registerComponent(bg.manipulation,MultiModeGizmo,"bg.manipulation.Gizmo"); - -})(); -(function() { - - let shader = {}; - - function initShaders() { - shader[bg.webgl1.EngineId] = { - vertex: ` - attribute vec3 inVertex; - - uniform mat4 inModelMatrix; - uniform mat4 inViewMatrix; - uniform mat4 inProjectionMatrix; - - void main() { - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - } - `, - - fragment:` - precision highp float; - - uniform vec4 inColorId; - - void main() { - gl_FragColor = inColorId; - } - ` - }; - } - - class ColorPickEffect extends bg.base.Effect { - constructor(context) { - super(context); - initShaders(); - } - - get inputVars() { - return { - vertex:'inVertex' - } - } - - set matrixState(m) { this._matrixState = m; } - get matrixState() { - return this._matrixState; - } - - set pickId(p) { this._pickId = p; } - get pickId() { return this._pickId || bg.Color.Transparent(); } - - get shader() { - if (!this._shader) { - this._shader = new bg.base.Shader(this.context); - this._shader.addShaderSource(bg.base.ShaderType.VERTEX, shader[bg.webgl1.EngineId].vertex); - this._shader.addShaderSource(bg.base.ShaderType.FRAGMENT, shader[bg.webgl1.EngineId].fragment); - this._shader.link(); - if (!this._shader.status) { - console.log(this._shader.compileError); - console.log(this._shader.linkError); - } - else { - this._shader.initVars([ - 'inVertex' - ],[ - 'inModelMatrix', - 'inViewMatrix', - 'inProjectionMatrix', - 'inColorId' - ]); - } - } - return this._shader - } - - setupVars() { - this.shader.setMatrix4('inModelMatrix',this.matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',new bg.Matrix4(this.matrixState.viewMatrixStack.matrixConst)); - this.shader.setMatrix4('inProjectionMatrix',this.matrixState.projectionMatrixStack.matrixConst); - this.shader.setVector4('inColorId', this.pickId); - } - - } - - bg.manipulation.ColorPickEffect = ColorPickEffect; - - class FindPickIdVisitor extends bg.scene.NodeVisitor { - constructor(target) { - super() - this._target = target; - } - - get target() { return this._target; } - set target(t) { this._target = t; this._result = null; } - - get result() { return this._result; } - - visit(node) { - let selectable = node.component("bg.manipulation.Selectable"); - let gizmo = node.component("bg.manipulation.Gizmo"); - if (gizmo && !gizmo.visible) { - gizmo = null; - } - this._result = this._result || - (selectable && selectable.findId(this.target)) || - (gizmo && gizmo.findId(this.target)); - } - } - - bg.manipulation.FindPickIdVisitor = FindPickIdVisitor; - - class MousePicker extends bg.app.ContextObject { - - constructor(context) { - super(context); - } - - get pipeline() { - if (!this._pipeline) { - this._pipeline = new bg.base.Pipeline(this.context); - - this._pipeline.effect = new ColorPickEffect(this.context); - this._renderSurface = new bg.base.TextureSurface(this.context); - this._renderSurface.create(); - this._pipeline.renderSurface = this._renderSurface; - this._pipeline.clearColor = new bg.Color(0,0,0,0); - } - return this._pipeline; - } - - get matrixState() { - if (!this._matrixState) { - this._matrixState = new bg.base.MatrixState(); - } - return this._matrixState; - } - - get drawVisitor() { - if (!this._drawVisitor) { - this._drawVisitor = new bg.scene.DrawVisitor(this.pipeline,this.matrixState); - } - return this._drawVisitor; - } - - pick(sceneRoot,camera,mousePosition) { - let restorePipeline = bg.base.Pipeline.Current(); - let restoreMatrixState = bg.base.MatrixState.Current(); - bg.base.Pipeline.SetCurrent(this.pipeline); - bg.base.MatrixState.SetCurrent(this.matrixState); - this.pipeline.viewport = camera.viewport; - this.pipeline.effect.matrixState = this.matrixState; - - - this.pipeline.clearBuffers(bg.base.ClearBuffers.COLOR | bg.base.ClearBuffers.DEPTH); - - this.matrixState.projectionMatrixStack.set(camera.projection); - this.matrixState.viewMatrixStack.set(camera.viewMatrix); - - let opacityLayer = this.pipeline.opacityLayer; - this.pipeline.opacityLayer = bg.base.OpacityLayer.SELECTION; - sceneRoot.accept(this.drawVisitor); - this.pipeline.opacityLayer = bg.base.OpacityLayer.GIZMOS_SELECTION; - this.pipeline.clearBuffers(bg.base.ClearBuffers.DEPTH); - sceneRoot.accept(this.drawVisitor); - this.pipeline.opacityLayer = opacityLayer; - - let buffer = this.pipeline.renderSurface.readBuffer(new bg.Viewport(mousePosition.x, mousePosition.y,1,1)); - let pickId = { - r: buffer[3], - g: buffer[2], - b: buffer[1], - a: buffer[0] - }; - - let findIdVisitor = new FindPickIdVisitor(pickId); - sceneRoot.accept(findIdVisitor); - - if (restorePipeline) { - bg.base.Pipeline.SetCurrent(restorePipeline); - } - if (restoreMatrixState) { - bg.base.MatrixState.SetCurrent(restoreMatrixState); - } - - return findIdVisitor.result; - } - } - - bg.manipulation.MousePicker = MousePicker; - -})(); - -(function() { - - let s_r = 0; - let s_g = 0; - let s_b = 0; - let s_a = 0; - - function incrementIdentifier() { - if (s_r==255) { - s_r = 0; - incG(); - } - else { - ++s_r; - } - } - - function incG() { - if (s_g==255) { - s_g = 0; - incB(); - } - else { - ++s_g; - } - } - - function incB() { - if (s_b==255) { - s_b = 0; - incA(); - } - else { - ++s_b; - } - } - - function incA() { - if (s_a==255) { - s_a = 0; - bg.log("WARNING: Maximum number of picker identifier reached."); - } - else { - ++s_a; - } - } - - function getIdentifier() { - incrementIdentifier(); - return { r:s_r, g:s_g, b:s_g, a:s_a }; - } - - let s_selectMode = false; - - bg.manipulation.SelectableType = { - PLIST:1, - GIZMO:2, - GIZMO_ICON:3 - }; - - let s_selectionIconPlist = null; - function selectionIconPlist() { - if (!s_selectionIconPlist) { - s_selectionIconPlist = bg.scene.PrimitiveFactory.SpherePolyList(this.node.context,0.5); - } - return s_selectionIconPlist; - } - - let g_selectableIcons = [ - "bg.scene.Camera", - "bg.scene.Light", - "bg.scene.Transform", - "bg.scene.TextRect" - ]; - - - class Selectable extends bg.scene.Component { - static SetSelectableIcons(sel) { - g_selectableIcons = sel; - } - - static AddSelectableIcon(sel) { - if (g_selectableIcons.indexOf(sel)==-1) { - g_selectableIcons.push(sel); - } - } - - static RemoveSelectableIcon(sel) { - let index = g_selectableIcons.indexOf(sel); - if (index>=0) { - g_selectableIcons.splice(index,1); - } - } - - static SetSelectMode(m) { s_selectMode = m; } - - static GetIdentifier() { return getIdentifier(); } - - constructor() { - super(); - this._initialized = false; - this._selectablePlist = []; - } - - clone() { - return new Selectable(); - } - - buildIdentifier() { - this._initialized = false; - this._selectablePlist = []; - } - - findId(id) { - let result = null; - this._selectablePlist.some((item) => { - if (item.id.r==id.r && item.id.g==id.g && item.id.b==id.b && item.id.a==id.a) { - result = item; - return true; - } - }); - return result; - } - - frame(delta) { - if (!this._initialized && this.drawable) { - this.drawable.forEach((plist,material) => { - let id = getIdentifier(); - this._selectablePlist.push({ - id:id, - type:bg.manipulation.SelectableType.PLIST, - plist:plist, - material:material, - drawable:this.drawable, - node:this.node - }); - }); - this._initialized = true; - } - else if (!this._initialized) { - // Use icon to pick item - let id = getIdentifier(); - this._selectablePlist.push({ - id:id, - type:bg.manipulation.SelectableType.GIZMO_ICON, - plist:null, - material:null, - drawable:null, - node:this.node - }); - this._initialized = true; - } - } - - display(pipeline,matrixState) { - if (pipeline.effect instanceof bg.manipulation.ColorPickEffect && - pipeline.opacityLayer & bg.base.OpacityLayer.SELECTION) - { - let selectableByIcon = g_selectableIcons.some((componentType) => { - return this.node.component(componentType)!=null; - }); - this._selectablePlist.forEach((item) => { - let pickId = new bg.Color(item.id.a/255,item.id.b/255,item.id.g/255,item.id.r/255); - if (item.plist && item.plist.visible) { - // The RGBA values are inverted because the alpha channel must be major than zero to - // produce any output in the framebuffer - pipeline.effect.pickId = pickId; - pipeline.draw(item.plist); - } - else if (!item.plist && selectableByIcon) { - let s = matrixState.cameraDistanceScale * 0.1; - pipeline.effect.pickId = pickId; - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.scale(s,s,s); - pipeline.draw(selectionIconPlist.apply(this)); - matrixState.modelMatrixStack.pop(); - } - }); - } - } - } - - bg.scene.registerComponent(bg.manipulation,Selectable,"bg.manipulation.Selectable"); -})(); -(function() { - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class BorderDetectionEffect extends bg.base.TextureEffect { - constructor(context) { - super(context); - - let vertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - let fragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - vertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - fragment.addParameter([ - lib().inputs.material.texture, - { name:"inTexSize", dataType:"vec2", role:"value" }, - { name:"inConvMatrix", dataType:"float", role:"value", vec:9 }, - { name:"inBorderColor", dataType:"vec4", role:"value" }, - { name:"inBorderWidth", dataType:"float", role:"value" }, - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - vertex.setMainBody(` - gl_Position = vec4(inVertex,1.0); - fsTexCoord = inTex0; - `); - fragment.addFunction(lib().functions.utils.applyConvolution); - fragment.setMainBody(` - vec4 selectionColor = applyConvolution(inTexture,fsTexCoord,inTexSize,inConvMatrix,inBorderWidth); - if (selectionColor.r!=0.0 && selectionColor.g!=0.0 && selectionColor.b!=0.0) { - gl_FragColor = inBorderColor; - } - else { - discard; - } - `); - } - - this.setupShaderSource([ - vertex, - fragment - ]); - - this._highlightColor = bg.Color.White(); - this._borderWidth = 2; - } - - get highlightColor() { return this._highlightColor; } - set highlightColor(c) { this._highlightColor = c; } - - get borderWidth() { return this._borderWidth; } - set borderWidth(w) { this._borderWidth = w; } - - setupVars() { - let texture = null; - if (this._surface instanceof bg.base.Texture) { - texture = this._surface; - } - else if (this._surface instanceof bg.base.RenderSurface) { - texture = this._surface.getTexture(0); - } - - if (texture) { - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2("inTexSize",texture.size); - } - - let convMatrix = [ - 0, 1, 0, - 1,-4, 1, - 0, 1, 0 - ]; - this.shader.setValueFloatPtr("inConvMatrix",convMatrix); - this.shader.setVector4("inBorderColor", this._highlightColor); - this.shader.setValueFloat("inBorderWidth", this._borderWidth); - } - } - - bg.manipulation.BorderDetectionEffect = BorderDetectionEffect; - - let s_plainColorVertex = null; - let s_plainColorFragment = null; - - function plainColorVertex() { - if (!s_plainColorVertex) { - s_plainColorVertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_plainColorVertex.addParameter(lib().inputs.buffers.vertex); - s_plainColorVertex.addParameter(lib().inputs.matrix.all); - - if (bg.Engine.Get().id=="webgl1") { - s_plainColorVertex.setMainBody(` - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - `); - } - } - return s_plainColorVertex; - } - - function plainColorFragment() { - if (!s_plainColorFragment) { - s_plainColorFragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - s_plainColorFragment.addParameter([ - { name:"inColor", dataType:"vec4", role:"value" }, - { name:"inSelectMode", dataType:"int", role:"value" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_plainColorFragment.setMainBody(` - if (inSelectMode==0) { - discard; - } - else { - gl_FragColor = inColor; - } - `); - } - } - return s_plainColorFragment; - } - - class PlainColorEffect extends bg.base.Effect { - constructor(context) { - super(context); - - let sources = [ - plainColorVertex(), - plainColorFragment() - ]; - this.setupShaderSource(sources); - } - - beginDraw() { - bg.Math.seed = 1; - } - - setupVars() { - this._baseColor = new bg.Color(bg.Math.seededRandom(),bg.Math.seededRandom(),bg.Math.seededRandom(),1); - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - this.shader.setMatrix4('inModelMatrix',matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',viewMatrix); - this.shader.setMatrix4('inProjectionMatrix',matrixState.projectionMatrixStack.matrixConst); - this.shader.setVector4('inColor', this._baseColor); - this.shader.setValueInt("inSelectMode", this.material.selectMode); - } - } - - bg.manipulation.PlainColorEffect = PlainColorEffect; - - function buildOffscreenPipeline() { - let offscreenPipeline = new bg.base.Pipeline(this.context); - - let renderSurface = new bg.base.TextureSurface(this.context); - offscreenPipeline.effect = new bg.manipulation.PlainColorEffect(this.context); - let colorAttachments = [ - { type:bg.base.RenderSurfaceType.RGBA, format:bg.base.RenderSurfaceFormat.UNSIGNED_BYTE }, - { type:bg.base.RenderSurfaceType.DEPTH, format:bg.base.RenderSurfaceFormat.RENDERBUFFER } - ]; - renderSurface.create(colorAttachments); - offscreenPipeline.renderSurface = renderSurface; - - return offscreenPipeline; - } - - class SelectionHighlight extends bg.app.ContextObject { - - constructor(context) { - super(context); - - this._offscreenPipeline = buildOffscreenPipeline.apply(this); - - this._pipeline = new bg.base.Pipeline(this.context); - this._pipeline.textureEffect = new bg.manipulation.BorderDetectionEffect(this.context); - - this._matrixState = new bg.base.MatrixState(); - - this._drawVisitor = new bg.scene.DrawVisitor(this._offscreenPipeline,this._matrixState); - this._drawVisitor.forceDraw = false; - } - - get highlightColor() { return this._pipeline.textureEffect.highlightColor; } - set highlightColor(c) { this._pipeline.textureEffect.highlightColor = c; } - - get borderWidth() { return this._pipeline.textureEffect.borderWidth; } - set borderWidth(w) { this._pipeline.textureEffect.borderWidth = w; } - - get drawInvisiblePolyList() { return this._drawVisitor.forceDraw; } - set drawInvisiblePolyList(d) { this._drawVisitor.forceDraw = d; } - - drawSelection(sceneRoot,camera) { - let restorePipeline = bg.base.Pipeline.Current(); - let restoreMatrixState = bg.base.MatrixState.Current(); - this._offscreenPipeline.viewport = camera.viewport; - this._pipeline.viewport = camera.viewport; - - bg.base.Pipeline.SetCurrent(this._offscreenPipeline); - bg.base.MatrixState.SetCurrent(this._matrixState); - this._offscreenPipeline.clearBuffers(bg.base.ClearBuffers.COLOR | bg.base.ClearBuffers.DEPTH); - this._matrixState.projectionMatrixStack.set(camera.projection); - this._matrixState.viewMatrixStack.set(camera.viewMatrix); - this._matrixState.modelMatrixStack.identity(); - sceneRoot.accept(this._drawVisitor); - - let texture = this._offscreenPipeline.renderSurface.getTexture(0); - bg.base.Pipeline.SetCurrent(this._pipeline); - this._pipeline.blend = true; - this._pipeline.blendMode = bg.base.BlendMode.ADD; - this._pipeline.drawTexture(texture); - - if (restorePipeline) { - bg.base.Pipeline.SetCurrent(restorePipeline); - } - if (restoreMatrixState) { - bg.base.MatrixState.SetCurrent(restoreMatrixState); - } - } - } - - bg.manipulation.SelectionHighlight = SelectionHighlight; - -})(); -(function() { - - let Action = { - ROTATE:0, - PAN:1, - ZOOM:2 - }; - - function getOrbitAction(cameraCtrl) { - let left = bg.app.Mouse.LeftButton(), - middle = bg.app.Mouse.MiddleButton(), - right = bg.app.Mouse.RightButton(); - - switch (true) { - case left==cameraCtrl._rotateButtons.left && - middle==cameraCtrl._rotateButtons.middle && - right==cameraCtrl._rotateButtons.right: - return Action.ROTATE; - case left==cameraCtrl._panButtons.left && - middle==cameraCtrl._panButtons.middle && - right==cameraCtrl._panButtons.right: - return Action.PAN; - case left==cameraCtrl._zoomButtons.left && - middle==cameraCtrl._zoomButtons.middle && - right==cameraCtrl._zoomButtons.right: - return Action.ZOOM; - } - } - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i OrbitCameraController.DisableAll(ch)); - } - - static SetUniqueEnabled(orbitCameraController,sceneRoot) { - OrbitCameraController.DisableAll(sceneRoot); - orbitCameraController.enabled = true; - } - - constructor() { - super(); - - this._rotateButtons = { left:true, middle:false, right:false }; - this._panButtons = { left:false, middle:false, right:true }; - this._zoomButtons = { left:false, middle:true, right:false }; - - this._rotation = new bg.Vector2(); - this._distance = 5; - this._center = new bg.Vector3(); - this._rotationSpeed = 0.2; - this._forward = 0; - this._left = 0; - this._wheelSpeed = 1; - this._minFocus = 2; - - this._minPitch = 0.1; - this._maxPitch = 85.0; - this._minDistance = 0.4; - this._maxDistance = 24.0; - - this._maxX = 15; - this._minX = -15; - this._minY = 0.1; - this._maxY = 2.0; - this._maxZ = 15; - this._minZ = -15; - - this._displacementSpeed = 0.1; - - this._enabled = true; - - // Do not serialize/deserialize this: - this._keys = {}; - this._showLimitGizmo = true; - this._limitGizmoColor = bg.Color.Green(); - - // This is used for orthographic projections - this._viewWidth = 50; - - this._lastTouch = []; - } - - clone() { - let result = new OrbitCameraController(); - let compData = {}; - this.serialize(compData,[],""); - result.deserialize(null,compData,""); - return result; - } - - setRotateButtons(left,middle,right) { - this._rotateButtons = { left:left, middle:middle, right:right }; - } - - setPanButtons(left,middle,right) { - this._panButtons = { left:left, middle:middle, right:right }; - } - - setZoomButtons(left,middle,right) { - this._zoomButtons = { left:left, middle:middle, right:right }; - } - - get rotation() { return this._rotation; } - set rotation(r) { this._rotation = r; } - get distance() { return this._distance; } - set distance(d) { this._distance = d; } - get center() { return this._center; } - set center(c) { this._center = c; } - get whellSpeed() { this._wheelSpeed; } - set wheelSpeed(w) { this._wheelSpeed = w; } - - get viewWidth() { return this._viewWidth; } - - get minCameraFocus() { return this._minFocus; } - set minCameraFocus(f) { this._minFocus = f; } - get minPitch() { return this._minPitch; } - set minPitch(p) { this._minPitch = p; } - get maxPitch() { return this._maxPitch; } - set maxPitch(p) { this._maxPitch = p; } - get minDistance() { return this._minDistance; } - set minDistance(d) { this._minDistance = d; } - get maxDistance() { return this._maxDistance; } - set maxDistance(d) { this._maxDistance = d; } - - get minX() { return this._minX; } - get maxX() { return this._maxX; } - get minY() { return this._minY; } - get maxY() { return this._maxY; } - get minZ() { return this._minZ; } - get maxZ() { return this._maxZ; } - - set minX(val) { this._minX = val; } - set maxX(val) { this._maxX = val; } - set minY(val) { this._minY = val; } - set maxY(val) { this._maxY = val; } - set minZ(val) { this._minZ = val; } - set maxZ(val) { this._maxZ = val; } - - get displacementSpeed() { return this._displacementSpeed; } - set displacementSpeed(s) { this._displacementSpeed = s; } - - get enabled() { return this._enabled; } - set enabled(e) { this._enabled = e; } - - get showLimitGizmo() { return this._showLimitGizmo; } - set showLimitGizmo(l) { this._showLimitGizmo = l; } - get limitGizmoColor() { return this._limitGizmoColor; } - set limitGizmoColor(c) { this._limitGizmoColor = c; } - - displayGizmo(pipeline,matrixState) { - if (!this._showLimitGizmo) return; - let plist = getGizmo.apply(this); - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.identity(); - if (plist) { - pipeline.draw(plist); - } - matrixState.modelMatrixStack.pop(); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.rotateButtons = this._rotateButtons; - componentData.panButtons = this._panButtons; - componentData.zoomButtons = this._zoomButtons; - componentData.rotation = this._rotation.toArray(); - componentData.distance = this._distance; - componentData.center = this._center.toArray(); - componentData.rotationSpeed = this._rotationSpeed; - componentData.forward = this._forward; - componentData.left = this._left; - componentData.wheelSpeed = this._wheelSpeed; - componentData.minFocus = this._minFocus; - componentData.minPitch = this._minPitch; - componentData.maxPitch = this._maxPitch; - componentData.minDistance = this._minDistance; - componentData.maxDistance = this._maxDistance; - componentData.maxX = this._maxX; - componentData.minX = this._minX; - componentData.minY = this._minY; - componentData.maxY = this._maxY; - componentData.maxZ = this._maxZ; - componentData.minZ = this._minZ; - componentData.displacementSpeed = this._displacementSpeed; - componentData.enabled = this._enabled; - } - - deserialize(context,componentData,url) { - this._rotateButtons = componentData.rotateButtons || this._rotateButtons; - this._panButtons = componentData.panButtons || this._panButtons; - this._zoomButtons = componentData.zoomButtons || this._zoomButtons; - this._rotation = new bg.Vector2(componentData.rotation) || this._rotation; - this._distance = componentData.distance!==undefined ? componentData.distance : this._distance; - this._center = new bg.Vector3(componentData.center) || this._center; - this._rotationSpeed = componentData.rotationSpeed!==undefined ? componentData.rotationSpeed : this._rotationSpeed; - this._forward = componentData.forward!==undefined ? componentData.forward : this._forward; - this._left = componentData.left!==undefined ? componentData.left : this._left; - this._wheelSpeed = componentData.wheelSpeed!==undefined ? componentData.wheelSpeed : this._wheelSpeed; - this._minFocus = componentData.minFocus!==undefined ? componentData.minFocus : this._minFocus; - this._minPitch = componentData.minPitch!==undefined ? componentData.minPitch : this._minPitch; - this._maxPitch = componentData.maxPitch!==undefined ? componentData.maxPitch : this._maxPitch; - this._minDistance = componentData.minDistance!==undefined ? componentData.minDistance : this._minDistance; - this._maxDistance = componentData.maxDistance!==undefined ? componentData.maxDistance : this._maxDistance; - this._maxX = componentData.maxX!==undefined ? componentData.maxX : this._maxX; - this._minX = componentData.minX!==undefined ? componentData.minX : this._minX; - this._minY = componentData.minY!==undefined ? componentData.minY : this._minY; - this._maxY = componentData.maxY!==undefined ? componentData.maxY : this._maxY; - this._maxZ = componentData.maxZ!==undefined ? componentData.maxZ : this._maxZ; - this._minZ = componentData.minZ!==undefined ? componentData.minZ : this._minZ; - this._displacementSpeed = componentData.displacementSpeed!==undefined ? componentData.displacementSpeed : this._displacementSpeed; - this._enabled = componentData.enabled!==undefined ? componentData.enabled : this._enabled; - } - - frame(delta) { - let orthoStrategy = this.camera && typeof(this.camera.projectionStrategy)=="object" && - this.camera.projectionStrategy instanceof bg.scene.OrthographicProjectionStrategy ? - this.camera.projectionStrategy : null; - - - if (this.transform && this.enabled) { - let forward = this.transform.matrix.forwardVector; - let left = this.transform.matrix.leftVector; - forward.scale(this._forward); - left.scale(this._left); - this._center.add(forward).add(left); - - let pitch = this._rotation.x>this._minPitch ? this._rotation.x:this._minPitch; - pitch = pitchthis._minDistance ? this._distance:this._minDistance; - this._distance = this._distancethis._maxX) this._center.x = this._maxX; - - if (this._center.ythis._maxY) this._center.y = this._maxY; - - if (this._center.zthis._maxZ) this._center.z = this._maxZ; - - this.transform.matrix - .identity() - .translate(this._center) - .rotate(bg.Math.degreesToRadians(this._rotation.y), 0,1,0) - .rotate(bg.Math.degreesToRadians(pitch), -1,0,0); - - if (orthoStrategy) { - orthoStrategy.viewWidth = this._viewWidth; - } - else { - this.transform.matrix.translate(0,0,this._distance); - } - } - - if (this.camera) { - this.camera.focus = this._distance>this._minFocus ? this._distance:this._minFocus; - - } - } - - mouseDown(evt) { - if (!this.enabled) return; - this._mouseButtonPressed = true; - this._lastPos = new bg.Vector2(evt.x,evt.y); - } - - mouseUp(evt) { - this._mouseButtonPressed = false; - } - - mouseDrag(evt) { - if (this.transform && this._lastPos && this.enabled) { - let delta = new bg.Vector2(this._lastPos.y - evt.y, - this._lastPos.x - evt.x); - this._lastPos.set(evt.x,evt.y); - let orthoStrategy = this.camera && typeof(this.camera.projectionStrategy)=="object" && - this.camera.projectionStrategy instanceof bg.scene.OrthographicProjectionStrategy ? - true : false; - - switch (getOrbitAction(this)) { - case Action.ROTATE: - delta.x = delta.x * -1; - this._rotation.add(delta.scale(0.5)); - break; - case Action.PAN: - let up = this.transform.matrix.upVector; - let left = this.transform.matrix.leftVector; - - if (orthoStrategy) { - up.scale(delta.x * -0.0005 * this._viewWidth); - left.scale(delta.y * -0.0005 * this._viewWidth); - } - else { - up.scale(delta.x * -0.001 * this._distance); - left.scale(delta.y * -0.001 * this._distance); - } - this._center.add(up).add(left); - break; - case Action.ZOOM: - this._distance += delta.x * 0.01 * this._distance; - this._viewWidth += delta.x * 0.01 * this._viewWidth; - if (this._viewWidth<0.5) this._viewWidth = 0.5; - break; - } - } - } - - mouseWheel(evt) { - if (!this.enabled) return; - let mult = this._distance>0.01 ? this._distance:0.01; - let wMult = this._viewWidth>1 ? this._viewWidth:1; - this._distance += evt.delta * 0.001 * mult * this._wheelSpeed; - this._viewWidth += evt.delta * 0.0001 * wMult * this._wheelSpeed; - if (this._viewWidth<0.5) this._viewWidth = 0.5; - } - - touchStart(evt) { - if (!this.enabled) return; - this._lastTouch = evt.touches; - } - - touchMove(evt) { - if (this._lastTouch.length==evt.touches.length && this.transform && this.enabled) { - if (this._lastTouch.length==1) { - // Rotate - let last = this._lastTouch[0]; - let t = evt.touches[0]; - let delta = new bg.Vector2((last.y - t.y) * -1.0, last.x - t.x); - - this._rotation.add(delta.scale(0.5)); - } - else if (this._lastTouch.length==2) { - // Pan/zoom - let l0 = this._lastTouch[0]; - let l1 = this._lastTouch[1]; - let t0 = null; - let t1 = null; - evt.touches.forEach((touch) => { - if (touch.identifier==l0.identifier) { - t0 = touch; - } - else if (touch.identifier==l1.identifier) { - t1 = touch; - } - }); - let dist0 = Math.round((new bg.Vector2(l0.x,l0.y)).sub(new bg.Vector3(l1.x,l1.y)).magnitude()); - let dist1 = Math.round((new bg.Vector2(t0.x,t0.y)).sub(new bg.Vector3(t1.x,t1.y)).magnitude()); - let delta = new bg.Vector2(l0.y - t0.y, l1.x - t1.x); - let up = this.transform.matrix.upVector; - let left = this.transform.matrix.leftVector; - - up.scale(delta.x * -0.001 * this._distance); - left.scale(delta.y * -0.001 * this._distance); - this._center.add(up).add(left); - - this._distance += (dist0 - dist1) * 0.005 * this._distance; - } - } - this._lastTouch = evt.touches; - } - - keyDown(evt) { - if (!this.enabled) return; - this._keys[evt.key] = true; - bg.app.MainLoop.singleton.windowController.postRedisplay(); - } - - keyUp(evt) { - if (!this.enabled) return; - this._keys[evt.key] = false; - } - } - - class FPSCameraController extends bg.scene.Component { - - } - - class TargetCameraController extends bg.scene.Component { - - } - - bg.scene.registerComponent(bg.manipulation,OrbitCameraController,"bg.manipulation.OrbitCameraController"); - bg.scene.registerComponent(bg.manipulation,FPSCameraController,"bg.manipulation.FPSCameraController"); - bg.scene.registerComponent(bg.manipulation,TargetCameraController,"bg.manipulation.TargetCameraController"); - -})(); - -bg.tools = { - -}; - -(function() { - class BoundingBox { - constructor(drawableOrPlist, transformMatrix) { - this._min = new bg.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE); - this._max = new bg.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE); - this._center = null; - this._size = null; - this._halfSize = null; - - this._vertexArray = []; - transformMatrix = transformMatrix || bg.Matrix4.Identity(); - if (drawableOrPlist instanceof bg.scene.Drawable) { - this.addDrawable(drawableOrPlist,transformMatrix); - } - else if (drawableOrPlist instanceof bg.scene.PolyList) { - this.addPolyList(drawableOrPlist,transformMatrix); - } - } - - clear() { - this._min = bg.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE); - this._max = bg.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE); - this._center = this._size = this._halfSize = null; - } - - get min() { return this._min; } - get max() { return this._max; } - get center() { - if (!this._center) { - let s = this.halfSize; - this._center = bg.Vector3.Add(this.halfSize, this._min); - } - return this._center; - } - - get size() { - if (!this._size) { - this._size = bg.Vector3.Sub(this.max, this.min); - } - return this._size; - } - - get halfSize() { - if (!this._halfSize) { - this._halfSize = new bg.Vector3(this.size); - this._halfSize.scale(0.5); - } - return this._halfSize; - } - - addPolyList(polyList, trx) { - this._center = this._size = this._halfSize = null; - for (let i = 0; ithis._max.x) this._max.x = vec.x; - if (vec.z>this._max.z) this._max.z = vec.z; - if (vec.y>this._max.y) this._max.y = vec.y; - } - } - - addDrawable(drawable, trxBase) { - drawable.forEach((plist,mat,elemTrx) => { - if (plist.visible) { - let trx = new bg.Matrix4(trxBase); - if (elemTrx) trx.mult(elemTrx); - this.addPolyList(plist,trx); - } - }); - } - } - - bg.tools.BoundingBox = BoundingBox; -})(); -(function() { - function createCanvas(width,height) { - let result = document.createElement("canvas"); - result.width = width; - result.height = height; - result.style.width = width + "px"; - result.style.height = height + "px"; - return result; - } - - function resizeCanvas(canvas,w,h) { - canvas.width = w; - canvas.height = h; - canvas.style.width = w + 'px'; - canvas.style.height = h + 'px'; - } - - let g_texturePreventRemove = []; - - class CanvasTexture extends bg.app.ContextObject { - - constructor(context,width,height,drawCallback) { - super(context); - - this._canvas = createCanvas(width,height); - - this._drawCallback = drawCallback; - - this._drawCallback(this._canvas.getContext("2d",{preserverDrawingBuffer:true}),this._canvas.width,this._canvas.height); - this._texture = bg.base.Texture.FromCanvas(context,this._canvas); - } - - get width() { return this._canvas.width; } - get height() { return this._canvas.height; } - get canvas() { return this._canvas; } - get texture() { return this._texture; } - - resize(w,h) { - resizeCanvas(this._canvas,w,h); - this.update(); - } - - update() { - this._drawCallback(this._canvas.getContext("2d",{preserverDrawingBuffer:true}),this.width,this.height); - - bg.base.Texture.UpdateCanvasImage(this._texture,this._canvas); - } - } - - bg.tools.CanvasTexture = CanvasTexture; -})(); -(function() { - - bg.tools = bg.tools || {}; - - function packUVs(rect, t1, t2, uvs, pad) { - let hpad = pad / 2; - uvs[t1.uv0.x] = rect.left + pad; uvs[t1.uv0.y] = rect.top + hpad; - uvs[t1.uv1.x] = rect.right - hpad; uvs[t1.uv1.y] = rect.top + hpad; - uvs[t1.uv2.x] = rect.right - hpad; uvs[t1.uv2.y] = rect.bottom - pad; - - if (t2) { - uvs[t2.uv0.x] = rect.right - pad; uvs[t2.uv0.y] = rect.bottom - hpad; - uvs[t2.uv1.x] = rect.left + hpad; uvs[t2.uv1.y] = rect.bottom - hpad; - uvs[t2.uv2.x] = rect.left + hpad; uvs[t2.uv2.y] = rect.top + pad; - } - } - - - function atlasPolyList(vertex,index,padding=0) { - let triangles = []; - let uv = []; - - for (let i=0; i { - let numTriangles = (polyList.index.length / 3); - // Avoid two poly list to share one quad - if (numTriangles%2!=0) numTriangles++; - triangleCount += numTriangles; - }); - let numQuads = triangleCount / 2; - let rows = numQuads, cols = Math.round(Math.sqrt(numQuads)); - while (rows%cols) { - cols--; - } - - rows = cols; - cols = numQuads / cols; - return { - rows: rows, - cols: cols, - triangleCount: triangleCount, - quadSize: { - width: 1 / cols, - height: 1 / rows - }, - currentRow:0, - currentCol:0, - nextRect:function() { - let rect = { - left: this.quadSize.width * this.currentCol, - top: this.quadSize.height * this.currentRow, - right: this.quadSize.width * this.currentCol + this.quadSize.width, - bottom: this.quadSize.height * this.currentRow + this.quadSize.height - }; - if (this.currentCol=this.rows) { - this.currentRow = 0; - } - return rect; - } - }; - } - - function atlasDrawable(drawable,padding) { - let quadData = generateLightmapQuads(drawable); - quadData.currentRow = 0; - quadData.currentCol = 0; - - drawable.forEach((polyList) => { - if (polyList.texCoord1.length>0) return; - let triangles = []; - let uv = []; - for (let i=0; i { - this.matrixState.modelMatrixStack.push(); - this.matrixState.viewMatrixStack.push(); - queue.forEach((objectData) => { - this.matrixState.modelMatrixStack.set(objectData.modelMatrix); - this.matrixState.viewMatrixStack.set(objectData.viewMatrix); - pipeline.effect.material = objectData.material; - pipeline.draw(objectData.plist); - }); - this.matrixState.modelMatrixStack.pop(); - this.matrixState.viewMatrixStack.pop(); - } - - bg.base.Pipeline.SetCurrent(this._gbufferUbyte); - this._gbufferUbyte.viewport = camera.viewport; - this._gbufferUbyte.clearBuffers(); - performRenderQueue(activeQueue,this._gbufferUbyte); - - bg.base.Pipeline.SetCurrent(this._gbufferFloat); - this._gbufferFloat.viewport = camera.viewport; - this._gbufferFloat.clearBuffers(); - performRenderQueue(activeQueue,this._gbufferFloat); - - // Render lights - this._lighting.viewport = camera.viewport; - this._lighting.clearcolor = bg.Color.White(); - bg.base.Pipeline.SetCurrent(this._lighting); - this._lighting.clearBuffers(bg.base.ClearBuffers.COLOR_DEPTH); - this._lighting.blendMode = bg.base.BlendMode.ADD; - this._lighting.blend = true; - this._shadow.viewport = camera.viewport; - - let lightIndex = 0; - bg.scene.Light.GetActiveLights().forEach((lightComponent) => { - if (lightComponent.light && lightComponent.light.enabled && - lightComponent.node && lightComponent.node.enabled) - { - if (lightComponent.light.type==bg.base.LightType.DIRECTIONAL) - { - this._shadowMap.update(scene,camera,lightComponent.light,lightComponent.transform,bg.base.ShadowCascade.NEAR); - - bg.base.Pipeline.SetCurrent(this._shadow); - this._shadow.viewport = camera.viewport; - this._shadow.clearBuffers(); - this._shadow.effect.light = lightComponent.light; - this._shadow.effect.shadowMap = this._shadowMap; - scene.accept(this.shadowVisitor); - } - else if (lightComponent.light.type==bg.base.LightType.SPOT) { - this._shadowMap.shadowType = this.settings.shadows.type; - this._shadowMap.update(scene,camera,lightComponent.light,lightComponent.transform); - bg.base.Pipeline.SetCurrent(this._shadow); - this._shadow.viewport = camera.viewport; - this._shadow.clearBuffers(); - this._shadow.effect.light = lightComponent.light; - this._shadow.effect.shadowMap = this._shadowMap; - scene.accept(this.shadowVisitor); - } - - bg.base.Pipeline.SetCurrent(this._lighting); - // Only render light emission in the first light source - this._lighting.textureEffect.lightEmissionFactor = lightIndex==0 ? 10:0; - - this._lighting.textureEffect.light = lightComponent.light; - this._lighting.textureEffect.lightTransform = lightComponent.transform; - this._lighting.textureEffect.shadowMap = this.maps.shadow; - this._lighting.drawTexture(this.maps); - ++lightIndex; - } - }); - - let renderSSAO = this.settings.ambientOcclusion.enabled; - let renderSSRT = this.settings.raytracer.enabled; - let vp = new bg.Viewport(camera.viewport); - - this._ssao.textureEffect.enabled = renderSSAO; - this._ssao.textureEffect.settings.kernelSize = this.settings.ambientOcclusion.kernelSize; - this._ssao.textureEffect.settings.sampleRadius = this.settings.ambientOcclusion.sampleRadius; - this._ssao.textureEffect.settings.maxDistance = this.settings.ambientOcclusion.maxDistance; - if (renderSSAO) { - bg.base.Pipeline.SetCurrent(this._ssao); - this._ssao.viewport = new bg.Viewport(vp.x,vp.y,vp.width * g_ssaoScale, vp.height * g_ssaoScale); - this._ssao.clearBuffers(); - this._ssao.textureEffect.viewport = camera.viewport; - this._ssao.textureEffect.projectionMatrix = camera.projection; - this._ssao.drawTexture(this.maps); - } - - - // SSRT - bg.base.Pipeline.SetCurrent(this._ssrt); - if (renderSSRT) { - this._ssrt.viewport = new bg.Viewport(vp.x,vp.y,vp.width * g_ssrtScale, vp.height * g_ssrtScale); - this._ssrt.clearBuffers(bg.base.ClearBuffers.DEPTH); - this._ssrt.textureEffect.quality = this.settings.raytracer.quality; - var cameraTransform = camera.node.component("bg.scene.Transform"); - if (cameraTransform) { - let viewProjection = new bg.Matrix4(camera.projection); - viewProjection.mult(camera.viewMatrix); - this._ssrt.textureEffect.cameraPosition= viewProjection.multVector(cameraTransform.matrix.position).xyz; - } - this._ssrt.textureEffect.projectionMatrix = camera.projection; - this._ssrt.textureEffect.rayFailColor = this.settings.raytracer.clearColor || bg.Color.Black(); - this._ssrt.textureEffect.basic = this.settings.raytracer.basicReflections || false; - this._ssrt.textureEffect.viewportSize = new bg.Vector2(this._ssrt.viewport.width,this._ssrt.viewport.height); - this._ssrt.drawTexture(this.maps); - } - - bg.base.Pipeline.SetCurrent(this.pipeline); - this.pipeline.viewport = camera.viewport; - this.pipeline.clearBuffers(); - this.pipeline.textureEffect.viewport = camera.viewport; - this.pipeline.textureEffect.ssaoBlur = renderSSAO ? this.settings.ambientOcclusion.blur : 1; - - this.pipeline.textureEffect.ssrtScale = g_ssrtScale * this.settings.renderScale; - this.pipeline.drawTexture({ - lightingMap:this.maps.lighting, - diffuseMap:this.maps.diffuse, - positionMap:this.maps.position, - ssaoMap:renderSSAO ? this.maps.ambientOcclusion:bg.base.TextureCache.WhiteTexture(this.context), - reflectionMap:renderSSRT ? this.maps.reflection:this.maps.lighting, - specularMap:this.maps.specular, - materialMap:this.maps.material, - opaqueDepthMap:this.maps.mixDepthMap, - shininess:this.maps.shininess - // TODO: bloom - }); // null: all textures are specified as parameters to the effect - - camera.viewport = vp; - } - } - - bg.render.DeferredRenderLayer = DeferredRenderLayer; - -})(); - -(function() { - - - - class DeferredRenderer extends bg.render.Renderer { - constructor(context) { - super(context); - this._size = new bg.Size2D(0); - } - - get isSupported() { - return bg.base.RenderSurface.MaxColorAttachments()>5 && - bg.base.RenderSurface.SupportFormat(bg.base.RenderSurfaceFormat.FLOAT) && - bg.base.RenderSurface.SupportType(bg.base.RenderSurfaceType.DEPTH); - } - - get pipeline() { return this._pipeline; } - - create() { - let ctx = this.context; - - this._renderQueueVisitor = new bg.scene.RenderQueueVisitor(); - - this._opaqueLayer = new bg.render.DeferredRenderLayer(ctx); - this._opaqueLayer.settings = this.settings; - this._opaqueLayer.createOpaque(); - - this._transparentLayer = new bg.render.DeferredRenderLayer(ctx); - this._transparentLayer.settings = this.settings; - this._transparentLayer.createTransparent(this._opaqueLayer.maps); - - this._shadowMap = new bg.base.ShadowMap(ctx); - this._shadowMap.size = new bg.Vector2(2048); - - this._opaqueLayer.shadowMap = this._shadowMap; - this._transparentLayer.shadowMap = this._shadowMap; - - let mixSurface = new bg.base.TextureSurface(ctx); - mixSurface.create(); - this._mixPipeline = new bg.base.Pipeline(ctx); - this._mixPipeline.textureEffect = new bg.render.RendererMixEffect(ctx); - this._mixPipeline.renderSurface = mixSurface; - - this._pipeline = new bg.base.Pipeline(ctx); - this._pipeline.textureEffect = new bg.render.PostprocessEffect(ctx); - - this.settings.renderScale = this.settings.renderScale || 1.0; - } - - draw(scene,camera) { - if (this._shadowMap.size.x!=this.settings.shadows.quality) { - this._shadowMap.size = new bg.Vector2(this.settings.shadows.quality); - } - - let vp = camera.viewport; - let aa = this.settings.antialiasing || {}; - let maxSize = aa.maxTextureSize || 4096; - let ratio = vp.aspectRatio; - let scaledWidth = vp.width; - let scaledHeight = vp.height; - if (aa.enabled) { - scaledWidth = vp.width * 2; - scaledHeight = vp.height * 2; - if (ratio>1 && scaledWidth>maxSize) { // Landscape - scaledWidth = maxSize; - scaledHeight = maxSize / ratio; - } - else if (scaledHeight>maxSize) { // Portrait - scaledHeight = maxSize; - scaledWidth = maxSize * ratio; - } - } - else if (true) { - scaledWidth = vp.width * this.settings.renderScale; - scaledHeight = vp.height * this.settings.renderScale; - if (ratio>1 && scaledWidth>maxSize) { // Landscape - scaledWidth = maxSize; - scaledHeight = maxSize / ratio; - } - else if (scaledHeight>maxSize) { // Portrait - scaledHeight = maxSize; - scaledWidth = maxSize * ratio; - } - } - - let scaledViewport = new bg.Viewport(0,0,scaledWidth,scaledHeight); - camera.viewport = scaledViewport; - let mainLight = null; - - this._opaqueLayer.clearColor = this.clearColor; - if (this._size.width!=camera.viewport.width || - this._size.height!=camera.viewport.height) - { - this._opaqueLayer.resize(camera); - this._transparentLayer.resize(camera); - } - - - // Update render queue - this._renderQueueVisitor.modelMatrixStack.identity(); - this._renderQueueVisitor.projectionMatrixStack.push(); - this._renderQueueVisitor.projectionMatrixStack.set(camera.projection); - this._renderQueueVisitor.viewMatrixStack.set(camera.viewMatrix); - this._renderQueueVisitor.renderQueue.beginFrame(camera.worldPosition); - scene.accept(this._renderQueueVisitor); - this._renderQueueVisitor.renderQueue.sortTransparentObjects(); - this._opaqueLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - this._transparentLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - this._renderQueueVisitor.projectionMatrixStack.pop(); - - bg.base.Pipeline.SetCurrent(this._mixPipeline); - this._mixPipeline.viewport = camera.viewport; - this._mixPipeline.clearColor = bg.Color.Black(); - this._mixPipeline.clearBuffers(); - this._mixPipeline.drawTexture({ - opaque:this._opaqueLayer.texture, - transparent:this._transparentLayer.texture, - transparentNormal:this._transparentLayer.maps.normal, - opaqueDepth:this._opaqueLayer.maps.position, - transparentDepth:this._transparentLayer.maps.position - }); - - bg.base.Pipeline.SetCurrent(this.pipeline); - this.pipeline.viewport = vp; - this.pipeline.clearColor = this.clearColor; - this.pipeline.clearBuffers(); - this.pipeline.drawTexture({ - texture: this._mixPipeline.renderSurface.getTexture(0) - }); - camera.viewport = vp; - } - - getImage(scene,camera,width,height) { - let prevViewport = camera.viewport; - camera.viewport = new bg.Viewport(0,0,width,height); - this.draw(scene,camera); - - let canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - let ctx = canvas.getContext('2d'); - - let buffer = this.pipeline.renderSurface.readBuffer(new bg.Viewport(0,0,width,height)); - let imgData = ctx.createImageData(width,height); - let len = width * 4; - // Flip image data - for (let i = 0; i { - this._pipeline.effect.lightArray.push(comp.light,comp.transform); - }); - this._pipeline.effect.shadowMap = this._shadowMap; - } - } - - performDraw(renderQueue,scene,camera) { - this._pipeline.viewport = camera.viewport; - - let activeQueue = this._pipeline.opacityLayer==bg.base.OpacityLayer.OPAQUE ? renderQueue.opaqueQueue : renderQueue.transparentQueue; - this.matrixState.modelMatrixStack.push(); - activeQueue.forEach((objectData) => { - this.matrixState.modelMatrixStack.set(objectData.modelMatrix); - this.matrixState.viewMatrixStack.set(objectData.viewMatrix); - this._pipeline.effect.material = objectData.material; - this._pipeline.draw(objectData.plist); - }); - this.matrixState.modelMatrixStack.pop(); - } - } - - bg.render.ForwardRenderLayer = ForwardRenderLayer; - -})(); - -(function() { - - class ForwardRenderer extends bg.render.Renderer { - constructor(context) { - super(context); - } - - get isSupported() { return true; } - create() { - let ctx = this.context; - this._transparentLayer = new bg.render.ForwardRenderLayer(ctx,bg.base.OpacityLayer.TRANSPARENT); - this._opaqueLayer = new bg.render.ForwardRenderLayer(ctx,bg.base.OpacityLayer.OPAQUE); - this._shadowMap = new bg.base.ShadowMap(ctx); - this._shadowMap.size = new bg.Vector2(2048); - - this.settings.shadows.cascade = bg.base.ShadowCascade.NEAR; - - this._renderQueueVisitor = new bg.scene.RenderQueueVisitor - } - - draw(scene,camera) { - let shadowLight = null; - let lightSources = []; - bg.scene.Light.GetActiveLights().some((lightComponent,index) => { - if (index>=bg.base.MAX_FORWARD_LIGHTS) return true; - if (lightComponent.light && - lightComponent.light.enabled && - lightComponent.node && - lightComponent.node.enabled) - { - lightSources.push(lightComponent); - if (lightComponent.light.type!=bg.base.LightType.POINT && lightComponent.light.castShadows) { - shadowLight = lightComponent; - } - } - }); - - if (shadowLight) { - if (this._shadowMap.size.x!=this.settings.shadows.quality) { - this._shadowMap.size = new bg.Vector2(this.settings.shadows.quality); - } - this._shadowMap.update(scene,camera,shadowLight.light,shadowLight.transform,this.settings.shadows.cascade); - } - if (lightSources.length) { - this._opaqueLayer.setLightSources(lightSources); - this._opaqueLayer.shadowMap = this._shadowMap; - - this._transparentLayer.setLightSources(lightSources); - this._transparentLayer.shadowMap = this._shadowMap; - } - else { - this._opaqueLayer.setLightSources([]); - this._opaqueLayer.shadowMap = null; - this._transparentLayer.setLightSources([]); - this._transparentLayer.shadowMap = null; - } - - // Update render queue - this._renderQueueVisitor.projectionMatrixStack.set(camera.projection); - this._renderQueueVisitor.modelMatrixStack.identity(); - this._renderQueueVisitor.viewMatrixStack.set(camera.viewMatrix); - this._renderQueueVisitor.renderQueue.beginFrame(camera.worldPosition); - scene.accept(this._renderQueueVisitor); - this._renderQueueVisitor.renderQueue.sortTransparentObjects(); - - this._opaqueLayer.pipeline.clearColor = this.clearColor; - this._opaqueLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - this._transparentLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - } - - getImage(scene,camera,width,height) { - let prevViewport = camera.viewport; - camera.viewport = new bg.Viewport(0,0,width,height); - this.draw(scene,camera); - this.draw(scene,camera); - - let canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - let ctx = canvas.getContext('2d'); - - let buffer = this._opaqueLayer.pipeline.renderSurface.readBuffer(new bg.Viewport(0,0,width,height)); - let imgData = ctx.createImageData(width,height); - let len = width * 4; - // Flip image data - for (let i = 0; i=inAlphaCutoff) { - vec3 normal = samplerNormal(inNormalMap,fsTex0Coord,inNormalMapOffset,inNormalMapScale); - normal = combineNormalWithMap(fsNormal,fsTangent,fsBitangent,normal); - vec4 specular = specularColor(inSpecularColor,inShininessMask,fsTex0Coord,inTextureOffset,inTextureScale, - inShininessMaskChannel,inShininessMaskInvert); - float lightEmission = applyTextureMask(inLightEmission, - inLightEmissionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inLightEmissionMaskChannel,inLightEmissionMaskInvert); - - float reflectionMask = applyTextureMask(inReflection, - inReflectionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inReflectionMaskChannel,inReflectionMaskInvert); - - float roughnessMask = applyTextureMask(inRoughness, - inRoughnessMask,fsTex0Coord,inTextureOffset,inTextureScale, - inRoughnessMaskChannel,inRoughnessMaskInvert); - - gl_FragData[0] = diffuse; - gl_FragData[1] = vec4(specular.rgb,roughnessMask); // Store roughness on A component of specular - if (!gl_FrontFacing) { // Flip the normal if back face - normal *= -1.0; - } - gl_FragData[2] = vec4(normal * 0.5 + 0.5, inUnlit ? 0.0 : 1.0); // Store !unlit parameter on A component of normal - gl_FragData[3] = vec4(lightEmission,inShininess/255.0,reflectionMask,float(inCastShadows)); - } - else { - gl_FragData[0] = vec4(0.0); - gl_FragData[1] = vec4(0.0); - gl_FragData[2] = vec4(0.0); - gl_FragData[3] = vec4(0.0); - discard; - }`); - } - } - return s_ubyteGbufferFragment; - }, - - gbuffer_float_vertex() { - if (!s_floatGbufferVertex) { - s_floatGbufferVertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_floatGbufferVertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - null, - lib().inputs.matrix.model, - lib().inputs.matrix.view, - lib().inputs.matrix.projection, - null, - { name:"fsPosition", dataType:"vec4", role:"out" }, - { name:"fsTex0Coord", dataType:"vec2", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_floatGbufferVertex.setMainBody(` - fsPosition = inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - fsTex0Coord = inTex0; - - gl_Position = inProjectionMatrix * fsPosition;`); - } - } - return s_floatGbufferVertex; - }, - - gbuffer_float_fragment() { - if (!s_floatGbufferFragment) { - s_floatGbufferFragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - s_floatGbufferFragment.addParameter([ - lib().inputs.material.texture, - lib().inputs.material.textureScale, - lib().inputs.material.textureOffset, - lib().inputs.material.alphaCutoff, - null, - { name:"fsPosition", dataType:"vec4", role:"in" }, - { name:"fsTex0Coord", dataType:"vec2", role:"in" } - ]); - - s_floatGbufferFragment.addFunction(lib().functions.materials.samplerColor); - - if (bg.Engine.Get().id=="webgl1") { - s_floatGbufferFragment.setMainBody(` - float alpha = samplerColor(inTexture,fsTex0Coord,inTextureOffset,inTextureScale).a; - if (alpha0.0) { - float refractionFactor = inRefractionAmount / texture2D(inTransparentDepth,fsTexCoord).z; - vec2 offset = fsTexCoord - normal.xy * refractionFactor; - vec4 opaqueDepth = texture2D(inOpaqueDepth,offset); - vec4 transparentDepth = texture2D(inTransparentDepth,offset); - //if (opaqueDepth.w>transparentDepth.w) { - opaque = texture2D(inOpaque,offset); - //} - } - vec3 color = opaque.rgb * (1.0 - transparent.a) + transparent.rgb * transparent.a; - gl_FragColor = vec4(color, 1.0); - `); - } - } - return this._fragmentShaderSource; - } - - setupVars() { - this.shader.setTexture("inOpaque",this._surface.opaque,bg.base.TextureUnit.TEXTURE_0); - this.shader.setTexture("inTransparent",this._surface.transparent,bg.base.TextureUnit.TEXTURE_1); - this.shader.setTexture("inTransparentNormal",this._surface.transparentNormal,bg.base.TextureUnit.TEXTURE_2); - this.shader.setTexture("inOpaqueDepth",this._surface.opaqueDepth,bg.base.TextureUnit.TEXTURE_3); - this.shader.setTexture("inTransparentDepth",this._surface.transparentDepth,bg.base.TextureUnit.TEXTURE_4); - this.shader.setValueFloat("inRefractionAmount",this.settings.refractionAmount); - } - - get settings() { - if (!this._settings) { - this._currentKernelSize = 0; - this._settings = { - refractionAmount: -0.05 - } - } - return this._settings; - } - - } - - bg.render.RendererMixEffect = RendererMixEffect; -})(); -(function() { - - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class ShadowEffect extends bg.base.Effect { - constructor(context) { - super(context); - - let vertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - let fragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - vertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - null, - lib().inputs.matrix.model, - lib().inputs.matrix.view, - lib().inputs.matrix.projection, - { name:"inLightProjectionMatrix", dataType:"mat4", role:"value" }, - { name:"inLightViewMatrix", dataType:"mat4", role:"value" }, - null, - { name:"fsTexCoord", dataType:"vec2", role:"out" }, - { name:"fsVertexPosFromLight", dataType:"vec4", role:"out" } - ]); - - fragment.addParameter(lib().inputs.shadows.all); - fragment.addFunction(lib().functions.utils.unpack); - fragment.addFunction(lib().functions.lighting.getShadowColor); - - fragment.addParameter([ - lib().inputs.material.receiveShadows, - lib().inputs.material.texture, - lib().inputs.material.textureOffset, - lib().inputs.material.textureScale, - lib().inputs.material.alphaCutoff, - null, - { name:"fsTexCoord", dataType:"vec2", role:"in" }, - { name:"fsVertexPosFromLight", dataType:"vec4", role:"in" } - ]); - - fragment.addFunction(lib().functions.materials.samplerColor); - - if (bg.Engine.Get().id=="webgl1") { - vertex.setMainBody(` - mat4 ScaleMatrix = mat4(0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0); - - fsVertexPosFromLight = ScaleMatrix * inLightProjectionMatrix * inLightViewMatrix * inModelMatrix * vec4(inVertex,1.0); - fsTexCoord = inTex0; - - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0);`); - - fragment.setMainBody(` - float alpha = samplerColor(inTexture,fsTexCoord,inTextureOffset,inTextureScale).a; - if (alpha>inAlphaCutoff) { - vec4 shadowColor = vec4(1.0, 1.0, 1.0, 1.0); - if (inReceiveShadows) { - shadowColor = getShadowColor(fsVertexPosFromLight,inShadowMap,inShadowMapSize, - inShadowType,inShadowStrength,inShadowBias,inShadowColor); - } - gl_FragColor = shadowColor; - } - else { - discard; - }`); - } - - this.setupShaderSource([ vertex, fragment ]); - } - - beginDraw() { - if (this.light && this.shadowMap) { - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - let lightTransform = this.shadowMap.viewMatrix; - - this.shader.setMatrix4("inLightProjectionMatrix", this.shadowMap.projection); - - this.shader.setMatrix4("inLightViewMatrix",lightTransform); - this.shader.setValueInt("inShadowType",this.shadowMap.shadowType); - this.shader.setTexture("inShadowMap",this.shadowMap.texture,bg.base.TextureUnit.TEXTURE_1); - this.shader.setVector2("inShadowMapSize",this.shadowMap.size); - this.shader.setValueFloat("inShadowStrength",this.light.shadowStrength); - this.shader.setVector4("inShadowColor",this.shadowMap.shadowColor); - this.shader.setValueFloat("inShadowBias",this.light.shadowBias); - } - } - - setupVars() { - if (this.material && this.light) { - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - - this.shader.setMatrix4("inModelMatrix",matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4("inViewMatrix",viewMatrix); - this.shader.setMatrix4("inProjectionMatrix",matrixState.projectionMatrixStack.matrixConst); - - let texture = this.material.texture || bg.base.TextureCache.WhiteTexture(this.context); - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2("inTextureOffset",this.material.textureOffset); - this.shader.setVector2("inTextureScale",this.material.textureScale); - this.shader.setValueFloat("inAlphaCutoff",this.material.alphaCutoff); - - this.shader.setValueInt("inReceiveShadows",this.material.receiveShadows); - } - } - - get material() { return this._material; } - set material(m) { this._material = m; } - - get light() { return this._light; } - set light(l) { this._light = l; } - - get shadowMap() { return this._shadowMap; } - set shadowMap(sm) { this._shadowMap = sm; } - } - - bg.render.ShadowEffect = ShadowEffect; - -})(); -(function() { - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - let MAX_KERN_OFFSETS = 64; - - class SSAOEffect extends bg.base.TextureEffect { - constructor(context) { - super(context); - } - - get fragmentShaderSource() { - if (!this._fragmentShaderSource) { - this._fragmentShaderSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - this._fragmentShaderSource.addParameter([ - { name:"inViewportSize", dataType:"vec2", role:"value" }, - { name:"inPositionMap", dataType:"sampler2D", role:"value"}, - { name:"inNormalMap", dataType:"sampler2D", role:"value"}, - { name:"inProjectionMatrix", dataType:"mat4", role:"value"}, - { name:"inRandomMap", dataType:"sampler2D", role:"value"}, - { name:"inRandomMapSize", dataType:"vec2", role:"value"}, - { name:"inSampleRadius", dataType:"float", role:"value" }, - { name:"inKernelOffsets", dataType:"vec3", role:"value", vec:MAX_KERN_OFFSETS }, - { name:"inKernelSize", dataType:"int", role:"value" }, - { name:"inSSAOColor", dataType:"vec4", role:"value" }, - { name:"inEnabled", dataType:"bool", role:"value"}, - { name:"inMaxDistance", dataType:"float", role:"value" }, - - { name:"fsTexCoord", dataType:"vec2", role:"in" } // vTexturePosition - ]); - - if (bg.Engine.Get().id=="webgl1") { - this._fragmentShaderSource.setMainBody(` - if (!inEnabled) discard; - else { - vec4 normalTex = texture2D(inNormalMap,fsTexCoord); - vec3 normal = normalTex.xyz * 2.0 - 1.0; - vec4 vertexPos = texture2D(inPositionMap,fsTexCoord); - if (distance(vertexPos.xyz,vec3(0))>inMaxDistance || vertexPos.w==1.0 || normalTex.a==0.0) { - discard; - } - else { - vec2 noiseScale = vec2(inViewportSize.x/inRandomMapSize.x,inViewportSize.y/inRandomMapSize.y); - vec3 randomVector = texture2D(inRandomMap, fsTexCoord * noiseScale).xyz * 2.0 - 1.0; - vec3 tangent = normalize(randomVector - normal * dot(randomVector, normal)); - vec3 bitangent = cross(normal,tangent); - mat3 tbn = mat3(tangent, bitangent, normal); - - float occlusion = 0.0; - for (int i=0; i<${ MAX_KERN_OFFSETS }; ++i) { - if (inKernelSize==i) break; - vec3 samplePos = tbn * inKernelOffsets[i]; - samplePos = samplePos * inSampleRadius + vertexPos.xyz; - - vec4 offset = inProjectionMatrix * vec4(samplePos, 1.0); // -w, w - offset.xyz /= offset.w; // -1, 1 - offset.xyz = offset.xyz * 0.5 + 0.5; // 0, 1 - - vec4 sampleRealPos = texture2D(inPositionMap, offset.xy); - if (samplePos.zMAX_KERN_OFFSETS) { - this.settings.kernelSize = MAX_KERN_OFFSETS; - } - this.shader.setVector2("inViewportSize",new bg.Vector2(this.viewport.width, this.viewport.height)); - - // Surface map parameters - this.shader.setTexture("inPositionMap",this._surface.position,bg.base.TextureUnit.TEXTURE_0); - this.shader.setTexture("inNormalMap",this._surface.normal,bg.base.TextureUnit.TEXTURE_1); - - this.shader.setMatrix4("inProjectionMatrix",this.projectionMatrix); - this.shader.setTexture("inRandomMap",this.randomMap,bg.base.TextureUnit.TEXTURE_2); - this.shader.setVector2("inRandomMapSize",this.randomMap.size); - this.shader.setValueFloat("inSampleRadius",this.settings.sampleRadius); - this.shader.setVector3Ptr("inKernelOffsets",this.kernelOffsets); - this.shader.setValueInt("inKernelSize",this.settings.kernelSize); - this.shader.setVector4("inSSAOColor",this.settings.color); - this.shader.setValueInt("inEnabled",this.settings.enabled); - this.shader.setValueFloat("inMaxDistance",this.settings.maxDistance); - } - - // The following parameters in this effect are required, and the program will crash if - // some of them are not set - get viewport() { return this._viewport; } - set viewport(vp) { this._viewport = vp; } - - get projectionMatrix() { return this._projectionMatrix; } - set projectionMatrix(p) { this._projectionMatrix = p; } - - // randomMap is optional. By default, it takes the default random texture from TextureCache - get randomMap() { - if (!this._randomMap) { - this._randomMap = bg.base.TextureCache.RandomTexture(this.context); - } - return this._randomMap; - } - - set randomMap(rm) { this._randomMap = rm; } - - // Settings: the following parameters are group in a settings object that can be exposed outside - // the renderer object. - get settings() { - if (!this._settings) { - this._currentKernelSize = 0; - this._settings = { - kernelSize: 32, - sampleRadius: 0.3, - color: bg.Color.Black(), - blur: 4, - maxDistance: 100.0, - enabled: true - } - } - return this._settings; - } - - // This parameter is generated automatically using the kernelSize setting - get kernelOffsets() { - if (this._currentKernelSize!=this.settings.kernelSize) { - this._kernelOffsets = []; - for (let i=0; i0.0) { // material[2] is reflectionAmount - vec3 normal = texture2D(inNormalMap,fsTexCoord).xyz * 2.0 - 1.0; - - vec4 specular = texture2D(inSpecularMap,fsTexCoord); - float roughness = specular.a * 0.3; - vec3 r = texture2D(inRandomTexture,fsTexCoord*200.0).xyz * 2.0 - 1.0; - vec3 roughnessFactor = normalize(r) * roughness; - normal = normal + roughnessFactor; - vec4 vertexPos = texture2D(inPositionMap,fsTexCoord); - vec3 cameraVector = vertexPos.xyz - inCameraPos; - vec3 rayDirection = reflect(cameraVector,normal); - vec4 lighting = texture2D(inLightingMap,fsTexCoord); - - vec4 rayFailColor = inRayFailColor; - - vec3 lookup = reflect(cameraVector,normal); - rayFailColor = textureCube(inCubeMap, lookup); - - float increment = ${q.rayIncrement}; - vec4 result = rayFailColor; - if (!inBasicMode) { - result = rayFailColor; - for (float i=0.0; i<${q.maxSamples}.0; ++i) { - if (i==${q.maxSamples}.0) { - break; - } - - float radius = i * increment; - increment *= 1.01; - vec3 ray = vertexPos.xyz + rayDirection * radius; - - vec4 offset = inProjectionMatrix * vec4(ray, 1.0); // -w, w - offset.xyz /= offset.w; // -1, 1 - offset.xyz = offset.xyz * 0.5 + 0.5; // 0, 1 - - vec4 rayActualPos = texture2D(inSamplePosMap, offset.xy); - float hitDistance = rayActualPos.z - ray.z; - if (offset.x>1.0 || offset.y>1.0 || offset.x<0.0 || offset.y<0.0) { - result = rayFailColor; - break; - } - else if (hitDistance>0.02 && hitDistance<0.15) { - result = texture2D(inLightingMap,offset.xy); - break; - } - } - } - if (result.a==0.0) { - gl_FragColor = rayFailColor; - } - else { - gl_FragColor = result; - } - } - else { - discard; - }`); - } - } - return this._fragmentShaderSource; - } - - setupVars() { - this._frameIndex = (this._frameIndex + 1) % 4; - this.shader.setTexture("inPositionMap",this._surface.position,bg.base.TextureUnit.TEXTURE_0); - this.shader.setTexture("inNormalMap",this._surface.normal,bg.base.TextureUnit.TEXTURE_1); - this.shader.setTexture("inLightingMap",this._surface.reflectionColor,bg.base.TextureUnit.TEXTURE_2); - this.shader.setTexture("inMaterialMap",this._surface.material,bg.base.TextureUnit.TEXTURE_3); - this.shader.setTexture("inSamplePosMap",this._surface.reflectionDepth, bg.base.TextureUnit.TEXTURE_4); - this.shader.setMatrix4("inProjectionMatrix",this._projectionMatrix); - this.shader.setVector3("inCameraPos",this._cameraPos); - this.shader.setVector4("inRayFailColor",this.rayFailColor); - this.shader.setValueInt("inBasicMode",this.basic); - this.shader.setValueFloat("inFrameIndex",this._frameIndex); - - this.shader.setTexture("inCubeMap",bg.scene.Cubemap.Current(this.context), bg.base.TextureUnit.TEXTURE_5); - - - if (!this._randomTexture) { - this._randomTexture = bg.base.TextureCache.RandomTexture(this.context,new bg.Vector2(1024)); - } - this.shader.setTexture("inRandomTexture",this._randomTexture, bg.base.TextureUnit.TEXTURE_6); - - this.shader.setTexture("inSpecularMap",this._surface.specular,bg.base.TextureUnit.TEXTURE_7); - } - - get projectionMatrix() { return this._projectionMatrix; } - set projectionMatrix(p) { this._projectionMatrix = p; } - - get cameraPosition() { return this._cameraPos; } - set cameraPosition(c) { this._cameraPos = c; } - - get rayFailColor() { return this._rayFailColor || bg.Color.Black(); } - set rayFailColor(c) { this._rayFailColor = c; } - - get viewportSize() { return this._viewportSize; } - set viewportSize(s) { this._viewportSize = s; } - - get quality() { return this._quality || bg.render.RaytracerQuality.low; } - set quality(q) { - if (!this._quality || this._quality.maxSamples!=q.maxSamples || - this._quality.rayIncrement!=q.rayIncrement) - { - this._quality = q; - this._fragmentShaderSource = null; - this.rebuildShaders(); - } - } - - get basic() { return this._basic; } - set basic(b) { this._basic = b; } - - // TODO: SSRT settings - get settings() { - if (!this._settings) { - } - return this._settings; - } - } - - bg.render.SSRTEffect = SSRTEffect; -})(); -bg.webgl1 = {}; - -(function() { - let WEBGL_1_STRING = "webgl1"; - - bg.webgl1.EngineId = WEBGL_1_STRING; - - class WebGL1Engine extends bg.Engine { - constructor(context) { - super(context); - - // Initialize webgl extensions - bg.webgl1.Extensions.Get(context); - - this._engineId = WEBGL_1_STRING; - this._texture = new bg.webgl1.TextureImpl(context); - this._pipeline = new bg.webgl1.PipelineImpl(context); - this._polyList = new bg.webgl1.PolyListImpl(context); - this._shader = new bg.webgl1.ShaderImpl(context); - this._colorBuffer = new bg.webgl1.ColorRenderSurfaceImpl(context); - this._textureBuffer = new bg.webgl1.TextureRenderSurfaceImpl(context); - this._shaderSource = new bg.webgl1.ShaderSourceImpl(); - } - } - - bg.webgl1.Engine = WebGL1Engine; - -})(); - -(function() { - - bg.webgl1.shaderLibrary = { - inputs:{}, - functions:{} - } - - class ShaderSourceImpl extends bg.base.ShaderSourceImpl { - header(shaderType) { - return "precision highp float;\nprecision highp int;"; - } - - parameter(shaderType,paramData) { - if (!paramData) return "\n"; - let role = ""; - switch (paramData.role) { - case "buffer": - role = "attribute"; - break; - case "value": - role = "uniform"; - break; - case "in": - case "out": - role = "varying"; - break; - } - let vec = ""; - if (paramData.vec) { - vec = `[${paramData.vec}]`; - } - return `${role} ${paramData.dataType} ${paramData.name}${vec};`; - } - - func(shaderType,funcData) { - if (!funcData) return "\n"; - let params = ""; - for (let name in funcData.params) { - params += `${funcData.params[name]} ${name},`; - } - let src = `${funcData.returnType} ${funcData.name}(${params}) {`.replace(',)',')'); - let body = ("\n" + bg.base.ShaderSource.FormatSource(funcData.body)).replace(/\n/g,"\n\t"); - return src + body + "\n}"; - } - } - - bg.webgl1.ShaderSourceImpl = ShaderSourceImpl; - - -})(); -(function() { - let s_singleton = null; - - class Extensions extends bg.app.ContextObject { - static Get(gl) { - if (!s_singleton) { - s_singleton = new Extensions(gl); - } - return s_singleton; - } - - constructor(gl) { - super(gl); - } - - getExtension(ext) { - return this.context.getExtension(ext); - } - - get textureFloat() { - if (this._textureFloat===undefined) { - this._textureFloat = this.getExtension("OES_texture_float"); - } - return this._textureFloat; - } - - get depthTexture() { - if (this._depthTexture===undefined) { - this._depthTexture = this.getExtension("WEBGL_depth_texture"); - } - return this._depthTexture; - } - - get drawBuffers() { - if (this._drawBuffers===undefined) { - this._drawBuffers = this.getExtension("WEBGL_draw_buffers"); - } - return this._drawBuffers; - } - } - - bg.webgl1.Extensions = Extensions; -})(); -(function() { - - class PipelineImpl extends bg.base.PipelineImpl { - initFlags(context) { - bg.base.ClearBuffers.COLOR = context.COLOR_BUFFER_BIT; - bg.base.ClearBuffers.DEPTH = context.DEPTH_BUFFER_BIT; - } - - setViewport(context,vp) { - context.viewport(vp.x,vp.y,vp.width,vp.height); - } - - clearBuffers(context,color,buffers) { - context.clearColor(color.r,color.g,color.b,color.a); - if (buffers) context.clear(buffers); - } - - setDepthTestEnabled(context,e) { - e ? context.enable(context.DEPTH_TEST):context.disable(context.DEPTH_TEST); - } - - setCullFace(context,e) { - e ? context.enable(context.CULL_FACE):context.disable(context.CULL_FACE); - } - - setBlendEnabled(context,e) { - e ? context.enable(context.BLEND):context.disable(context.BLEND); - } - - setBlendMode(gl,m) { - switch (m) { - case bg.base.BlendMode.NORMAL: - gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.MULTIPLY: - gl.blendFunc(gl.ZERO,gl.SRC_COLOR); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.ADD: - gl.blendFunc(gl.ONE,gl.ONE); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.SUBTRACT: - gl.blendFunc(gl.ONE,gl.ONE); - gl.blendEquation(gl.FUNC_SUBTRACT); - break; - case bg.base.BlendMode.ALPHA_ADD: - gl.blendFunc(gl.SRC_ALPHA,gl.SRC_ALPHA); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.ALPHA_SUBTRACT: - gl.blendFunc(gl.SRC_ALPHA,gl.SRC_ALPHA); - gl.blendEquation(gl.FUNC_SUBTRACT); - break; - } - } - } - - bg.webgl1.PipelineImpl = PipelineImpl; -})(); -(function() { - function createBuffer(context,array,itemSize,drawMode) { - let result = null; - if (array.length) { - result = context.createBuffer(); - context.bindBuffer(context.ARRAY_BUFFER,result); - context.bufferData(context.ARRAY_BUFFER, new Float32Array(array), drawMode); - result.itemSize = itemSize; - result.numItems = array.length/itemSize; - } - return result; - } - - function deleteBuffer(context,buffer) { - if (buffer) { - context.deleteBuffer(buffer); - } - return null; - } - - let s_uintElements = false; - - class PolyListImpl extends bg.base.PolyListImpl { - initFlags(context) { - bg.base.DrawMode.TRIANGLES = context.TRIANGLES; - bg.base.DrawMode.TRIANGLE_FAN = context.TRIANGLE_FAN; - bg.base.DrawMode.TRIANGLE_STRIP = context.TRIANGLE_STRIP; - bg.base.DrawMode.LINES = context.LINES; - bg.base.DrawMode.LINE_STRIP = context.LINE_STRIP; - - s_uintElements = context.getExtension("OES_element_index_uint"); - } - - create(context) { - return { - vertexBuffer:null, - normalBuffer:null, - tex0Buffer:null, - tex1Buffer:null, - tex2Buffer:null, - colorBuffer:null, - tangentBuffer:null, - indexBuffer:null - } - } - - build(context,plist,vert,norm,t0,t1,t2,col,tan,index) { - plist.vertexBuffer = createBuffer(context,vert,3,context.STATIC_DRAW); - plist.normalBuffer = createBuffer(context,norm,3,context.STATIC_DRAW); - plist.tex0Buffer = createBuffer(context,t0,2,context.STATIC_DRAW); - plist.tex1Buffer = createBuffer(context,t1,2,context.STATIC_DRAW); - plist.tex2Buffer = createBuffer(context,t2,2,context.STATIC_DRAW); - plist.colorBuffer = createBuffer(context,col,4,context.STATIC_DRAW); - plist.tangentBuffer = createBuffer(context,tan,3,context.STATIC_DRAW); - - if (index.length>0 && s_uintElements) { - plist.indexBuffer = context.createBuffer(); - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint32Array(index),context.STATIC_DRAW); - plist.indexBuffer.itemSize = 3; - plist.indexBuffer.numItems = index.length; - } - else { - plist.indexBuffer = context.createBuffer(); - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint16Array(index),context.STATIC_DRAW); - plist.indexBuffer.itemSize = 3; - plist.indexBuffer.numItems = index.length; - } - - return plist.vertexBuffer && plist.indexBuffer; - } - - draw(context,plist,drawMode,numberOfIndex) { - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - if (s_uintElements) { - context.drawElements(drawMode, numberOfIndex, context.UNSIGNED_INT, 0); - } - else { - context.drawElements(drawMode, numberOfIndex, context.UNSIGNED_SHORT, 0); - } - } - - destroy(context,plist) { - context.bindBuffer(context.ARRAY_BUFFER, null); - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, null); - - plist.vertexBuffer = deleteBuffer(context,plist.vertexBuffer); - plist.normalBuffer = deleteBuffer(context,plist.normalBuffer); - plist.tex0Buffer = deleteBuffer(context,plist.tex0Buffer); - plist.tex1Buffer = deleteBuffer(context,plist.tex1Buffer); - plist.tex2Buffer = deleteBuffer(context,plist.tex2Buffer); - plist.colorBuffer = deleteBuffer(context,plist.colorBuffer); - plist.tangentBuffer = deleteBuffer(context,plist.tangentBuffer); - plist.indexBuffer = deleteBuffer(context,plist.indexBuffer); - } - - update(context,plist,bufferType,newData) { - if (bufferType==bg.base.BufferType.INDEX) { - if (s_uintElements) { - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint32Array(index),context.STATIC_DRAW); - } - else { - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint16Array(index),context.STATIC_DRAW); - } - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER,null); - } - else { - switch (bufferType) { - case bg.base.BufferType.VERTEX: - context.bindBuffer(context.ARRAY_BUFFER, plist.vertexBuffer); - break; - case bg.base.BufferType.NORMAL: - context.bindBuffer(context.ARRAY_BUFFER, plist.normalBuffer); - break; - case bg.base.BufferType.TEX_COORD_0: - context.bindBuffer(context.ARRAY_BUFFER, plist.tex0Buffer); - break; - case bg.base.BufferType.TEX_COORD_1: - context.bindBuffer(context.ARRAY_BUFFER, plist.tex1Buffer); - break; - case bg.base.BufferType.TEX_COORD_2: - context.bindBuffer(context.ARRAY_BUFFER, plist.tex2Buffer); - break; - case bg.base.BufferType.COLOR: - context.bindBuffer(context.ARRAY_BUFFER, plist.colorBuffer); - break; - case bg.base.BufferType.TANGENT: - context.bindBuffer(context.ARRAY_BUFFER, plist.tangentBuffer); - break; - } - context.bufferData(context.ARRAY_BUFFER, new Float32Array(newData), context.STATIC_DRAW); - context.bindBuffer(context.ARRAY_BUFFER,null); - } - } - } - - bg.webgl1.PolyListImpl = PolyListImpl; -})(); - -(function() { - - let ext = null; - - function getMaxColorAttachments() { - if (ext.drawBuffers) { - return ext.drawBuffers.MAX_COLOR_ATTACHMENTS || - ext.drawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL; - } - return 1; - } - - // type: RGBA, format: UNSIGNED_BYTE => regular RGBA texture - // type: RGBA, format: FLOAT => float texture attachment - // type: DEPTH, format: RENDERBUFFER => regular depth renderbuffer - // type: DEPTH, format: UNSIGNED_SHORT => depth texture - // every one else: error, unsupported combination - function checkValid(attachment) { - switch (true) { - case attachment.type==bg.base.RenderSurfaceType.RGBA && attachment.format==bg.base.RenderSurfaceFormat.UNSIGNED_BYTE: - return true; - case attachment.type==bg.base.RenderSurfaceType.RGBA && attachment.format==bg.base.RenderSurfaceFormat.FLOAT: - return true; - case attachment.type==bg.base.RenderSurfaceType.DEPTH && attachment.format==bg.base.RenderSurfaceFormat.RENDERBUFFER: - return true; - case attachment.type==bg.base.RenderSurfaceType.DEPTH && attachment.format==bg.base.RenderSurfaceFormat.UNSIGNED_SHORT: - return true; - // TODO: Cubemaps - default: - return false; - } - } - - function getTypeString(type) { - switch (type) { - case bg.base.RenderSurfaceType.RGBA: - return "RGBA"; - case bg.base.RenderSurfaceType.DEPTH: - return "DEPTH"; - default: - return "unknown"; - } - } - - function getFormatString(format) { - switch (format) { - case bg.base.RenderSurfaceFormat.UNSIGNED_BYTE: - return "UNSIGNED_BYTE"; - case bg.base.RenderSurfaceFormat.FLOAT: - return "FLOAT"; - case bg.base.RenderSurfaceFormat.RENDERBUFFER: - return "RENDERBUFFER"; - case bg.base.RenderSurfaceFormat.UNSIGNED_SHORT: - return "UNSIGNED_SHORT"; - default: - return "unknown"; - } - } - - function checkCompatibility(attachments) { - let colorAttachments = 0; - let maxColorAttachments = getMaxColorAttachments(); - let error = null; - - attachments.every(function(att,index) { - if (!checkValid(att)) { - error = `Error in attachment ${index}: Invalid combination of type and format (${getTypeString(att.type)} is incompatible with ${getFormatString(att.format)}).`; - return false; - } - - if (att.type==bg.base.RenderSurfaceType.DEPTH && - index!=attachments.length-1 - ) { - error = `Error in attachment ${index}: Depth attachment must be specified as the last attachment. Specified at index ${index} of ${attachments.length - 1}`; - return false; - } - - if (att.type==bg.base.RenderSurfaceType.RGBA) { - ++colorAttachments; - } - - if (att.format==bg.base.RenderSurfaceFormat.FLOAT && !ext.textureFloat) { - error = `Error in attachment ${index}: Floating point render surface requested, but the required extension is not present: OES_texture_float.`; - return false; - } - if (att.type==bg.base.RenderSurfaceType.DEPTH && - att.format!=bg.base.RenderSurfaceFormat.RENDERBUFFER && - !ext.depthTexture - ) { - error = `Error in attachment ${index}: Depth texture attachment requested, but the requiered extension is not present: WEBGL_depth_texture.`; - return false; - } - if (colorAttachments>maxColorAttachments) { - error = `Error in attachment ${index}: Maximum number of ${maxColorAttachments} color attachment exceeded.`; - return false; - } - - return true; - }); - - return error; - } - - function addAttachment(gl,size,attachment,index) { - if (attachment.format==bg.base.RenderSurfaceFormat.RENDERBUFFER) { - let renderbuffer = gl.createRenderbuffer(); - - gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); - gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,size.width,size.height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer); - gl.bindRenderbuffer(gl.RENDERBUFFER,null); - - return { _renderbuffer: renderbuffer }; - } - else { - let texture = new bg.base.Texture(gl); - let format = attachment.format; - let type = attachment.type; - - texture.create(); - texture.bind(); - texture.minFilter = bg.base.TextureFilter.LINEAR; - texture.magFilter = bg.base.TextureFilter.LINEAR; - texture.wrapX = bg.base.TextureWrap.CLAMP; - texture.wrapY = bg.base.TextureWrap.CLAMP; - texture.setImageRaw(size.width,size.height,null,type,format); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + index, gl.TEXTURE_2D, texture._texture, 0); - texture.unbind(); - - return texture; - } - } - - function resizeAttachment(gl,size,att,index) { - if (att.texture) { - att.texture.bind(); - att.texture.setImageRaw(size.width,size.height,null,att.type,att.format); - att.texture.unbind(); - } - if (att.renderbuffer) { - let rb = att.renderbuffer._renderbuffer; - gl.bindRenderbuffer(gl.RENDERBUFFER,rb); - gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16, size.width, size.height); - gl.bindRenderbuffer(gl.RENDERBUFFER,null); - } - } - - - class WebGLRenderSurfaceImpl extends bg.base.RenderSurfaceBufferImpl { - initFlags(gl) { - bg.base.RenderSurfaceType.RGBA = gl.RGBA; - bg.base.RenderSurfaceType.DEPTH = gl.DEPTH_COMPONENT; - - bg.base.RenderSurfaceFormat.UNSIGNED_BYTE = gl.UNSIGNED_BYTE; - bg.base.RenderSurfaceFormat.UNSIGNED_SHORT = gl.UNSIGNED_SHORT; - bg.base.RenderSurfaceFormat.FLOAT = gl.FLOAT; - // This is not a format. This will create a renderbuffer instead a texture - bg.base.RenderSurfaceFormat.RENDERBUFFER = gl.RENDERBUFFER; - - ext = bg.webgl1.Extensions.Get(); - } - - supportType(type) { - switch (type) { - case bg.base.RenderSurfaceType.RGBA: - return true; - case bg.base.RenderSurfaceType.DEPTH: - return ext.depthTexture!=null; - default: - return false; - } - } - - supportFormat(format) { - switch (format) { - case bg.base.RenderSurfaceFormat.UNSIGNED_BYTE: - case bg.base.RenderSurfaceFormat.UNSIGNED_SHORT: - return true; - case bg.base.RenderSurfaceFormat.FLOAT: - return ext.textureFloat!=null; - default: - return false; - } - } - - get maxColorAttachments() { - return getMaxColorAttachments(); - } - } - - class ColorRenderSurfaceImpl extends WebGLRenderSurfaceImpl { - create(gl) { - return {}; - } - setActive(gl,renderSurface,attachments) { - gl.bindFramebuffer(gl.FRAMEBUFFER,null); - } - resize(gl,renderSurface,size) {} - destroy(gl,renderSurface) {} - - readBuffer(gl,renderSurface,rectangle,viewportSize) { - let pixels = new Uint8Array(rectangle.width * rectangle.height * 4); - // Note that the webgl texture is flipped vertically, so we need to convert the Y coord - gl.readPixels(rectangle.x, rectangle.y, rectangle.width, rectangle.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - return pixels; - } - } - - bg.webgl1.ColorRenderSurfaceImpl = ColorRenderSurfaceImpl; - - class TextureRenderSurfaceImpl extends WebGLRenderSurfaceImpl { - initFlags(gl) {} // Flags initialized in ColorRenderSurfaceImpl - - create(gl,attachments) { - // If this function returns no error, the browser is compatible with - // the specified attachments. - let error = checkCompatibility(attachments); - if (error) { - throw new Error(error); - } - // Initial size of 256. The actual size will be defined in resize() function - let size = new bg.Vector2(256); - let surfaceData = { - fbo: gl.createFramebuffer(), - size: size, - attachments: [] - }; - - gl.bindFramebuffer(gl.FRAMEBUFFER, surfaceData.fbo); - - let colorAttachments = []; - attachments.forEach((att,i) => { - // This will return a bg.base.Texture or a renderbuffer - let result = addAttachment(gl,size,att,i); - if (result instanceof bg.base.Texture) { - colorAttachments.push(ext.drawBuffers ? ext.drawBuffers.COLOR_ATTACHMENT0_WEBGL + i : gl.COLOR_ATTACHMENT0); - } - surfaceData.attachments.push({ - texture: result instanceof bg.base.Texture ? result:null, - renderbuffer: result instanceof bg.base.Texture ? null:result, - format:att.format, - type:att.type - }); - }); - if (colorAttachments.length>1) { - ext.drawBuffers.drawBuffersWEBGL(colorAttachments); - } - - gl.bindFramebuffer(gl.FRAMEBUFFER,null); - return surfaceData; - } - - setActive(gl,renderSurface) { - gl.bindFramebuffer(gl.FRAMEBUFFER,renderSurface.fbo); - } - - readBuffer(gl,renderSurface,rectangle,viewportSize) { - let pixels = new Uint8Array(rectangle.width * rectangle.height * 4); - // Note that the webgl texture is flipped vertically, so we need to convert the Y coord - gl.readPixels(rectangle.x, viewportSize.height - rectangle.y, rectangle.width, rectangle.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - return pixels; - } - - resize(gl,renderSurface,size) { - renderSurface.size.width = size.width; - renderSurface.size.height = size.height; - renderSurface.attachments.forEach((att,index) => { - resizeAttachment(gl,size,att,index); - }); - } - - destroy(gl,renderSurface) { - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - let attachments = renderSurface && renderSurface.attachments; - if (renderSurface.fbo) { - gl.deleteFramebuffer(renderSurface.fbo); - } - if (attachments) { - attachments.forEach((attachment) => { - if (attachment.texture) { - attachment.texture.destroy(); - } - else if (attachment.renderbuffer) { - gl.deleteRenderbuffer(attachment.renderbuffer._renderbuffer); - } - }); - } - renderSurface.fbo = null; - renderSurface.size = null; - renderSurface.attachments = null; - } - } - - bg.webgl1.TextureRenderSurfaceImpl = TextureRenderSurfaceImpl; -})(); -(function() { - let MAX_BLUR_ITERATIONS = 40; - - let BLUR_DOWNSAMPLE = 15 ; - - let textureCubeDownsampleParams = { - textureInput:'samplerCube', texCoord:'vec3', size:'vec2', reduction:'vec2' - }; - let textureCubeDownsampleBody = ` - float dx = reduction.x / size.x; - float dy = reduction.y / size.y; - vec2 coord = vec2(dx * texCoord.x / dx, dy * texCoord.y / dy); - return textureCube(textureInput,coord); - `; - - let textureDownsampleParams = { - textureInput:'sampler2D', texCoord:'vec2', size:'vec2', reduction:'vec2' - }; - let textureDownsampleBody = ` - float dx = reduction.x / size.x; - float dy = reduction.y / size.y; - vec2 coord = vec2(dx * texCoord.x / dx, dy * texCoord.y / dy); - return texture2D(textureInput,coord); - `; - - let blurParams = { - textureInput:'sampler2D', texCoord:'vec2', size:'int', samplerSize:'vec2' - }; - let blurBody = ` - int downsample = ${ BLUR_DOWNSAMPLE }; - vec2 texelSize = 1.0 / samplerSize; - vec3 result = vec3(0.0); - size = int(max(float(size / downsample),1.0)); - vec2 hlim = vec2(float(-size) * 0.5 + 0.5); - vec2 sign = vec2(1.0); - float blurFactor = 10.0 - 0.2 * float(size) * log(float(size)); - for (int x=0; x<${ MAX_BLUR_ITERATIONS }; ++x) { - if (x==size) break; - for (int y=0; y<${ MAX_BLUR_ITERATIONS }; ++y) { - if (y==size) break; - vec2 offset = (hlim + vec2(float(x), float(y))) * texelSize * float(downsample) / blurFactor; - result += textureDownsample(textureInput, texCoord + offset,samplerSize,vec2(downsample)).rgb; - } - } - return vec4(result / float(size * size), 1.0); - `; - - let glowParams = { - textureInput:'sampler2D', texCoord:'vec2', size:'int', samplerSize:'vec2' - }; - let glowBody = ` - int downsample = ${ BLUR_DOWNSAMPLE }; - vec2 texelSize = 1.0 / samplerSize; - vec3 result = vec3(0.0); - size = int(max(float(size / downsample),1.0)); - vec2 hlim = vec2(float(-size) * 0.5 + 0.5); - vec2 sign = vec2(1.0); - for (int x=0; x<${ MAX_BLUR_ITERATIONS }; ++x) { - if (x==size) break; - for (int y=0; y<${ MAX_BLUR_ITERATIONS }; ++y) { - if (y==size) break; - vec2 offset = (hlim + vec2(float(x), float(y))) * texelSize; - result += textureDownsample(textureInput, texCoord + offset,samplerSize,vec2(downsample)).rgb; - } - } - return vec4(result / float(size * size), 1.0); - `; - - let blurCubeParams = { - textureInput:'samplerCube', texCoord:'vec3', size:'int', samplerSize:'vec2', dist:'float' - }; - let blurCubeBody = ` - int downsample = int(max(1.0,dist)); - vec2 texelSize = 1.0 / samplerSize; - vec3 result = vec3(0.0); - size = int(max(float(size / downsample),1.0)); - vec2 hlim = vec2(float(-size) * 0.5 + 0.5); - vec2 sign = vec2(1.0); - for (int x=0; x<40; ++x) { - if (x==size) break; - for (int y=0; y<40; ++y) { - if (y==size) break; - vec3 offset = vec3((hlim + vec2(float(x*downsample), float(y*downsample))) * texelSize,0.0); - result += textureCube(textureInput, texCoord + offset,2.0).rgb; - } - } - return vec4(result / float(size * size), 1.0); - `; - - bg.webgl1.shaderLibrary - .functions - .blur = { - textureDownsample:{ - returnType:"vec4", name:'textureDownsample', params:textureDownsampleParams, body:textureDownsampleBody - }, - gaussianBlur:{ - returnType:"vec4", name:"gaussianBlur", params:blurParams, body:blurBody - }, - blur:{ - returnType:"vec4", name:"blur", params:blurParams, body:blurBody - }, - glowBlur:{ - returnType:"vec4", name:"glowBlur", params:glowParams, body:glowBody - }, - blurCube:{ - returnType:"vec4", name:"blurCube", params:blurCubeParams, body:blurCubeBody - }, - - // Require: utils.borderDetection - antiAlias:{ - returnType:'vec4', name:'antiAlias', params: { - sampler:'sampler2D', texCoord:'vec2', frameSize:'vec2', tresshold:'float', iterations:'int' - }, body: ` - return (borderDetection(sampler,texCoord,frameSize)>tresshold) ? - gaussianBlur(sampler,texCoord,iterations,frameSize) : - texture2D(sampler,texCoord); - ` - } - } -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .colorCorrection = { - rgb2hsv: { - returnType:"vec3", name:"rgb2hsv", params:{ c:"vec3" }, body:` - vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); - vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); - - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);` - }, - hsv2rgb: { - returnType:"vec3", name:"hsv2rgb", params: { c:"vec3" }, body:` - vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); - return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);` - }, - applyBrightness: { - returnType:"vec4", name:"applyBrightness", params: { color:"vec4", brightness:"float" }, body:` - return clamp(vec4(color.rgb + brightness - 0.5,1.0),0.0,1.0); - ` - }, - applyContrast: { - returnType:"vec4", name:"applyContrast", params:{ color:"vec4", contrast:"float" }, body:` - return clamp(vec4((color.rgb * max(contrast + 0.5,0.0)),1.0),0.0,1.0);` - }, - applySaturation: { - returnType:"vec4", name:"applySaturation", params:{ color:"vec4", hue:"float", saturation:"float", lightness:"float" }, body:` - vec3 fragRGB = clamp(color.rgb + vec3(0.001),0.0,1.0); - vec3 fragHSV = rgb2hsv(fragRGB); - lightness -= 0.01; - float h = hue; - fragHSV.x *= h; - fragHSV.yz *= vec2(saturation,lightness); - fragHSV.x = mod(fragHSV.x, 1.0); - fragHSV.y = mod(fragHSV.y, 1.0); - fragHSV.z = mod(fragHSV.z, 1.0); - fragRGB = hsv2rgb(fragHSV); - return clamp(vec4(hsv2rgb(fragHSV), color.w),0.0,1.0);` - }, - colorCorrection: { - returnType:"vec4", name:"colorCorrection", params:{ - fragColor:"vec4", hue:"float", saturation:"float", - lightness:"float", brightness:"float", contrast:"float" }, - body:` - return applyContrast(applyBrightness(applySaturation(fragColor,hue,saturation,lightness),brightness),contrast);` - } - } - -})(); -(function() { - - bg.webgl1.shaderLibrary - .inputs = { - // Input buffers - buffers: { - vertex: { name:"inVertex", dataType:"vec3", role:"buffer", target:"vertex" }, // role:buffer => attribute - normal: { name:"inNormal", dataType:"vec3", role:"buffer", target:"normal" }, - tangent: { name:"inTangent", dataType:"vec3", role:"buffer", target:"tangent" }, - tex0: { name:"inTex0", dataType:"vec2", role:"buffer", target:"tex0" }, - tex1: { name:"inTex1", dataType:"vec2", role:"buffer", target:"tex1" }, - tex2: { name:"inTex2", dataType:"vec2", role:"buffer", target:"tex2" }, - color: { name:"inColor", dataType:"vec4", role:"buffer", target:"color" } - }, - - // Matrixes - matrix: { - model: { name:"inModelMatrix", dataType:"mat4", role:"value" }, // role:value => uniform - view: { name:"inViewMatrix", dataType:"mat4", role:"value" }, - projection: { name:"inProjectionMatrix", dataType:"mat4", role:"value" }, - normal: { name:"inNormalMatrix", dataType:"mat4", role:"value" }, - viewInv: { name:"inViewMatrixInv", dataType:"mat4", role:"value" } - }, - - ///// Material properties - material: { - // Color - diffuse: { name:"inDiffuseColor", dataType:"vec4", role:"value" }, - specular: { name:"inSpecularColor", dataType:"vec4", role:"value" }, - - // Shininess - shininess: { name:"inShininess", dataType:"float", role:"value" }, - shininessMask: { name:"inShininessMask", dataType:"sampler2D", role:"value" }, - shininessMaskChannel: { name:"inShininessMaskChannel", dataType:"vec4", role:"value" }, - shininessMaskInvert: { name:"inShininessMaskInvert", dataType:"bool", role:"value" }, - - // Light emission - lightEmission: { name:"inLightEmission", dataType:"float", role:"value" }, - lightEmissionMask: { name:"inLightEmissionMask", dataType:"sampler2D", role:"value" }, - lightEmissionMaskChannel: { name:"inLightEmissionMaskChannel", dataType:"vec4", role:"value" }, - lightEmissionMaskInvert: { name:"inLightEmissionMaskInvert", dataType:"bool", role:"value" }, - - - // Textures - texture: { name:"inTexture", dataType:"sampler2D", role:"value" }, - textureOffset: { name:"inTextureOffset", dataType:"vec2", role:"value" }, - textureScale: { name:"inTextureScale", dataType:"vec2", role:"value" }, - alphaCutoff: { name:"inAlphaCutoff", dataType:"float", role:"value" }, - - lightMap: { name:"inLightMap", dataType:"sampler2D", role:"value" }, - lightMapOffset: { name:"inLightMapOffset", dataType:"vec2", role:"value" }, - lightMapScale: { name:"inLightMapScale", dataType:"vec2", role:"value" }, - - normalMap: { name:"inNormalMap", dataType:"sampler2D", role:"value" }, - normalMapOffset: { name:"inNormalMapOffset", dataType:"vec2", role:"value" }, - normalMapScale: { name:"inNormalMapScale", dataType:"vec2", role:"value" }, - - // Reflection - reflection: { name:"inReflection", dataType:"float", role:"value" }, - reflectionMask: { name:"inReflectionMask", dataType:"sampler2D", role:"value" }, - reflectionMaskChannel: { name:"inReflectionMaskChannel", dataType:"vec4", role:"value" }, - reflectionMaskInvert: { name:"inReflectionMaskInvert", dataType:"bool", role:"value" }, - - // Shadows - castShadows: { name:"inCastShadows", dataType:"bool", role:"value" }, - receiveShadows: { name:"inReceiveShadows", dataType:"bool", role:"value" }, - - // Roughness - roughness: { name:"inRoughness", dataType:"float", role:"value" }, - roughnessMask: { name:"inRoughnessMask", dataType:"sampler2D", role:"value" }, - roughnessMaskChannel: { name:"inRoughnessMaskChannel", dataType:"vec4", role:"value" }, - roughnessMaskInvert: { name:"inRoughnessMaskInvert", dataType:"bool", role:"value" }, - - unlit: { name:"inUnlit", dataType:"bool", role:"value" } - }, - - // Lighting - lighting: { - type: { name:"inLightType", dataType:"int", role:"value" }, - position: { name:"inLightPosition", dataType:"vec3", role:"value" }, - direction: { name:"inLightDirection", dataType:"vec3", role:"value" }, - ambient: { name:"inLightAmbient", dataType:"vec4", role:"value" }, - diffuse: { name:"inLightDiffuse", dataType:"vec4", role:"value" }, - specular: { name:"inLightSpecular", dataType:"vec4", role:"value" }, - attenuation: { name:"inLightAttenuation", dataType:"vec3", role:"value" }, // const, linear, exp - spotExponent: { name:"inSpotExponent", dataType:"float", role:"value" }, - spotCutoff: { name:"inSpotCutoff", dataType:"float", role:"value" }, - cutoffDistance: { name:"inLightCutoffDistance", dataType:"float", role:"value" }, - exposure: { name:"inLightExposure", dataType:"float", role:"value" }, - castShadows: { name:"inLightCastShadows", dataType:"bool", role:"value" } - }, - - lightingForward: { - type: { name:"inLightType", dataType:"int", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - position: { name:"inLightPosition", dataType:"vec3", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - direction: { name:"inLightDirection", dataType:"vec3", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - ambient: { name:"inLightAmbient", dataType:"vec4", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - diffuse: { name:"inLightDiffuse", dataType:"vec4", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - specular: { name:"inLightSpecular", dataType:"vec4", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - attenuation: { name:"inLightAttenuation", dataType:"vec3", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, // const, linear, exp - spotExponent: { name:"inSpotExponent", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - spotCutoff: { name:"inSpotCutoff", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - cutoffDistance: { name:"inLightCutoffDistance", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - exposure: { name:"inLightExposure", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - castShadows: { name:"inLightCastShadows", dataType:"bool", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - numLights: { name:"inNumLights", dataType:"int", role:"value" } - }, - - // Shadows - shadows: { - shadowMap: { name:"inShadowMap", dataType:"sampler2D", role:"value" }, - shadowMapSize: { name:"inShadowMapSize", dataType:"vec2", role:"value" }, - shadowStrength: { name:"inShadowStrength", dataType:"float", role:"value" }, - shadowColor: { name:"inShadowColor", dataType:"vec4", role:"value" }, - shadowBias: { name:"inShadowBias", dataType:"float", role:"value" }, - shadowType: { name:"inShadowType", dataType:"int", role:"value" } - }, - - // Color correction - colorCorrection: { - hue: { name:"inHue", dataType:"float", role:"value" }, - saturation: { name:"inSaturation", dataType:"float", role:"value" }, - lightness: { name:"inLightness", dataType:"float", role:"value" }, - brightness: { name:"inBrightness", dataType:"float", role:"value" }, - contrast: { name:"inContrast", dataType:"float", role:"value" } - } - - } -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .lighting = { - beckmannDistribution: { - returnType:"float", name:"beckmannDistribution", params: { - x:"float", roughness:"float" - }, body: ` - float NdotH = max(x,0.0001); - float cos2Alpha = NdotH * NdotH; - float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha; - float roughness2 = roughness * roughness; - float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha; - return exp(tan2Alpha / roughness2) / denom; - ` - }, - - beckmannSpecular: { - returnType:"float", name:"beckmannSpecular", params:{ - lightDirection:"vec3", viewDirection:"vec3", surfaceNormal:"vec3", roughness:"float" - }, body: ` - return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness); - ` - }, - - getDirectionalLight: { - returnType:"vec4", name:"getDirectionalLight", params:{ - ambient:"vec4", diffuse:"vec4", specular:"vec4", shininess:"float", - direction:"vec3", vertexPos:"vec3", normal:"vec3", matDiffuse:"vec4", matSpecular:"vec4", - shadowColor:"vec4", - specularOut:"out vec4" - }, body: ` - vec3 color = ambient.rgb * matDiffuse.rgb; - vec3 diffuseWeight = max(0.0, dot(normal,direction)) * diffuse.rgb; - color += min(diffuseWeight,shadowColor.rgb) * matDiffuse.rgb; - specularOut = vec4(0.0,0.0,0.0,1.0); - if (shininess>0.0) { - vec3 eyeDirection = normalize(-vertexPos); - vec3 reflectionDirection = normalize(reflect(-direction,normal)); - float specularWeight = clamp(pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess), 0.0, 1.0); - //sspecularWeight = beckmannSpecular(direction,eyeDirection,normal,0.01); - vec3 specularColor = specularWeight * pow(shadowColor.rgb,vec3(10.0)); - //color += specularColor * specular.rgb * matSpecular.rgb; - specularOut = vec4(specularColor * specular.rgb * matSpecular.rgb,1.0); - } - return vec4(color,1.0);` - }, - - getPointLight: { - returnType:"vec4", name:"getPointLight", params: { - ambient: "vec4", diffuse: "vec4", specular: "vec4", shininess: "float", - position: "vec3", constAtt: "float", linearAtt: "float", expAtt: "float", - vertexPos: "vec3", normal: "vec3", matDiffuse: "vec4", matSpecular: "vec4", - specularOut:"out vec4" - }, body: ` - vec3 pointToLight = position - vertexPos; - float distance = length(pointToLight); - vec3 lightDir = normalize(pointToLight); - float attenuation = 1.0 / (constAtt + linearAtt * distance + expAtt * distance * distance); - vec3 color = ambient.rgb * matDiffuse.rgb; - vec3 diffuseWeight = max(0.0,dot(normal,lightDir)) * diffuse.rgb * attenuation; - color += diffuseWeight * matDiffuse.rgb; - specularOut = vec4(0.0,0.0,0.0,1.0); - if (shininess>0.0) { - vec3 eyeDirection = normalize(-vertexPos); - vec3 reflectionDirection = normalize(reflect(-lightDir, normal)); - float specularWeight = clamp(pow(max(dot(reflectionDirection,eyeDirection),0.0), shininess), 0.0, 1.0); - //color += specularWeight * specular.rgb * matSpecular.rgb * attenuation; - specularOut = vec4(specularWeight * specular.rgb * matSpecular.rgb * attenuation,1.0); - } - return vec4(color,1.0);` - }, - - getSpotLight: { - returnType:"vec4", name:"getSpotLight", params: { - ambient:"vec4", diffuse:"vec4", specular:"vec4", shininess:"float", - position:"vec3", direction:"vec3", - constAtt:"float", linearAtt:"float", expAtt:"float", - spotCutoff:"float", spotExponent:"float", - vertexPos:"vec3", normal:"vec3", - matDiffuse:"vec4", matSpecular:"vec4", shadowColor:"vec4", - specularOut:"out vec4" - }, body: ` - vec4 matAmbient = vec4(1.0); - vec3 s = normalize(position - vertexPos); - float angle = acos(dot(-s, direction)); - float cutoff = radians(clamp(spotCutoff / 2.0,0.0,90.0)); - float distance = length(position - vertexPos); - float attenuation = 1.0 / (constAtt );//+ linearAtt * distance + expAtt * distance * distance); - if (angle0.0) { - specularOut.rgb = matSpecular.rgb * specular.rgb * pow(max(dot(h,normal), 0.0),shininess); - specularOut.rgb *= pow(shadowColor.rgb,vec3(10.0)); - //diffuseAmount += matSpecular.rgb * specular.rgb * pow(max(dot(h,normal), 0.0),shininess); - //diffuseAmount *= pow(shadowColor.rgb,vec3(10.0)); - } - diffuseAmount.r = min(diffuseAmount.r, shadowColor.r); - diffuseAmount.g = min(diffuseAmount.g, shadowColor.g); - diffuseAmount.b = min(diffuseAmount.b, shadowColor.b); - return vec4(ambient.rgb * matDiffuse.rgb + attenuation * spotFactor * diffuseAmount,1.0); - } - else { - return vec4(ambient.rgb * matDiffuse.rgb,1.0); - }` - }, - - getLight: { - returnType:"vec4", name:"getLight", params: { - lightType:"int", - ambient:"vec4", diffuse:"vec4", specular:"vec4", shininess:"float", - lightPosition:"vec3", lightDirection:"vec3", - constAtt:"float", linearAtt:"float", expAtt:"float", - spotCutoff:"float", spotExponent:"float",cutoffDistance:"float", - vertexPosition:"vec3", vertexNormal:"vec3", - matDiffuse:"vec4", matSpecular:"vec4", shadowColor:"vec4", - specularOut:"out vec4" - }, body: ` - vec4 light = vec4(0.0); - if (lightType==${ bg.base.LightType.DIRECTIONAL }) { - light = getDirectionalLight(ambient,diffuse,specular,shininess, - -lightDirection,vertexPosition,vertexNormal,matDiffuse,matSpecular,shadowColor,specularOut); - } - else if (lightType==${ bg.base.LightType.SPOT }) { - float d = distance(vertexPosition,lightPosition); - if (d<=cutoffDistance || cutoffDistance==-1.0) { - light = getSpotLight(ambient,diffuse,specular,shininess, - lightPosition,lightDirection, - constAtt,linearAtt,expAtt, - spotCutoff,spotExponent, - vertexPosition,vertexNormal,matDiffuse,matSpecular,shadowColor,specularOut); - } - } - else if (lightType==${ bg.base.LightType.POINT }) { - float d = distance(vertexPosition,lightPosition); - if (d<=cutoffDistance || cutoffDistance==-1.0) { - light = getPointLight(ambient,diffuse,specular,shininess, - lightPosition, - constAtt,linearAtt,expAtt, - vertexPosition,vertexNormal,matDiffuse,matSpecular,specularOut); - } - } - return light; - ` - }, - - getShadowColor:{ - returnType:"vec4", name:"getShadowColor", params:{ - vertexPosFromLight:'vec4', shadowMap:'sampler2D', shadowMapSize:'vec2', - shadowType:'int', shadowStrength:'float', shadowBias:'float', shadowColor:'vec4' - }, body:` - float visibility = 1.0; - vec3 depth = vertexPosFromLight.xyz / vertexPosFromLight.w; - const float kShadowBorderOffset = 3.0; - float shadowBorderOffset = kShadowBorderOffset / shadowMapSize.x; - float bias = shadowBias; - vec4 shadow = vec4(1.0); - if (shadowType==${ bg.base.ShadowType.HARD }) { // hard - float shadowDepth = unpack(texture2D(shadowMap,depth.xy)); - if (shadowDepth0.0 && depth.x<1.0 && depth.y>0.0 && depth.y<1.0)) - { - visibility = 1.0 - shadowStrength; - } - shadow = clamp(shadowColor + visibility,0.0,1.0); - } - else if (shadowType>=${ bg.base.ShadowType.SOFT }) { // soft / soft stratified (not supported on webgl, fallback to soft) - vec2 poissonDisk[4]; - poissonDisk[0] = vec2( -0.94201624, -0.39906216 ); - poissonDisk[1] = vec2( 0.94558609, -0.76890725 ); - poissonDisk[2] = vec2( -0.094184101, -0.92938870 ); - poissonDisk[3] = vec2( 0.34495938, 0.29387760 ); - - for (int i=0; i<4; ++i) { - float shadowDepth = unpack(texture2D(shadowMap, depth.xy + poissonDisk[i]/1000.0)); - - if (shadowDepth0.0 && depth.x<1.0 && depth.y>0.0 && depth.y<1.0)) { - visibility -= (shadowStrength) * 0.25; - } - } - shadow = clamp(shadowColor + visibility,0.0,1.0); - } - return shadow;` - } - } -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .materials = { - samplerColor: { - returnType:"vec4", name:"samplerColor", params: { - sampler:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2" - }, body:` - return texture2D(sampler,uv * scale + offset);` - }, - - samplerNormal: { - returnType:"vec3", name:"samplerNormal", params:{ - sampler:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2" - }, body:` - return normalize(samplerColor(sampler,uv,offset,scale).xyz * 2.0 - 1.0); - ` - }, - - combineNormalWithMap:{ - returnType:"vec3", name:"combineNormalWithMap", params:{ - normalCoord:"vec3", - tangent:"vec3", - bitangent:"vec3", - normalMapValue:"vec3" - }, body:` - mat3 tbnMat = mat3( tangent.x, bitangent.x, normalCoord.x, - tangent.y, bitangent.y, normalCoord.y, - tangent.z, bitangent.z, normalCoord.z - ); - return normalize(normalMapValue * tbnMat);` - }, - - applyTextureMask:{ - returnType:"float", name:"applyTextureMask", params: { - value:"float", - textureMask:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2", - channelMask:"vec4", - invert:"bool" - }, body:` - float mask; - vec4 color = samplerColor(textureMask,uv,offset,scale); - mask = color.r * channelMask.r + - color.g * channelMask.g + - color.b * channelMask.b + - color.a * channelMask.a; - if (invert) { - mask = 1.0 - mask; - } - return value * mask;` - }, - - specularColor:{ - returnType:"vec4", name:"specularColor", params:{ - specular:"vec4", - shininessMask:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2", - channelMask:"vec4", - invert:"bool" - }, body:` - float maskValue = applyTextureMask(1.0, shininessMask,uv,offset,scale,channelMask,invert); - return vec4(specular.rgb * maskValue, 1.0);` - } - }; - -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .utils = { - pack: { - returnType:"vec4", name:"pack", params:{ depth:"float" }, body: ` - const vec4 bitSh = vec4(256 * 256 * 256, - 256 * 256, - 256, - 1.0); - const vec4 bitMsk = vec4(0, - 1.0 / 256.0, - 1.0 / 256.0, - 1.0 / 256.0); - vec4 comp = fract(depth * bitSh); - comp -= comp.xxyz * bitMsk; - return comp;` - }, - - unpack: { - returnType:"float", name:"unpack", params:{ color:"vec4" }, body:` - const vec4 bitShifts = vec4(1.0 / (256.0 * 256.0 * 256.0), - 1.0 / (256.0 * 256.0), - 1.0 / 256.0, - 1.0); - return dot(color, bitShifts);` - }, - - random: { - returnType:"float", name:"random", params:{ - seed:"vec3", i:"int" - }, body:` - vec4 seed4 = vec4(seed,i); - float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673)); - return fract(sin(dot_product) * 43758.5453);` - }, - - texOffset: { - returnType: 'vec4', name:'texOffset', params: { - sampler:'sampler2D', - texCoord:'vec2', - offset:'vec2', - frameSize:'vec2' - }, body: ` - return texture2D(sampler,texCoord + vec2(offset.x * 1.0/frameSize.x,offset.y * 1.0 / frameSize.y)); - ` - }, - - luminance: { - returnType: 'float', name:'luminance', params: { color:'vec3' }, body: ` - return dot(vec3(0.2126,0.7152,0.0722), color); - ` - }, - - // Require: colorCorrection.luminance and utils.texOffset - borderDetection:{ - returnType: 'float', name:'borderDetection', params: { - sampler:'sampler2D', texCoord:'vec2', frameSize:'vec2' - }, body: ` - float s00 = luminance(texOffset(sampler,texCoord,vec2(-1.0, 1.0),frameSize).rgb); - float s10 = luminance(texOffset(sampler,texCoord,vec2(-1.0, 0.0),frameSize).rgb); - float s20 = luminance(texOffset(sampler,texCoord,vec2(-1.0,-1.0),frameSize).rgb); - float s01 = luminance(texOffset(sampler,texCoord,vec2(-1.0, 1.0),frameSize).rgb); - float s21 = luminance(texOffset(sampler,texCoord,vec2( 0.0,-1.0),frameSize).rgb); - float s02 = luminance(texOffset(sampler,texCoord,vec2( 1.0, 1.0),frameSize).rgb); - float s12 = luminance(texOffset(sampler,texCoord,vec2( 1.0, 0.0),frameSize).rgb); - float s22 = luminance(texOffset(sampler,texCoord,vec2( 1.0,-1.0),frameSize).rgb); - - float sx = s00 + 2.0 * s10 + s20 - (s02 + 2.0 * s12 + s22); - float sy = s00 + 2.0 * s01 + s02 - (s20 + 2.0 * s21 + s22); - - return sx * sx + sy * sy; - ` - }, - - applyConvolution:{ - returnType:'vec4', name:'applyConvolution', params: { - texture:'sampler2D', texCoord:'vec2', texSize:'vec2', convMatrix:'float[9]', radius:'float' - }, body: ` - vec2 onePixel = vec2(1.0,1.0) / texSize * radius; - vec4 colorSum = - texture2D(texture, texCoord + onePixel * vec2(-1, -1)) * convMatrix[0] + - texture2D(texture, texCoord + onePixel * vec2( 0, -1)) * convMatrix[1] + - texture2D(texture, texCoord + onePixel * vec2( 1, -1)) * convMatrix[2] + - texture2D(texture, texCoord + onePixel * vec2(-1, 0)) * convMatrix[3] + - texture2D(texture, texCoord + onePixel * vec2( 0, 0)) * convMatrix[4] + - texture2D(texture, texCoord + onePixel * vec2( 1, 0)) * convMatrix[5] + - texture2D(texture, texCoord + onePixel * vec2(-1, 1)) * convMatrix[6] + - texture2D(texture, texCoord + onePixel * vec2( 0, 1)) * convMatrix[7] + - texture2D(texture, texCoord + onePixel * vec2( 1, 1)) * convMatrix[8]; - float kernelWeight = - convMatrix[0] + - convMatrix[1] + - convMatrix[2] + - convMatrix[3] + - convMatrix[4] + - convMatrix[5] + - convMatrix[6] + - convMatrix[7] + - convMatrix[8]; - if (kernelWeight <= 0.0) { - kernelWeight = 1.0; - } - return vec4((colorSum / kernelWeight).rgb, 1.0); - ` - } - } -})(); -(function() { - - class ShaderImpl extends bg.base.ShaderImpl { - initFlags(context) { - bg.base.ShaderType.VERTEX = context.VERTEX_SHADER; - bg.base.ShaderType.FRAGMENT = context.FRAGMENT_SHADER; - } - - setActive(context,shaderProgram) { - context.useProgram(shaderProgram && shaderProgram.program); - } - - create(context) { - return { - program:context.createProgram(), - attribLocations:{}, - uniformLocations:{} - }; - } - - addShaderSource(context,shaderProgram,shaderType,source) { - let error = null; - - if (!shaderProgram || !shaderProgram.program ) { - error = "Could not attach shader. Invalid shader program"; - } - else { - let shader = context.createShader(shaderType); - context.shaderSource(shader,source); - context.compileShader(shader); - - if (!context.getShaderParameter(shader, context.COMPILE_STATUS)) { - error = context.getShaderInfoLog(shader); - } - else { - context.attachShader(shaderProgram.program,shader); - } - - context.deleteShader(shader); - } - - return error; - } - - link(context,shaderProgram) { - let error = null; - if (!shaderProgram || !shaderProgram.program ) { - error = "Could not link shader. Invalid shader program"; - } - else { - context.linkProgram(shaderProgram.program); - if (!context.getProgramParameter(shaderProgram.program,context.LINK_STATUS)) { - error = context.getProgramInfoLog(shaderProgram.program); - } - } - return error; - } - - initVars(context,shader,inputBufferVars,valueVars) { - inputBufferVars.forEach(function(name) { - shader.attribLocations[name] = context.getAttribLocation(shader.program,name); - }); - - valueVars.forEach(function(name) { - shader.uniformLocations[name] = context.getUniformLocation(shader.program,name); - }); - } - - setInputBuffer(context,shader,varName,vertexBuffer,itemSize) { - if (vertexBuffer && shader && shader.program) { - let loc = shader.attribLocations[varName]; - if (loc!=-1) { - context.bindBuffer(context.ARRAY_BUFFER,vertexBuffer); - context.enableVertexAttribArray(loc); - context.vertexAttribPointer(loc,itemSize,context.FLOAT,false,0,0); - } - } - } - - disableInputBuffer(context,shader,name) { - context.disableVertexAttribArray(shader.attribLocations[name]); - } - - setValueInt(context,shader,name,v) { - context.uniform1i(shader.uniformLocations[name],v); - } - - setValueIntPtr(context,shader,name,v) { - context.uniform1iv(shader.uniformLocations[name],v); - } - - setValueFloat(context,shader,name,v) { - context.uniform1f(shader.uniformLocations[name],v); - } - - setValueFloatPtr(context,shader,name,v) { - context.uniform1fv(shader.uniformLocations[name],v); - } - - setValueVector2(context,shader,name,v) { - context.uniform2fv(shader.uniformLocations[name],v.v); - } - - setValueVector3(context,shader,name,v) { - context.uniform3fv(shader.uniformLocations[name],v.v); - } - - setValueVector4(context,shader,name,v) { - context.uniform4fv(shader.uniformLocations[name],v.v); - } - - setValueVector2v(context,shader,name,v) { - context.uniform2fv(shader.uniformLocations[name],v); - } - - setValueVector3v(context,shader,name,v) { - context.uniform3fv(shader.uniformLocations[name],v); - } - - setValueVector4v(context,shader,name,v) { - context.uniform4fv(shader.uniformLocations[name],v); - } - - setValueMatrix3(context,shader,name,traspose,v) { - context.uniformMatrix3fv(shader.uniformLocations[name],traspose,v.m); - } - - setValueMatrix4(context,shader,name,traspose,v) { - context.uniformMatrix4fv(shader.uniformLocations[name],traspose,v.m); - } - - setTexture(context,shader,name,texture,textureUnit) { - texture.setActive(textureUnit); - texture.bind(); - context.uniform1i(shader.uniformLocations[name],textureUnit); - } - } - - bg.webgl1.ShaderImpl = ShaderImpl; - -})(); - -(function() { - - class TextureImpl extends bg.base.TextureImpl { - initFlags(context) { - bg.base.TextureWrap.REPEAT = context.REPEAT; - bg.base.TextureWrap.CLAMP = context.CLAMP_TO_EDGE; - bg.base.TextureWrap.MIRRORED_REPEAT = context.MIRRORED_REPEAT; - - bg.base.TextureFilter.NEAREST_MIPMAP_NEAREST = context.NEAREST_MIPMAP_NEAREST; - bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST = context.LINEAR_MIPMAP_NEAREST; - bg.base.TextureFilter.NEAREST_MIPMAP_LINEAR = context.NEAREST_MIPMAP_LINEAR; - bg.base.TextureFilter.LINEAR_MIPMAP_LINEAR = context.LINEAR_MIPMAP_LINEAR; - bg.base.TextureFilter.NEAREST = context.NEAREST; - bg.base.TextureFilter.LINEAR = context.LINEAR; - - bg.base.TextureTarget.TEXTURE_2D = context.TEXTURE_2D; - bg.base.TextureTarget.CUBE_MAP = context.TEXTURE_CUBE_MAP; - bg.base.TextureTarget.POSITIVE_X_FACE = context.TEXTURE_CUBE_MAP_POSITIVE_X; - bg.base.TextureTarget.NEGATIVE_X_FACE = context.TEXTURE_CUBE_MAP_NEGATIVE_X; - bg.base.TextureTarget.POSITIVE_Y_FACE = context.TEXTURE_CUBE_MAP_POSITIVE_Y; - bg.base.TextureTarget.NEGATIVE_Y_FACE = context.TEXTURE_CUBE_MAP_NEGATIVE_Y; - bg.base.TextureTarget.POSITIVE_Z_FACE = context.TEXTURE_CUBE_MAP_POSITIVE_Z; - bg.base.TextureTarget.NEGATIVE_Z_FACE = context.TEXTURE_CUBE_MAP_NEGATIVE_Z; - } - - requireMipmaps(minFilter,magFilter) { - return minFilter==bg.base.TextureFilter.NEAREST_MIPMAP_NEAREST || - minFilter==bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST || - minFilter==bg.base.TextureFilter.NEAREST_MIPMAP_LINEAR || - minFilter==bg.base.TextureFilter.LINEAR_MIPMAP_LINEAR || - magFilter==bg.base.TextureFilter.NEAREST_MIPMAP_NEAREST || - magFilter==bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST || - magFilter==bg.base.TextureFilter.NEAREST_MIPMAP_LINEAR || - magFilter==bg.base.TextureFilter.LINEAR_MIPMAP_LINEAR; - } - - create(context) { - return context.createTexture(); - } - - setActive(context,texUnit) { - context.activeTexture(context.TEXTURE0 + texUnit); - } - - bind(context,target,texture) { - context.bindTexture(target, texture); - } - - unbind(context,target) { - this.bind(context,target,null); - } - - setTextureWrapX(context,target,texture,wrap) { - context.texParameteri(target, context.TEXTURE_WRAP_S, wrap); - } - - setTextureWrapY(context,target,texture,wrap) { - context.texParameteri(target, context.TEXTURE_WRAP_T, wrap); - } - - setImage(context,target,minFilter,magFilter,texture,img,flipY) { - if (flipY) context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, true); - context.texParameteri(target, context.TEXTURE_MIN_FILTER, minFilter); - context.texParameteri(target, context.TEXTURE_MAG_FILTER, magFilter); - context.texImage2D(target,0,context.RGBA,context.RGBA,context.UNSIGNED_BYTE, img); - if (this.requireMipmaps(minFilter,magFilter)) { - context.generateMipmap(target); - } - } - - setImageRaw(context,target,minFilter,magFilter,texture,width,height,data,type,format) { - if (!type) { - type = context.RGBA; - } - if (!format) { - format = context.UNSIGNED_BYTE; - } - if (format==bg.base.RenderSurfaceFormat.FLOAT) { - minFilter = bg.base.TextureFilter.NEAREST; - magFilter = bg.base.TextureFilter.NEAREST; - } - context.texParameteri(target, context.TEXTURE_MIN_FILTER, minFilter); - context.texParameteri(target, context.TEXTURE_MAG_FILTER, magFilter); - context.texImage2D(target,0, type,width,height,0,type,format, data); - if (this.requireMipmaps(minFilter,magFilter)) { - context.generateMipmap(target); - } - } - - setTextureFilter(context,target,minFilter,magFilter) { - context.texParameteri(target,context.TEXTURE_MIN_FILTER,minFilter); - context.texParameteri(target,context.TEXTURE_MAG_FILTER,magFilter); - } - - setCubemapImage(context,face,image) { - context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false); - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MIN_FILTER, bg.base.TextureFilter.LINEAR); - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MAG_FILTER, bg.base.TextureFilter.LINEAR); - context.texImage2D(face, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image); - } - - setCubemapRaw(context,face,rawImage,w,h) { - let type = context.RGBA; - let format = context.UNSIGNED_BYTE; - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MIN_FILTER, bg.base.TextureFilter.LINEAR); - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MAG_FILTER, bg.base.TextureFilter.LINEAR); - context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false); - context.texImage2D(face, 0, type, w, h, 0, type, format, rawImage); - } - - setVideo(context,target,texture,video,flipY) { - if (flipY) context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false); - context.texParameteri(target, context.TEXTURE_MAG_FILTER, context.LINEAR); - context.texParameteri(target, context.TEXTURE_MIN_FILTER, context.LINEAR); - context.texParameteri(target, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE); - context.texParameteri(target, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE); - context.texImage2D(target,0,context.RGBA,context.RGBA,context.UNSIGNED_BYTE,video); - } - - updateVideoData(context,target,texture,video) { - context.bindTexture(target, texture); - context.texImage2D(target,0,context.RGBA,context.RGBA,context.UNSIGNED_BYTE,video); - context.bindTexture(target,null); - } - - destroy(context,texture) { - context.deleteTexture(this._texture); - } - } - - bg.webgl1.TextureImpl = TextureImpl; - -})(); \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js b/node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js deleted file mode 100644 index 1e3dccf1a..000000000 --- a/node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){if(!e.hasInitialised){var t={escapeRegExp:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},hasClass:function(e,t){var i=" ";return 1===e.nodeType&&(i+e.className+i).replace(/[\n\t]/g,i).indexOf(i+t+i)>=0},addClass:function(e,t){e.className+=" "+t},removeClass:function(e,t){var i=new RegExp("\\b"+this.escapeRegExp(t)+"\\b");e.className=e.className.replace(i,"")},interpolateString:function(e,t){return e.replace(/{{([a-z][a-z0-9\-_]*)}}/gi,function(e){return t(arguments[1])||""})},getCookie:function(e){var t=("; "+document.cookie).split("; "+e+"=");return t.length<2?void 0:t.pop().split(";").shift()},setCookie:function(e,t,i,n,o,s){var r=new Date;r.setHours(r.getHours()+24*(i||365));var a=[e+"="+t,"expires="+r.toUTCString(),"path="+(o||"/")];n&&a.push("domain="+n),s&&a.push("secure"),document.cookie=a.join(";")},deepExtend:function(e,t){for(var i in t)t.hasOwnProperty(i)&&(i in e&&this.isPlainObject(e[i])&&this.isPlainObject(t[i])?this.deepExtend(e[i],t[i]):e[i]=t[i]);return e},throttle:function(e,t){var i=!1;return function(){i||(e.apply(this,arguments),i=!0,setTimeout(function(){i=!1},t))}},hash:function(e){var t,i,n=0;if(0===e.length)return n;for(t=0,i=e.length;t=128?"#000":"#fff"},getLuminance:function(e){var t=parseInt(this.normaliseHex(e),16),i=38+(t>>16),n=38+(t>>8&255),o=38+(255&t);return"#"+(16777216+65536*(i<255?i<1?0:i:255)+256*(n<255?n<1?0:n:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)},isMobile:function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},isPlainObject:function(e){return"object"==typeof e&&null!==e&&e.constructor==Object},traverseDOMPath:function(e,i){return e&&e.parentNode?t.hasClass(e,i)?e:this.traverseDOMPath(e.parentNode,i):null}};e.status={deny:"deny",allow:"allow",dismiss:"dismiss"},e.transitionEnd=function(){var e=document.createElement("div"),t={t:"transitionend",OT:"oTransitionEnd",msT:"MSTransitionEnd",MozT:"transitionend",WebkitT:"webkitTransitionEnd"};for(var i in t)if(t.hasOwnProperty(i)&&void 0!==e.style[i+"ransition"])return t[i];return""}(),e.hasTransition=!!e.transitionEnd;var i=Object.keys(e.status).map(t.escapeRegExp);e.customStyles={},e.Popup=function(){var n={enabled:!0,container:null,cookie:{name:"cookieconsent_status",path:"/",domain:"",expiryDays:365,secure:!1},onPopupOpen:function(){},onPopupClose:function(){},onInitialise:function(e){},onStatusChange:function(e,t){},onRevokeChoice:function(){},onNoCookieLaw:function(e,t){},content:{header:"Cookies used on the website!",message:"This website uses cookies to ensure you get the best experience on our website.",dismiss:"Got it!",allow:"Allow cookies",deny:"Decline",link:"Learn more",href:"https://www.cookiesandyou.com",close:"❌",target:"_blank",policy:"Cookie Policy"},elements:{header:'{{header}} ',message:'{{message}}',messagelink:'{{message}} {{link}}',dismiss:'{{dismiss}}',allow:'{{allow}}',deny:'{{deny}}',link:'{{link}}',close:'{{close}}'},window:'',revokeBtn:'
{{policy}}
',compliance:{info:'
{{dismiss}}
',"opt-in":'
{{deny}}{{allow}}
',"opt-out":'
{{deny}}{{allow}}
'},type:"info",layouts:{basic:"{{messagelink}}{{compliance}}","basic-close":"{{messagelink}}{{compliance}}{{close}}","basic-header":"{{header}}{{message}}{{link}}{{compliance}}"},layout:"basic",position:"bottom",theme:"block",static:!1,palette:null,revokable:!1,animateRevokable:!0,showLink:!0,dismissOnScroll:!1,dismissOnTimeout:!1,dismissOnWindowClick:!1,ignoreClicksFrom:["cc-revoke","cc-btn"],autoOpen:!0,autoAttach:!0,whitelistPage:[],blacklistPage:[],overrideHTML:null};function o(){this.initialise.apply(this,arguments)}function s(e){this.openingTimeout=null,t.removeClass(e,"cc-invisible")}function r(t){t.style.display="none",t.removeEventListener(e.transitionEnd,this.afterTransition),this.afterTransition=null}function a(){var e=this.options.position.split("-"),t=[];return e.forEach(function(e){t.push("cc-"+e)}),t}function c(n){var o=this.options,s=document.createElement("div"),r=o.container&&1===o.container.nodeType?o.container:document.body;s.innerHTML=n;var a=s.children[0];return a.style.display="none",t.hasClass(a,"cc-window")&&e.hasTransition&&t.addClass(a,"cc-invisible"),this.onButtonClick=function(n){var o=t.traverseDOMPath(n.target,"cc-btn")||n.target;if(t.hasClass(o,"cc-btn")){var s=o.className.match(new RegExp("\\bcc-("+i.join("|")+")\\b")),r=s&&s[1]||!1;r&&(this.setStatus(r),this.close(!0))}t.hasClass(o,"cc-close")&&(this.setStatus(e.status.dismiss),this.close(!0));t.hasClass(o,"cc-revoke")&&this.revokeChoice()}.bind(this),a.addEventListener("click",this.onButtonClick),o.autoAttach&&(r.firstChild?r.insertBefore(a,r.firstChild):r.appendChild(a)),a}function l(e){return"000000"==(e=t.normaliseHex(e))?"#222":t.getLuminance(e)}function u(e,t){for(var i=0,n=e.length;i=0;o&&t(n);return o}.call(this)&&(this.options.enabled=!1),u(this.options.blacklistPage,location.pathname)&&(this.options.enabled=!1),u(this.options.whitelistPage,location.pathname)&&(this.options.enabled=!0);var o=this.options.window.replace("{{classes}}",function(){var i=this.options,n="top"==i.position||"bottom"==i.position?"banner":"floating";t.isMobile()&&(n="floating");var o=["cc-"+n,"cc-type-"+i.type,"cc-theme-"+i.theme];i.static&&o.push("cc-static");o.push.apply(o,a.call(this));(function(i){var n=t.hash(JSON.stringify(i)),o="cc-color-override-"+n,s=t.isPlainObject(i);this.customStyleSelector=s?o:null,s&&function(i,n,o){if(e.customStyles[i])return void++e.customStyles[i].references;var s={},r=n.popup,a=n.button,c=n.highlight;r&&(r.text=r.text?r.text:t.getContrast(r.background),r.link=r.link?r.link:r.text,s[o+".cc-window"]=["color: "+r.text,"background-color: "+r.background],s[o+".cc-revoke"]=["color: "+r.text,"background-color: "+r.background],s[o+" .cc-link,"+o+" .cc-link:active,"+o+" .cc-link:visited"]=["color: "+r.link],a&&(a.text=a.text?a.text:t.getContrast(a.background),a.border=a.border?a.border:"transparent",s[o+" .cc-btn"]=["color: "+a.text,"border-color: "+a.border,"background-color: "+a.background],a.padding&&s[o+" .cc-btn"].push("padding: "+a.padding),"transparent"!=a.background&&(s[o+" .cc-btn:hover, "+o+" .cc-btn:focus"]=["background-color: "+(a.hover||l(a.background))]),c?(c.text=c.text?c.text:t.getContrast(c.background),c.border=c.border?c.border:"transparent",s[o+" .cc-highlight .cc-btn:first-child"]=["color: "+c.text,"border-color: "+c.border,"background-color: "+c.background]):s[o+" .cc-highlight .cc-btn:first-child"]=["color: "+r.text]));var u=document.createElement("style");document.head.appendChild(u),e.customStyles[i]={references:1,element:u.sheet};var h=-1;for(var p in s)s.hasOwnProperty(p)&&u.sheet.insertRule(p+"{"+s[p].join(";")+"}",++h)}(n,i,"."+o);return s}).call(this,this.options.palette);this.customStyleSelector&&o.push(this.customStyleSelector);return o}.call(this).join(" ")).replace("{{children}}",function(){var e={},i=this.options;i.showLink||(i.elements.link="",i.elements.messagelink=i.elements.message);Object.keys(i.elements).forEach(function(n){e[n]=t.interpolateString(i.elements[n],function(e){var t=i.content[e];return e&&"string"==typeof t&&t.length?t:""})});var n=i.compliance[i.type];n||(n=i.compliance.info);e.compliance=t.interpolateString(n,function(t){return e[t]});var o=i.layouts[i.layout];o||(o=i.layouts.basic);return t.interpolateString(o,function(t){return e[t]})}.call(this)),s=this.options.overrideHTML;if("string"==typeof s&&s.length&&(o=s),this.options.static){var r=c.call(this,'
'+o+"
");r.style.display="",this.element=r.firstChild,this.element.style.display="none",t.addClass(this.element,"cc-invisible")}else this.element=c.call(this,o);(function(){var i=this.setStatus.bind(this),n=this.close.bind(this),o=this.options.dismissOnTimeout;"number"==typeof o&&o>=0&&(this.dismissTimeout=window.setTimeout(function(){i(e.status.dismiss),n(!0)},Math.floor(o)));var s=this.options.dismissOnScroll;if("number"==typeof s&&s>=0){var r=function(t){window.pageYOffset>Math.floor(s)&&(i(e.status.dismiss),n(!0),window.removeEventListener("scroll",r),this.onWindowScroll=null)};this.options.enabled&&(this.onWindowScroll=r,window.addEventListener("scroll",r))}var a=this.options.dismissOnWindowClick,c=this.options.ignoreClicksFrom;if(a){var l=function(o){for(var s=!1,r=o.path.length,a=c.length,u=0;uo&&(i=!0),i?t.hasClass(n,"cc-active")||t.addClass(n,"cc-active"):t.hasClass(n,"cc-active")&&t.removeClass(n,"cc-active")},200);this.onMouseMove=o,window.addEventListener("mousemove",o)}}}.call(this),this.options.autoOpen&&this.autoOpen()},o.prototype.destroy=function(){this.onButtonClick&&this.element&&(this.element.removeEventListener("click",this.onButtonClick),this.onButtonClick=null),this.dismissTimeout&&(clearTimeout(this.dismissTimeout),this.dismissTimeout=null),this.onWindowScroll&&(window.removeEventListener("scroll",this.onWindowScroll),this.onWindowScroll=null),this.onWindowClick&&(window.removeEventListener("click",this.onWindowClick),this.onWindowClick=null),this.onMouseMove&&(window.removeEventListener("mousemove",this.onMouseMove),this.onMouseMove=null),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.revokeBtn&&this.revokeBtn.parentNode&&this.revokeBtn.parentNode.removeChild(this.revokeBtn),this.revokeBtn=null,function(i){if(t.isPlainObject(i)){var n=t.hash(JSON.stringify(i)),o=e.customStyles[n];if(o&&!--o.references){var s=o.element.ownerNode;s&&s.parentNode&&s.parentNode.removeChild(s),e.customStyles[n]=null}}}(this.options.palette),this.options=null},o.prototype.open=function(t){if(this.element)return this.isOpen()||(e.hasTransition?this.fadeIn():this.element.style.display="",this.options.revokable&&this.toggleRevokeButton(),this.options.onPopupOpen.call(this)),this},o.prototype.close=function(t){if(this.element)return this.isOpen()&&(e.hasTransition?this.fadeOut():this.element.style.display="none",t&&this.options.revokable&&this.toggleRevokeButton(!0),this.options.onPopupClose.call(this)),this},o.prototype.fadeIn=function(){var i=this.element;if(e.hasTransition&&i&&(this.afterTransition&&r.call(this,i),t.hasClass(i,"cc-invisible"))){if(i.style.display="",this.options.static){var n=this.element.clientHeight;this.element.parentNode.style.maxHeight=n+"px"}this.openingTimeout=setTimeout(s.bind(this,i),20)}},o.prototype.fadeOut=function(){var i=this.element;e.hasTransition&&i&&(this.openingTimeout&&(clearTimeout(this.openingTimeout),s.bind(this,i)),t.hasClass(i,"cc-invisible")||(this.options.static&&(this.element.parentNode.style.maxHeight=""),this.afterTransition=r.bind(this,i),i.addEventListener(e.transitionEnd,this.afterTransition),t.addClass(i,"cc-invisible")))},o.prototype.isOpen=function(){return this.element&&""==this.element.style.display&&(!e.hasTransition||!t.hasClass(this.element,"cc-invisible"))},o.prototype.toggleRevokeButton=function(e){this.revokeBtn&&(this.revokeBtn.style.display=e?"":"none")},o.prototype.revokeChoice=function(e){this.options.enabled=!0,this.clearStatus(),this.options.onRevokeChoice.call(this),e||this.autoOpen()},o.prototype.hasAnswered=function(t){return Object.keys(e.status).indexOf(this.getStatus())>=0},o.prototype.hasConsented=function(t){var i=this.getStatus();return i==e.status.allow||i==e.status.dismiss},o.prototype.autoOpen=function(e){!this.hasAnswered()&&this.options.enabled?this.open():this.hasAnswered()&&this.options.revokable&&this.toggleRevokeButton(!0)},o.prototype.setStatus=function(i){var n=this.options.cookie,o=t.getCookie(n.name),s=Object.keys(e.status).indexOf(o)>=0;Object.keys(e.status).indexOf(i)>=0?(t.setCookie(n.name,i,n.expiryDays,n.domain,n.path,n.secure),this.options.onStatusChange.call(this,i,s)):this.clearStatus()},o.prototype.getStatus=function(){return t.getCookie(this.options.cookie.name)},o.prototype.clearStatus=function(){var e=this.options.cookie;t.setCookie(e.name,"",-1,e.domain,e.path)},o}(),e.Location=function(){var e={timeout:5e3,services:["ipinfo"],serviceDefinitions:{ipinfo:function(){return{url:"//ipinfo.io",headers:["Accept: application/json"],callback:function(e,t){try{var i=JSON.parse(t);return i.error?s(i):{code:i.country}}catch(e){return s({error:"Invalid response ("+e+")"})}}}},ipinfodb:function(e){return{url:"//api.ipinfodb.com/v3/ip-country/?key={api_key}&format=json&callback={callback}",isScript:!0,callback:function(e,t){try{var i=JSON.parse(t);return"ERROR"==i.statusCode?s({error:i.statusMessage}):{code:i.countryCode}}catch(e){return s({error:"Invalid response ("+e+")"})}}}},maxmind:function(){return{url:"//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js",isScript:!0,callback:function(e){window.geoip2?geoip2.country(function(t){try{e({code:t.country.iso_code})}catch(t){e(s(t))}},function(t){e(s(t))}):e(new Error("Unexpected response format. The downloaded script should have exported `geoip2` to the global scope"))}}}}};function i(i){t.deepExtend(this.options={},e),t.isPlainObject(i)&&t.deepExtend(this.options,i),this.currentServiceIndex=-1}function n(e,t,i){var n,o=document.createElement("script");o.type="text/"+(e.type||"javascript"),o.src=e.src||e,o.async=!1,o.onreadystatechange=o.onload=function(){var e=o.readyState;clearTimeout(n),t.done||e&&!/loaded|complete/.test(e)||(t.done=!0,t(),o.onreadystatechange=o.onload=null)},document.body.appendChild(o),n=setTimeout(function(){t.done=!0,t(),o.onreadystatechange=o.onload=null},i)}function o(e,t,i,n,o){var s=new(window.XMLHttpRequest||window.ActiveXObject)("MSXML2.XMLHTTP.3.0");if(s.open(n?"POST":"GET",e,1),s.setRequestHeader("Content-type","application/x-www-form-urlencoded"),Array.isArray(o))for(var r=0,a=o.length;r3&&t(s)}),s.send(n)}function s(e){return new Error("Error ["+(e.code||"UNKNOWN")+"]: "+e.error)}return i.prototype.getNextService=function(){var e;do{e=this.getServiceByIdx(++this.currentServiceIndex)}while(this.currentServiceIndex=0,revokable:t.revokable.indexOf(e)>=0,explicitAction:t.explicitAction.indexOf(e)>=0}},i.prototype.applyLaw=function(e,t){var i=this.get(t);return i.hasLaw||(e.enabled=!1,"function"==typeof e.onNoCookieLaw&&e.onNoCookieLaw(t,i)),this.options.regionalLaw&&(i.revokable&&(e.revokable=!0),i.explicitAction&&(e.dismissOnScroll=!1,e.dismissOnTimeout=!1)),e},i}(),e.initialise=function(i,n,o){var s=new e.Law(i.law);n||(n=function(){}),o||(o=function(){});var r=Object.keys(e.status),a=t.getCookie("cookieconsent_status");r.indexOf(a)>=0?n(new e.Popup(i)):e.getCountryCode(i,function(t){delete i.law,delete i.location,t.code&&(i=s.applyLaw(i,t.code)),n(new e.Popup(i))},function(t){delete i.law,delete i.location,o(t,new e.Popup(i))})},e.getCountryCode=function(t,i,n){t.law&&t.law.countryCode?i({code:t.law.countryCode}):t.location?new e.Location(t.location).locate(function(e){i(e||{})},n):i({})},e.utils=t,e.hasInitialised=!0,window.cookieconsent=e}}(window.cookieconsent||{}); \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/hls.min.js b/node_modules/paellaplayer/build/player/javascript/hls.min.js deleted file mode 100644 index 703092cd5..000000000 --- a/node_modules/paellaplayer/build/player/javascript/hls.min.js +++ /dev/null @@ -1,2 +0,0 @@ -"undefined"!=typeof window&&function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,(function(){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var a=e[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=t,r.c=e,r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)r.d(i,a,function(e){return t[e]}.bind(null,a));return i},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=20)}([function(t,e,r){"use strict";var i;r.d(e,"a",(function(){return i})),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},function(t,e,r){"use strict";r.d(e,"a",(function(){return o})),r.d(e,"b",(function(){return l}));var i=function(){},a={trace:i,debug:i,log:i,warn:i,info:i,error:i},n=a;function s(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.a.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,a,n){void 0===n&&(n=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,a)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:a,partial:n}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},c(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(a.a)(this.programDateTime))return null;var t=Object(a.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(f),v=function(t){function e(e,r,i,a,n){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.a,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=a;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,n),n&&(s.fragOffset=n.fragOffset+n.duration),s}return u(e,t),c(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(f)},function(t,e,r){"use strict";r.d(e,"b",(function(){return h})),r.d(e,"g",(function(){return d})),r.d(e,"f",(function(){return c})),r.d(e,"d",(function(){return f})),r.d(e,"c",(function(){return g})),r.d(e,"e",(function(){return p})),r.d(e,"h",(function(){return m})),r.d(e,"a",(function(){return y}));var i=r(9),a=r(5),n=Math.pow(2,32)-1,s=[].push;function o(t){return String.fromCharCode.apply(null,t)}function l(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function u(t,e,r){"data"in t&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function h(t,e){var r,i,a,n=[];if(!e.length)return n;"data"in t?(r=t.data,i=t.start,a=t.end):(i=0,a=(r=t).byteLength);for(var u=i;u1?u+d:a;if(o(r.subarray(u+4,u+8))===e[0])if(1===e.length)n.push({data:r,start:u+8,end:c});else{var f=h({data:r,start:u+8,end:c},e.slice(1));f.length&&s.apply(n,f)}u=c}return n}function d(t){var e=h(t,["moov"])[0],r=e?e.end:null,i=h(t,["sidx"]);if(!i||!i[0])return null;var a=[],n=i[0],s=n.data[0],o=0===s?8:16,u=l(n,o);o+=4;o+=0===s?8:16,o+=2;var d=n.end+0,c=function(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r}(n,o);o+=2;for(var f=0;f>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var m=l(n,g);g+=4,a.push({referenceSize:p,subsegmentDuration:m,info:{duration:m/u,start:d,end:d+p-1}}),d+=p,o=g+=4}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:c,references:a,moovEndOffset:r}}function c(t){for(var e=[],r=h(t,["moov","trak"]),i=0;i0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return a(t,e)&&o(t,e+6)+10<=t.length-e},u=function(t){for(var e=c(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:s=t[h++],u+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=t[h++],o=t[h++],u+=String.fromCharCode((15&n)<<12|(63&s)<<6|(63&o)<<0)}}return u};function T(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},function(t,e,r){"use strict";r.d(e,"c",(function(){return a})),r.d(e,"b",(function(){return n})),r.d(e,"a",(function(){return s}));function i(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=t*e*r;return i?Math.round(a):a}function a(t,e,r,a){return void 0===r&&(r=1),void 0===a&&(a=!1),i(t,e,1/r,a)}function n(t,e){return void 0===e&&(e=!1),i(t,1e3,1/9e4,e)}function s(t,e){return void 0===e&&(e=1),i(t,9e4,1/e)}},function(t,e,r){"use strict";function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.d(e,"a",(function(){return i}))},function(t,e,r){"use strict";r.d(e,"c",(function(){return lt})),r.d(e,"d",(function(){return ht})),r.d(e,"a",(function(){return dt})),r.d(e,"b",(function(){return ct}));var i=r(0),a=r(2),n=r(15),s=r(3),o=r(7);var l=r(6),u=r(9),h=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r){this._id3Track={type:"id3",id:0,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(){},e.resetContiguity=function(){},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Object(l.a)(this.cachedData,t),this.cachedData=null);var r,i,a=o.b(t,0),n=a?a.length:0,s=this._audioTrack,h=this._id3Track,c=a?o.d(a):void 0,f=t.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=d(c,e)),a&&a.length>0&&h.samples.push({pts:this.initPTS,dts:this.initPTS,data:a}),i=this.initPTS;n>>5}function m(t,e){return e+1=t.length)return!1;var i=p(t,e);if(i<=r)return!1;var a=e+i;return a===t.length||m(t,a)}return!1}function T(t,e,r,n,s){if(!t.samplerate){var o=function(t,e,r,n){var s,o,l,u,h=navigator.userAgent.toLowerCase(),d=n,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[r+2])>>>6);var g=(60&e[r+2])>>>2;if(!(g>c.length-1))return l=(1&e[r+2])<<2,l|=(192&e[r+3])>>>6,f.b.log("manifest codec:"+n+", ADTS type:"+s+", samplingIndex:"+g),/firefox/i.test(h)?g>=6?(s=5,u=new Array(4),o=g-3):(s=2,u=new Array(2),o=g):-1!==h.indexOf("android")?(s=2,u=new Array(2),o=g):(s=5,u=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&g>=6?o=g-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(g>=6&&1===l||/vivaldi/i.test(h))||!n&&1===l)&&(s=2,u=new Array(2)),o=g)),u[0]=s<<3,u[0]|=(14&g)>>1,u[1]|=(1&g)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:c[g],channelCount:l,codec:"mp4a.40."+s,manifestCodec:d};t.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+g})}(e,r,n,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,f.b.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function E(t){return 9216e4/t}function b(t,e,r,i,a){var n=function(t,e,r,i,a){var n=v(t,e),s=p(t,e);if((s-=n)>0)return{headerLength:n,frameLength:s,stamp:r+i*a}}(e,r,i,a,E(t.samplerate));if(n){var s,o=n.frameLength,l=n.headerLength,u=n.stamp,h=l+o,d=Math.max(0,r+h-e.length);d?(s=new Uint8Array(h-l)).set(e.subarray(r+l,e.length),0):s=e.subarray(r+l,r+h);var c={unit:s,pts:u};return d||t.samples.push(c),{sample:c,length:h,missing:d}}}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var L=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var a=i.prototype;return a.resetInitSegment=function(e,r,i){t.prototype.resetInitSegment.call(this,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:0,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(o.b(t,0)||[]).length,r=t.length;e0},e.demux=function(t){var e=t,r={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};if(this.config.progressive){this.remainderData&&(e=Object(l.a)(this.remainderData,t));var i=Object(l.h)(e);this.remainderData=i.remainder,r.samples=i.valid||new Uint8Array}else r.samples=e;return{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:r,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.flush=function(){var t={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};return t.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:t,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}();R.minProbeByteLength=1024;var D=R,k=null,_=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],I=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],C=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],w=[0,1,1,4];function O(t,e,r,i,a){if(!(r+24>e.length)){var n=x(e,r);if(n&&r+n.frameLength<=e.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function x(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,a=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==a&&15!==a&&3!==n){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*_[14*(3===r?3-i:3===i?3:4)+a-1],u=I[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,d=C[r][i],c=w[i],f=8*d*c,g=Math.floor(d*l/u+s)*c;if(null===k){var v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);k=v?parseInt(v[1]):0}return!!k&&k<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:h,frameLength:g,samplesPerFrame:f}}}function P(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function F(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&f.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)r.set(t.subarray(a,a+16),i);return r},e.getAvcDecryptedUnit=function(t,e){for(var r=new Uint8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)t.set(r.subarray(i,i+16),a);return t},e.decryptAvcSample=function(t,e,r,i,a,n){var s=q(a.data),o=this.getAvcEncryptedData(s),l=this;this.decryptBuffer(o.buffer,(function(o){a.data=l.getAvcDecryptedUnit(s,o),n||l.decryptAvcSamples(t,e,r+1,i)}))},e.decryptAvcSamples=function(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();for(var a=t[e].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,n,s),!s)return}}}},t}(),B={video:1,audio:2,id3:3,text:4},G=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return!(r<0)&&(r&&f.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t.syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r>4>1){if((k=A+5+e[A+4])===A+188)continue}else k=A+4;switch(D){case c:R&&(g&&(o=V(g))&&this.parseAVCPES(o,!1),g={data:[],size:0}),g&&(g.data.push(e.subarray(k,A+188)),g.size+=A+188-k);break;case v:R&&(m&&(o=V(m))&&(h.isAAC?this.parseAACPES(o):this.parseMPEGPES(o)),m={data:[],size:0}),m&&(m.data.push(e.subarray(k,A+188)),m.size+=A+188-k);break;case p:R&&(y&&(o=V(y))&&this.parseID3PES(o),y={data:[],size:0}),y&&(y.data.push(e.subarray(k,A+188)),y.size+=A+188-k);break;case 0:R&&(k+=e[k]+1),b=this._pmtId=j(e,k);break;case b:R&&(k+=e[k]+1);var _=H(e,k,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,n);(c=_.avc)>0&&(u.pid=c),(v=_.audio)>0&&(h.pid=v,h.isAAC=_.isAAC),(p=_.id3)>0&&(d.pid=p),T&&!E&&(f.b.log("reparse from beginning"),T=!1,A=L-188),E=this.pmtParsed=!0;break;case 17:case 8191:break;default:T=!0}}else this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});u.pesData=g,h.pesData=m,d.pesData=y;var I={audioTrack:h,avcTrack:u,id3Track:d,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(I),I},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.avcTrack,a=t.id3Track,n=i.pesData,s=r.pesData,o=a.pesData;n&&(e=V(n))?(this.parseAVCPES(e,!0),i.pesData=null):i.pesData=n,s&&(e=V(s))?(r.isAAC?this.parseAACPES(e):this.parseMPEGPES(e),r.pesData=null):(null!=s&&s.size&&f.b.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(e=V(o))?(this.parseID3PES(e),a.pesData=null):a.pesData=o},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),a=this.sampleAes=new U(this.observer,this.config,e);return this.decrypt(i,a)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,a=t.avcTrack;i.samples&&i.isAAC?e.decryptAacSamples(i.samples,0,(function(){a.samples?e.decryptAvcSamples(a.samples,0,0,(function(){r(t)})):r(t)})):a.samples&&e.decryptAvcSamples(a.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function(t,e){var r,i=this,a=this._avcTrack,n=this.parseAVCNALu(t.data),s=this.avcSample,l=!1;t.data=null,s&&n.length&&!a.audFound&&(W(s,a),s=this.avcSample=K(!1,t.pts,t.dts,"")),n.forEach((function(e){switch(e.type){case 1:r=!0,s||(s=i.avcSample=K(!0,t.pts,t.dts,"")),s.frame=!0;var n=e.data;if(l&&n.length>4){var u=new N(n).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(s.key=!0)}break;case 5:r=!0,s||(s=i.avcSample=K(!0,t.pts,t.dts,"")),s.key=!0,s.frame=!0;break;case 6:r=!0;var h=new N(q(e.data));h.readUByte();for(var d=0,c=0,f=!1,g=0;!f&&h.bytesAvailable>1;){d=0;do{d+=g=h.readUByte()}while(255===g);c=0;do{c+=g=h.readUByte()}while(255===g);if(4===d&&0!==h.bytesAvailable){if(f=!0,181===h.readUByte())if(49===h.readUShort())if(1195456820===h.readUInt())if(3===h.readUByte()){for(var v=h.readUByte(),p=31&v,m=[v,h.readUByte()],y=0;y16){for(var T=[],E=0;E<16;E++)T.push(h.readUByte().toString(16)),3!==E&&5!==E&&7!==E&&9!==E||T.push("-");for(var b=c-16,S=new Uint8Array(b),L=0;L=0){var d={data:t.subarray(u,l-n-1),type:h};o.push(d)}else{var c=this.getLastNalUnit();if(c&&(s&&l<=4-s&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-s)),(r=l-n-1)>0)){var f=new Uint8Array(c.data.byteLength+r);f.set(c.data,0),f.set(t.subarray(0,r),c.data.byteLength),c.data=f}}l=0&&n>=0){var g={data:t.subarray(u,i),type:h,state:n};o.push(g)}if(0===o.length){var v=this.getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+t.byteLength);p.set(v.data,0),p.set(t,v.data.byteLength),v.data=p}}return a.naluState=n,o},e.parseAACPES=function(t){var e,r,n,s,o,l=0,u=this._audioTrack,h=this.aacOverFlow,d=t.data;if(h){this.aacOverFlow=null;var c=h.sample.unit.byteLength,g=Math.min(h.missing,c),v=c-g;h.sample.unit.set(d.subarray(0,g),v),u.samples.push(h.sample),l=h.missing}for(e=l,r=d.length;e1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(a=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?a-(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(f.b.warn(Math.round((a-n)/9e4)+"s delta between PTS and DTS, align them"),a=n):n=a);var h=(i=e[8])+9;if(t.size<=h)return null;t.size-=h;for(var d=new Uint8Array(t.size),c=0,g=o.length;cv){h-=v;continue}e=e.subarray(h),v-=h,h=0}d.set(e,s),s+=v}return r&&(r-=i+3),{data:d,pts:a,dts:n,len:r}}return null}function W(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var a=r[i-1];t.pts=a.pts,t.dts=a.dts}e.samples.push(t)}t.debug.length&&f.b.log(t.pts+"/"+t.dts+":"+t.debug)}function Y(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts0?this.lastEndDTS=p:(f.b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var m=!!c.audio,y=!!c.video,T="";m&&(T+="audio"),y&&(T+="video");var E={data1:h,startPTS:v,startDTS:v,endPTS:p,endDTS:p,type:T,hasAudio:m,hasVideo:y,nb:1,dropped:0};return u.audio="audio"===E.type?E:void 0,u.video="audio"!==E.type?E:void 0,u.text=i,u.id3=r,u.initSegment=d,u},t}(),et=function(t,e,r){return Object(l.d)(t,e)-r};function rt(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===Z.a.VIDEO?"avc1.42e01e":"mp4a.40.5"}var it,at=tt,nt=r(13);try{it=self.performance.now.bind(self.performance)}catch(t){f.b.debug("Unable to use Performance API on this environment"),it=self.Date.now}var st=[{demux:X,remux:J.a},{demux:D,remux:at},{demux:A,remux:J.a},{demux:$,remux:J.a}],ot=1024;st.forEach((function(t){var e=t.demux;ot=Math.max(ot,e.minProbeByteLength)}));var lt=function(){function t(t,e,r,i,a){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new nt.a,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=a}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var a=this,n=r.transmuxing;n.executeStart=it();var s=new Uint8Array(t),o=this.cache,u=this.config,h=this.currentTransmuxState,d=this.transmuxConfig;i&&(this.currentTransmuxState=i);var c=function(t,e){var r=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e);return r}(s,e);if(c&&"AES-128"===c.method){var f=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=f.webCryptoDecrypt(s,c.key.buffer,c.iv.buffer).then((function(t){var e=a.push(t,null,r);return a.decryptionPromise=null,e})),this.decryptionPromise;var g=f.softwareDecrypt(s,c.key.buffer,c.iv.buffer);if(!g)return n.executeEnd=it(),ut(r);s=new Uint8Array(g)}var v=i||h,p=v.contiguous,m=v.discontinuity,y=v.trackSwitch,T=v.accurateTimeOffset,E=v.timeOffset,b=d.audioCodec,S=d.videoCodec,L=d.defaultInitPts,A=d.duration,R=d.initSegmentData;if((m||y)&&this.resetInitSegment(R,b,S,A),m&&this.resetInitialTimestamp(L),p||this.resetContiguity(),this.needsProbing(s,m,y)){if(o.dataLength){var D=o.flush();s=Object(l.a)(D,s)}this.configureTransmuxer(s,d)}var k=this.transmux(s,c,E,T,r),_=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,n.executeEnd=it(),k},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=it();var n=this.decrypter,s=this.cache,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var u=[],h=o.timeOffset;if(n){var d=n.flush();d&&u.push(this.push(d,null,t))}var c=s.dataLength;s.reset();var f=this.demuxer,g=this.remuxer;if(!f||!g)return c>=ot&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=it(),[ut(t)];var v=f.flush(h);return ht(v)?v.then((function(r){return e.flushRemux(u,r,t),u})):(this.flushRemux(u,v,t),u)},e.flushRemux=function(t,e,r){var i=e.audioTrack,a=e.avcTrack,n=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;f.b.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var h=this.remuxer.remux(i,a,n,s,u,l,!0,this.id);t.push({remuxResult:h,chunkMeta:r}),r.transmuxing.executeEnd=it()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var a=this.demuxer,n=this.remuxer;a&&n&&(a.resetInitSegment(e,r,i),n.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,a){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,a):this.transmuxUnencrypted(t,r,i,a)},e.transmuxUnencrypted=function(t,e,r,i){var a=this.demuxer.demux(t,e,!1,!this.config.progressive),n=a.audioTrack,s=a.avcTrack,o=a.id3Track,l=a.textTrack;return{remuxResult:this.remuxer.remux(n,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,a){var n=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.avcTrack,t.id3Track,t.textTrack,r,i,!1,n.id),chunkMeta:a}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,a=this.observer,n=this.typeSupported,s=this.vendor,o=e.audioCodec,l=e.defaultInitPts,u=e.duration,h=e.initSegmentData,d=e.videoCodec,c=0,g=st.length;c>>8^255&p^99,t[f]=p,e[p]=f;var m=c[f],y=c[m],T=c[y],E=257*c[p]^16843008*p;i[f]=E<<24|E>>>8,a[f]=E<<16|E>>>16,n[f]=E<<8|E>>>24,s[f]=E,E=16843009*T^65537*y^257*m^16843008*f,l[p]=E<<24|E>>>8,u[p]=E<<16|E>>>16,h[p]=E<<8|E>>>24,d[p]=E,f?(f=m^c[c[c[T^m]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i1?r-1:0),a=1;a>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(n+1)),a=Math.floor(r%(n+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,s)},t.sdtp=function(e){var r,i,a=e.samples||[],n=new Uint8Array(4+a.length);for(r=0;r>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,a=e.width,s=e.height,o=Math.floor(i/(n+1)),l=Math.floor(i%(n+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,s>>8&255,255&s,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),a=e.id,s=Math.floor(r/(n+1)),o=Math.floor(r%(n+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,a,n,s,o,l,u=e.samples||[],h=u.length,d=12+16*h,c=new Uint8Array(d);for(r+=8+d,c.set([0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();s.types=void 0,s.HDLR_TYPES=void 0,s.STTS=void 0,s.STSC=void 0,s.STCO=void 0,s.STSZ=void 0,s.VMHD=void 0,s.SMHD=void 0,s.STSD=void 0,s.FTYP=void 0,s.DINF=void 0;var o=s,l=r(0),u=r(2),h=r(1),d=r(4),c=r(8);function f(){return(f=Object.assign||function(t){for(var e=1;e0?t:r.pts}),t[0].pts);return e&&h.b.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,a,n,s,o){var l,u,c,f,g,v,p=a,m=a,T=t.pid>-1,E=e.pid>-1,b=e.samples.length,S=t.samples.length>0,L=b>1;if((!T||S)&&(!E||L)||this.ISGenerated||s){this.ISGenerated||(c=this.generateIS(t,e,a));var A=this.isVideoContiguous,R=-1;if(L&&(R=function(t){for(var e=0;e0){h.b.warn("[mp4-remuxer]: Dropped "+R+" out of "+b+" video samples due to a missing keyframe");var D=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(R),e.dropped+=R,m+=(e.samples[0].pts-D)/(e.timescale||9e4)}else-1===R&&(h.b.warn("[mp4-remuxer]: No keyframe found out of "+b+" video samples"),v=!1);if(this.ISGenerated){if(S&&L){var k=this.getVideoStartPts(e.samples),_=(y(t.samples[0].pts,k)-k)/e.inputTimeScale;p+=Math.max(0,_),m+=Math.max(0,-_)}if(S){if(t.samplerate||(h.b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,e,a)),u=this.remuxAudio(t,p,this.isAudioContiguous,n,E||L||o===d.b.AUDIO?m:void 0),L){var I=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(h.b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,e,a)),l=this.remuxVideo(e,m,A,I)}}else L&&(l=this.remuxVideo(e,m,A,0));l&&(l.firstKeyFrame=R,l.independent=-1!==R)}}return this.ISGenerated&&(r.samples.length&&(g=this.remuxID3(r,a)),i.samples.length&&(f=this.remuxText(i,a))),{audio:u,video:l,initSegment:c,independent:v,text:f,id3:g}},e.generateIS=function(t,e,r){var a,n,s,l=t.samples,u=e.samples,h=this.typeSupported,d={},c=!Object(i.a)(this._initPTS),f="audio/mp4";if(c&&(a=n=1/0),t.config&&l.length&&(t.timescale=t.samplerate,t.isAAC||(h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3")),d.audio={id:"audio",container:f,codec:t.codec,initSegment:!t.isAAC&&h.mpeg?new Uint8Array(0):o.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(s=t.inputTimeScale,a=n=l[0].pts-Math.round(s*r))),e.sps&&e.pps&&u.length&&(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:o.initSegment([e]),metadata:{width:e.width,height:e.height}},c)){s=e.inputTimeScale;var g=this.getVideoStartPts(u),v=Math.round(s*r);n=Math.min(n,y(u[0].dts,g)-v),a=Math.min(a,g-v)}if(Object.keys(d).length)return this.ISGenerated=!0,c&&(this._initPTS=a,this._initDTS=n),{tracks:d,initPTS:a,timescale:s}},e.remuxVideo=function(t,e,r,i){var a,n,s,d=t.inputTimeScale,v=t.samples,m=[],E=v.length,b=this._initPTS,S=this.nextAvcDts,L=8,A=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,D=0,k=!1;r&&null!==S||(S=e*d-(v[0].pts-y(v[0].dts,v[0].pts)));for(var _=0;_I.pts){D=Math.max(Math.min(D,I.pts-I.dts),-18e3)}I.dts0?_-1:_].dts&&(k=!0)}k&&v.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),n=v[0].dts,s=v[v.length-1].dts;var C=Math.round((s-n)/(E-1));if(D<0){if(D<-2*C){h.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+Object(c.b)(-C,!0)+" ms");for(var w=D,O=0;OC;if(F||P<-1){F?h.b.warn("AVC: "+Object(c.b)(P,!0)+" ms ("+P+"dts) hole between fragments detected, filling it"):h.b.warn("AVC: "+Object(c.b)(-P,!0)+" ms ("+P+"dts) overlapping between fragments detected"),n=S;var M=v[0].pts-P;v[0].dts=n,v[0].pts=M,h.b.log("Video: First PTS/DTS adjusted: "+Object(c.b)(M,!0)+"/"+Object(c.b)(n,!0)+", delta: "+Object(c.b)(P,!0)+" ms")}}p&&(n=Math.max(0,n));for(var N=0,U=0,B=0;B0?X-1:X].dts;if(it.stretchShortVideoTrack&&null!==this.nextAudioPts){var nt=Math.floor(it.maxBufferHole*d),st=(i?A+i*d:this.nextAudioPts)-z.pts;st>nt?((a=st-at)<0&&(a=at),h.b.log("[mp4-remuxer]: It is approximately "+st/90+" ms to the next segment; using duration "+a/90+" ms for the last video frame.")):a=at}else a=at}var ot=Math.round(z.pts-z.dts);m.push(new T(z.key,a,$,ot))}if(m.length&&g&&g<70){var lt=m[0].flags;lt.dependsOn=2,lt.isNonSync=0}this.nextAvcDts=S=s+a,this.isVideoContiguous=!0;var ut={data1:o.moof(t.sequenceNumber++,n,f({},t,{samples:m})),data2:W,startPTS:A/d,endPTS:(R+a)/d,startDTS:n/d,endDTS:S/d,type:"video",hasAudio:!1,hasVideo:!0,nb:m.length,dropped:t.dropped};return t.samples=[],t.dropped=0,ut},e.remuxAudio=function(t,e,r,i,n){var s=t.inputTimeScale,d=s/(t.samplerate?t.samplerate:s),c=t.isAAC?1024:1152,g=c*d,v=this._initPTS,p=!t.isAAC&&this.typeSupported.mpeg,m=[],E=t.samples,b=p?0:8,S=this.nextAudioPts||-1,L=e*s;if(this.isAudioContiguous=r=r||E.length&&S>0&&(i&&Math.abs(L-S)<9e3||Math.abs(y(E[0].pts-v,L)-S)<20*g),E.forEach((function(t){t.pts=y(t.pts-v,L)})),!r||S<0){if(!(E=E.filter((function(t){return t.pts>=0}))).length)return;S=0===n?0:i?Math.max(0,L):E[0].pts}if(t.isAAC)for(var A=void 0!==n,R=this.config.maxAudioFramesDrift,D=0,k=S;D=R*g&&w<1e4&&A){var O=Math.round(C/g);(k=I-O*g)<0&&(O--,k+=g),0===D&&(this.nextAudioPts=S=k),h.b.warn("[mp4-remuxer]: Injecting "+O+" audio frame @ "+(k/s).toFixed(3)+"s due to "+Math.round(1e3*C/s)+" ms gap.");for(var x=0;x0))return;B+=b;try{M=new Uint8Array(B)}catch(t){return void this.observer.emit(l.a.ERROR,l.a.ERROR,{type:u.b.MUX_ERROR,details:u.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:B,reason:"fail allocating audio mdat "+B})}p||(new DataView(M.buffer).setUint32(0,B),M.set(o.types.mdat,4))}M.set(V,b);var Y=V.byteLength;b+=Y,m.push(new T(!0,c,Y,0)),U=W}var q=m.length;if(q){var X=m[m.length-1];this.nextAudioPts=S=U+d*X.duration;var z=p?new Uint8Array(0):o.moof(t.sequenceNumber++,N/d,f({},t,{samples:m}));t.samples=[];var Q=N/s,$=S/s,J={data1:z,data2:M,startPTS:Q,endPTS:$,startDTS:Q,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:q};return this.isAudioContiguous=!0,J}},e.remuxEmptyAudio=function(t,e,r,i){var n=t.inputTimeScale,s=n/(t.samplerate?t.samplerate:n),o=this.nextAudioPts,l=(null!==o?o:i.startDTS*n)+this._initDTS,u=i.endDTS*n+this._initDTS,d=1024*s,c=Math.ceil((u-l)/d),f=a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(h.b.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],v=0;v4294967296;)t+=r;return t}var T=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new E(t)},E=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}},function(t,e,r){"use strict";r.d(e,"a",(function(){return n}));var i=r(11);function a(t,e){for(var r=0;r0}),!1)}t.exports=function(t,e){e=e||{};var a={main:r.m},o=e.all?{main:Object.keys(a.main)}:function(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};s(r);)for(var o=Object.keys(r),l=0;lt.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(a.a)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&h(e.prototype,r),i&&h(e,i),t}(),c=r(17),f=/^(\d+)x(\d+)$/,g=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,v=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=f.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(g.lastIndex=0;null!==(e=g.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function m(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}var y=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,T=/#EXT-X-MEDIA:(.*)/g,E=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),b=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),S=/\.(mp4|m4s|m4v|m4a)$/i;var L=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).substr(-4)}return t},t.resolve=function(t,e){return i.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,a=[],n={},s=!1;for(y.lastIndex=0;null!=(i=y.exec(e));)if(i[1]){var o=new v(i[1]),l={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),A((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=t.convertAVC1ToAVCOTI(l.videoCodec)),a.push(l)}else if(i[3]){var h=new v(i[3]);h["DATA-ID"]&&(s=!0,n[h["DATA-ID"]]=h)}return{levels:a,sessionData:s?n:null}},t.parseMasterPlaylistMedia=function(e,r,i,a){var n;void 0===a&&(a=[]);var s=[],o=0;for(T.lastIndex=0;null!==(n=T.exec(e));){var l=new v(n[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(a.length){var h=t.findGroup(a,u.groupId)||a[0];R(u,h,"audioCodec"),R(u,h,"textCodec")}s.push(u)}}return s},t.parseLevelPlaylist=function(t,e,r,n,s){var l,h,f,g=new d(e),p=g.fragments,m=null,y=0,T=0,L=0,A=0,R=null,k=new u.b(n,e),_=-1,I=!1;for(E.lastIndex=0,g.m3u8=t;null!==(l=E.exec(t));){I&&(I=!1,(k=new u.b(n,e)).start=L,k.sn=y,k.cc=A,k.level=r,m&&(k.initSegment=m,k.rawProgramDateTime=m.rawProgramDateTime));var C=l[1];if(C){k.duration=parseFloat(C);var w=(" "+l[2]).slice(1);k.title=w||null,k.tagList.push(w?["INF",C,w]:["INF",C])}else if(l[3])Object(a.a)(k.duration)&&(k.start=L,f&&(k.levelkey=f),k.sn=y,k.level=r,k.cc=A,k.urlId=s,p.push(k),k.relurl=(" "+l[3]).slice(1),D(k,R),R=k,L+=k.duration,y++,T=0,I=!0);else if(l[4]){var O=(" "+l[4]).slice(1);R?k.setByteRange(O,R):k.setByteRange(O)}else if(l[5])k.rawProgramDateTime=(" "+l[5]).slice(1),k.tagList.push(["PROGRAM-DATE-TIME",k.rawProgramDateTime]),-1===_&&(_=p.length);else{if(!(l=l[0].match(b))){o.b.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h-1){o.b.warn("Keyformat "+q+" is not supported from the manifest");continue}if("identity"!==q)continue;j&&(f=c.a.fromURL(e,H),H&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(j)>=0&&(f.method=j,f.keyFormat=q,Y&&(f.keyID=Y),W&&(f.keyFormatVersions=W),f.iv=V));break;case"START":var X=new v(P).decimalFloatingPoint("TIME-OFFSET");Object(a.a)(X)&&(g.startTimeOffset=X);break;case"MAP":var z=new v(P);k.relurl=z.URI,z.BYTERANGE&&k.setByteRange(z.BYTERANGE),k.level=r,k.sn="initSegment",f&&(k.levelkey=f),k.initSegment=null,m=k,I=!0;break;case"SERVER-CONTROL":var Q=new v(P);g.canBlockReload=Q.bool("CAN-BLOCK-RELOAD"),g.canSkipUntil=Q.optionalFloat("CAN-SKIP-UNTIL",0),g.canSkipDateRanges=g.canSkipUntil>0&&Q.bool("CAN-SKIP-DATERANGES"),g.partHoldBack=Q.optionalFloat("PART-HOLD-BACK",0),g.holdBack=Q.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var $=new v(P);g.partTarget=$.decimalFloatingPoint("PART-TARGET");break;case"PART":var J=g.partList;J||(J=g.partList=[]);var Z=T>0?J[J.length-1]:void 0,tt=T++,et=new u.c(new v(P),k,e,tt,Z);J.push(et),k.duration+=et.duration;break;case"PRELOAD-HINT":var rt=new v(P);g.preloadHint=rt;break;case"RENDITION-REPORT":var it=new v(P);g.renditionReports=g.renditionReports||[],g.renditionReports.push(it);break;default:o.b.warn("line parsed but not handled: "+l)}}}R&&!R.relurl?(p.pop(),L-=R.duration,g.partList&&(g.fragmentHint=R)):g.partList&&(D(k,R),k.cc=A,g.fragmentHint=k);var at=p.length,nt=p[0],st=p[at-1];if((L+=g.skippedSegments*g.targetduration)>0&&at&&st){g.averagetargetduration=L/at;var ot=st.sn;g.endSN="initSegment"!==ot?ot:0,nt&&(g.startCC=nt.cc,nt.initSegment||g.fragments.every((function(t){return t.relurl&&(e=t.relurl,S.test(null!=(r=null===(a=i.parseURL(e))||void 0===a?void 0:a.path)?r:""));var e,r,a}))&&(o.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(k=new u.b(n,e)).relurl=st.relurl,k.level=r,k.sn="initSegment",nt.initSegment=k,g.needSidxRanges=!0))}else g.endSN=0,g.startCC=0;return g.fragmentHint&&(L+=g.fragmentHint.duration),g.totalduration=L,g.endCC=A,_>0&&function(t,e){for(var r=t[e],i=e;i--;){var a=t[i];if(!a)return;a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(p,_),g},t}();function A(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=p[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var a=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=a.length>0?a[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function R(t,e,r){var i=e[r];i&&(t[r]=i)}function D(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Object(a.a)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}var k=r(4);function _(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var I=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=new(r||i)(e);return t.loader=a,this.loaders[t.type]=a,a},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:k.a.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:k.a.LEVEL,url:a,deliveryDirectives:n})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:k.a.AUDIO_TRACK,url:a,deliveryDirectives:n})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:k.a.SUBTITLE_TRACK,url:a,deliveryDirectives:n})},e.load=function(t){var e,r,i,a,n,s,l=this.hls.config,u=this.getInternalLoader(t);if(u){var h=u.context;if(h&&h.url===t.url)return void o.b.trace("[playlist-loader]: playlist request ongoing");o.b.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case k.a.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,a=l.manifestLoadingRetryDelay,n=l.manifestLoadingMaxRetryTimeout;break;case k.a.LEVEL:case k.a.AUDIO_TRACK:case k.a.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,a=l.levelLoadingRetryDelay,n=l.levelLoadingMaxRetryTimeout}if((u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part)&&(t.type===k.a.LEVEL&&null!==t.level?s=this.hls.levels[t.level].details:t.type===k.a.AUDIO_TRACK&&null!==t.id?s=this.hls.audioTracks[t.id].details:t.type===k.a.SUBTITLE_TRACK&&null!==t.id&&(s=this.hls.subtitleTracks[t.id].details),s)){var d=s.partTarget,c=s.targetduration;d&&c&&(i=Math.min(1e3*Math.max(3*d,.8*c),i))}var f={timeout:i,maxRetry:r,retryDelay:a,maxRetryDelay:n,highWaterMark:0},g={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,f,g)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var a=this.hls,s=t.data,l=_(t,r),u=L.parseMasterPlaylist(s,l),h=u.levels,d=u.sessionData;if(h.length){var c=h.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),f=h.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),g=L.parseMasterPlaylistMedia(s,l,"AUDIO",c),p=L.parseMasterPlaylistMedia(s,l,"SUBTITLES",f),m=L.parseMasterPlaylistMedia(s,l,"CLOSED-CAPTIONS");if(g.length)g.some((function(t){return!t.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(o.b.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new v({}),bitrate:0,url:""}));a.trigger(n.a.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,url:l,stats:e,networkDetails:i,sessionData:d})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,i){var o=this.hls,l=r.id,u=r.level,h=r.type,d=_(t,r),c=Object(a.a)(l)?l:0,f=Object(a.a)(u)?u:c,g=function(t){switch(t.type){case k.a.AUDIO_TRACK:return k.b.AUDIO;case k.a.SUBTITLE_TRACK:return k.b.SUBTITLE;default:return k.b.MAIN}}(r),p=L.parseLevelPlaylist(t.data,d,f,g,c);if(p.fragments.length){if(h===k.a.MANIFEST){var m={attrs:new v({}),bitrate:0,details:p,name:"",url:d};o.trigger(n.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:d,stats:e,networkDetails:i,sessionData:null})}if(e.parsing.end=performance.now(),p.needSidxRanges){var y,T=null===(y=p.fragments[0].initSegment)||void 0===y?void 0:y.url;this.load({url:T,isSidxRequest:!0,type:h,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(t,e,r,i)}else o.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.LEVEL_EMPTY_ERROR,fatal:!1,url:d,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=Object(l.g)(new Uint8Array(t.data));if(r){var i=r.references,a=e.levelDetails;i.forEach((function(t,e){var i=t.info,n=a.fragments[e];0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:e.type===k.a.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),o.b.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var a=s.a.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case k.a.MANIFEST:a=r?s.a.MANIFEST_LOAD_TIMEOUT:s.a.MANIFEST_LOAD_ERROR,l=!0;break;case k.a.LEVEL:a=r?s.a.LEVEL_LOAD_TIMEOUT:s.a.LEVEL_LOAD_ERROR,l=!1;break;case k.a.AUDIO_TRACK:a=r?s.a.AUDIO_TRACK_LOAD_TIMEOUT:s.a.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case k.a.SUBTITLE_TRACK:a=r?s.a.SUBTITLE_TRACK_LOAD_TIMEOUT:s.a.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var h={type:s.b.NETWORK_ERROR,details:a,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(h.response=i),this.hls.trigger(n.a.ERROR,h)},e.handlePlaylistLoaded=function(t,e,r,i){var a=r.type,s=r.level,o=r.id,l=r.groupId,u=r.loader,h=r.levelDetails,d=r.deliveryDirectives;if(null!=h&&h.targetduration){if(u)switch(h.live&&(u.getCacheAge&&(h.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(h.ageHeader)||(h.ageHeader=0)),a){case k.a.MANIFEST:case k.a.LEVEL:this.hls.trigger(n.a.LEVEL_LOADED,{details:h,level:s||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:d});break;case k.a.AUDIO_TRACK:this.hls.trigger(n.a.AUDIO_TRACK_LOADED,{details:h,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:d});break;case k.a.SUBTITLE_TRACK:this.hls.trigger(n.a.SUBTITLE_TRACK_LOADED,{details:h,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:d})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}(),C=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){this.hls.on(n.a.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function(){this.hls.off(n.a.KEY_LOADING,this.onKeyLoading)},e.destroy=function(){for(var t in this._unregisterListeners(),this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.onKeyLoading=function(t,e){var r=e.frag,i=r.type,a=this.loaders[i];if(r.decryptdata){var s=r.decryptdata.uri;if(s!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(o.b.warn("abort previous key loader for type:"+i),a.abort()),!s)return void o.b.warn("key uri is falsy");var u=l.loader,h=r.loader=this.loaders[i]=new u(l);this.decrypturl=s,this.decryptkey=null;var d={url:s,frag:r,responseType:"arraybuffer"},c={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};h.load(d,c,f)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(n.a.KEY_LOADED,{frag:r}))}else o.b.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(n.a.KEY_LOADED,{frag:i})):o.b.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}();function w(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function O(t,e){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(r){o.b.debug("[texttrack-utils]: "+r);var i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}"disabled"===r&&(t.mode=r)}function x(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(var r=t.cues.length;r--;)t.removeCue(t.cues[r]);"disabled"===e&&(t.mode=e)}function P(t,e,r){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var a=function(t,e,r){var i=[],a=function(t,e){if(et[r].endTime)return-1;var i=0,a=r;for(;i<=a;){var n=Math.floor((a+i)/2);if(et[n].startTime&&i-1)for(var n=a,s=t.length;n=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),n=0;n.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,h))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},a.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},a.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,a=this.config,n=a.liveSyncDuration,s=a.liveSyncDurationCount,o=a.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==n?n:s*i);var h=i;return u+Math.min(1*this.stallCount,h)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,a=t-e-this.edgeStalled,n=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,a),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return r?t.buffered.end(r-1):e.edge-this.currentTime}}])&&N(e.prototype,r),i&&N(e,i),t}();function G(t,e){for(var r=0;rt.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function Y(t,e,r,i,n,s){i-r<=0&&(o.b.warn("Fragment should have a positive duration",e),i=r+e.duration,s=n+e.duration);var l=r,u=i,h=e.startPTS,d=e.endPTS;if(Object(a.a)(h)){var c=Math.abs(h-r);Object(a.a)(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,l=Math.max(r,h),r=Math.min(r,h),n=Math.min(n,e.startDTS),u=Math.min(i,d),i=Math.max(i,d),s=Math.max(s,e.endDTS)}e.duration=i-r;var f=r-e.start;e.appendedPTS=i,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=u,e.endDTS=s;var g,v=e.sn;if(!t||vt.endSN)return 0;var p=v-t.startSN,m=t.fragments;for(m[p]=e,g=p;g>0;g--)W(m[g],m[g-1]);for(g=p;g=0;n--){var s=i[n].initSegment;if(s){r=s;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var l,u=0;if(function(t,e,r){for(var i=e.skippedSegments,a=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=a;u<=n;u++){var h=l[s+u],d=o[u];i&&!d&&u=i.length||z(e,i[r].start)}function z(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;ie.partTarget&&(l+=1)}if(Object(a.a)(o))return new K(o,Object(a.a)(l)?l:void 0,U.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,a=e.details,n=e.stats,s=n.loading.end?Math.max(0,self.performance.now()-n.loading.end):0;if(a.advancedDateTime=Date.now()-s,a.live||null!=r&&r.live){if(a.reloaded(r),r&&this.log("live playlist "+t+" "+(a.advanced?"REFRESHED "+a.lastPartSn+"-"+a.lastPartIndex:"MISSED")),r&&a.fragments.length>0&&q(r,a),!this.canLoad||!a.live)return;var o,l=void 0,u=void 0;if(a.canBlockReload&&a.endSN&&a.advanced){var h=this.hls.config.lowLatencyMode,d=a.lastPartSn,c=a.endSN,f=a.lastPartIndex,g=d===c;-1!==f?(l=g?c+1:d,u=g?h?0:f:f+1):l=c+1;var v=a.age,p=v+a.ageHeader,m=Math.min(p-a.partTarget,1.5*a.targetduration);if(m>0){if(r&&m>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+m+" with playlist age: "+a.age),m=0;else{var y=Math.floor(m/a.targetduration);if(l+=y,void 0!==u)u+=Math.round(m%a.targetduration/a.partTarget);this.log("CDN Tune-in age: "+a.ageHeader+"s last advanced "+v.toFixed(2)+"s goal: "+m+" skip sn "+y+" to part "+u)}a.tuneInGoal=m}if(o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u),h||!g)return void this.loadPlaylist(o)}else o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u);var T=function(t,e){var r,i=1e3*t.levelTargetDuration,a=i/2,n=t.age,s=n>0&&n<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(s){var u=333*t.misses;r=Math.max(Math.min(a,2*o),u),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=a;else s?(l=Math.min(l||i/2,n),t.availabilityDelay=l,r=l+i-n):r=i-o;return Math.round(r)}(a,n);void 0!==l&&a.canBlockReload&&(T-=a.partTarget||1),this.log("reload live playlist "+t+" in "+Math.round(T)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(o)}),T)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var a=function(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,a=t.endSN;return r&&(void 0!==e?e-a:0)-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var n=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),n),this.warn("retry playlist loading #"+this.retryCount+" in "+n+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return a},t}();function $(){return($=Object.assign||function(t){for(var e=1;e0){r=a[0].bitrate,a.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=a;for(var f=0;fthis.hls.config.fragLoadingMaxRetry&&(n=r.frag.level)):n=r.frag.level}break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),n=i.level),o=!0;break;case s.a.REMUX_ALLOC_ERROR:n=r.level,o=!0}void 0!==n&&this.recoverLevel(r,n,o,l)}}},u.recoverLevel=function(t,e,r,i){var a=t.details,n=this._levels[e];if(n.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var s=n.url.length;if(s>1&&n.loadError1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},u.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===k.b.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},u.onLevelLoaded=function(t,e){var r,i,a=e.level,n=e.details,s=this._levels[a];if(!s)return this.warn("Invalid level index "+a),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(n.deltaUpdateFailed=!0));a===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(a,e,s.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(n.deltaUpdateFailed=!0)},u.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,a=this.hls.audioTracks[e.id].groupId,n=0;n0){var i=r.urlId,a=r.url[i];if(t)try{a=t.addDirectives(a)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+a),this.clearTimer(),this.hls.trigger(n.a.LEVEL_LOADING,{url:a,level:e,id:i,deliveryDirectives:t||null})}},u.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,a){return a!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(n.a.LEVELS_UPDATED,{levels:i})},a=i,(o=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[t];this.log("switching to level "+t+" from "+a),this.currentLevelIndex=t;var u=$({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(n.a.LEVEL_SWITCHING,u);var h=l.details;if(!h||h.live){var d=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(d)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&J(a.prototype,o),l&&J(a,l),i}(Q);!function(t){t.NOT_LOADED="NOT_LOADED",t.BACKTRACKED="BACKTRACKED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}(tt||(tt={}));var it=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.a.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.a.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===k.b.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var a=i.length;a--;){var n=i[a],s=n?n.end:r.appendedPTS;if(n.start<=t&&void 0!==s&&t<=s)return a>9&&(this.activeParts=i.slice(a-9)),n}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),a=i.length;a--;){var n=r[i[a]];if((null==n?void 0:n.body.type)===e&&n.buffered){var s=n.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(a){var n=i.fragments[a];if(n)if(n.buffered){var s=n.range[t];s&&s.time.some((function(t){var r=!i.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&i.removeFragment(n.body),r}))}else n.body.type===r&&i.removeFragment(n.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,a=t.part;if(r&&"initSegment"!==i.sn){var n=nt(i),s=this.fragments[n];s&&(Object.keys(r).forEach((function(t){var n=i.elementaryStreams[t];if(n){var o=r[t],l=null!==a||!0===n.partial;s.range[t]=e.getBufferedTimes(i,a,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.fragBuffered=function(t){var e=nt(t),r=this.fragments[e];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var a={time:[],partial:r},n=e?e.start:t.start,s=e?e.end:t.end,o=t.minEndPTS||s,l=t.maxStartPTS||n,u=0;u=h&&o<=d){a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(nh)a.partial=!0,a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=h)break}return a},e.getPartialFragment=function(t){var e,r,i,a=null,n=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&at(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(a=u.body,n=e)))})),a},e.getState=function(t){var e=nt(t),r=this.fragments[e];return r?r.buffered?at(r)?tt.PARTIAL:tt.OK:r.backtrack?tt.BACKTRACKED:tt.APPENDING:tt.NOT_LOADED},e.backtrack=function(t,e){var r=nt(t),i=this.fragments[r];if(!i||i.backtrack)return null;var a=i.backtrack=e||i.loaded;return i.loaded=null,a},e.getBacktrackData=function(t){var e=nt(t),r=this.fragments[e];if(r){var i,a=r.backtrack;if(null!=a&&null!==(i=a.payload)&&void 0!==i&&i.byteLength)return a;this.removeFragment(t)}return null},e.isTimeBuffered=function(t,e,r){for(var i,a,n=0;n=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var a=nt(r);this.fragments[a]={body:r,loaded:e,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,a=e.part,n=e.timeRanges;if(i.type===k.b.MAIN)if(this.activeFragment=i,a){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(a)}else this.activeParts=null;this.timeRanges=n,Object.keys(n).forEach((function(t){var e=n[t];if(r.detectEvictedFragments(t,e),!a)for(var s=0;st&&i.removeFragment(s)}}))},e.removeFragment=function(t){var e=nt(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),delete this.fragments[e]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},t}();function at(t){var e,r;return t.buffered&&((null===(e=t.range.video)||void 0===e?void 0:e.partial)||(null===(r=t.range.audio)||void 0===r?void 0:r.partial))}function nt(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}var st=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),ot={length:0,start:function(){return 0},end:function(){return 0}},lt=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),a=0;a=i.start(a)&&r<=i.end(a))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var a,n=t.getBuffered(e),s=[];for(a=0;as&&(i[n-1].end=t[a].end):i.push(t[a])}else i.push(t[a])}else i=t;for(var o,l=0,u=e,h=e,d=0;d=c&&er.startCC||t&&t.cc0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}};function pt(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!Object(a.a)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;it&&r.start?-1:0}function Tt(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function Et(t){var e="function"==typeof Map?new Map:void 0;return(Et=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return bt(t,arguments,At(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Lt(i,t)})(t)}function bt(t,e,r){return(bt=St()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&Lt(a,r.prototype),a}).apply(null,arguments)}function St(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function Lt(t,e){return(Lt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function At(t){return(At=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var Rt=Math.pow(2,17),Dt=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new _t({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=t.loader=n?new n(a):new o(a),h=kt(t),d={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:Rt};t.stats=u.stats,u.load(h,d,{onSuccess:function(e,a,n,s){r.resetLoader(t,u),i({frag:t,part:null,payload:e.data,networkDetails:s})},onError:function(e,i,a){r.resetLoader(t,u),l(new _t({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:a}))},onAbort:function(e,i,a){r.resetLoader(t,u),l(new _t({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:a}))},onTimeout:function(e,i,a){r.resetLoader(t,u),l(new _t({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:a}))},onProgress:function(r,i,a,n){e&&e({frag:t,part:null,payload:a,networkDetails:n})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var h=i.loader=t.loader=n?new n(a):new o(a),d=kt(t,e),c={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:Rt};e.stats=h.stats,h.load(d,c,{onSuccess:function(a,n,s,o){i.resetLoader(t,h),i.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:a.data,networkDetails:o};r(u),l(u)},onError:function(r,a,n){i.resetLoader(t,h),u(new _t({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:n}))},onAbort:function(r,a,n){t.stats.aborted=e.stats.aborted,i.resetLoader(t,h),u(new _t({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:n}))},onTimeout:function(r,a,n){i.resetLoader(t,h),u(new _t({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:n}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,a=i.total;if(r.loaded+=i.loaded,a){var n=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/a),n),o=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function kt(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(a.a)(n)&&Object(a.a)(s)&&(i.rangeStart=n,i.rangeEnd=s),i}var _t=function(t){var e,r;function i(e){for(var r,i=arguments.length,a=new Array(i>1?i-1:0),n=1;ne.start+e.duration+l;(s0&&s&&s.key&&s.iv&&"AES-128"===s.method){var o=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(a),s.key.buffer,s.iv.buffer).then((function(e){var a=self.performance.now();return i.trigger(n.a.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:o,tdecrypt:a}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,a=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");s[t.level].details;var o=t.stats;e.state=Pt,e.fragLoadError=0,t.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&a.trigger(n.a.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.warn(r),e.resetFragmentLoading(t)}))},c.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},c.fragBufferedComplete=function(t,e){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+Ct.toString(lt.getBuffered(r))),this.state=Pt,this.tick()},c._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,a=t.partsLoaded,n=!a||0===a.length||a.some((function(t){return!t})),s=new ut(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(s)}},c._handleFragmentLoadProgress=function(t){},c._doFragLoad=function(t,e,r,i){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var o=e.partList;if(o&&i){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var l=this.getNextPart(o,t,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=Mt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(t,o,l,i).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),Object(a.a)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Mt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,i).catch((function(t){return s.handleFragLoadError(t)}))},c.doFragPartsLoad=function(t,e,r,i){var a=this;return new Promise((function(s,o){var l=[];!function r(u){var h=e[u];a.fragmentLoader.loadPart(t,h,i).then((function(i){l[h.index]=i;var o=i.part;a.hls.trigger(n.a.FRAG_LOADED,i);var d=e[u+1];if(!d||d.fragment!==t)return s({frag:t,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},c.handleFragLoadError=function(t){var e=t.data;return e&&e.details===s.a.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(n.a.ERROR,e),null},c._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===Bt){var r=e.frag,i=e.part,a=e.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,a,t.partial)}else this.fragCurrent||(this.state=Pt)},c.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,a=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var n=e[r],s=a>-1?function(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var a=i.length;a--;){var n=i[a];if(n.index===r&&n.fragment.sn===e)return n}return null}(n,i,a):null,o=s?s.fragment:function(t,e,r){if(!t||!t.details)return null;var i=t.details,a=i.fragments[e-i.startSN];return a||((a=i.fragmentHint)&&a.sn===e?a:en&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},c.getFwdBufferInfo=function(t,e){var r=this.config,i=this.getLoadPosition();if(!Object(a.a)(i))return null;var n=lt.bufferInfo(t,i,r.maxBufferHole);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(i,e);if(s&&n.nextStart=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},c.getNextFragment=function(t,e){var r,i,a=e.fragments,n=a.length;if(!n)return null;var s,o=this.config,l=a[0].start;if(e.live){var u=o.initialLiveManifestSize;if(n-1&&rr.start&&r.loaded},c.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=pt(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var a=r.sn+1;if(a>=t.startSN&&a<=t.endSN){var n=e[a-t.startSN];r.cc===n.cc&&(i=n,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return vt.search(t,(function(t){return t.cce?-1:0}))}(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},c.getFragmentAtPosition=function(t,e,r){var i,a=this.config,n=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=a.maxFragLookUpTolerance,h=!!(a.lowLatencyMode&&r.partList&&l);(h&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),te-u?0:u):i=s[s.length-1];if(i){var d=i.sn-r.startSN,c=n&&i.level===n.level,f=s[d+1];if(this.fragmentTracker.getState(i)===tt.BACKTRACKED){i=null;for(var g=d;s[g]&&this.fragmentTracker.getState(s[g])===tt.BACKTRACKED;)i=n?s[g--]:s[--g];i||(i=f)}else n&&i.sn===n.sn&&!h&&c&&(i.sn=n-e.maxFragLookUpTolerance&&a<=s;if(null!==i&&r.duration>i&&(a"+t.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+o),d}return l},c.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},c.setStartPosition=function(t,e){var r=this.startPosition;if(r"+t))}}])&&wt(u.prototype,h),d&&wt(u,d),i}(st);function qt(){return self.MediaSource||self.WebKitMediaSource}function Xt(){return self.SourceBuffer||self.WebKitSourceBuffer}var zt=r(18),Qt=r(10),$t=r(14),Jt=qt()||{isTypeSupported:function(){return!1}},Zt=function(){function t(t,e,r,i){var a=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=t,this.id=e,this.onTransmuxComplete=r,this.onFlush=i;var l=t.config,u=function(e,r){(r=r||{}).frag=a.frag,r.id=a.id,t.trigger(e,r)};this.observer=new $t.EventEmitter,this.observer.on(n.a.FRAG_DECRYPTED,u),this.observer.on(n.a.ERROR,u);var h={mp4:Jt.isTypeSupported("video/mp4"),mpeg:Jt.isTypeSupported("audio/mpeg"),mp3:Jt.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(l.enableWorker&&"undefined"!=typeof Worker){var c;o.b.log("demuxing in webworker");try{c=this.worker=zt(19),this.onwmsg=this.onWorkerMessage.bind(this),c.addEventListener("message",this.onwmsg),c.onerror=function(e){t.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(e.message+" ("+e.filename+":"+e.lineno+")")})},c.postMessage({cmd:"init",typeSupported:h,vendor:d,id:e,config:JSON.stringify(l)})}catch(t){o.b.warn("Error in worker:",t),o.b.error("Error while initializing DemuxerWorker, fallback to inline"),c&&self.URL.revokeObjectURL(c.objectURL),this.transmuxer=new Qt.c(this.observer,h,l,d,e),this.worker=null}}else this.transmuxer=new Qt.c(this.observer,h,l,d,e)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function(t,e,r,i,a,n,s,l,u,h){var d=this;u.transmuxing.start=self.performance.now();var c=this.transmuxer,f=this.worker,g=n?n.start:a.start,v=a.decryptdata,p=this.frag,m=!(p&&a.cc===p.cc),y=!(p&&u.level===p.level),T=p?u.sn-p.sn:-1,E=this.part?u.part-this.part.index:1,b=!y&&(1===T||0===T&&1===E),S=self.performance.now();(y||T||0===a.stats.parsing.start)&&(a.stats.parsing.start=S),!n||!E&&b||(n.stats.parsing.start=S);var L=new Qt.b(m,b,l,y,g);if(!b||m){o.b.log("[transmuxer-interface, "+a.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+m+"\n trackSwitch: "+y+"\n contiguous: "+b+"\n accurateTimeOffset: "+l+"\n timeOffset: "+g);var A=new Qt.a(r,i,e,s,h);this.configureTransmuxer(A)}if(this.frag=a,this.part=n,f)f.postMessage({cmd:"demux",data:t,decryptdata:v,chunkMeta:u,state:L},t instanceof ArrayBuffer?[t]:[]);else if(c){var R=c.push(t,v,u,L);Object(Qt.d)(R)?R.then((function(t){d.handleTransmuxComplete(t)})):this.handleTransmuxComplete(R)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var a=r.flush(t);Object(Qt.d)(a)?a.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(a,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),te=function(){function t(t,e,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.hls=this.fragmentTracker=this.media=null},e.poll=function(t){var e=this.config,r=this.media,i=this.stalled,a=r.currentTime,n=r.seeking,s=this.seeking&&!n,l=!this.seeking&&n;if(this.seeking=n,a===t){if((l||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&<.getBuffered(r).length){var u=lt.bufferInfo(r,a,0),h=u.len>0,d=u.nextStart||0;if(h||d){if(n){var c=u.len>2,f=!d||d-a>2&&!this.fragmentTracker.getPartialFragment(a);if(c||f)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var g,v=Math.max(d,u.start||0)-a,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null===(g=p.details)||void 0===g?void 0:g.live)?2*p.details.targetduration:2;if(v>0&&v<=m)return void this._trySkipBufferHole(null)}var y=self.performance.now();if(null!==i){var T=y-i;!n&&T>=250&&this._reportStall(u.len);var E=lt.bufferInfo(r,a,e.maxBufferHole);this._tryFixBufferStall(E,T)}else this.stalled=y}}}else if(this.moved=!0,null!==i){if(this.stallReported){var b=self.performance.now()-i;o.b.warn("playback not stuck anymore @"+a+", after "+Math.round(b)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,a=this.media.currentTime,n=i.getPartialFragment(a);if(n&&this._trySkipBufferHole(n))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(o.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,o.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+t+")"),e.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e._trySkipBufferHole=function(t){for(var e=this.config,r=this.hls,i=this.media,a=i.currentTime,l=0,u=lt.getBuffered(i),h=0;h=l&&a0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Pt,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=xt},c.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},c.doTick=function(){switch(this.state){case Pt:this.doTickIdle();break;case Wt:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=Pt;break}break;case Nt:var a,n=self.performance.now(),s=this.retryDate;(!s||n>=s||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=Pt)}this.onTickEnd()},c.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},c.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,a=this.levels,s=this.media,o=r.config,l=r.nextLoadLevel;if(null!==i&&(s||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&a&&a[l]){var h=a[l];this.level=r.nextLoadLevel=l;var d=h.details;if(!d||this.state===Wt||d.live&&this.levelLastLoaded!==l)this.state=Wt;else{var c=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:s,k.b.MAIN);if(null!==c)if(!(c.len>=this.getMaxBufferLength(h.maxBitrate))){if(this._streamEnded(c,d)){var f={};return this.altAudio&&(f.type="video"),this.hls.trigger(n.a.BUFFER_EOS,f),void(this.state=jt)}var g=c.end,v=this.getNextFragment(g,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&"initSegment"!==v.sn){var p=v.sn-d.startSN;p>1&&(v=d.fragments[p-1],this.fragmentTracker.removeFragment(v))}if(v&&this.fragmentTracker.getState(v)===tt.OK&&this.nextLoadPosition>g){var m=this.audioOnly&&!this.altAudio?u.a.AUDIO:u.a.VIDEO;this.afterBufferFlushed(s,m,k.b.MAIN),v=this.getNextFragment(this.nextLoadPosition,d)}v&&(!v.initSegment||v.initSegment.data||this.bitrateTest||(v=v.initSegment),"identity"!==(null===(t=v.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=v.decryptdata)&&void 0!==e&&e.key?this.loadFragment(v,d,g):this.loadKey(v,d))}}}},c.loadFragment=function(e,r,i){var a,n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,n===tt.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(e);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);n=tt.NOT_LOADED}n===tt.NOT_LOADED||n===tt.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e):this.bitrateTest?(e.bitrateTest=!0,this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):n===tt.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(a=this.media)||void 0===a?void 0:a.buffered.length)&&this.fragmentTracker.removeAllFragments()},c.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,k.b.MAIN);return e&&"fragment"in e?e.fragment:e},c.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,k.b.MAIN)},c.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},c.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},c.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var a=t[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*n)+1:0}else r=0;var s=this.getBufferedFrag(e.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,h=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}},c.abortCurrentFrag=function(){var t=this.fragCurrent;this.fragCurrent=null,null!=t&&t.loader&&t.loader.abort(),this.state===Ft&&(this.state=Pt),this.nextLoadPosition=this.getLoadPosition()},c.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},c.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new te(this.config,i,this.fragmentTracker,this.hls)},c.onMediaDetaching=function(){var e=this.media;e&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},c.onMediaPlaying=function(){this.tick()},c.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;Object(a.a)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},c.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(n.a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},c.onManifestParsed=function(t,e){var r,i,a,n=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(a=Xt())||null===(i=a.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},c.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===Pt){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=Wt)}},c.onLevelLoaded=function(t,e){var r,i=this.levels,a=e.level,s=e.details,o=s.totalduration;if(i){this.log("Level "+a+" loaded ["+s.startSN+","+s.endSN+"], cc ["+s.startCC+", "+s.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==Mt&&this.state!==Nt||l.level!==e.level&&l.loader&&(this.state=Pt,l.loader.abort());var u=i[a],h=0;if(s.live||null!==(r=u.details)&&void 0!==r&&r.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;h=this.alignPlaylists(s,u.details)}if(u.details=s,this.levelLastLoaded=a,this.hls.trigger(n.a.LEVEL_UPDATED,{details:s,level:a}),this.state===Wt){if(this.waitForCdnTuneIn(s))return;this.state=Pt}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,h),this.tick()}else this.warn("Levels were reset while loading level "+a)},c._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.levels;if(n){var s=n[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,h=null===(e=r.initSegment)||void 0===e?void 0:e.data,d=this._getAudioCodec(s),c=this.transmuxer=this.transmuxer||new Zt(this.hls,k.b.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,v=new ut(r.level,r.sn,r.stats.chunkCount,a.byteLength,f,g),p=this.initPTS[r.cc];c.push(a,h,d,l,r,i,o.totalduration,u,v,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},c.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,a=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:a})}},c.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()},c.onBufferCreated=function(t,e){var r,i,a=e.tracks,n=!1;for(var s in a){var o=a[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=a[s];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},c.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===k.b.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Gt&&(this.state=Pt));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},c.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(k.b.MAIN,e);break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==Ht&&(e.fatal?(this.warn(""+e.details),this.state=Ht):e.levelRetry||this.state!==Wt||(this.state=Pt));break;case s.a.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===Bt||this.state===Gt)){var r=!0,i=this.getFwdBufferInfo(this.media,k.b.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},c.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){var r=lt.getBuffered(t);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):e.poll(this.lastCurrentTime),this.lastCurrentTime=t.currentTime}},c.onFragLoadEmergencyAborted=function(){this.state=Pt,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},c.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.a.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.a.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,k.b.MAIN)}},c.onLevelsUpdated=function(t,e){this.levels=e.levels},c.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},c.seekToStartPos=function(){var t=this.media,e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&(a1&&!1===t.seeking){var r=t.currentTime;if(lt.isBuffered(t,r)?e=this.getAppendedFrag(r):lt.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){var i=this.fragPlaying,a=e.level;i&&e.sn===i.sn&&i.level===a&&e.urlId===i.urlId||(this.hls.trigger(n.a.FRAG_CHANGED,{frag:e}),i&&i.level===a||this.hls.trigger(n.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=e)}}},l=i,(h=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);return this.followingBufferedFrag(e)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&ee(l.prototype,h),d&&ee(l,d),i}(Yt),ae=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),ne=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ae(t),this.fast_=new ae(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new ae(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new ae(e,i.getEstimate(),i.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}();function se(t,e){for(var r=0;r=2*h/c||y<=E)){var b,S=Number.POSITIVE_INFINITY;for(b=t.level-1;b>g;b--){if((S=h*f[b].maxBitrate/(6.4*m))=y)){var L=this.bwEstimator.getEstimate();o.b.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+b+"\n Current BW estimate: "+(Object(a.a)(L)?(L/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+y.toFixed(3)+" s\n Estimated load time for the next fragment: "+S.toFixed(3)+" s\n Time to underbuffer: "+E.toFixed(3)+" s"),r.nextLoadLevel=b,this.bwEstimator.sample(d,u.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(n.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:u})}}}}}},l.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if(r.type===k.b.MAIN&&Object(a.a)(r.sn)){var s=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+s.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:h},l.realBitrate=Math.round(8*u/h)}if(r.bitrateTest){var d={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(n.a.FRAG_BUFFERED,d),r.bitrateTest=!1}}},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part,a=i?i.stats:r.stats;if(!a.aborted&&r.type===k.b.MAIN&&"initSegment"!==r.sn){var n=a.parsing.end-a.loading.start;this.bwEstimator.sample(n,a.loaded),a.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},l.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},l.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},l.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,a=r.config,n=r.minAutoLevel,s=r.media,l=e?e.duration:t?t.duration:0,u=s?s.currentTime:0,h=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():a.abrEwmaDefaultEstimate,c=(lt.bufferInfo(s,u,a.maxBufferHole).end-u)/h,f=this.findBestLevel(d,n,i,c,a.abrBandWidthFactor,a.abrBandWidthUpFactor);if(f>=0)return f;o.b.trace((c?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var g=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay,v=a.abrBandWidthFactor,p=a.abrBandWidthUpFactor;if(!c){var m=this.bitrateTestDelay;if(m)g=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-m,o.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),v=p=1}return f=this.findBestLevel(d,n,i,c+g,v,p),Math.max(f,0)},l.findBestLevel=function(t,e,r,i,a,n){for(var s,l=this.fragCurrent,u=this.partCurrent,h=this.lastLoadedFragLevel,d=this.hls.levels,c=d[h],f=!(null==c||null===(s=c.details)||void 0===s||!s.live),g=null==c?void 0:c.codecSet,v=u?u.duration:l?l.duration:0,p=r;p>=e;p--){var m=d[p];if(m&&(!g||m.codecSet===g)){var y=m.details,T=(u?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||v,E=void 0;E=p<=h?a*t:n*t;var b=d[p].maxBitrate,S=b*T/E;if(o.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(E)+"/"+b+"/"+T+"/"+i+"/"+S),E>b&&(!S||f&&!this.bitrateTestDelay||S0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),this.state=Pt):(this.loadedmetadata=!1,this.state=Ut),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},l.doTick=function(){switch(this.state){case Pt:this.doTickIdle();break;case Ut:var e,r=this.levels,i=this.trackId,a=null==r||null===(e=r[i])||void 0===e?void 0:e.details;if(a){if(this.waitForCdnTuneIn(a))break;this.state=Vt}break;case Nt:var n,s=performance.now(),l=this.retryDate;(!l||s>=l||null!==(n=this.media)&&void 0!==n&&n.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.state=Pt);break;case Vt:var u=this.waitingData;if(u){var h=u.frag,d=u.part,c=u.cache,f=u.complete;if(void 0!==this.initPTS[h.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Mt;var g={frag:h,part:d,payload:c.flush(),networkDetails:null};this._handleFragmentLoadProgress(g),f&&t.prototype._handleFragmentLoadComplete.call(this,g)}else if(this.videoTrackCC!==this.waitingVideoCC)o.b.log("Waiting fragment cc ("+h.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var v=this.getLoadPosition(),p=lt.bufferInfo(this.mediaBuffer,v,this.config.maxBufferHole);yt(p.end,this.config.maxFragLookUpTolerance,h)<0&&(o.b.log("Waiting fragment cc ("+h.cc+") @ "+h.start+" cancelled because another fragment at "+p.end+" is needed"),this.clearWaitingFragment())}}else this.state=Pt}this.onTickEnd()},l.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Pt)},l.onTickEnd=function(){var t=this.media;if(t&&t.readyState){var e=(this.mediaBuffer?this.mediaBuffer:t).buffered;!this.loadedmetadata&&e.length&&(this.loadedmetadata=!0),this.lastCurrentTime=t.currentTime}},l.doTickIdle=function(){var t,e,r=this.hls,i=this.levels,a=this.media,s=this.trackId,o=r.config;if(i&&i[s]&&(a||!this.startFragRequested&&o.startFragPrefetch)){var l=i[s].details;if(!l||l.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(l))this.state=Ut;else{this.bufferFlushed&&(this.bufferFlushed=!1,this.afterBufferFlushed(this.mediaBuffer?this.mediaBuffer:this.media,u.a.AUDIO,k.b.AUDIO));var h=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,k.b.AUDIO);if(null!==h){var d=h.len,c=this.getMaxBufferLength(),f=this.audioSwitch;if(!(d>=c)||f){if(!f&&this._streamEnded(h,l))return r.trigger(n.a.BUFFER_EOS,{type:"audio"}),void(this.state=jt);var g=l.fragments[0].start,v=h.end;if(f){var p=this.getLoadPosition();v=p,l.PTSKnown&&pg||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=g+.05)}var m=this.getNextFragment(v,l);m?"identity"!==(null===(t=m.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=m.decryptdata)&&void 0!==e&&e.key?this.loadFragment(m,l,v):this.loadKey(m,l):this.bufferFlushed=!0}}}}},l.getMaxBufferLength=function(){var e=t.prototype.getMaxBufferLength.call(this),r=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,k.b.MAIN);return null===r?e:Math.max(e,r.len)},l.onMediaDetaching=function(){this.videoBuffer=null,t.prototype.onMediaDetaching.call(this)},l.onAudioTracksUpdated=function(t,e){var r=e.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(t){return new j(t)}))},l.onAudioTrackSwitching=function(t,e){var r=!!e.url;this.trackId=e.id;var i=this.fragCurrent;null!=i&&i.loader&&i.loader.abort(),this.fragCurrent=null,this.clearWaitingFragment(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.audioSwitch=!0,this.state=Pt):this.state=xt,this.tick()},l.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1},l.onLevelLoaded=function(t,e){this.mainDetails=e.details},l.onAudioTrackLoaded=function(t,e){var r,i=this.levels,a=e.details,n=e.id;if(i){this.log("Track "+n+" loaded ["+a.startSN+","+a.endSN+"],duration:"+a.totalduration);var s=i[n],o=0;if(a.live||null!==(r=s.details)&&void 0!==r&&r.live){var l=this.mainDetails;if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed||!l)return;!s.details&&a.hasProgramDateTime&&l.hasProgramDateTime?(gt(a,l),o=a.fragments[0].start):o=this.alignPlaylists(a,s.details)}s.details=a,this.levelLastLoaded=n,this.startFragRequested||!this.mainDetails&&a.live||this.setStartPosition(s.details,o),this.state!==Ut||this.waitForCdnTuneIn(a)||(this.state=Pt),this.tick()}else this.warn("Audio tracks were reset while loading level "+n)},l._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.config,s=this.trackId,l=this.levels;if(l){var u=l[s],h=u.details,d=n.defaultAudioCodec||u.audioCodec||"mp4a.40.2",c=this.transmuxer;c||(c=this.transmuxer=new Zt(this.hls,k.b.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var f=this.initPTS[r.cc],g=null===(e=r.initSegment)||void 0===e?void 0:e.data;if(void 0!==f){var v=i?i.index:-1,p=-1!==v,m=new ut(r.level,r.sn,r.stats.chunkCount,a.byteLength,v,p);c.push(a,g,d,"",r,i,h.totalduration,!1,m,f)}else{o.b.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+s),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new le.a,complete:!1}).cache.push(new Uint8Array(a)),this.waitingVideoCC=this.videoTrackCC,this.state=Vt}}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},l._handleFragmentLoadComplete=function(e){this.waitingData?this.waitingData.complete=!0:t.prototype._handleFragmentLoadComplete.call(this,e)},l.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},l.onBufferCreated=function(t,e){var r=e.tracks.audio;r&&(this.mediaBuffer=r.buffer),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part;r.type===k.b.AUDIO&&(this.fragContextChanged(r)?this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+this.audioSwitch):("initSegment"!==r.sn&&(this.fragPrevious=r,this.audioSwitch&&(this.audioSwitch=!1,this.hls.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:this.trackId}))),this.fragBufferedComplete(r,i)))},l.onError=function(e,r){switch(r.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(k.b.AUDIO,r);break;case s.a.AUDIO_TRACK_LOAD_ERROR:case s.a.AUDIO_TRACK_LOAD_TIMEOUT:this.state!==Ht&&this.state!==xt&&(this.state=r.fatal?Ht:Pt,this.warn(r.details+" while loading frag, switching to "+this.state+" state"));break;case s.a.BUFFER_FULL_ERROR:if("audio"===r.parent&&(this.state===Bt||this.state===Gt)){var i=!0,a=this.getFwdBufferInfo(this.mediaBuffer,k.b.AUDIO);a&&a.len>.5&&(i=!this.reduceMaxBufferLength(a.len)),i&&(this.warn("Buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.resetLoadingState()}}},l.onBufferFlushed=function(t,e){e.type===u.a.AUDIO&&(this.bufferFlushed=!0)},l._handleTransmuxComplete=function(t){var e,r="audio",i=this.hls,a=t.remuxResult,s=t.chunkMeta,o=this.getCurrentContext(s);if(!o)return this.warn("The loading context changed while buffering fragment "+s.sn+" of level "+s.level+". This chunk will not be buffered."),void this.resetLiveStartWhenNotLoaded(s.level);var l=o.frag,h=o.part,d=a.audio,c=a.text,f=a.id3,g=a.initSegment;if(!this.fragContextChanged(l)){if(this.state=Bt,this.audioSwitch&&d&&this.completeAudioSwitch(),null!=g&&g.tracks&&(this._bufferInitSegment(g.tracks,l,s),i.trigger(n.a.FRAG_PARSING_INIT_SEGMENT,{frag:l,id:r,tracks:g.tracks})),d){var v=d.startPTS,p=d.endPTS,m=d.startDTS,y=d.endDTS;h&&(h.elementaryStreams[u.a.AUDIO]={startPTS:v,endPTS:p,startDTS:m,endDTS:y}),l.setElementaryStreamInfo(u.a.AUDIO,v,p,m,y),this.bufferFragmentData(d,l,h,s)}if(null!=f&&null!==(e=f.samples)&&void 0!==e&&e.length){var T=ue({frag:l,id:r},f);i.trigger(n.a.FRAG_PARSING_METADATA,T)}if(c){var E=ue({frag:l,id:r},c);i.trigger(n.a.FRAG_PARSING_USERDATA,E)}}},l._bufferInitSegment=function(t,e,r){if(this.state===Bt){t.video&&delete t.video;var i=t.audio;if(i){i.levelCodec=i.codec,i.id="audio",this.log("Init audio buffer, container:"+i.container+", codecs[parsed]=["+i.codec+"]"),this.hls.trigger(n.a.BUFFER_CODECS,t);var a=i.initSegment;if(null!=a&&a.byteLength){var s={type:"audio",frag:e,part:null,chunkMeta:r,parent:e.type,data:a};this.hls.trigger(n.a.BUFFER_APPENDING,s)}this.tick()}}},l.loadFragment=function(e,r,i){var n=this.fragmentTracker.getState(e);this.fragCurrent=e,(this.audioSwitch||n===tt.NOT_LOADED||n===tt.PARTIAL)&&("initSegment"===e.sn?this._loadInitSegment(e):r.live&&!Object(a.a)(this.initPTS[e.cc])?(this.log("Waiting for video PTS in continuity counter "+e.cc+" of live stream before loading audio fragment "+e.sn+" of level "+this.trackId),this.state=Vt):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)))},l.completeAudioSwitch=function(){var e=this.hls,r=this.media,i=this.trackId;r&&(this.log("Switching audio track : flushing all audio"),t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.audioSwitch=!1,e.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:i})},i}(Yt);function ce(t,e){for(var r=0;r=e.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var r=e[this.trackId];this.log("Now switching to audio-track index "+t);var i=e[t],a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,h=i.url;if(this.trackId=t,this.trackName=l,this.selectDefaultTrack=!1,this.hls.trigger(n.a.AUDIO_TRACK_SWITCHING,{id:a,groupId:o,name:l,type:u,url:h}),!i.details||i.details.live){var d=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(d)}}},u.selectInitialTrack=function(){this.tracksInGroup;var t=this.trackName,e=this.findTrackId(t)||this.findTrackId();-1!==e?this.setAudioTrack(e):(this.warn("No track found for running audio group-ID: "+this.groupId),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))},u.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=a[o].start&&s<=a[o].end){n=a[o];break}var l=r.start+r.duration;n?n.end=l:(n={start:s,end:l},a.push(n)),this.fragmentTracker.fragBuffered(r)}}},u.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var a=this.currentTrackId,n=this.levels;if(!n.length||!n[a]||!n[a].details)return;var s=i-n[a].details.targetduration;if(s<=0)return;e.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(t){for(var e=0;e=s.length||a!==n)&&o){if(this.mediaBuffer=this.mediaBufferTimeRanges,i.live||null!==(r=o.details)&&void 0!==r&&r.live){var l=this.mainDetails;if(i.deltaUpdateFailed||!l)return;var u=l.fragments[0];if(o.details)0===this.alignPlaylists(i,o.details)&&u&&z(i,u.start);else i.hasProgramDateTime&&l.hasProgramDateTime?gt(i,l):u&&z(i,u.start)}if(o.details=i,this.levelLastLoaded=a,this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===Pt)mt(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}},u._handleFragmentLoadComplete=function(t){var e=t.frag,r=t.payload,i=e.decryptdata,a=this.hls;if(!this.fragContextChanged(e)&&r&&r.byteLength>0&&i&&i.key&&i.iv&&"AES-128"===i.method){var s=performance.now();this.decrypter.webCryptoDecrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).then((function(t){var r=performance.now();a.trigger(n.a.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:s,tdecrypt:r}})}))}},u.doTick=function(){if(this.media){if(this.state===Pt){var t,e=this.currentTrackId,r=this.levels;if(!r.length||!r[e]||!r[e].details)return;var i=r[e].details,a=i.targetduration,s=this.config,l=this.media,u=lt.bufferedInfo(this.mediaBufferTimeRanges,l.currentTime-a,s.maxBufferHole),h=u.end;if(u.len>this.getMaxBufferLength()+a)return;var d,c=i.fragments,f=c.length,g=i.edge,v=this.fragPrevious;if(h-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},l.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)},l.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Ee(this.media.textTracks).forEach((function(t){x(t)})),this.subtitleTrack=-1,this.media=null)},l.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},l.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},l.onSubtitleTrackLoaded=function(t,e){var r=e.id,i=e.details,a=this.trackId,n=this.tracksInGroup[a];if(n){var s=n.details;n.details=e.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,e,s))}else this.warn("Invalid subtitle track id "+r)},l.onLevelLoading=function(t,e){this.switchLevel(e.level)},l.onLevelSwitching=function(t,e){this.switchLevel(e.level)},l.switchLevel=function(t){var e=this.hls.levels[t];if(null!=e&&e.textGroupIds){var r=e.textGroupIds[e.urlId];if(this.groupId!==r){var i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0,a=this.tracks.filter((function(t){return!r||t.groupId===r}));this.tracksInGroup=a;var s=this.findTrackId(null==i?void 0:i.name)||this.findTrackId();this.groupId=r;var o={subtitleTracks:a};this.log("Updating subtitle tracks, "+a.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(n.a.SUBTITLE_TRACKS_UPDATED,o),-1!==s&&this.setSubtitleTrack(s,i)}}},l.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=i.length)){this.clearTimer();var a=i[t];if(this.log("Switching to subtitle track "+t),this.trackId=t,a){var s=a.id,o=a.groupId,l=void 0===o?"":o,u=a.name,h=a.type,d=a.url;this.hls.trigger(n.a.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:h,url:d});var c=this.switchParams(a.url,null==e?void 0:e.details);this.loadPlaylist(c)}else this.hls.trigger(n.a.SUBTITLE_TRACK_SWITCH,{id:t})}}else this.queuedDefaultTrack=t},l.onTextTracksChanged=function(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var t=-1,e=Ee(this.media.textTracks),r=0;r0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.a.BUFFER_RESET,this.onBufferReset,this),t.on(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.a.BUFFER_EOS,this.onBufferEos,this),t.on(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.a.FRAG_PARSED,this.onFragParsed,this),t.on(n.a.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.a.BUFFER_RESET,this.onBufferReset,this),t.off(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.a.BUFFER_EOS,this.onBufferEos,this),t.off(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.a.FRAG_PARSED,this.onFragParsed,this),t.off(n.a.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new Le(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,o.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&Ae){var i=this.mediaSource=new Ae;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(o.b.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){o.b.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):o.b.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.a.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){o.b.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var a=r.tracks[t];if(a&&"function"==typeof a.buffer.changeType){var n=e[t],s=n.codec,o=n.levelCodec,l=n.container;if((a.levelCodec||a.codec).replace(Re,"$1")!==(o||s).replace(Re,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(t,u)}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,a={execute:function(){var a=r.sourceBuffer[t];a&&(o.b.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),a.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){o.b.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(a,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,a=this.operationQueue,l=this.tracks,u=e.data,h=e.type,d=e.frag,c=e.part,f=e.chunkMeta,g=f.buffering[h],v=self.performance.now();g.start=v;var p=d.stats.buffering,m=c?c.stats.buffering:null;0===p.start&&(p.start=v),m&&0===m.start&&(m.start=v);var y=l.audio,T="audio"===h&&1===f.id&&"audio/mpeg"===(null==y?void 0:y.container),E={execute:function(){if(g.executeStart=self.performance.now(),T){var t=r.sourceBuffer[h];if(t){var e=d.start-t.timestampOffset;Math.abs(e)>=.1&&(o.b.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+d.start+" (delta: "+e+") sn: "+d.sn+")"),t.timestampOffset=d.start)}}r.appendExecutor(u,h)},onStart:function(){},onComplete:function(){var t=self.performance.now();g.executeEnd=g.end=t,0===p.first&&(p.first=t),m&&0===m.first&&(m.first=t);var e=r.sourceBuffer,i={};for(var a in e)i[a]=lt.getBuffered(e[a]);r.appendError=0,r.hls.trigger(n.a.BUFFER_APPENDED,{type:h,frag:d,part:c,chunkMeta:f,parent:d.type,timeRanges:i})},onError:function(t){o.b.error("[buffer-controller]: Error encountered while trying to append to the "+h+" SourceBuffer",t);var e={type:s.b.MEDIA_ERROR,parent:d.type,details:s.a.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=s.a.BUFFER_FULL_ERROR:(r.appendError++,e.details=s.a.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(o.b.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(n.a.ERROR,e)}};a.append(E,h)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,a=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(n.a.BUFFER_FLUSHED,{type:t})},onError:function(e){o.b.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(a(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(a(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,a=e.part,s=[],l=a?a.elementaryStreams:i.elementaryStreams;l[u.a.AUDIOVIDEO]?s.push("audiovideo"):(l[u.a.AUDIO]&&s.push("audio"),l[u.a.VIDEO]&&s.push("video"));0===s.length&&o.b.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,a&&(a.stats.buffering.end=t);var e=a?a.stats:i.stats;r.hls.trigger(n.a.FRAG_BUFFERED,{frag:i,part:a,stats:e,id:i.type})}),s)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var a=r.sourceBuffer[i];return e.type&&e.type!==i||a&&!a.ended&&(a.ended=!0,o.b.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(a&&!a.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var s=this.getSourceBufferTypes();if(s.length){var o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(Object(a.a)(o)&&!(o<0)){var l=r.currentTime,u=e.levelTargetDuration,h=Math.max(o,u),d=Math.floor(l/u)*u-h;s.forEach((function(r){var a=i[r];if(a){var s=lt.getBuffered(a);s.length>0&&d>s.start(0)&&(t.trigger(n.a.BACK_BUFFER_REACHED,{bufferEnd:d}),e.live&&t.trigger(n.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d}),t.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,s=r.duration,l=Object(a.a)(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(o.b.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(n>l&&n>s||!Object(a.a)(s))&&(o.b.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),a=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,a)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var a=this.getSourceBufferTypes();if(0===a.length)return void this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});a.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var a in t)if(!e[a]){var l=t[a];if(!l)throw Error("source buffer exists for track "+a+", however track does not");var u=l.levelCodec||l.codec,h=l.container+";codecs="+u;o.b.log("[buffer-controller]: creating sourceBuffer("+h+")");try{var d=e[a]=r.addSourceBuffer(h),c=a;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[a]={buffer:d,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(t){o.b.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:h})}}i&&this.hls.trigger(n.a.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){o.b.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,l=this.sourceBuffer[t];if(!i||!n||!l)return o.b.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(t);var u=Object(a.a)(i.duration)?i.duration:1/0,h=Object(a.a)(n.duration)?n.duration:1/0,d=Math.max(0,e),c=Math.min(r,u,h);c>d?(o.b.log("[buffer-controller]: Removing ["+d+","+c+"] from the "+t+" SourceBuffer"),l.remove(d,c)):s.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return o.b.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return o.b.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(t);var i=this.operationQueue,a=e.map((function(t){return i.appendBlocker(t)}));Promise.all(a).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var a=r.bind(this,t);this.listeners[t].push({event:e,listener:a}),i.addEventListener(e,a)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}(),ke={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},_e=function(t){var e=t;return ke.hasOwnProperty(t)&&(e=ke[t]),String.fromCharCode(e)},Ie={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ce={17:2,18:4,21:6,22:8,23:10,19:13,20:15},we={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Oe={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xe=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];!function(t){t[t.ERROR=0]="ERROR",t[t.TEXT=1]="TEXT",t[t.WARNING=2]="WARNING",t[t.INFO=2]="INFO",t[t.DEBUG=3]="DEBUG",t[t.DATA=3]="DATA"}(be||(be={}));var Pe=function(){function t(){this.time=null,this.verboseLevel=be.ERROR}return t.prototype.log=function(t,e){this.verboseLevel>=t&&o.b.log(this.time+" ["+t+"] "+e)},t}(),Fe=function(t){for(var e=[],r=0;r100&&(this.logger.log(be.DEBUG,"Too large cursor position "+this.pos),this.pos=100)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r=144&&this.backSpace();var e=_e(t);this.pos>=100?this.logger.log(be.ERROR,"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e<100;e++)this.chars[e].reset()},e.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.getTextString=function(){for(var t=[],e=!0,r=0;r<100;r++){var i=this.chars[r].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")},e.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),Be=function(){function t(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var e=0;e<15;e++)this.rows.push(new Ue(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}var e=t.prototype;return e.reset=function(){for(var t=0;t<15;t++)this.rows[t].clear();this.currRow=14},e.equals=function(t){for(var e=!0,r=0;r<15;r++)if(!this.rows[r].equals(t.rows[r])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<15;e++)this.rows[e].copy(t.rows[e])},e.isEmpty=function(){for(var t=!0,e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},e.backSpace=function(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function(t){this.rows[this.currRow].insertChar(t)},e.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},e.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},e.setCursor=function(t){this.logger.log(be.INFO,"setCursor: "+t),this.rows[this.currRow].setCursor(t)},e.setPAC=function(t){this.logger.log(be.INFO,"pacData = "+JSON.stringify(t));var e=t.row-1;if(this.nrRollUpRows&&e0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},e.getTextAndFormat=function(){return this.rows},t}(),Ge=function(){function t(t,e,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Be(r),this.nonDisplayedMemory=new Be(r),this.lastOutputScreen=new Be(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(be.INFO,"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)},e.insertChars=function(t){for(var e=0;e=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(be.INFO,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}();function Ke(t,e,r){r.a=t,r.b=e}function je(t,e,r){return r.a===t&&r.b===e}var He=function(){function t(t,e,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new Pe;this.channels=[null,new Ge(t,e,i),new Ge(t+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var r,i,a,n=!1;this.logger.time=t;for(var s=0;s ("+Fe([i,a])+")"),(r=this.parseCmd(i,a))||(r=this.parseMidrow(i,a)),r||(r=this.parsePAC(i,a)),r||(r=this.parseBackgroundAttributes(i,a)),!r&&(n=this.parseChars(i,a))){var o=this.currentChannel;if(o&&o>0)this.channels[o].insertChars(n);else this.logger.log(be.WARNING,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(be.WARNING,"Couldn't parse cleaned data "+Fe([i,a])+" orig: "+Fe([e[s],e[s+1]]))}},e.parseCmd=function(t,e){var r=this.cmdHistory;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(je(t,e,r))return Ke(null,null,r),this.logger.log(be.DEBUG,"Repeated command ("+Fe([t,e])+") is dropped"),!0;var i=20===t||21===t||23===t?1:2,a=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?a.ccRCL():33===e?a.ccBS():34===e?a.ccAOF():35===e?a.ccAON():36===e?a.ccDER():37===e?a.ccRU(2):38===e?a.ccRU(3):39===e?a.ccRU(4):40===e?a.ccFON():41===e?a.ccRDC():42===e?a.ccTR():43===e?a.ccRTD():44===e?a.ccEDM():45===e?a.ccCR():46===e?a.ccENM():47===e&&a.ccEOC():a.ccTO(e-32),Ke(t,e,r),this.currentChannel=i,!0},e.parseMidrow=function(t,e){var r=0;if((17===t||25===t)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currentChannel)return this.logger.log(be.ERROR,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(e),this.logger.log(be.DEBUG,"MIDROW ("+Fe([t,e])+")"),!0)}return!1},e.parsePAC=function(t,e){var r,i=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(je(t,e,i))return Ke(null,null,i),!0;var a=t<=23?1:2;r=e>=64&&e<=95?1===a?Ie[t]:we[t]:1===a?Ce[t]:Oe[t];var n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(r,e)),Ke(t,e,i),this.currentChannel=a,!0)},e.interpretPAC=function(t,e){var r,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.parseChars=function(t,e){var r,i,a=null,n=null;(t>=25?(r=2,n=t-8):(r=1,n=t),n>=17&&n<=19)?(i=17===n?e+80:18===n?e+112:e+144,this.logger.log(be.INFO,"Special char '"+_e(i)+"' in channel "+r),a=[i]):t>=32&&t<=127&&(a=0===e?[t]:[t,e]);if(a){var s=Fe(a);this.logger.log(be.DEBUG,"Char codes = "+s.join(",")),Ke(t,e,this.cmdHistory)}return a},e.parseBackgroundAttributes=function(t,e){var r;if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;var i={};16===t||24===t?(r=Math.floor((e-32)/2),i.background=xe[r],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));var a=t<=23?1:2;return this.channels[a].setBkgData(i),Ke(t,e,this.cmdHistory),!0},e.reset=function(){for(var t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[]},t}(),We=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function r(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var r=e.toLowerCase();return!!~t.indexOf(r)&&r}function i(t){return r(e,t)}function a(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",a({},l,{get:function(){return E},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",a({},l,{get:function(){return b},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",a({},l,{get:function(){return S},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),Ye=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function qe(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}var Xe=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,r){for(var i=0;i=0&&r<=100)return this.set(t,r),!0}return!1},t}();function ze(t,e,r,i){var a=i?t.split(i):[t];for(var n in a)if("string"==typeof a[n]){var s=a[n].split(r);if(2===s.length)e(s[0],s[1])}}var Qe=new We(0,0,""),$e="middle"===Qe.align?"middle":"center";function Je(t,e,r){var i=t;function a(){var e=qe(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=a(),n(),"--\x3e"!==t.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.substr(3),n(),e.endTime=a(),n(),function(t,e){var i=new Xe;ze(t,(function(t,e){var a;switch(t){case"region":for(var n=r.length-1;n>=0;n--)if(r[n].id===e){i.set(t,r[n].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":a=e.split(","),i.integer(t,a[0]),i.percent(t,a[0])&&i.set("snapToLines",!1),i.alt(t,a[0],["auto"]),2===a.length&&i.alt("lineAlign",a[1],["start",$e,"end"]);break;case"position":a=e.split(","),i.percent(t,a[0]),2===a.length&&i.alt("positionAlign",a[1],["start",$e,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",$e,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&-1===Qe.line&&(a=-1),e.line=a,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",$e);var n=i.get("position","auto");"auto"===n&&50===Qe.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Ze(t){return t.replace(//gi,"\n")}var tr=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new Ye,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function r(){var t=e.buffer,r=0;for(t=Ze(t);r>>0).toString()};function sr(t,e,r){return nr(t.toString())+nr(e.toString())+nr(r)}function or(t,e,r,i,n,s,o,l){var u,h=new tr,d=Object(F.f)(new Uint8Array(t)).trim().replace(ir,"\n").split("\n"),c=[],f=Object(er.a)(e,r),g="00:00.000",v=0,p=0,m=!0,y=!1;h.oncue=function(t){var e=i[n],r=i.ccOffset,a=(v-f)/9e4;if(null!=e&&e.new&&(void 0!==p?r=i.ccOffset=e.start:function(t,e,r){var i=t[e],a=t[i.prevCC];if(!a||!a.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!==(n=a)&&void 0!==n&&n.new;){var n;t.ccOffset+=i.start-a.start,i.new=!1,a=t[(i=a).prevCC]}t.presentationOffset=r}(i,n,a)),a&&(r=a-i.presentationOffset),y){var o=t.endTime-t.startTime,l=Object(rr.b)(9e4*(t.startTime+r-p),9e4*s)/9e4;t.startTime=l,t.endTime=l+o}var u=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(u)),t.id||(t.id=sr(t.startTime,t.endTime,u)),t.endTime>0&&c.push(t)},h.onparsingerror=function(t){u=t},h.onflush=function(){u?l(u):o(c)},d.forEach((function(t){if(m){if(ar(t,"X-TIMESTAMP-MAP=")){m=!1,y=!0,t.substr(16).split(",").forEach((function(t){ar(t,"LOCAL:")?g=t.substr(6):ar(t,"MPEGTS:")&&(v=parseInt(t.substr(7)))}));try{p=function(t){var e=parseInt(t.substr(-3)),r=parseInt(t.substr(-6,2)),i=parseInt(t.substr(-9,2)),n=t.length>9?parseInt(t.substr(0,t.indexOf(":"))):0;if(!(Object(a.a)(e)&&Object(a.a)(r)&&Object(a.a)(i)&&Object(a.a)(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*r,e+=6e4*i,e+=36e5*n}(g)/1e3}catch(t){y=!1,u=t}return}""===t&&(m=!1)}h.parse(t+"\n")})),h.flush()}function lr(){return(lr=Object.assign||function(t){for(var e=1;e=0&&(c[0]=Math.min(c[0],e),c[1]=Math.max(c[1],r),h=!0,f/(r-e)>.5))return}if(h||a.push([e,r]),this.config.renderTextTracksNatively){var g=this.captionsTracks[t];this.Cues.newCue(g,e,r,i)}else{var v=this.Cues.newCue(null,e,r,i);this.hls.trigger(n.a.CUES_PARSED,{type:"captions",cues:v,track:t})}},e.onInitPtsFound=function(t,e){var r=this,i=e.frag,a=e.id,s=e.initPTS,o=e.timescale,l=this.unparsedVttFrags;"main"===a&&(this.initPTS[i.cc]=s,this.timescale[i.cc]=o),l.length&&(this.unparsedVttFrags=[],l.forEach((function(t){r.onFragLoaded(n.a.FRAG_LOADED,t)})))},e.getExistingTrack=function(t){var e=this.media;if(e)for(var r=0;r0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},a.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var a=i.filter((function(i,a){return t.isLevelAllowed(a,r.restrictedLevels)&&a<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(a,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,a,n=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(a=t[s+1])||i.width!==a.width||i.height!==a.height)){n=s;break}}return n},e=t,i=[{key:"contentScaleFactor",get:function(){var t=1;try{t=self.devicePixelRatio}catch(t){}return t}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*t.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*t.contentScaleFactor}}])&&Er(e.prototype,r),i&&Er(e,i),t}(),Lr=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var a=i-this.lastTime,s=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,u=1e3*s/a,h=this.hls;if(h.trigger(n.a.FPS_DROP,{currentDropped:s,currentDecoded:l,totalDroppedFrames:r}),u>0&&s>h.config.fpsDroppedMonitoringThreshold*l){var d=h.currentLevel;o.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=d)&&(d-=1,h.trigger(n.a.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:h.currentLevel}),h.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}();!function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(br||(br={}));var Ar="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Rr(t,e){for(var r=0;r3)return void this.hls.trigger(n.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var u=3-this._requestLicenseFailureCount+1;o.b.warn("Retrying license request, "+u+" attempts left"),this._requestLicense(r,i)}}},a._generateLicenseRequestChallenge=function(t,e){switch(t.mediaKeySystemDomain){case br.WIDEVINE:return e}throw new Error("unsupported key-system: "+t.mediaKeySystemDomain)},a._requestLicense=function(t,e){o.b.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return o.b.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(n.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var i=this.getLicenseServerUrl(r.mediaKeySystemDomain),a=this._createLicenseXhr(i,t,e);o.b.log("Sending license request to URL: "+i);var l=this._generateLicenseRequestChallenge(r,t);a.send(l)}catch(t){o.b.error("Failure requesting DRM license: "+t),this.hls.trigger(n.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},a.onMediaAttached=function(t,e){if(this._emeEnabled){var r=e.media;this._media=r,r.addEventListener("encrypted",this._onMediaEncrypted)}},a.onMediaDetached=function(){var t=this._media,e=this._mediaKeysList;t&&(t.removeEventListener("encrypted",this._onMediaEncrypted),this._media=null,this._mediaKeysList=[],Promise.all(e.map((function(t){if(t.mediaKeysSession)return t.mediaKeysSession.close().catch((function(){}))}))).then((function(){return t.setMediaKeys(null)})).catch((function(){})))},a.onManifestParsed=function(t,e){if(this._emeEnabled){var r=e.levels.map((function(t){return t.audioCodec})).filter((function(t){return!!t})),i=e.levels.map((function(t){return t.videoCodec})).filter((function(t){return!!t}));this._attemptKeySystemAccess(br.WIDEVINE,r,i)}},e=t,(r=[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}])&&Rr(e.prototype,r),i&&Rr(e,i),t}(),kr=r(12),_r=/^age:\s*[\d.]+\s*$/m,Ir=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t?t.xhrSetup:null,this.stats=new kr.a,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.retryDelay=e.retryDelay,this.loadInternal()},e.loadInternal=function(){var t=this.config,e=this.context;if(t){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var a=this.xhrSetup;try{if(a)try{a(r,e.url)}catch(t){r.open("GET",e.url,!0),a(r,e.url)}r.readyState||r.open("GET",e.url,!0)}catch(t){return void this.callbacks.onError({code:r.status,text:t.message},e,r)}e.rangeEnd&&r.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=e.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),t.timeout),r.send()}},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var i=e.readyState,a=this.config;if(!r.aborted&&i>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){e.onreadystatechange=null,e.onprogress=null;var n=e.status;if(n>=200&&n<300){var s,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===t.responseType?(s=e.response).byteLength:(s=e.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,s,e),!this.callbacks)return;var h={url:e.responseURL,data:s};this.callbacks.onSuccess(h,r,t,e)}else r.retry>=a.maxRetry||n>=400&&n<499?(o.b.error(n+" while loading "+t.url),this.callbacks.onError({code:n,text:e.statusText},t,e)):(o.b.warn(n+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout)}},e.loadtimeout=function(){o.b.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&_r.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}();function Cr(t){var e="function"==typeof Map?new Map:void 0;return(Cr=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return wr(t,arguments,Pr(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),xr(i,t)})(t)}function wr(t,e,r){return(wr=Or()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&xr(a,r.prototype),a}).apply(null,arguments)}function Or(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function xr(t,e){return(xr=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Pr(t){return(Pr=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var Fr=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Mr,this.controller=new self.AbortController,this.stats=new kr.a}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=null,this.abortInternal()},e.abortInternal=function(){var t=this.response;t&&t.ok||(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(t,e){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:e};t.rangeEnd&&(r.headers=new self.Headers({Range:"bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)}));return r}(t,this.controller.signal),o=r.onProgress,l="arraybuffer"===t.responseType,u=l?"byteLength":"length";this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),e.timeout),self.fetch(this.request).then((function(r){if(i.response=i.loader=r,!r.ok){var s=r.status,u=r.statusText;throw new Nr(u||"fetch, bad network response",s,r)}return n.loading.first=Math.max(self.performance.now(),n.loading.start),n.total=parseInt(r.headers.get("Content-Length")||"0"),o&&Object(a.a)(e.highWaterMark)?i.loadProgressively(r,n,t,e.highWaterMark,o):l?r.arrayBuffer():r.text()})).then((function(s){var l=i.response;self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first),n.loaded=n.total=s[u];var h={url:l.url,data:s};o&&!Object(a.a)(e.highWaterMark)&&o(n,t,s,l),r.onSuccess(h,n,t,l)})).catch((function(e){if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=e.code||0;r.onError({code:a,text:e.message},t,e.details)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.loadProgressively=function(t,e,r,i,a){void 0===i&&(i=0);var n=new le.a,s=t.body.getReader();return function o(){return s.read().then((function(s){if(s.done)return n.dataLength&&a(e,r,n.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return e.loaded+=u,u=i&&a(e,r,n.flush(),t)):a(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function Mr(t,e){return new self.Request(t.url,e)}var Nr=function(t){var e,r;function i(e,r,i){var a;return(a=t.call(this,e)||this).code=void 0,a.details=void 0,a.code=r,a.details=i,a}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,xr(e,r),i}(Cr(Error)),Ur=Fr,Br=/\s/;function Gr(){return(Gr=Object.assign||function(t){for(var e=1;e=16?o--:o++;var f=Ze(l.trim()),g=sr(e,r,f);t&&t.cues&&t.cues.getCueById(g)||((n=new h(e,r,f)).id=g,n.line=d+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(n))}return t&&u.length&&(u.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),u.forEach((function(e){return O(t,e)}))),u}},enableCEA708Captions:!0,enableWebVTT:!0,enableIMSC1:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:me,subtitleTrackController:Se,timelineController:yr,audioStreamController:de,audioTrackController:ge,emeController:Dr});function Wr(t){var e=t.loader;e!==Ur&&e!==Ir?(o.b.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=Ur,t.progressive=!0,t.enableSoftwareAES=!0,o.b.log("[config]: Progressive streaming enabled, using FetchLoader"))}function Yr(t,e){for(var r=0;re)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&Yr(e.prototype,r),a&&Yr(e,a),t}();qr.defaultConfig=void 0}]).default})); -//# sourceMappingURL=hls.min.js.map \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/jquery.min.js b/node_modules/paellaplayer/build/player/javascript/jquery.min.js deleted file mode 100644 index b0614034a..000000000 --- a/node_modules/paellaplayer/build/player/javascript/jquery.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 00){var u=T.utils.clone(t)||{};u.position=[o,a],u.index=n.length,n.push(new T.Token(r.slice(o,s),u))}o=s+1}}return n},T.tokenizer.separator=/[\s\-]+/ -/*! - * lunr.Pipeline - * Copyright (C) 2020 Oliver Nightingale - */,T.Pipeline=function(){this._stack=[]},T.Pipeline.registeredFunctions=Object.create(null),T.Pipeline.registerFunction=function(e,t){t in this.registeredFunctions&&T.utils.warn("Overwriting existing registered function: "+t),e.label=t,T.Pipeline.registeredFunctions[e.label]=e},T.Pipeline.warnIfFunctionNotRegistered=function(e){e.label&&e.label in this.registeredFunctions||T.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",e)},T.Pipeline.load=function(e){var t=new T.Pipeline;return e.forEach((function(e){var r=T.Pipeline.registeredFunctions[e];if(!r)throw new Error("Cannot load unregistered function: "+e);t.add(r)})),t},T.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach((function(e){T.Pipeline.warnIfFunctionNotRegistered(e),this._stack.push(e)}),this)},T.Pipeline.prototype.after=function(e,t){T.Pipeline.warnIfFunctionNotRegistered(t);var r=this._stack.indexOf(e);if(-1==r)throw new Error("Cannot find existingFn");r+=1,this._stack.splice(r,0,t)},T.Pipeline.prototype.before=function(e,t){T.Pipeline.warnIfFunctionNotRegistered(t);var r=this._stack.indexOf(e);if(-1==r)throw new Error("Cannot find existingFn");this._stack.splice(r,0,t)},T.Pipeline.prototype.remove=function(e){var t=this._stack.indexOf(e);-1!=t&&this._stack.splice(t,1)},T.Pipeline.prototype.run=function(e){for(var t=this._stack.length,r=0;r1&&(se&&(r=n),s!=e);)i=r-t,n=t+Math.floor(i/2),s=this.elements[2*n];return s==e?2*n:s>e?2*n:sa?l+=2:o==a&&(t+=r[u+1]*i[l+1],u+=2,l+=2);return t},T.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},T.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),t=1,r=0;t0){var s,o=n.str.charAt(0);o in n.node.edges?s=n.node.edges[o]:(s=new T.TokenSet,n.node.edges[o]=s),1==n.str.length&&(s.final=!0),i.push({node:s,editsRemaining:n.editsRemaining,str:n.str.slice(1)})}if(0!=n.editsRemaining){if("*"in n.node.edges)var a=n.node.edges["*"];else{a=new T.TokenSet;n.node.edges["*"]=a}if(0==n.str.length&&(a.final=!0),i.push({node:a,editsRemaining:n.editsRemaining-1,str:n.str}),n.str.length>1&&i.push({node:n.node,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)}),1==n.str.length&&(n.node.final=!0),n.str.length>=1){if("*"in n.node.edges)var u=n.node.edges["*"];else{u=new T.TokenSet;n.node.edges["*"]=u}1==n.str.length&&(u.final=!0),i.push({node:u,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)})}if(n.str.length>1){var l,c=n.str.charAt(0),h=n.str.charAt(1);h in n.node.edges?l=n.node.edges[h]:(l=new T.TokenSet,n.node.edges[h]=l),1==n.str.length&&(l.final=!0),i.push({node:l,editsRemaining:n.editsRemaining-1,str:c+n.str.slice(2)})}}}return r},T.TokenSet.fromString=function(e){for(var t=new T.TokenSet,r=t,i=0,n=e.length;i=e;t--){var r=this.uncheckedNodes[t],i=r.child.toString();i in this.minimizedNodes?r.parent.edges[r.char]=this.minimizedNodes[i]:(r.child._str=i,this.minimizedNodes[i]=r.child),this.uncheckedNodes.pop()}} -/*! - * lunr.Index - * Copyright (C) 2020 Oliver Nightingale - */,T.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},T.Index.prototype.search=function(e){return this.query((function(t){new T.QueryParser(e,t).parse()}))},T.Index.prototype.query=function(e){for(var t=new T.Query(this.fields),r=Object.create(null),i=Object.create(null),n=Object.create(null),s=Object.create(null),o=Object.create(null),a=0;a1?1:e},T.Builder.prototype.k1=function(e){this._k1=e},T.Builder.prototype.add=function(e,t){var r=e[this._ref],i=Object.keys(this._fields);this._documents[r]=t||{},this.documentCount+=1;for(var n=0;n=this.length)return T.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},T.QueryLexer.prototype.width=function(){return this.pos-this.start},T.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},T.QueryLexer.prototype.backup=function(){this.pos-=1},T.QueryLexer.prototype.acceptDigitRun=function(){var e,t;do{t=(e=this.next()).charCodeAt(0)}while(t>47&&t<58);e!=T.QueryLexer.EOS&&this.backup()},T.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(T.QueryLexer.TERM)),e.ignore(),e.more())return T.QueryLexer.lexText},T.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(T.QueryLexer.EDIT_DISTANCE),T.QueryLexer.lexText},T.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(T.QueryLexer.BOOST),T.QueryLexer.lexText},T.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(T.QueryLexer.TERM)},T.QueryLexer.termSeparator=T.tokenizer.separator,T.QueryLexer.lexText=function(e){for(;;){var t=e.next();if(t==T.QueryLexer.EOS)return T.QueryLexer.lexEOS;if(92!=t.charCodeAt(0)){if(":"==t)return T.QueryLexer.lexField;if("~"==t)return e.backup(),e.width()>0&&e.emit(T.QueryLexer.TERM),T.QueryLexer.lexEditDistance;if("^"==t)return e.backup(),e.width()>0&&e.emit(T.QueryLexer.TERM),T.QueryLexer.lexBoost;if("+"==t&&1===e.width())return e.emit(T.QueryLexer.PRESENCE),T.QueryLexer.lexText;if("-"==t&&1===e.width())return e.emit(T.QueryLexer.PRESENCE),T.QueryLexer.lexText;if(t.match(T.QueryLexer.termSeparator))return T.QueryLexer.lexTerm}else e.escapeCharacter()}},T.QueryParser=function(e,t){this.lexer=new T.QueryLexer(e),this.query=t,this.currentClause={},this.lexemeIdx=0},T.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=T.QueryParser.parseClause;e;)e=e(this);return this.query},T.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},T.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},T.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},T.QueryParser.parseClause=function(e){var t=e.peekLexeme();if(null!=t)switch(t.type){case T.QueryLexer.PRESENCE:return T.QueryParser.parsePresence;case T.QueryLexer.FIELD:return T.QueryParser.parseField;case T.QueryLexer.TERM:return T.QueryParser.parseTerm;default:var r="expected either a field or a term, found "+t.type;throw t.str.length>=1&&(r+=" with value '"+t.str+"'"),new T.QueryParseError(r,t.start,t.end)}},T.QueryParser.parsePresence=function(e){var t=e.consumeLexeme();if(null!=t){switch(t.str){case"-":e.currentClause.presence=T.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=T.Query.presence.REQUIRED;break;default:var r="unrecognised presence operator'"+t.str+"'";throw new T.QueryParseError(r,t.start,t.end)}var i=e.peekLexeme();if(null==i){r="expecting term or field, found nothing";throw new T.QueryParseError(r,t.start,t.end)}switch(i.type){case T.QueryLexer.FIELD:return T.QueryParser.parseField;case T.QueryLexer.TERM:return T.QueryParser.parseTerm;default:r="expecting term or field, found '"+i.type+"'";throw new T.QueryParseError(r,i.start,i.end)}}},T.QueryParser.parseField=function(e){var t=e.consumeLexeme();if(null!=t){if(-1==e.query.allFields.indexOf(t.str)){var r=e.query.allFields.map((function(e){return"'"+e+"'"})).join(", "),i="unrecognised field '"+t.str+"', possible fields: "+r;throw new T.QueryParseError(i,t.start,t.end)}e.currentClause.fields=[t.str];var n=e.peekLexeme();if(null==n){i="expecting term, found nothing";throw new T.QueryParseError(i,t.start,t.end)}switch(n.type){case T.QueryLexer.TERM:return T.QueryParser.parseTerm;default:i="expecting term, found '"+n.type+"'";throw new T.QueryParseError(i,n.start,n.end)}}},T.QueryParser.parseTerm=function(e){var t=e.consumeLexeme();if(null!=t){e.currentClause.term=t.str.toLowerCase(),-1!=t.str.indexOf("*")&&(e.currentClause.usePipeline=!1);var r=e.peekLexeme();if(null!=r)switch(r.type){case T.QueryLexer.TERM:return e.nextClause(),T.QueryParser.parseTerm;case T.QueryLexer.FIELD:return e.nextClause(),T.QueryParser.parseField;case T.QueryLexer.EDIT_DISTANCE:return T.QueryParser.parseEditDistance;case T.QueryLexer.BOOST:return T.QueryParser.parseBoost;case T.QueryLexer.PRESENCE:return e.nextClause(),T.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+r.type+"'";throw new T.QueryParseError(i,r.start,r.end)}else e.nextClause()}},T.QueryParser.parseEditDistance=function(e){var t=e.consumeLexeme();if(null!=t){var r=parseInt(t.str,10);if(isNaN(r)){var i="edit distance must be numeric";throw new T.QueryParseError(i,t.start,t.end)}e.currentClause.editDistance=r;var n=e.peekLexeme();if(null!=n)switch(n.type){case T.QueryLexer.TERM:return e.nextClause(),T.QueryParser.parseTerm;case T.QueryLexer.FIELD:return e.nextClause(),T.QueryParser.parseField;case T.QueryLexer.EDIT_DISTANCE:return T.QueryParser.parseEditDistance;case T.QueryLexer.BOOST:return T.QueryParser.parseBoost;case T.QueryLexer.PRESENCE:return e.nextClause(),T.QueryParser.parsePresence;default:i="Unexpected lexeme type '"+n.type+"'";throw new T.QueryParseError(i,n.start,n.end)}else e.nextClause()}},T.QueryParser.parseBoost=function(e){var t=e.consumeLexeme();if(null!=t){var r=parseInt(t.str,10);if(isNaN(r)){var i="boost must be numeric";throw new T.QueryParseError(i,t.start,t.end)}e.currentClause.boost=r;var n=e.peekLexeme();if(null!=n)switch(n.type){case T.QueryLexer.TERM:return e.nextClause(),T.QueryParser.parseTerm;case T.QueryLexer.FIELD:return e.nextClause(),T.QueryParser.parseField;case T.QueryLexer.EDIT_DISTANCE:return T.QueryParser.parseEditDistance;case T.QueryLexer.BOOST:return T.QueryParser.parseBoost;case T.QueryLexer.PRESENCE:return e.nextClause(),T.QueryParser.parsePresence;default:i="Unexpected lexeme type '"+n.type+"'";throw new T.QueryParseError(i,n.start,n.end)}else e.nextClause()}},b=this,P=function(){return T},"function"==typeof define&&define.amd?define(P):"object"==typeof exports?module.exports=P():b.lunr=P()}(); \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/paella_player.js b/node_modules/paellaplayer/build/player/javascript/paella_player.js deleted file mode 100644 index 85f3d8388..000000000 --- a/node_modules/paellaplayer/build/player/javascript/paella_player.js +++ /dev/null @@ -1,24700 +0,0 @@ -"use strict"; - -var _this5 = void 0; - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } - -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } - -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ -var GlobalParams = { - video: { - zIndex: 1 - }, - background: { - zIndex: 0 - } -}; -window.paella = window.paella || {}; -paella.player = null; -paella.version = "6.5.5 - build: 43c930ea"; - -(function buildBaseUrl() { - if (window.paella_debug_baseUrl) { - paella.baseUrl = window.paella_debug_baseUrl; - } else { - paella.baseUrl = location.href.replace(/[^/]*$/, ''); - } -})(); - -paella.events = { - play: "paella:play", - pause: "paella:pause", - next: "paella:next", - previous: "paella:previous", - seeking: "paella:seeking", - seeked: "paella:seeked", - timeupdate: "paella:timeupdate", - timeUpdate: "paella:timeupdate", - seekTo: "paella:setseek", - endVideo: "paella:endvideo", - // Triggered when a single video stream ends (once per video) - ended: "paella:ended", - // Triggered when the video ends - seekToTime: "paella:seektotime", - setTrim: "paella:settrim", - setPlaybackRate: "paella:setplaybackrate", - setVolume: 'paella:setVolume', - setComposition: 'paella:setComposition', - loadStarted: 'paella:loadStarted', - loadComplete: 'paella:loadComplete', - loadPlugins: 'paella:loadPlugins', - error: 'paella:error', - documentChanged: 'paella:documentChanged', - didSaveChanges: 'paella:didsavechanges', - controlBarWillHide: 'paella:controlbarwillhide', - controlBarDidHide: 'paella:controlbardidhide', - controlBarDidShow: 'paella:controlbardidshow', - hidePopUp: 'paella:hidePopUp', - showPopUp: 'paella:showPopUp', - enterFullscreen: 'paella:enterFullscreen', - exitFullscreen: 'paella:exitFullscreen', - resize: 'paella:resize', - // params: { width:paellaPlayerContainer width, height:paellaPlayerContainer height } - videoZoomChanged: 'paella:videoZoomChanged', - audioTagChanged: 'paella:audiotagchanged', - zoomAvailabilityChanged: 'paella:zoomavailabilitychanged', - qualityChanged: 'paella:qualityChanged', - singleVideoReady: 'paella:singleVideoReady', - singleVideoUnloaded: 'paella:singleVideoUnloaded', - videoReady: 'paella:videoReady', - videoUnloaded: 'paella:videoUnloaded', - controlBarLoaded: 'paella:controlBarLoaded', - captionAdded: 'paella:caption:add', - // Event triggered when new caption is available. - captionsEnabled: 'paella:caption:enabled', - // Event triguered when a caption es enabled. - captionsDisabled: 'paella:caption:disabled', - // Event triguered when a caption es disabled. - profileListChanged: 'paella:profilelistchanged', - setProfile: 'paella:setprofile', - seekAvailabilityChanged: 'paella:seekAvailabilityChanged', - trigger: function trigger(event, params) { - $(document).trigger(event, params); - }, - bind: function bind(event, callback) { - $(document).bind(event, function (event, params) { - callback(event, params); - }); - }, - setupExternalListener: function setupExternalListener() { - window.addEventListener("message", function (event) { - if (event.data && event.data.event) { - paella.events.trigger(event.data.event, event.data.params); - } - }, false); - } -}; -paella.events.setupExternalListener(); - -(function () { - paella.utils = paella.utils || {}; // This class requires jquery - - paella.utils.ajax = { - // onSuccess/onFail(data,type,returnCode,rawData) - send: function send(type, params, onSuccess, onFail) { - this.assertParams(params); - var ajaxObj = jQuery.ajax({ - url: params.url, - data: params.params, - type: type - }); - - if (typeof onSuccess == 'function') { - ajaxObj.done(function (data, textStatus, jqXHR) { - var contentType = jqXHR.getResponseHeader('content-type'); - onSuccess(data, contentType, jqXHR.status, jqXHR.responseText); - }); - } - - if (typeof onFail == 'function') { - ajaxObj.fail(function (jqXHR, textStatus, error) { - onFail(textStatus + ' : ' + error, 'text/plain', jqXHR.status, jqXHR.responseText); - }); - } - }, - assertParams: function assertParams(params) { - if (!params.url) throw new Error("paella.utils.ajax.send: url parameter not found"); - if (!params.params) params.params = {}; - } - }; - - paella.utils.ajax["get"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('get', params, onSuccess, onFail); - }; - - paella.utils.ajax["post"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('post', params, onSuccess, onFail); - }; - - paella.utils.ajax["put"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('put', params, onSuccess, onFail); - }; - - paella.utils.ajax["delete"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('delete', params, onSuccess, onFail); - }; // TODO: AsyncLoader is deprecated and should be replaced by promises - - - var AsyncLoaderCallback = /*#__PURE__*/function () { - function AsyncLoaderCallback(name) { - _classCallCheck(this, AsyncLoaderCallback); - - this.name = name; - this.prevCb = null; - this.nextCb = null; - this.loader = null; - } - - _createClass(AsyncLoaderCallback, [{ - key: "load", - value: function load(onSuccess, onError) { - onSuccess(); // If error: onError() - } - }]); - - return AsyncLoaderCallback; - }(); - - paella.utils.AsyncLoaderCallback = AsyncLoaderCallback; - - var AjaxCallback = /*#__PURE__*/function (_paella$utils$AsyncLo) { - _inherits(AjaxCallback, _paella$utils$AsyncLo); - - var _super = _createSuper(AjaxCallback); - - function AjaxCallback(params, type) { - var _this; - - _classCallCheck(this, AjaxCallback); - - _this = _super.call(this); - _this.params = null; - _this.type = 'get'; - _this.data = null; - _this.mimeType = null; - _this.statusCode = null; - _this.rawData = null; - _this.name = "ajaxCallback"; - if (type) _this.type = type; - if (typeof params == 'string') _this.params = { - url: params - };else if (_typeof(params) == 'object') _this.params = params;else _this.params = {}; - return _this; - } - - _createClass(AjaxCallback, [{ - key: "getParams", - value: function getParams() { - return this.params; - } - }, { - key: "willLoad", - value: function willLoad(callback) {} - }, { - key: "didLoadSuccess", - value: function didLoadSuccess(callback) { - return true; - } - }, { - key: "didLoadFail", - value: function didLoadFail(callback) { - return false; - } - }, { - key: "load", - value: function load(onSuccess, onError) { - var This = this; - if (typeof this.willLoad == 'function') this.willLoad(this); - paella.utils.ajax.send(this.type, this.getParams(), function (data, type, code, rawData) { - var status = true; - This.data = data; - This.mimeType = type; - This.statusCode = code; - This.rawData = rawData; - if (typeof This.didLoadSuccess == 'function') status = This.didLoadSuccess(This); - if (status) onSuccess();else onError(); - }, function (data, type, code, rawData) { - var status = false; - This.data = data; - This.mimeType = type; - This.statusCode = code; - This.rawData = rawData; - if (typeof This.didLoadFail == 'function') status = This.didLoadFail(This); - if (status) onSuccess();else onError(); - }); - } - }]); - - return AjaxCallback; - }(paella.utils.AsyncLoaderCallback); - - paella.utils.AjaxCallback = AjaxCallback; - - var JSONCallback = /*#__PURE__*/function (_paella$utils$AjaxCal) { - _inherits(JSONCallback, _paella$utils$AjaxCal); - - var _super2 = _createSuper(JSONCallback); - - function JSONCallback(params, type) { - _classCallCheck(this, JSONCallback); - - return _super2.call(this, params, type); - } - - _createClass(JSONCallback, [{ - key: "didLoadSuccess", - value: function didLoadSuccess(callback) { - if (_typeof(callback.data) == 'object') return true; - - try { - callback.data = JSON.parse(callback.data); - return true; - } catch (e) { - callback.data = { - error: "Unexpected data format", - data: callback.data - }; - return false; - } - } - }]); - - return JSONCallback; - }(paella.utils.AjaxCallback); - - paella.utils.JSONCallback = JSONCallback; - - var AsyncLoader = /*#__PURE__*/function () { - function AsyncLoader() { - _classCallCheck(this, AsyncLoader); - - this.firstCb = null; - this.lastCb = null; - this.callbackArray = null; - this.generatedId = 0; - this.continueOnError = false; - this.errorCallbacks = null; - this.currentCb = null; - this.callbackArray = {}; - this.errorCallbacks = []; - this.generatedId = 0; - } - - _createClass(AsyncLoader, [{ - key: "clearError", - value: function clearError() { - this.errorCallbacks = []; - } - }, { - key: "addCallback", - value: function addCallback(cb, name) { - if (!name) { - name = "callback_" + this.generatedId++; - } - - cb.__cbName__ = name; - this.callbackArray[name] = cb; - - if (!this.firstCb) { - this.firstCb = cb; - this.currentCb = cb; - } - - cb.prevCb = this.lastCb; - if (this.lastCb) this.lastCb.nextCb = cb; - this.lastCb = cb; - cb.loader = this; - return cb; - } - }, { - key: "getCallback", - value: function getCallback(name) { - return this.callbackArray[name]; - } - }, { - key: "load", - value: function load(onSuccess, onError) { - console.warn("paella.utils.AsyncLoader is deprecated. Consider to replace it with JavaScript promises."); - var This = this; - - if (this.currentCb) { - this.currentCb.load(function () { - This.onComplete(This.currentCb, This.currentCb.__cbName__, true); - This.currentCb = This.currentCb.nextCb; - This.load(onSuccess, onError); - }, function () { - This.onComplete(This.currentCb, This.currentCb.__cbName__, false); - - if (This.continueOnError) { - This.errorCallbacks.push(This.currentCb); - This.currentCb = This.currentCb.nextCb; - This.load(onSuccess, onError); - } else if (typeof onError == 'function') { - onError(); - } - }); - } else if (typeof onSuccess == 'function') { - onSuccess(); - } - } - }, { - key: "onComplete", - value: function onComplete(callback, cbName, status) {} - }]); - - return AsyncLoader; - }(); - - paella.utils.AsyncLoader = AsyncLoader; -})(); - -(function () { - var g_delegateCallbacks = {}; - var g_dataDelegates = []; - - var DataDelegate = /*#__PURE__*/function () { - function DataDelegate() { - _classCallCheck(this, DataDelegate); - } - - _createClass(DataDelegate, [{ - key: "read", - value: function read(context, params, onSuccess) { - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }, { - key: "write", - value: function write(context, params, value, onSuccess) { - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }, { - key: "remove", - value: function remove(context, params, onSuccess) { - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }]); - - return DataDelegate; - }(); - - paella.DataDelegate = DataDelegate; - paella.dataDelegates = {}; - - var Data = /*#__PURE__*/function () { - function Data(config) { - _classCallCheck(this, Data); - - this._enabled = config.data.enabled; // Delegate callbacks - - var executedCallbacks = []; - - var _loop = function _loop(context) { - var callback = g_delegateCallbacks[context]; - var DelegateClass = null; - var delegateName = null; - - if (!executedCallbacks.some(function (execCallbackData) { - if (execCallbackData.callback == callback) { - delegateName = execCallbackData.delegateName; - return true; - } - })) { - DelegateClass = g_delegateCallbacks[context](); - delegateName = DelegateClass.name; - paella.dataDelegates[delegateName] = DelegateClass; - executedCallbacks.push({ - callback: callback, - delegateName: delegateName - }); - } - - if (!config.data.dataDelegates[context]) { - config.data.dataDelegates[context] = delegateName; - } - }; - - for (var context in g_delegateCallbacks) { - _loop(context); - } - - for (var key in config.data.dataDelegates) { - try { - var delegateName = config.data.dataDelegates[key]; - var DelegateClass = paella.dataDelegates[delegateName]; - var delegateInstance = new DelegateClass(); - g_dataDelegates[key] = delegateInstance; - } catch (e) { - console.warn("Warning: delegate not found - " + delegateName); - } - } // Default data delegate - - - if (!this.dataDelegates["default"]) { - this.dataDelegates["default"] = new paella.dataDelegates.DefaultDataDelegate(); - } - } - - _createClass(Data, [{ - key: "enabled", - get: function get() { - return this._enabled; - } - }, { - key: "dataDelegates", - get: function get() { - return g_dataDelegates; - } - }, { - key: "read", - value: function read(context, key, onSuccess) { - var del = this.getDelegate(context); - del.read(context, key, onSuccess); - } - }, { - key: "write", - value: function write(context, key, params, onSuccess) { - var del = this.getDelegate(context); - del.write(context, key, params, onSuccess); - } - }, { - key: "remove", - value: function remove(context, key, onSuccess) { - var del = this.getDelegate(context); - del.remove(context, key, onSuccess); - } - }, { - key: "getDelegate", - value: function getDelegate(context) { - if (this.dataDelegates[context]) return this.dataDelegates[context];else return this.dataDelegates["default"]; - } - }]); - - return Data; - }(); - - paella.Data = Data; - - paella.addDataDelegate = function (context, callback) { - if (Array.isArray(context)) { - context.forEach(function (ctx) { - g_delegateCallbacks[ctx] = callback; - }); - } else if (typeof context == "string") { - g_delegateCallbacks[context] = callback; - } - }; -})(); - -paella.addDataDelegate(["default", "trimming"], function () { - paella.dataDelegates.DefaultDataDelegate = /*#__PURE__*/function (_paella$DataDelegate) { - _inherits(CookieDataDelegate, _paella$DataDelegate); - - var _super3 = _createSuper(CookieDataDelegate); - - function CookieDataDelegate() { - _classCallCheck(this, CookieDataDelegate); - - return _super3.apply(this, arguments); - } - - _createClass(CookieDataDelegate, [{ - key: "serializeKey", - value: function serializeKey(context, params) { - if (_typeof(params) == 'object') { - params = JSON.stringify(params); - } - - return context + '|' + params; - } - }, { - key: "read", - value: function read(context, params, onSuccess) { - var key = this.serializeKey(context, params); - var value = paella.utils.cookies.get(key); - - try { - value = unescape(value); - value = JSON.parse(value); - } catch (e) {} - - if (typeof onSuccess == 'function') { - onSuccess(value, true); - } - } - }, { - key: "write", - value: function write(context, params, value, onSuccess) { - var key = this.serializeKey(context, params); - - if (_typeof(value) == 'object') { - value = JSON.stringify(value); - } - - value = escape(value); - paella.utils.cookies.set(key, value); - - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }, { - key: "remove", - value: function remove(context, params, onSuccess) { - var key = this.serializeKey(context, params); - - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) == 'object') { - value = JSON.stringify(value); - } - - paella.utils.cookies.set(key, ''); - - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }]); - - return CookieDataDelegate; - }(paella.DataDelegate); - - return paella.dataDelegates.DefaultDataDelegate; -}); // Will be initialized inmediately after loading config.json, in PaellaPlayer.onLoadConfig() - -paella.data = null; - -(function () { - paella.utils = paella.utils || {}; - - var Dictionary = /*#__PURE__*/function () { - function Dictionary() { - _classCallCheck(this, Dictionary); - - this._dictionary = {}; - } - - _createClass(Dictionary, [{ - key: "addDictionary", - value: function addDictionary(dict) { - for (var key in dict) { - this._dictionary[key] = dict[key]; - } - } - }, { - key: "translate", - value: function translate(key) { - return this._dictionary[key] || key; - } - }, { - key: "currentLanguage", - value: function currentLanguage() { - var lang = navigator.language || window.navigator.userLanguage; - return lang.substr(0, 2).toLowerCase(); - } - }]); - - return Dictionary; - }(); - - paella.utils.dictionary = new Dictionary(); -})(); - -(function () { - var MessageBox = /*#__PURE__*/function () { - function MessageBox() { - var _this2 = this; - - _classCallCheck(this, MessageBox); - - this._messageContainer = null; - $(window).resize(function (event) { - return _this2.adjustTop(); - }); - } - - _createClass(MessageBox, [{ - key: "modalContainerClassName", - get: function get() { - return 'modalMessageContainer'; - } - }, { - key: "frameClassName", - get: function get() { - return 'frameContainer'; - } - }, { - key: "messageClassName", - get: function get() { - return 'messageContainer'; - } - }, { - key: "errorClassName", - get: function get() { - return 'errorContainer'; - } - }, { - key: "currentMessageBox", - get: function get() { - return this._currentMessageBox; - }, - set: function set(m) { - this._currentMessageBox = m; - } - }, { - key: "messageContainer", - get: function get() { - return this._messageContainer; - } - }, { - key: "onClose", - get: function get() { - return this._onClose; - }, - set: function set(c) { - this._onClose = c; - } - }, { - key: "showFrame", - value: function showFrame(src, params) { - var closeButton = true; - var onClose = null; - - if (params) { - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowFrame(src, closeButton, onClose); - } - }, { - key: "doShowFrame", - value: function doShowFrame(src, closeButton, onClose) { - this.onClose = onClose; - $('#playerContainer').addClass("modalVisible"); - - if (this.currentMessageBox) { - this.close(); - } - - var modalContainer = document.createElement('div'); - modalContainer.className = this.modalContainerClassName; - modalContainer.style.position = 'fixed'; - modalContainer.style.top = '0px'; - modalContainer.style.left = '0px'; - modalContainer.style.right = '0px'; - modalContainer.style.bottom = '0px'; - modalContainer.style.zIndex = 999999; - var messageContainer = document.createElement('div'); - messageContainer.className = this.frameClassName; - modalContainer.appendChild(messageContainer); - var iframeContainer = document.createElement('iframe'); - iframeContainer.src = src; - iframeContainer.setAttribute("frameborder", "0"); - iframeContainer.style.width = "100%"; - iframeContainer.style.height = "100%"; - messageContainer.appendChild(iframeContainer); - - if (paella.player && paella.player.isFullScreen()) { - paella.player.mainContainer.appendChild(modalContainer); - } else { - $('body')[0].appendChild(modalContainer); - } - - this.currentMessageBox = modalContainer; - this._messageContainer = messageContainer; - this.adjustTop(); - - if (closeButton) { - this.createCloseButton(); - } - } - }, { - key: "showElement", - value: function showElement(domElement, params) { - var closeButton = true; - var onClose = null; - var className = this.messageClassName; - - if (params) { - className = params.className; - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowElement(domElement, closeButton, className, onClose); - } - }, { - key: "showMessage", - value: function showMessage(message, params) { - var closeButton = true; - var onClose = null; - var className = this.messageClassName; - - if (params) { - className = params.className; - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowMessage(message, closeButton, className, onClose); - } - }, { - key: "doShowElement", - value: function doShowElement(domElement, closeButton, className, onClose) { - this.onClose = onClose; - $('#playerContainer').addClass("modalVisible"); - - if (this.currentMessageBox) { - this.close(); - } - - if (!className) className = this.messageClassName; - var modalContainer = document.createElement('div'); - modalContainer.className = this.modalContainerClassName; - modalContainer.style.position = 'fixed'; - modalContainer.style.top = '0px'; - modalContainer.style.left = '0px'; - modalContainer.style.right = '0px'; - modalContainer.style.bottom = '0px'; - modalContainer.style.zIndex = 999999; - var messageContainer = document.createElement('div'); - messageContainer.className = className; - messageContainer.appendChild(domElement); - modalContainer.appendChild(messageContainer); - $('body')[0].appendChild(modalContainer); - this.currentMessageBox = modalContainer; - this._messageContainer = messageContainer; - this.adjustTop(); - - if (closeButton) { - this.createCloseButton(); - } - } - }, { - key: "doShowMessage", - value: function doShowMessage(message, closeButton, className, onClose) { - this.onClose = onClose; - $('#playerContainer').addClass("modalVisible"); - - if (this.currentMessageBox) { - this.close(); - } - - if (!className) className = this.messageClassName; - var modalContainer = document.createElement('div'); - modalContainer.className = this.modalContainerClassName; - modalContainer.style.position = 'fixed'; - modalContainer.style.top = '0px'; - modalContainer.style.left = '0px'; - modalContainer.style.right = '0px'; - modalContainer.style.bottom = '0px'; - modalContainer.style.zIndex = 999999; - var messageContainer = document.createElement('div'); - messageContainer.className = className; - messageContainer.innerHTML = message; - modalContainer.appendChild(messageContainer); - - if (paella.player && paella.player.isFullScreen()) { - paella.player.mainContainer.appendChild(modalContainer); - } else { - $('body')[0].appendChild(modalContainer); - } - - this.currentMessageBox = modalContainer; - this._messageContainer = messageContainer; - this.adjustTop(); - - if (closeButton) { - this.createCloseButton(); - } - } - }, { - key: "showError", - value: function showError(message, params) { - var closeButton = false; - var onClose = null; - - if (params) { - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowError(message, closeButton, onClose); - } - }, { - key: "doShowError", - value: function doShowError(message, closeButton, onClose) { - this.doShowMessage(message, closeButton, this.errorClassName, onClose); - } - }, { - key: "createCloseButton", - value: function createCloseButton() { - var _this3 = this; - - if (this._messageContainer) { - var closeButton = document.createElement('span'); - - this._messageContainer.appendChild(closeButton); - - closeButton.className = 'paella_messageContainer_closeButton icon-cancel-circle'; - $(closeButton).click(function (event) { - return _this3.onCloseButtonClick(); - }); - $(window).keyup(function (evt) { - if (evt.keyCode == 27) { - _this3.onCloseButtonClick(); - } - }); - } - } - }, { - key: "adjustTop", - value: function adjustTop() { - if (this.currentMessageBox) { - var msgHeight = $(this._messageContainer).outerHeight(); - var containerHeight = $(this.currentMessageBox).height(); - var top = containerHeight / 2 - msgHeight / 2; - this._messageContainer.style.marginTop = top + 'px'; - } - } - }, { - key: "close", - value: function close() { - if (this.currentMessageBox && this.currentMessageBox.parentNode) { - var msgBox = this.currentMessageBox; - var parent = msgBox.parentNode; - $('#playerContainer').removeClass("modalVisible"); - $(msgBox).animate({ - opacity: 0.0 - }, 300, function () { - parent.removeChild(msgBox); - }); - - if (this.onClose) { - this.onClose(); - } - } - } - }, { - key: "onCloseButtonClick", - value: function onCloseButtonClick() { - this.close(); - } - }]); - - return MessageBox; - }(); - - paella.MessageBox = MessageBox; - paella.messageBox = new paella.MessageBox(); -})(); - -(function () { - paella.utils = paella.utils || {}; - paella.utils.cookies = { - set: function set(name, value) { - document.cookie = name + "=" + value; - }, - get: function get(name) { - var i, - x, - y, - ARRcookies = document.cookie.split(";"); - - for (i = 0; i < ARRcookies.length; i++) { - x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); - y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); - x = x.replace(/^\s+|\s+$/g, ""); - - if (x == name) { - return unescape(y); - } - } - } - }; - paella.utils.hashParams = { - extractUrl: function extractUrl() { - var urlOnly = window.location.href; - - if (urlOnly.lastIndexOf('#') >= 0) { - urlOnly = urlOnly.substr(0, urlOnly.lastIndexOf('#')); - } - - return urlOnly; - }, - extractParams: function extractParams() { - var params = window.location.href; - - if (params.lastIndexOf('#') >= 0) { - params = params.substr(window.location.href.lastIndexOf('#')); - } else { - params = ""; - } - - return params; - }, - clear: function clear() { - window.location.href = this.extractUrl() + '#'; - }, - unset: function unset(key) { - var url = location.href; - var lastIndex = url.lastIndexOf('#'); - var urlOnly = this.extractUrl(); - - if (lastIndex >= 0 && lastIndex + 1 < url.length) { - var newParams = ""; - var params = url.substr(url.lastIndexOf('#') + 1); - params = params.split('&'); - - for (var i = 0; i < params.length; ++i) { - var current = params[i]; - var keyValue = current.split('='); - - if (keyValue.length >= 2 && keyValue[0] != key || keyValue.length < 2) { - if (newParams == "") newParams += '#';else newParams += "&"; - newParams += current; - } - } - - if (newParams == "") newParams = "#"; - location.href = urlOnly + newParams; - } - }, - set: function set(key, value) { - if (key && value) { - this.unset(key); - var url = this.extractUrl(); - var params = this.extractParams(); - var result = url; - - if (params.length == 0) { - result += '#' + key + '=' + value; - } else if (params.length == 1) { - result += params + key + '=' + value; - } else { - result += params + "&" + key + '=' + value; - } - - location.href = result; - } - }, - get: function get(key) { - var url = location.href; - var index = url.indexOf("#"); - if (index == -1) return ""; - index = url.indexOf(key, index) + key.length; - - if (url.charAt(index) == "=") { - var result = url.indexOf("&", index); - - if (result == -1) { - result = url.length; - } - - return url.substring(index + 1, result); - } - - return ""; - } - }; - paella.utils.parameters = { - list: null, - parse: function parse() { - if (!this.list) { - var url = window.location.href; - this.list = {}; - - if (/(http|https|file)?:\/\/([a-z0-9.\-_\/\~:]*\?)([a-z0-9.\/\-_\%\=\&]*)\#*/i.test(url)) { - var params = RegExp.$3; - var paramArray = params.split('&'); - this.list = {}; - - for (var i = 0; i < paramArray.length; ++i) { - var keyValue = paramArray[i].split('='); - var key = keyValue[0]; - var value = keyValue.length == 2 ? keyValue[1] : ''; - this.list[key] = value; - } - } - } - }, - get: function get(parameter) { - if (this.list == null) { - this.parse(); - } - - return this.list[parameter]; - }, - extractUrl: function extractUrl() { - var urlOnly = paella.utils.hashParams.extractUrl(); - - if (urlOnly.lastIndexOf('?') >= 0) { - urlOnly = urlOnly.substr(0, urlOnly.lastIndexOf('?')); - } - - return urlOnly; - }, - extractParams: function extractParams() { - // Primero quitar los parámetros hash - var urlAndParams = paella.utils.hashParams.extractUrl(); - var params = urlAndParams; - - if (params.lastIndexOf('?') >= 0) { - params = params.substr(window.location.href.lastIndexOf('?')); - } else { - params = ""; - } - - return params; - }, - // Pasa los parámetros de la URL a hash. Esta acción recargará la página - toHash: function toHash() { - var urlOnly = this.extractUrl(); - var hashParameters = paella.utils.hashParams.extractParams(); - var parameters = this.extractParams(); - var newHashParams = ""; - var result = urlOnly; - - if (parameters.length == 0 || parameters.length == 1) { - result += hashParameters; - } else { - parameters = parameters.substr(1); - parameters = parameters.split('&'); - - for (var i = 0; i < parameters.length; ++i) { - keyValue = parameters[i].split('='); - - if (keyValue.length >= 2 && paella.utils.hashParams.get(keyValue[0]) == '') { - if (hashParameters == "" && newHashParams == "") newHashParams += '#';else newHashParams += '&'; - newHashParams += keyValue[0] + '=' + keyValue[1]; - } - } - - result += hashParameters + newHashParams; - } - - if (location.href != result) { - location.href = result; - } - } - }; -})(); - -(function () { - paella.utils = paella.utils || {}; - - function parseOperatingSystem(userAgentString) { - this.system.MacOS = /Macintosh/.test(userAgentString); - this.system.Windows = /Windows/.test(userAgentString); - this.system.iPhone = /iPhone/.test(userAgentString); - this.system.iPodTouch = /iPod/.test(userAgentString); - this.system.iPad = /iPad/.test(userAgentString) || /FxiOS/.test(userAgentString); - this.system.iOS = this.system.iPhone || this.system.iPad || this.system.iPodTouch; - this.system.Android = /Android/.test(userAgentString); - this.system.Linux = this.system.Android ? false : /Linux/.test(userAgentString); - - if (this.system.MacOS) { - this.system.OSName = "Mac OS X"; - parseMacOSVersion.apply(this, [userAgentString]); - } else if (this.system.Windows) { - this.system.OSName = "Windows"; - parseWindowsVersion.apply(this, [userAgentString]); - } else if (this.system.Linux) { - this.system.OSName = "Linux"; - parseLinuxVersion.apply(this, [userAgentString]); - } else if (this.system.iOS) { - this.system.OSName = "iOS"; - parseIOSVersion.apply(this, [userAgentString]); - } else if (this.system.Android) { - this.system.OSName = "Android"; - parseAndroidVersion.apply(this, [userAgentString]); - } - } - - function parseBrowser(userAgentString) { - // Safari: Version/X.X.X Safari/XXX - // Chrome: Chrome/XX.X.XX.XX Safari/XXX - // Opera: Opera/X.XX - // Firefox: Gecko/XXXXXX Firefox/XX.XX.XX - // Explorer: MSIE X.X - this.browser.Version = {}; - this.browser.Safari = /Version\/([\d\.]+) Safari\//.test(userAgentString); - - if (this.browser.Safari) { - this.browser.Name = "Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Chrome = /Chrome\/([\d\.]+) Safari\//.test(userAgentString) || /Chrome\/([\d\.]+) Electron\//.test(userAgentString); - - if (this.browser.Chrome) { - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } // The attribute this.browser.Chrome will still be true, because it is the same browser after all - - - this.browser.EdgeChromium = /Chrome.*Edg\/([0-9\.]+)/.test(userAgentString); - - if (this.browser.EdgeChromium) { - this.browser.Name = "Edge Chromium"; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Opera = /Opera\/[\d\.]+/.test(userAgentString); - - if (this.browser.Opera) { - this.browser.Name = "Opera"; - this.browser.Vendor = "Opera Software"; - var versionString = /Version\/([\d\.]+)/.test(userAgentString); - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Firefox = /Gecko\/[\d\.]+ Firefox\/([\d\.]+)/.test(userAgentString); - - if (this.browser.Firefox) { - this.browser.Name = "Firefox"; - this.browser.Vendor = "Mozilla Foundation"; - this.browser.Version.versionString = RegExp.$1; - } - - var firefoxIOS = this.browser.Firefox || /FxiOS\/(\d+\.\d+)/.test(userAgentString); - - if (firefoxIOS) { - this.browser.Firefox = true; - this.browser.Name = "Firefox"; - this.browser.Vendor = "Mozilla Foundation"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Edge = /Edge\/(.*)/.test(userAgentString); - - if (this.browser.Edge) { - var result = /Edge\/(.*)/.exec(userAgentString); - this.browser.Name = "Edge"; - this.browser.Chrome = false; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = result[1]; - } - - this.browser.Explorer = /MSIE ([\d\.]+)/.test(userAgentString); - - if (!this.browser.Explorer) { - var re = /\Mozilla\/5.0 \(([^)]+)\) like Gecko/; - var matches = re.exec(userAgentString); - - if (matches) { - re = /rv:(.*)/; - var version = re.exec(matches[1]); - this.browser.Explorer = true; - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - - if (version) { - this.browser.Version.versionString = version[1]; - } else { - this.browser.Version.versionString = "unknown"; - } - } - } else { - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = RegExp.$1; - } - - if (this.system.iOS) { - this.browser.IsMobileVersion = true; - this.browser.MobileSafari = /Version\/([\d\.]+) Mobile/.test(userAgentString); - - if (this.browser.MobileSafari) { - this.browser.Name = "Mobile Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Android = false; - } else if (this.system.Android) { - this.browser.IsMobileVersion = true; - this.browser.Android = /Version\/([\d\.]+) Mobile/.test(userAgentString); - - if (this.browser.MobileSafari) { - this.browser.Name = "Android Browser"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } else { - this.browser.Chrome = /Chrome\/([\d\.]+)/.test(userAgentString); - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Safari = false; - } else { - this.browser.IsMobileVersion = false; - } - - parseBrowserVersion.apply(this, [userAgentString]); - } - - function parseBrowserVersion(userAgentString) { - if (/([\d]+)\.([\d]+)\.*([\d]*)/.test(this.browser.Version.versionString)) { - this.browser.Version.major = Number(RegExp.$1); - this.browser.Version.minor = Number(RegExp.$2); - this.browser.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - } - } - - function parseMacOSVersion(userAgentString) { - var versionString = /Mac OS X (\d+_\d+_*\d*)/.test(userAgentString) ? RegExp.$1 : ''; - this.system.Version = {}; // Safari/Chrome - - if (versionString != '') { - if (/(\d+)_(\d+)_*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - } - } // Firefox/Opera - else { - versionString = /Mac OS X (\d+\.\d+\.*\d*)/.test(userAgentString) ? RegExp.$1 : 'Unknown'; - - if (/(\d+)\.(\d+)\.*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - } - } - - if (!this.system.Version.major) { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - - this.system.Version.stringValue = this.system.Version.major + '.' + this.system.Version.minor + '.' + this.system.Version.revision; - - switch (this.system.Version.minor) { - case 0: - this.system.Version.name = "Cheetah"; - break; - - case 1: - this.system.Version.name = "Puma"; - break; - - case 2: - this.system.Version.name = "Jaguar"; - break; - - case 3: - this.system.Version.name = "Panther"; - break; - - case 4: - this.system.Version.name = "Tiger"; - break; - - case 5: - this.system.Version.name = "Leopard"; - break; - - case 6: - this.system.Version.name = "Snow Leopard"; - break; - - case 7: - this.system.Version.name = "Lion"; - break; - - case 8: - this.system.Version.name = "Mountain Lion"; - break; - - case 9: - this.system.Version.name = "Mavericks"; - break; - - case 10: - this.system.Version.name = "Yosemite"; - break; - - case 11: - this.system.Version.name = "El Capitan"; - break; - - case 12: - this.system.Version.name = "Sierra"; - break; - - case 13: - this.system.Version.name = "High Sierra"; - break; - - case 14: - this.system.Version.name = "Mojave"; - break; - - case 15: - this.system.Version.name = "Catalina"; - break; - } - } - - function parseWindowsVersion(userAgentString) { - this.system.Version = {}; - - if (/NT (\d+)\.(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = 0; // Solo por compatibilidad - - this.system.Version.stringValue = "NT " + this.system.Version.major + "." + this.system.Version.minor; - var major = this.system.Version.major; - var minor = this.system.Version.minor; - var name = 'undefined'; - - if (major == 5) { - if (minor == 0) this.system.Version.name = '2000';else this.system.Version.name = 'XP'; - } else if (major == 6) { - if (minor == 0) this.system.Version.name = 'Vista';else if (minor == 1) this.system.Version.name = '7';else if (minor == 2) this.system.Version.name = '8'; - } else if (major == 10) { - this.system.Version.name = "10"; - } - } else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - function parseLinuxVersion(userAgentString) { - // Muchos navegadores no proporcionan información sobre la distribución de linux... no se puede hacer mucho más que esto - this.system.Version = {}; - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - this.system.Version.name = ""; - this.system.Version.stringValue = "Unknown distribution"; - } - - function parseIOSVersion(userAgentString) { - this.system.Version = {}; - - if (/iPhone OS (\d+)_(\d+)_*(\d*)/i.test(userAgentString) || /iPad; CPU OS (\d+)_(\d+)_*(\d*)/i.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - this.system.Version.name = "iOS"; - } else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - function parseAndroidVersion(userAgentString) { - this.system.Version = {}; - - if (/Android (\d+)\.(\d+)\.*(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - - if (/Build\/([a-zA-Z]+)/.test(userAgentString)) { - this.system.Version.name = RegExp.$1; - } else { - this.system.Version.name = "Unknown version"; - } - - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } - - function getInfoString() { - return navigator.userAgent; - } - - var UserAgent = /*#__PURE__*/function () { - function UserAgent() { - var userAgentString = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - - _classCallCheck(this, UserAgent); - - if (!userAgentString) { - userAgentString = navigator.userAgent; - } - - this._system = {}; - this._browser = {}; - parseOperatingSystem.apply(this, [userAgentString]); - parseBrowser.apply(this, [userAgentString]); - } - - _createClass(UserAgent, [{ - key: "system", - get: function get() { - return this._system; - } - }, { - key: "browser", - get: function get() { - return this._browser; - } - }, { - key: "getInfoString", - value: function getInfoString() { - return navigator.userAgent; - } - }, { - key: "infoString", - get: function get() { - navigator.userAgent; - } - }]); - - return UserAgent; - }(); - - paella.UserAgent = UserAgent; - paella.utils.userAgent = new paella.UserAgent(); -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ -// Paella Mouse Manager -/////////////////////////////////////////////////////// - - -(function () { - var MouseManager = /*#__PURE__*/function () { - function MouseManager() { - var _this4 = this; - - _classCallCheck(this, MouseManager); - - paella.events.bind('mouseup', function (event) { - return _this4.up(event); - }); - paella.events.bind('mousemove', function (event) { - return _this4.move(event); - }); - paella.events.bind('mouseover', function (event) { - return _this4.over(event); - }); - } - - _createClass(MouseManager, [{ - key: "targetObject", - get: function get() { - return this._targetObject; - }, - set: function set(t) { - this._targetObject = t; - } - }, { - key: "down", - value: function down(targetObject, event) { - this.targetObject = targetObject; - - if (this.targetObject && this.targetObject.down) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.down(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }, { - key: "up", - value: function up(event) { - if (this.targetObject && this.targetObject.up) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.up(event, pageX, pageY); - event.cancelBubble = true; - } - - this.targetObject = null; - return false; - } - }, { - key: "out", - value: function out(event) { - if (this.targetObject && this.targetObject.out) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.out(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }, { - key: "move", - value: function move(event) { - if (this.targetObject && this.targetObject.move) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.move(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }, { - key: "over", - value: function over(event) { - if (this.targetObject && this.targetObject.over) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.over(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }]); - - return MouseManager; - }(); - - paella.MouseManager = MouseManager; -})(); // paella.utils -/////////////////////////////////////////////////////// - - -(function initSkinDeps() { - var link = document.createElement('link'); - link.rel = 'stylesheet'; - link.href = paella.baseUrl + 'resources/bootstrap/css/bootstrap.min.css'; - link.type = 'text/css'; - link.media = 'screen'; - link.charset = 'utf-8'; - document.head.appendChild(link); -})(); - -paella.utils = paella.utils || {}; -paella.utils.mouseManager = new paella.MouseManager(); -paella.utils.folders = { - get: function get(folder) { - if (paella.player && paella.player.config && paella.player.config.folders && paella.player.config.folders[folder]) { - return paella.player.config.folders[folder]; - } - - return undefined; - }, - profiles: function profiles() { - return paella.baseUrl + (paella.utils.folders.get("profiles") || "config/profiles"); - }, - resources: function resources() { - return paella.baseUrl + (paella.utils.folders.get("resources") || "resources"); - }, - skins: function skins() { - return paella.baseUrl + (paella.utils.folders.get("skins") || paella.utils.folders.get("resources") + "/style"); - } -}; -paella.utils.styleSheet = { - removeById: function removeById(id) { - var outStyleSheet = $(document.head).find('#' + id)[0]; - - if (outStyleSheet) { - document.head.removeChild(outStyleSheet); - } - }, - remove: function remove(fileName) { - var links = document.head.getElementsByTagName('link'); - - for (var i = 0; i < links.length; ++i) { - if (links[i].href) { - document.head.removeChild(links[i]); - break; - } - } - }, - add: function add(fileName, id) { - var link = document.createElement('link'); - link.rel = 'stylesheet'; - link.href = fileName; - link.type = 'text/css'; - link.media = 'screen'; - link.charset = 'utf-8'; - if (id) link.id = id; - document.head.appendChild(link); - }, - swap: function swap(outFile, inFile) { - this.remove(outFile); - this.add(inFile); - } -}; -paella.utils.skin = { - set: function set(skinName) { - var skinId = 'paellaSkin'; - paella.utils.styleSheet.removeById(skinId); - paella.utils.styleSheet.add(paella.utils.folders.skins() + '/style_' + skinName + '.css'); - paella.utils.cookies.set("skin", skinName); - }, - restore: function restore(defaultSkin) { - var storedSkin = paella.utils.cookies.get("skin"); - - if (storedSkin && storedSkin != "") { - this.set(storedSkin); - } else { - this.set(defaultSkin); - } - } -}; -paella.utils.timeParse = { - timeToSeconds: function timeToSeconds(timeString) { - var hours = 0; - var minutes = 0; - var seconds = 0; - - if (/([0-9]+)h/i.test(timeString)) { - hours = parseInt(RegExp.$1) * 60 * 60; - } - - if (/([0-9]+)m/i.test(timeString)) { - minutes = parseInt(RegExp.$1) * 60; - } - - if (/([0-9]+)s/i.test(timeString)) { - seconds = parseInt(RegExp.$1); - } - - return hours + minutes + seconds; - }, - secondsToTime: function secondsToTime(seconds) { - var hrs = ~~(seconds / 3600); - if (hrs < 10) hrs = '0' + hrs; - var mins = ~~(seconds % 3600 / 60); - if (mins < 10) mins = '0' + mins; - var secs = Math.floor(seconds % 60); - if (secs < 10) secs = '0' + secs; - return hrs + ':' + mins + ':' + secs; - }, - secondsToText: function secondsToText(secAgo) { - // Seconds - if (secAgo <= 1) { - return paella.utils.dictionary.translate("1 second ago"); - } - - if (secAgo < 60) { - return paella.utils.dictionary.translate("{0} seconds ago").replace(/\{0\}/g, secAgo); - } // Minutes - - - var minAgo = Math.round(secAgo / 60); - - if (minAgo <= 1) { - return paella.utils.dictionary.translate("1 minute ago"); - } - - if (minAgo < 60) { - return paella.utils.dictionary.translate("{0} minutes ago").replace(/\{0\}/g, minAgo); - } //Hours - - - var hourAgo = Math.round(secAgo / (60 * 60)); - - if (hourAgo <= 1) { - return paella.utils.dictionary.translate("1 hour ago"); - } - - if (hourAgo < 24) { - return paella.utils.dictionary.translate("{0} hours ago").replace(/\{0\}/g, hourAgo); - } //Days - - - var daysAgo = Math.round(secAgo / (60 * 60 * 24)); - - if (daysAgo <= 1) { - return paella.utils.dictionary.translate("1 day ago"); - } - - if (daysAgo < 24) { - return paella.utils.dictionary.translate("{0} days ago").replace(/\{0\}/g, daysAgo); - } //Months - - - var monthsAgo = Math.round(secAgo / (60 * 60 * 24 * 30)); - - if (monthsAgo <= 1) { - return paella.utils.dictionary.translate("1 month ago"); - } - - if (monthsAgo < 12) { - return paella.utils.dictionary.translate("{0} months ago").replace(/\{0\}/g, monthsAgo); - } //Years - - - var yearsAgo = Math.round(secAgo / (60 * 60 * 24 * 365)); - - if (yearsAgo <= 1) { - return paella.utils.dictionary.translate("1 year ago"); - } - - return paella.utils.dictionary.translate("{0} years ago").replace(/\{0\}/g, yearsAgo); - }, - matterhornTextDateToDate: function matterhornTextDateToDate(mhdate) { - var d = new Date(); - d.setFullYear(parseInt(mhdate.substring(0, 4), 10)); - d.setMonth(parseInt(mhdate.substring(5, 7), 10) - 1); - d.setDate(parseInt(mhdate.substring(8, 10), 10)); - d.setHours(parseInt(mhdate.substring(11, 13), 10)); - d.setMinutes(parseInt(mhdate.substring(14, 16), 10)); - d.setSeconds(parseInt(mhdate.substring(17, 19), 10)); - return d; - } -}; - -paella.utils.objectFromString = function (str) { - var arr = str.split("."); - var fn = window || _this5; - - for (var i = 0, len = arr.length; i < len; i++) { - fn = fn[arr[i]]; - } - - if (typeof fn !== "function") { - throw new Error("constructor not found"); - } - - return fn; -}; - -paella.utils.uuid = function () { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = Math.random() * 16 | 0; - var v = (c == 'x' ? r : r) & 0x3 | 0x8; - return v.toString(16); - }); -}; - -(function () { - var TimerManager = /*#__PURE__*/function () { - function TimerManager() { - _classCallCheck(this, TimerManager); - - this.timerArray = []; - this.lastId = 0; - } - - _createClass(TimerManager, [{ - key: "setupTimer", - value: function setupTimer(timer, time) { - this.lastId++; - timer.timerId = this.lastId; - timer.timeout = time; - this.timerArray[this.lastId] = timer; - timer.jsTimerId = setTimeout("g_timerManager.executeTimerCallback(".concat(this.lastId, ")"), time); - } - }, { - key: "executeTimerCallback", - value: function executeTimerCallback(timerId) { - var timer = this.timerArray[timerId]; - - if (timer && timer.callback) { - timer.callback(timer, timer.params); - } - - if (timer.repeat) { - timer.jsTimerId = setTimeout("g_timerManager.executeTimerCallback(".concat(timer.timerId, ")"), timer.timeout); - } - } - }]); - - return TimerManager; - }(); - - window.g_timerManager = new TimerManager(); - - var Timer = /*#__PURE__*/function () { - function Timer(callback, time, params) { - _classCallCheck(this, Timer); - - this.callback = callback; - this.params = params; - this._repeat = false; - g_timerManager.setupTimer(this, time); - } - - _createClass(Timer, [{ - key: "repeat", - get: function get() { - return this._repeat; - }, - set: function set(r) { - this._repeat = r; - } - }, { - key: "cancel", - value: function cancel() { - clearTimeout(this.jsTimerId); - } - }], [{ - key: "sleep", - value: function sleep(milliseconds) { - var start = new Date().getTime(); - - for (var i = 0; i < 1e7; ++i) { - if (new Date().getTime() - start > milliseconds) { - break; - } - } - } - }]); - - return Timer; - }(); - - paella.utils.Timer = Timer; -})(); - -(function () { - // Include scripts in header - var g_requiredScripts = {}; - - paella.require = function (path) { - if (!g_requiredScripts[path]) { - g_requiredScripts[path] = new Promise(function (resolve, reject) { - paella.utils.ajax.get({ - url: path - }, function (data) { - try { - var _module = { - exports: null - }; - var exports = null; - eval(data); - - if (_module && _module.exports) { - resolve(_module.exports); - } else { - var geval = eval; - geval(data); - resolve(); - } - } catch (err) { - reject(err); - } - }, function (err) { - reject(err); - }); - }); - } - - return g_requiredScripts[path]; - }; - - paella.tabIndex = new ( /*#__PURE__*/function () { - function TabIndexManager() { - _classCallCheck(this, TabIndexManager); - - this._last = 1; - } - - _createClass(TabIndexManager, [{ - key: "next", - get: function get() { - return this._last++; - } - }, { - key: "last", - get: function get() { - return this._last - 1; - } - }, { - key: "tabIndexElements", - get: function get() { - var result = Array.from($('[tabindex]')); // Sort by tabIndex - - result.sort(function (a, b) { - return a.tabIndex - b.tabIndex; - }); - return result; - } - }, { - key: "insertAfter", - value: function insertAfter(target, elements) { - if (target.tabIndex == null || target.tabIndex == -1) { - throw Error("Insert tab index: the target element does not have a valid tabindex."); - } - - var targetIndex = -1; - var newTabIndexElements = this.tabIndexElements; - newTabIndexElements.some(function (elem, i) { - if (elem == target) { - targetIndex = i; - return true; - } - }); - newTabIndexElements.splice.apply(newTabIndexElements, [targetIndex + 1, 0].concat(_toConsumableArray(elements))); - newTabIndexElements.forEach(function (elem, index) { - elem.tabIndex = index; - +1; - }); - this._last = newTabIndexElements.length; - } - }, { - key: "removeTabIndex", - value: function removeTabIndex(elements) { - var _this6 = this; - - Array.from(elements).forEach(function (e) { - e.removeAttribute("tabindex"); - }); - this.tabIndexElements.forEach(function (elem, index) { - elem.tabIndex = index + 1; - _this6._last = elem.tabIndex + 1; - }); - } - }]); - - return TabIndexManager; - }())(); - - paella.URL = /*#__PURE__*/function () { - function PaellaURL(urlText) { - _classCallCheck(this, PaellaURL); - - this._urlText = urlText; - } - - _createClass(PaellaURL, [{ - key: "text", - get: function get() { - return this._urlText; - } - }, { - key: "isAbsolute", - get: function get() { - return new RegExp('^([a-z]+://|//)', 'i').test(this._urlText) || /^\//.test(this._urlText); // We consider that the URLs starting with / are absolute and local to this server - } - }, { - key: "isExternal", - get: function get() { - var thisUrl = new URL(this.absoluteUrl); - var localUrl = new URL(location.href); - return thisUrl.hostname != localUrl.hostname; - } - }, { - key: "absoluteUrl", - get: function get() { - var result = ""; - - if (new RegExp('^([a-z]+://|//)', 'i').test(this._urlText)) { - result = this._urlText; - } else if (/^\//.test(this._urlText)) { - result = "".concat(location.origin).concat(this._urlText); - } else { - var pathname = location.pathname; - - if (pathname.lastIndexOf(".") > pathname.lastIndexOf("/")) { - pathname = pathname.substring(0, pathname.lastIndexOf("/")) + '/'; - } - - result = "".concat(location.origin).concat(pathname).concat(this._urlText); - } - - result = new URL(result).href; - return result; - } - }, { - key: "appendPath", - value: function appendPath(text) { - if (this._urlText.endsWith("/") && text.startsWith("/")) { - this._urlText += text.substring(1, text.length); - } else if (this._urlText.endsWith("/") || text.startsWith("/")) { - this._urlText += text; - } else { - this._urlText += "/" + text; - } - - return this; - } - }]); - - return PaellaURL; - }(); - - var Log = /*#__PURE__*/function () { - function Log() { - _classCallCheck(this, Log); - - this._currentLevel = 0; - var logLevelParam = paella.utils.parameters.get("logLevel"); - logLevelParam = logLevelParam ? logLevelParam : paella.utils.hashParams.get("logLevel"); - logLevelParam = logLevelParam.toLowerCase(); - - switch (logLevelParam) { - case "error": - this.setLevel(this.kLevelError); - break; - - case "warning": - this.setLevel(this.kLevelWarning); - break; - - case "debug": - this.setLevel(this.kLevelDebug); - break; - - case "log": - this.setLevel(this.kLevelLog); - break; - } - } - - _createClass(Log, [{ - key: "kLevelError", - get: function get() { - return 1; - } - }, { - key: "kLevelWarning", - get: function get() { - return 2; - } - }, { - key: "kLevelDebug", - get: function get() { - return 3; - } - }, { - key: "kLevelLog", - get: function get() { - return 4; - } - }, { - key: "logMessage", - value: function logMessage(level, message) { - var prefix = ""; - - if (typeof level == "string") { - message = level; - } else if (level >= paella.log.kLevelError && level <= paella.log.kLevelLog) { - switch (level) { - case paella.log.kLevelError: - prefix = "ERROR: "; - break; - - case paella.log.kLevelWarning: - prefix = "WARNING: "; - break; - - case paella.log.kLevelDebug: - prefix = "DEBUG: "; - break; - - case paella.log.kLevelLog: - prefix = "LOG: "; - break; - } - } - - if (this._currentLevel >= level && console.log) { - console.log(prefix + message); - } - } - }, { - key: "error", - value: function error(message) { - this.logMessage(paella.log.kLevelError, message); - } - }, { - key: "warning", - value: function warning(message) { - this.logMessage(paella.log.kLevelWarning, message); - } - }, { - key: "debug", - value: function debug(message) { - this.logMessage(paella.log.kLevelDebug, message); - } - }, { - key: "log", - value: function log(message) { - this.logMessage(paella.log.kLevelLog, message); - } - }, { - key: "setLevel", - value: function setLevel(level) { - this._currentLevel = level; - } - }]); - - return Log; - }(); - - paella.log = new Log(); -})(); - -paella.AntiXSS = { - htmlEscape: function htmlEscape(str) { - return String(str).replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>'); - }, - htmlUnescape: function htmlUnescape(value) { - return String(value).replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'); - } -}; - -function paella_DeferredResolved(param) { - return new Promise(function (resolve) { - resolve(param); - }); -} - -function paella_DeferredRejected(param) { - return new Promise(function (resolve, reject) { - reject(param); - }); -} - -function paella_DeferredNotImplemented() { - return paella_DeferredRejected(new Error("not implemented")); -} -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ - - -(function () { - var Node = /*#__PURE__*/function () { - function Node(id) { - _classCallCheck(this, Node); - - this._nodeList = {}; - this.identifier = id; - } - - _createClass(Node, [{ - key: "identifier", - get: function get() { - return this._identifier; - }, - set: function set(id) { - this._identifier = id; - } - }, { - key: "nodeList", - get: function get() { - return this._nodeList; - } - }, { - key: "parent", - get: function get() { - return this._parent; - }, - set: function set(p) { - this._parent = p; - } - }, { - key: "addTo", - value: function addTo(parentNode) { - parentNode.addNode(this); - } - }, { - key: "addNode", - value: function addNode(childNode) { - childNode.parent = this; - this.nodeList[childNode.identifier] = childNode; - return childNode; - } - }, { - key: "getNode", - value: function getNode(id) { - return this.nodeList[id]; - } - }, { - key: "removeNode", - value: function removeNode(childNode) { - if (this.nodeList[childNode.identifier]) { - delete this.nodeList[childNode.identifier]; - return true; - } - - return false; - } - }]); - - return Node; - }(); - - paella.Node = Node; - - var DomNode = /*#__PURE__*/function (_paella$Node) { - _inherits(DomNode, _paella$Node); - - var _super4 = _createSuper(DomNode); - - function DomNode(elementType, id, style) { - var _this7; - - _classCallCheck(this, DomNode); - - _this7 = _super4.call(this, id); - _this7._elementType = elementType; - _this7._domElement = document.createElement(elementType); - _this7.domElement.id = id; - if (style) _this7.style = style; - return _this7; - } - - _createClass(DomNode, [{ - key: "domElement", - get: function get() { - return this._domElement; - } - }, { - key: "domElementType", - get: function get() { - return this._elementType; - }, - set: function set(newType) { - this._elementType = newType; - var oldElement = this._domElement; - var parent = oldElement.parentNode; - var newElement = document.createElement(newType); - parent.removeChild(oldElement); - parent.appendChild(newElement); - this._domElement = newElement; - newElement.innerHTML = oldElement.innerHTML; - - for (var i = 0; i < oldElement.attributes.length; ++i) { - var attr = oldElement.attributes[i]; - newElement.setAttribute(attr.name, attr.value); - } - } - }, { - key: "style", - set: function set(s) { - $(this.domElement).css(s); - } - }, { - key: "addNode", - value: function addNode(childNode) { - var returnValue = _get(_getPrototypeOf(DomNode.prototype), "addNode", this).call(this, childNode); - - this.domElement.appendChild(childNode.domElement); - return returnValue; - } - }, { - key: "onresize", - value: function onresize() {} - }, { - key: "removeNode", - value: function removeNode(childNode) { - if (_get(_getPrototypeOf(DomNode.prototype), "removeNode", this).call(this, childNode)) { - this.domElement.removeChild(childNode.domElement); - } - } - }]); - - return DomNode; - }(paella.Node); - - paella.DomNode = DomNode; - - var Button = /*#__PURE__*/function (_paella$DomNode) { - _inherits(Button, _paella$DomNode); - - var _super5 = _createSuper(Button); - - function Button(id, className, action, isToggle) { - var _this8; - - _classCallCheck(this, Button); - - var style = {}; - _this8 = _super5.call(this, 'div', id, style); - _this8.isToggle = isToggle; - _this8.domElement.className = className; - - if (isToggle) { - $(_this8.domElement).click(function (event) { - _this8.toggleIcon(); - }); - } - - $(_this8.domElement).click('click', action); - return _this8; - } - - _createClass(Button, [{ - key: "isToggle", - get: function get() { - return this._isToggle; - }, - set: function set(t) { - this._isToggle = t; - } - }, { - key: "isToggled", - value: function isToggled() { - if (this.isToggle) { - var element = this.domElement; - return /([a-zA-Z0-9_]+)_active/.test(element.className); - } else { - return false; - } - } - }, { - key: "toggle", - value: function toggle() { - this.toggleIcon(); - } - }, { - key: "toggleIcon", - value: function toggleIcon() { - var element = this.domElement; - - if (/([a-zA-Z0-9_]+)_active/.test(element.className)) { - element.className = RegExp.$1; - } else { - element.className = element.className + '_active'; - } - } - }, { - key: "show", - value: function show() { - $(this.domElement).show(); - } - }, { - key: "hide", - value: function hide() { - $(this.domElement).hide(); - } - }, { - key: "visible", - value: function visible() { - return this.domElement.visible(); - } - }]); - - return Button; - }(paella.DomNode); - - paella.Button = Button; -})(); - -(function () { - var g_profiles = []; - - paella.addProfile = function (cb) { - cb().then(function (profileData) { - if (profileData) { - g_profiles.push(profileData); - - if (typeof profileData.onApply != "function") { - profileData.onApply = function () {}; - } - - if (typeof profileData.onDeactivte != "function") { - profileData.onDeactivate = function () {}; - } - - paella.events.trigger(paella.events.profileListChanged, { - profileData: profileData - }); - } - }); - }; // Utility functions - - - function hideBackground() { - var bkgNode = this.container.getNode("videoContainerBackground"); - if (bkgNode) this.container.removeNode(bkgNode); - } - - function showBackground(bkgData) { - if (!bkgData) return; - hideBackground.apply(this); - this.backgroundData = bkgData; - var style = { - backgroundImage: "url(".concat(paella.baseUrl).concat(paella.utils.folders.get("resources"), "/style/").concat(bkgData.content, ")"), - backgroundSize: "100% 100%", - zIndex: bkgData.layer, - position: 'absolute', - left: bkgData.rect.left + "px", - right: bkgData.rect.right + "px", - width: "100%", - height: "100%" - }; - this.container.addNode(new paella.DomNode('div', "videoContainerBackground", style)); - } - - function hideAllLogos() { - if (this.logos == undefined) return; - - for (var i = 0; i < this.logos.length; ++i) { - var logoId = this.logos[i].content.replace(/\./ig, "-"); - var logo = this.container.getNode(logoId); - $(logo.domElement).hide(); - } - } - - function showLogos(logos) { - this.logos = logos; - var relativeSize = new paella.RelativeVideoSize(); - - for (var i = 0; i < logos.length; ++i) { - var logo = logos[i]; - var logoId = logo.content.replace(/\./ig, "-"); - var logoNode = this.container.getNode(logoId); - var rect = logo.rect; - - if (!logoNode) { - style = {}; - logoNode = this.container.addNode(new paella.DomNode('img', logoId, style)); - logoNode.domElement.setAttribute('src', "".concat(paella.baseUrl).concat(paella.utils.folders.get("resources"), "/style/").concat(logo.content)); - } else { - $(logoNode.domElement).show(); - } - - var percentTop = Number(relativeSize.percentVSize(rect.top)) + '%'; - var percentLeft = Number(relativeSize.percentWSize(rect.left)) + '%'; - var percentWidth = Number(relativeSize.percentWSize(rect.width)) + '%'; - var percentHeight = Number(relativeSize.percentVSize(rect.height)) + '%'; - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute', - zIndex: logo.zIndex - }; - $(logoNode.domElement).css(style); - } - } - - function hideButtons() { - var _this9 = this; - - if (this.buttons) { - this.buttons.forEach(function (btn) { - _this9.container.removeNode(_this9.container.getNode(btn.id)); - }); - this.buttons = null; - } - } - - function showButtons(buttons, profileData) { - var _this10 = this; - - hideButtons.apply(this); - - if (buttons) { - var relativeSize = new paella.RelativeVideoSize(); - this.buttons = buttons; - buttons.forEach(function (btn, index) { - btn.id = "button_" + index; - var rect = btn.rect; - var percentTop = relativeSize.percentVSize(rect.top) + '%'; - var percentLeft = relativeSize.percentWSize(rect.left) + '%'; - var percentWidth = relativeSize.percentWSize(rect.width) + '%'; - var percentHeight = relativeSize.percentVSize(rect.height) + '%'; - var url = paella.baseUrl; - url = url.replace(/\\/ig, '/'); - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute', - zIndex: btn.layer, - backgroundImage: "url(".concat(paella.baseUrl).concat(paella.utils.folders.get("resources"), "/style/").concat(btn.icon, ")"), - backgroundSize: '100% 100%', - display: 'block' - }; - - var logoNode = _this10.container.addNode(new paella.DomNode('div', btn.id, style)); - - logoNode.domElement.className = "paella-profile-button"; - logoNode.domElement.data = { - action: btn.onClick, - profileData: profileData - }; - $(logoNode.domElement).click(function (evt) { - this.data.action.apply(this.data.profileData, [evt]); - evt.stopPropagation(); - return false; - }); - }); - } - } - - function getClosestRect(profileData, videoDimensions) { - var minDiff = 10; - var re = /([0-9\.]+)\/([0-9\.]+)/; - var result = profileData.rect[0]; - var videoAspectRatio = videoDimensions.h == 0 ? 1.777777 : videoDimensions.w / videoDimensions.h; - var profileAspectRatio = 1; - var reResult = false; - profileData.rect.forEach(function (rect) { - if (reResult = re.exec(rect.aspectRatio)) { - profileAspectRatio = Number(reResult[1]) / Number(reResult[2]); - } - - var diff = Math.abs(profileAspectRatio - videoAspectRatio); - - if (minDiff > diff) { - minDiff = diff; - result = rect; - } - }); - return result; - } - - function applyProfileWithJson(profileData, animate) { - var _this11 = this; - - if (animate == undefined) animate = true; - if (!profileData) return; - - var getProfile = function getProfile(content) { - var result = null; - profileData && profileData.videos.some(function (videoProfile) { - if (videoProfile.content == content) { - result = videoProfile; - } - - return result != null; - }); - return result; - }; - - var applyVideoRect = function applyVideoRect(profile, videoData, videoWrapper, player) { - var frameStrategy = _this11.profileFrameStrategy; - - if (frameStrategy) { - var rect = getClosestRect(profile, videoData.res); - var videoSize = videoData.res; - var containerSize = { - width: $(_this11.domElement).width(), - height: $(_this11.domElement).height() - }; - var scaleFactor = rect.width / containerSize.width; - var scaledVideoSize = { - width: videoSize.w * scaleFactor, - height: videoSize.h * scaleFactor - }; - rect.left = Number(rect.left); - rect.top = Number(rect.top); - rect.width = Number(rect.width); - rect.height = Number(rect.height); - rect = frameStrategy.adaptFrame(scaledVideoSize, rect); - var visible = /true/i.test(profile.visible); - rect.visible = visible; - var layer = parseInt(profile.layer); - videoWrapper.domElement.style.zIndex = layer; - videoWrapper.setRect(rect, animate); - videoWrapper.setVisible(visible, animate); // The disable/enable functions may not be called on main audio player - - var isMainAudioPlayer = paella.player.videoContainer.streamProvider.mainAudioPlayer == player; - visible ? player.enable(isMainAudioPlayer) : player.disable(isMainAudioPlayer); - } - }; - - profileData && profileData.onApply(); - hideAllLogos.apply(this); - profileData && showLogos.apply(this, [profileData.logos]); - hideBackground.apply(this); - profileData && showBackground.apply(this, [profileData.background]); - hideButtons.apply(this); - profileData && showButtons.apply(this, [profileData.buttons, profileData]); - this.streamProvider.videoStreams.forEach(function (streamData, index) { - var profile = getProfile(streamData.content); - var player = _this11.streamProvider.videoPlayers[index]; - var videoWrapper = _this11.videoWrappers[index]; - - if (profile) { - player.getVideoData().then(function (data) { - applyVideoRect(profile, data, videoWrapper, player); - }); - } else if (videoWrapper) { - videoWrapper.setVisible(false, animate); - player.disable(paella.player.videoContainer.streamProvider.mainAudioPlayer == player); - } - }); - } - - var profileReloadCount = 0; - var maxProfileReloadCunt = 20; - - var Profiles = /*#__PURE__*/function () { - function Profiles() { - var _this12 = this; - - _classCallCheck(this, Profiles); - - paella.events.bind(paella.events.controlBarDidHide, function () { - return _this12.hideButtons(); - }); - paella.events.bind(paella.events.controlBarDidShow, function () { - return _this12.showButtons(); - }); - paella.events.bind(paella.events.profileListChanged, function () { - if (paella.player && paella.player.videoContainer && (!_this12.currentProfile || _this12.currentProfileName != _this12.currentProfile.id)) { - _this12.setProfile(_this12.currentProfileName, false); - } - }); - } - - _createClass(Profiles, [{ - key: "profileList", - get: function get() { - return g_profiles; - } - }, { - key: "getDefaultProfile", - value: function getDefaultProfile() { - if (paella.player.videoContainer.masterVideo() && paella.player.videoContainer.masterVideo().defaultProfile()) { - return paella.player.videoContainer.masterVideo().defaultProfile(); - } - - if (paella.player && paella.player.config && paella.player.config.defaultProfile) { - return paella.player.config.defaultProfile; - } - - return undefined; - } - }, { - key: "loadProfile", - value: function loadProfile(profileId) { - var result = null; - g_profiles.some(function (profile) { - if (profile.id == profileId) { - result = profile; - } - - return result; - }); - return result; - } - }, { - key: "currentProfile", - get: function get() { - return this.getProfile(this._currentProfileName); - } - }, { - key: "currentProfileName", - get: function get() { - return this._currentProfileName; - } - }, { - key: "setProfile", - value: function setProfile(profileName, animate) { - var _this13 = this; - - if (!profileName) { - return false; - } - - animate = paella.utils.userAgent.browser.Explorer ? false : animate; - - if (this.currentProfile) { - this.currentProfile.onDeactivate(); - } - - if (!paella.player.videoContainer.ready) { - return false; // Nothing to do, the video is not loaded - } else { - var profileData = this.loadProfile(profileName) || g_profiles.length > 0 && g_profiles[0]; - - if (!profileData && g_profiles.length == 0) { - if (profileReloadCount < maxProfileReloadCunt) { - profileReloadCount++; // Try to load the profile again later, maybe the profiles are not loaded yet - - setTimeout(function () { - _this13.setProfile(profileName, animate); - }, 100); - return false; - } else { - console.error("No valid video layout profiles were found. Check that the 'content' attribute setting in 'videoSets', at config.json file, matches the 'content' property in the video manifest."); - return false; - } - } else { - this._currentProfileName = profileName; - applyProfileWithJson.apply(paella.player.videoContainer, [profileData, animate]); - return true; - } - } - } - }, { - key: "getProfile", - value: function getProfile(profileName) { - var result = null; - this.profileList.some(function (p) { - if (p.id == profileName) { - result = p; - return true; - } - }); - return result; - } - }, { - key: "placeVideos", - value: function placeVideos() { - this.setProfile(this._currentProfileName, false); - } - }, { - key: "hideButtons", - value: function hideButtons() { - $('.paella-profile-button').hide(); - } - }, { - key: "showButtons", - value: function showButtons() { - $('.paella-profile-button').show(); - } - }]); - - return Profiles; - }(); - - paella.profiles = new Profiles(); -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ - - -(function () { - var VideoQualityStrategy = /*#__PURE__*/function () { - function VideoQualityStrategy() { - _classCallCheck(this, VideoQualityStrategy); - } - - _createClass(VideoQualityStrategy, [{ - key: "getParams", - value: function getParams() { - return paella.player.config.player.videoQualityStrategyParams || {}; - } - }, { - key: "getQualityIndex", - value: function getQualityIndex(source) { - if (source.length > 0) { - return source[source.length - 1]; - } else { - return source; - } - } - }], [{ - key: "Factory", - value: function Factory() { - var config = paella.player.config; - - try { - var strategyClass = config.player.videoQualityStrategy; - var ClassObject = paella.utils.objectFromString(strategyClass); - var strategy = new ClassObject(); - - if (strategy instanceof paella.VideoQualityStrategy) { - return strategy; - } - } catch (e) {} - - return null; - } - }]); - - return VideoQualityStrategy; - }(); - - paella.VideoQualityStrategy = VideoQualityStrategy; - - var BestFitVideoQualityStrategy = /*#__PURE__*/function (_paella$VideoQualityS) { - _inherits(BestFitVideoQualityStrategy, _paella$VideoQualityS); - - var _super6 = _createSuper(BestFitVideoQualityStrategy); - - function BestFitVideoQualityStrategy() { - _classCallCheck(this, BestFitVideoQualityStrategy); - - return _super6.apply(this, arguments); - } - - _createClass(BestFitVideoQualityStrategy, [{ - key: "getQualityIndex", - value: function getQualityIndex(source) { - var index = source.length - 1; - - if (source.length > 0) { - var selected = source[0]; - var win_w = $(window).width(); - var win_h = $(window).height(); - var win_res = win_w * win_h; - - if (selected.res && selected.res.w && selected.res.h) { - var selected_res = parseInt(selected.res.w) * parseInt(selected.res.h); - var selected_diff = Math.abs(win_res - selected_res); - - for (var i = 0; i < source.length; ++i) { - var res = source[i].res; - - if (res) { - var m_res = parseInt(source[i].res.w) * parseInt(source[i].res.h); - var m_diff = Math.abs(win_res - m_res); - - if (m_diff <= selected_diff) { - selected_diff = m_diff; - index = i; - } - } - } - } - } - - return index; - } - }]); - - return BestFitVideoQualityStrategy; - }(paella.VideoQualityStrategy); - - paella.BestFitVideoQualityStrategy = BestFitVideoQualityStrategy; - - var LimitedBestFitVideoQualityStrategy = /*#__PURE__*/function (_paella$VideoQualityS2) { - _inherits(LimitedBestFitVideoQualityStrategy, _paella$VideoQualityS2); - - var _super7 = _createSuper(LimitedBestFitVideoQualityStrategy); - - function LimitedBestFitVideoQualityStrategy() { - _classCallCheck(this, LimitedBestFitVideoQualityStrategy); - - return _super7.apply(this, arguments); - } - - _createClass(LimitedBestFitVideoQualityStrategy, [{ - key: "getQualityIndex", - value: function getQualityIndex(source) { - var index = source.length - 1; - var params = this.getParams(); - - if (source.length > 0) { - //var selected = source[0]; - var selected = null; - var win_h = $(window).height(); - var maxRes = params.maxAutoQualityRes || 720; - var diff = Number.MAX_VALUE; - source.forEach(function (item, i) { - if (item.res && item.res.h <= maxRes) { - var itemDiff = Math.abs(win_h - item.res.h); - - if (itemDiff < diff) { - selected = item; - index = i; - } - } - }); - } - - return index; - } - }]); - - return LimitedBestFitVideoQualityStrategy; - }(paella.VideoQualityStrategy); - - paella.LimitedBestFitVideoQualityStrategy = LimitedBestFitVideoQualityStrategy; - - var VideoFactory = /*#__PURE__*/function () { - function VideoFactory() { - _classCallCheck(this, VideoFactory); - } - - _createClass(VideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return false; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - return null; - } - }]); - - return VideoFactory; - }(); - - paella.VideoFactory = VideoFactory; - paella.videoFactories = paella.videoFactories || {}; - paella.videoFactory = { - _factoryList: [], - initFactories: function initFactories() { - if (paella.videoFactories) { - var This = this; - paella.player.config.player.methods.forEach(function (method) { - if (method.enabled && paella.videoFactories[method.factory]) { - This.registerFactory(new paella.videoFactories[method.factory]()); - } - }); - this.registerFactory(new paella.videoFactories.EmptyVideoFactory()); - } - }, - getVideoObject: function getVideoObject(id, streamData, rect) { - if (this._factoryList.length == 0) { - this.initFactories(); - } - - var selectedFactory = null; - - if (this._factoryList.some(function (factory) { - if (factory.isStreamCompatible(streamData)) { - selectedFactory = factory; - return true; - } - })) { - return selectedFactory.getVideoObject(id, streamData, rect); - } - - return null; - }, - registerFactory: function registerFactory(factory) { - this._factoryList.push(factory); - } - }; -})(); - -(function () { - var AudioElementBase = /*#__PURE__*/function (_paella$DomNode2) { - _inherits(AudioElementBase, _paella$DomNode2); - - var _super8 = _createSuper(AudioElementBase); - - function AudioElementBase(id, stream) { - var _this14; - - _classCallCheck(this, AudioElementBase); - - _this14 = _super8.call(this, 'div', id); - _this14._stream = stream; - _this14._ready = false; - return _this14; - } - - _createClass(AudioElementBase, [{ - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "currentTimeSync", - get: function get() { - return null; - } - }, { - key: "volumeSync", - get: function get() { - return null; - } - }, { - key: "pausedSync", - get: function get() { - return null; - } - }, { - key: "durationSync", - get: function get() { - return null; - } - }, { - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "setAutoplay", - value: function setAutoplay() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "load", - value: function load() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "play", - value: function play() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "pause", - value: function pause() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "isPaused", - value: function isPaused() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "duration", - value: function duration() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "currentTime", - value: function currentTime() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "volume", - value: function volume() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "playbackRate", - value: function playbackRate() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "unload", - value: function unload() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "getQualities", - value: function getQualities() { - return Promise.resolve([{ - index: 0, - res: { - w: 0, - h: 1 - }, - src: "", - toString: function toString() { - return ""; - }, - shortLabel: function shortLabel() { - return ""; - }, - compare: function compare() { - return 0; - } - }]); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - return Promise.resolve(0); - } - }, { - key: "defaultProfile", - value: function defaultProfile() { - return null; - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return false; - } - }]); - - return AudioElementBase; - }(paella.DomNode); - - ; - paella.AudioElementBase = AudioElementBase; - paella.audioFactories = {}; - - var AudioFactory = /*#__PURE__*/function () { - function AudioFactory() { - _classCallCheck(this, AudioFactory); - } - - _createClass(AudioFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return false; - } - }, { - key: "getAudioObject", - value: function getAudioObject(id, streamData) { - return null; - } - }]); - - return AudioFactory; - }(); - - paella.AudioFactory = AudioFactory; - paella.audioFactory = { - _factoryList: [], - initFactories: function initFactories() { - if (paella.audioFactories) { - var This = this; - paella.player.config.player.audioMethods = paella.player.config.player.audioMethods || {}; - paella.player.config.player.audioMethods.forEach(function (method) { - if (method.enabled) { - This.registerFactory(new paella.audioFactories[method.factory]()); - } - }); - } - }, - getAudioObject: function getAudioObject(id, streamData) { - if (this._factoryList.length == 0) { - this.initFactories(); - } - - var selectedFactory = null; - - if (this._factoryList.some(function (factory) { - if (factory.isStreamCompatible(streamData)) { - selectedFactory = factory; - return true; - } - })) { - return selectedFactory.getAudioObject(id, streamData); - } - - return null; - }, - registerFactory: function registerFactory(factory) { - this._factoryList.push(factory); - } - }; -})(); - -(function () { - function checkReady(cb) { - var This = this; - return new Promise(function (resolve, reject) { - if (This._ready) { - resolve(typeof cb == 'function' ? cb() : true); - } else { - function doCheck() { - if (This.audio.readyState >= This.audio.HAVE_CURRENT_DATA) { - This._ready = true; - resolve(typeof cb == 'function' ? cb() : true); - } else { - setTimeout(doCheck, 50); - } - } - - doCheck(); - } - }); - } - - var MultiformatAudioElement = /*#__PURE__*/function (_paella$AudioElementB) { - _inherits(MultiformatAudioElement, _paella$AudioElementB); - - var _super9 = _createSuper(MultiformatAudioElement); - - function MultiformatAudioElement(id, stream) { - var _this15; - - _classCallCheck(this, MultiformatAudioElement); - - _this15 = _super9.call(this, id, stream); - _this15._streamName = "audio"; - _this15._audio = document.createElement('audio'); - - _this15.domElement.appendChild(_this15._audio); - - return _this15; - } - - _createClass(MultiformatAudioElement, [{ - key: "buffered", - get: function get() { - return this.audio && this.audio.buffered; - } - }, { - key: "audio", - get: function get() { - return this._audio; - } - }, { - key: "currentTimeSync", - get: function get() { - return this.ready ? this.audio.currentTimeSync : null; - } - }, { - key: "volumeSync", - get: function get() { - return this.ready ? this.audio.volumeSync : null; - } - }, { - key: "pausedSync", - get: function get() { - return this.ready ? this.audio.pausedSync : null; - } - }, { - key: "durationSync", - get: function get() { - return this.ready ? this.audio.durationSync : null; - } - }, { - key: "setAutoplay", - value: function setAutoplay(ap) { - this.audio.autoplay = ap; - } - }, { - key: "load", - value: function load() { - var This = this; - var sources = this._stream.sources[this._streamName]; - var stream = sources.length > 0 ? sources[0] : null; - this.audio.innerText = ""; - - if (stream) { - var sourceElem = this.audio.querySelector('source'); - - if (!sourceElem) { - sourceElem = document.createElement('source'); - this.audio.appendChild(sourceElem); - } - - sourceElem.src = stream.src; - if (stream.type) sourceElem.type = stream.type; - this.audio.load(); - return checkReady.apply(this, [function () { - return stream; - }]); - } else { - return Promise.reject(new Error("Could not load video: invalid quality stream index")); - } - } - }, { - key: "play", - value: function play() { - var _this16 = this; - - return checkReady.apply(this, [function () { - _this16.audio.play(); - }]); - } - }, { - key: "pause", - value: function pause() { - var _this17 = this; - - return checkReady.apply(this, [function () { - _this17.audio.pause(); - }]); - } - }, { - key: "isPaused", - value: function isPaused() { - var _this18 = this; - - return checkReady.apply(this, [function () { - return _this18.audio.paused; - }]); - } - }, { - key: "duration", - value: function duration() { - var _this19 = this; - - return checkReady.apply(this, [function () { - return _this19.audio.duration; - }]); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this20 = this; - - return checkReady.apply(this, [function () { - _this20.audio.currentTime = time; - }]); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this21 = this; - - return checkReady.apply(this, [function () { - return _this21.audio.currentTime; - }]); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - var _this22 = this; - - return checkReady.apply(this, [function () { - return _this22.audio.volume = volume; - }]); - } - }, { - key: "volume", - value: function volume() { - var _this23 = this; - - return checkReady.apply(this, [function () { - return _this23.audio.volume; - }]); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - var _this24 = this; - - return checkReady.apply(this, [function () { - _this24.audio.playbackRate = rate; - }]); - } - }, { - key: "playbackRate", - value: function playbackRate() { - var _this25 = this; - - return checkReady.apply(this, [function () { - return _this25.audio.playbackRate; - }]); - } - }, { - key: "unload", - value: function unload() { - return Promise.resolve(); - } - }]); - - return MultiformatAudioElement; - }(paella.AudioElementBase); - - ; - paella.MultiformatAudioElement = MultiformatAudioElement; - - var MultiformatAudioFactory = /*#__PURE__*/function () { - function MultiformatAudioFactory() { - _classCallCheck(this, MultiformatAudioFactory); - } - - _createClass(MultiformatAudioFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return true; - } - }, { - key: "getAudioObject", - value: function getAudioObject(id, streamData) { - return new paella.MultiformatAudioElement(id, streamData); - } - }]); - - return MultiformatAudioFactory; - }(); - - paella.audioFactories.MultiformatAudioFactory = MultiformatAudioFactory; -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ - - -(function () { - paella.Profiles = { - profileList: null, - getDefaultProfile: function getDefaultProfile() { - if (paella.player.videoContainer.masterVideo() && paella.player.videoContainer.masterVideo().defaultProfile()) { - return paella.player.videoContainer.masterVideo().defaultProfile(); - } - - if (paella.player && paella.player.config && paella.player.config.defaultProfile) { - return paella.player.config.defaultProfile; - } - - return undefined; - }, - loadProfile: function loadProfile(profileName, onSuccessFunction) { - var defaultProfile = this.getDefaultProfile(); - this.loadProfileList(function (data) { - var profileData; - - if (data[profileName]) { - // Successful mapping - profileData = data[profileName]; - } else if (data[defaultProfile]) { - // Fallback to default profile - profileData = data[defaultProfile]; - } else { - // Unable to find or map defaultProfile in profiles.json - paella.log.debug("Error loading the default profile. Check your Paella Player configuration"); - return false; - } - - onSuccessFunction(profileData); - }); - }, - loadProfileList: function loadProfileList(onSuccessFunction) { - var thisClass = this; - - if (this.profileList == null) { - var params = { - url: paella.utils.folders.profiles() + "/profiles.json" - }; - paella.utils.ajax.get(params, function (data, mimetype, code) { - if (typeof data == "string") { - data = JSON.parse(data); - } - - thisClass.profileList = data; - onSuccessFunction(thisClass.profileList); - }, function (data, mimetype, code) { - paella.log.debug("Error loading video profiles. Check your Paella Player configuration"); - }); - } else { - onSuccessFunction(thisClass.profileList); - } - } - }; - - var RelativeVideoSize = /*#__PURE__*/function () { - function RelativeVideoSize() { - _classCallCheck(this, RelativeVideoSize); - } - - _createClass(RelativeVideoSize, [{ - key: "w", - get: function get() { - return this._w || 1280; - }, - set: function set(v) { - this._w = v; - } - }, { - key: "h", - get: function get() { - return this._h || 720; - }, - set: function set(v) { - this._h = v; - } - }, { - key: "proportionalHeight", - value: function proportionalHeight(newWidth) { - return Math.floor(this.h * newWidth / this.w); - } - }, { - key: "proportionalWidth", - value: function proportionalWidth(newHeight) { - return Math.floor(this.w * newHeight / this.h); - } - }, { - key: "percentVSize", - value: function percentVSize(pxSize) { - return pxSize * 100 / this.h; - } - }, { - key: "percentWSize", - value: function percentWSize(pxSize) { - return pxSize * 100 / this.w; - } - }, { - key: "aspectRatio", - value: function aspectRatio() { - return this.w / this.h; - } - }]); - - return RelativeVideoSize; - }(); - - paella.RelativeVideoSize = RelativeVideoSize; - - var VideoRect = /*#__PURE__*/function (_paella$DomNode3) { - _inherits(VideoRect, _paella$DomNode3); - - var _super10 = _createSuper(VideoRect); - - function VideoRect(id, domType, left, top, width, height) { - var _this26; - - _classCallCheck(this, VideoRect); - - _this26 = _super10.call(this, domType, id, {}); - var zoomSettings = paella.player.config.player.videoZoom || {}; - - var zoomEnabled = (zoomSettings.enabled !== undefined ? zoomSettings.enabled : true) && _this26.allowZoom(); - - _this26.style = zoomEnabled ? { - width: _this26._zoom + '%', - height: "100%", - position: 'absolute' - } : { - width: "100%", - height: "100%" - }; - _this26._rect = null; - var eventCapture = document.createElement('div'); - setTimeout(function () { - return _this26.domElement.parentElement.appendChild(eventCapture); - }, 10); - eventCapture.id = id + "EventCapture"; - eventCapture.style.position = "absolute"; - eventCapture.style.top = "0px"; - eventCapture.style.left = "0px"; - eventCapture.style.right = "0px"; - eventCapture.style.bottom = "0px"; - _this26.eventCapture = eventCapture; - - if (zoomEnabled) { - _this26._zoomAvailable = true; - - function checkZoomAvailable() { - var minWindowSize = paella.player.config.player && paella.player.config.player.videoZoom && paella.player.config.player.videoZoom.minWindowSize || 500; - var available = $(window).width() >= minWindowSize; - - if (this._zoomAvailable != available) { - this._zoomAvailable = available; - paella.events.trigger(paella.events.zoomAvailabilityChanged, { - available: available - }); - } - } - - checkZoomAvailable.apply(_assertThisInitialized(_this26)); - $(window).resize(function () { - checkZoomAvailable.apply(_assertThisInitialized(_this26)); - }); - _this26._zoom = 100; - _this26._mouseCenter = { - x: 0, - y: 0 - }; - _this26._mouseDown = { - x: 0, - y: 0 - }; - _this26._zoomOffset = { - x: 0, - y: 0 - }; - _this26._maxZoom = zoomSettings.max || 400; - $(_this26.domElement).css({ - width: "100%", - height: "100%", - left: "0%", - top: "0%" - }); - Object.defineProperty(_assertThisInitialized(_this26), 'zoom', { - get: function get() { - return this._zoom; - } - }); - Object.defineProperty(_assertThisInitialized(_this26), 'zoomOffset', { - get: function get() { - return this._zoomOffset; - } - }); - - function mousePos(evt) { - return { - x: evt.originalEvent.offsetX, - y: evt.originalEvent.offsetY - }; - } - - function wheelDelta(evt) { - var wheel = evt.originalEvent.deltaY * (paella.utils.userAgent.Firefox ? 2 : 1); - var maxWheel = 6; - return -Math.abs(wheel) < maxWheel ? wheel : maxWheel * Math.sign(wheel); - } - - function touchesLength(p0, p1) { - return Math.sqrt((p1.x - p0.x) * (p1.x - p0.x) + (p1.y - p0.y) * (p1.y - p0.y)); - } - - function centerPoint(p0, p1) { - return { - x: (p1.x - p0.x) / 2 + p0.x, - y: (p1.y - p0.y) / 2 + p0.y - }; - } - - function panImage(o) { - var center = { - x: this._mouseCenter.x - o.x * 1.1, - y: this._mouseCenter.y - o.y * 1.1 - }; - var videoSize = { - w: $(this.domElement).width(), - h: $(this.domElement).height() - }; - var maxOffset = this._zoom - 100; - var offset = { - x: center.x * maxOffset / videoSize.w * (maxOffset / 100), - y: center.y * maxOffset / videoSize.h * (maxOffset / 100) - }; - - if (offset.x > maxOffset) { - offset.x = maxOffset; - } else if (offset.x < 0) { - offset.x = 0; - } else { - this._mouseCenter.x = center.x; - } - - if (offset.y > maxOffset) { - offset.y = maxOffset; - } else if (offset.y < 0) { - offset.y = 0; - } else { - this._mouseCenter.y = center.y; - } - - $(this.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - this._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: this - }); - } - - var touches = []; - $(eventCapture).on('touchstart', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - touches = []; - var videoOffset = $(_this26.domElement).offset(); - - for (var i = 0; i < evt.originalEvent.targetTouches.length; ++i) { - var touch = evt.originalEvent.targetTouches[i]; - touches.push({ - x: touch.screenX - videoOffset.left, - y: touch.screenY - videoOffset.top - }); - } - - if (touches.length > 1) evt.preventDefault(); - }); - $(eventCapture).on('touchmove', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - var curTouches = []; - var videoOffset = $(_this26.domElement).offset(); - - for (var i = 0; i < evt.originalEvent.targetTouches.length; ++i) { - var touch = evt.originalEvent.targetTouches[i]; - curTouches.push({ - x: touch.screenX - videoOffset.left, - y: touch.screenY - videoOffset.top - }); - } - - if (curTouches.length > 1 && touches.length > 1) { - var l0 = touchesLength(touches[0], touches[1]); - var l1 = touchesLength(curTouches[0], curTouches[1]); - var delta = l1 - l0; - var center = centerPoint(touches[0], touches[1]); - _this26._mouseCenter = center; - _this26._zoom += delta; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - var mouse = _this26._mouseCenter; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w, - y: mouse.y * maxOffset / newVideoSize.h - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - touches = curTouches; - evt.preventDefault(); - } else if (curTouches.length > 0) { - var desp = { - x: curTouches[0].x - touches[0].x, - y: curTouches[0].y - touches[0].y - }; - panImage.apply(_assertThisInitialized(_this26), [desp]); - touches = curTouches; - evt.preventDefault(); - } - }); - $(eventCapture).on('touchend', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - if (touches.length > 1) evt.preventDefault(); - }); - - _this26.zoomIn = function () { - if (_this26._zoom >= _this26._maxZoom || !_this26._zoomAvailable) return; - - if (!_this26._mouseCenter) { - _this26._mouseCenter = { - x: $(_this26.domElement).width() / 2, - y: $(_this26.domElement).height() / 2 - }; - } - - _this26._zoom += 25; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - var mouse = _this26._mouseCenter; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w * (maxOffset / 100), - y: mouse.y * maxOffset / newVideoSize.h * (maxOffset / 100) - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - }; - - _this26.zoomOut = function () { - if (_this26._zoom <= 100 || !_this26._zoomAvailable) return; - - if (!_this26._mouseCenter) { - _this26._mouseCenter = { - x: $(_this26.domElement).width() / 2, - y: $(_this26.domElement).height() / 2 - }; - } - - _this26._zoom -= 25; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - var mouse = _this26._mouseCenter; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w * (maxOffset / 100), - y: mouse.y * maxOffset / newVideoSize.h * (maxOffset / 100) - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - }; - - var altScrollMessageContainer = document.createElement('div'); - altScrollMessageContainer.className = "alt-scroll-message-container"; - altScrollMessageContainer.innerHTML = "

" + paella.utils.dictionary.translate("Use Alt+Scroll to zoom the video") + "

"; - eventCapture.appendChild(altScrollMessageContainer); - $(altScrollMessageContainer).css({ - opacity: 0.0 - }); - var altScrollMessageTimer = null; - - function clearAltScrollMessage() { - var animate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - animate ? $(altScrollMessageContainer).animate({ - opacity: 0.0 - }) : $(altScrollMessageContainer).css({ - opacity: 0.0 - }); - } - - function showAltScrollMessage() { - if (altScrollMessageTimer) { - clearTimeout(altScrollMessageTimer); - altScrollMessageTimer = null; - } else { - $(altScrollMessageContainer).css({ - opacity: 1.0 - }); - } - - altScrollMessageTimer = setTimeout(function () { - clearAltScrollMessage(); - altScrollMessageTimer = null; - }, 500); - } - - $(eventCapture).on('mousewheel wheel', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - - if (!evt.altKey) { - showAltScrollMessage(); - return; - } else { - clearAltScrollMessage(false); - - if (altScrollMessageTimer) { - clearTimeout(altScrollMessageTimer); - altScrollMessageTimer = null; - } - } - - var mouse = mousePos(evt); - var wheel = wheelDelta(evt); - if (_this26._zoom >= _this26._maxZoom && wheel > 0) return; - _this26._zoom += wheel; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w * (maxOffset / 100), - y: mouse.y * maxOffset / newVideoSize.h * (maxOffset / 100) - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - _this26._mouseCenter = mouse; - evt.stopPropagation(); - return false; - }); - $(eventCapture).on('mousedown', function (evt) { - _this26._mouseDown = mousePos(evt); - _this26.drag = true; - }); - $(eventCapture).on('mousemove', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - var mouse = mousePos(evt); - var offset = { - x: mouse.x - _this26._mouseDown.x, - y: mouse.y - _this26._mouseDown.y - }; // We have not found out why there are sometimes sudden jumps in the - // position of the mouse cursos, so we avoid the problem - - if ((Math.abs(offset.x) > 80 || Math.abs(_this26.y) > 80) && _this26.drag) { - _this26._mouseDown = mouse; - return; - } - - _this26.drag = evt.buttons > 0; - - if (_this26.drag) { - paella.player.videoContainer.disablePlayOnClick(); - panImage.apply(_assertThisInitialized(_this26), [offset]); - _this26._mouseDown = mouse; - } - }); - $(eventCapture).on('mouseup', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - _this26.drag = false; - paella.player.videoContainer.enablePlayOnClick(1000); - }); - $(eventCapture).on('mouseleave', function (evt) { - _this26.drag = false; - }); - } - - return _this26; - } - - _createClass(VideoRect, [{ - key: "canvasData", - get: function get() { - var canvasType = this._stream && Array.isArray(this._stream.canvas) && this._stream.canvas[0]; - - var canvasData = canvasType && paella.getVideoCanvasData(this._stream.canvas[0]) || { - mouseEventsSupport: false, - webglSupport: false - }; - return canvasData; - } - }, { - key: "allowZoom", - value: function allowZoom() { - return !this.canvasData.mouseEventsSupport; - } - }, { - key: "setZoom", - value: function setZoom(zoom, left, top) { - var tween = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - - if (this.zoomAvailable()) { - this._zoomOffset.x = left; - this._zoomOffset.y = top; - this._zoom = zoom; - - if (tween == 0) { - $(this.domElement).css({ - width: this._zoom + '%', - height: this._zoom + '%', - left: "-" + this._zoomOffset.x + "%", - top: "-" + this._zoomOffset.y + "%" - }); - } else { - $(this.domElement).stop(true, false).animate({ - width: this._zoom + '%', - height: this._zoom + '%', - left: "-" + this._zoomOffset.x + "%", - top: "-" + this._zoomOffset.y + "%" - }, tween, "linear"); - } - - paella.events.trigger(paella.events.videoZoomChanged, { - video: this - }); - } - } - }, { - key: "captureFrame", - value: function captureFrame() { - return Promise.resolve(null); - } - }, { - key: "supportsCaptureFrame", - value: function supportsCaptureFrame() { - return Promise.resolve(false); - } // zoomAvailable will only return true if the zoom is enabled, the - // video plugin supports zoom and the current video resolution is higher than - // the current video size - - }, { - key: "zoomAvailable", - value: function zoomAvailable() { - return this.allowZoom() && this._zoomAvailable; - } - }, { - key: "disableEventCapture", - value: function disableEventCapture() { - this.eventCapture.style.pointerEvents = 'none'; - } - }, { - key: "enableEventCapture", - value: function enableEventCapture() { - this.eventCapture.style.pointerEvents = ''; - } - }]); - - return VideoRect; - }(paella.DomNode); - - paella.VideoRect = VideoRect; - - var VideoElementBase = /*#__PURE__*/function (_paella$VideoRect) { - _inherits(VideoElementBase, _paella$VideoRect); - - var _super11 = _createSuper(VideoElementBase); - - function VideoElementBase(id, stream, containerType, left, top, width, height) { - var _this27; - - _classCallCheck(this, VideoElementBase); - - _this27 = _super11.call(this, id, containerType, left, top, width, height); - _this27._stream = stream; - _this27._ready = false; - _this27._autoplay = false; - _this27._videoQualityStrategy = null; - if (_this27._stream.preview) _this27.setPosterFrame(_this27._stream.preview); - - if (_this27.canvasData.mouseEventsSupport) { - _this27.disableEventCapture(); - } - - return _this27; - } - - _createClass(VideoElementBase, [{ - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "defaultProfile", - value: function defaultProfile() { - return null; - } // Synchronous functions: returns null if the resource is not loaded. Use only if - // the resource is loaded. - - }, { - key: "currentTimeSync", - get: function get() { - return null; - } - }, { - key: "volumeSync", - get: function get() { - return null; - } - }, { - key: "pausedSync", - get: function get() { - return null; - } - }, { - key: "durationSync", - get: function get() { - return null; - } // Initialization functions - - }, { - key: "setVideoQualityStrategy", - value: function setVideoQualityStrategy(strategy) { - this._videoQualityStrategy = strategy; - } - }, { - key: "setPosterFrame", - value: function setPosterFrame(url) { - paella.log.debug("TODO: implement setPosterFrame() function"); - } - }, { - key: "setAutoplay", - value: function setAutoplay(autoplay) { - this._autoplay = autoplay; - } - }, { - key: "setMetadata", - value: function setMetadata(data) { - this._metadata = data; - } - }, { - key: "load", - value: function load() { - return paella_DeferredNotImplemented(); - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return true; - } // Video canvas functions - - }, { - key: "videoCanvas", - value: function videoCanvas() { - return Promise.reject(new Error("VideoElementBase::videoCanvas(): Not implemented in child class.")); - } // Multi audio functions - - }, { - key: "supportsMultiaudio", - value: function supportsMultiaudio() { - return Promise.resolve(false); - } - }, { - key: "getAudioTracks", - value: function getAudioTracks() { - return Promise.resolve([]); - } - }, { - key: "setCurrentAudioTrack", - value: function setCurrentAudioTrack(trackId) { - return Promise.resolve(false); - } - }, { - key: "getCurrentAudioTrack", - value: function getCurrentAudioTrack() { - return Promise.resolve(-1); - } // Playback functions - - }, { - key: "getVideoData", - value: function getVideoData() { - return paella_DeferredNotImplemented(); - } - }, { - key: "play", - value: function play() { - paella.log.debug("TODO: implement play() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "pause", - value: function pause() { - paella.log.debug("TODO: implement pause() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "isPaused", - value: function isPaused() { - paella.log.debug("TODO: implement isPaused() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "duration", - value: function duration() { - paella.log.debug("TODO: implement duration() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - paella.log.debug("TODO: implement setCurrentTime() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "currentTime", - value: function currentTime() { - paella.log.debug("TODO: implement currentTime() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - paella.log.debug("TODO: implement setVolume() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "volume", - value: function volume() { - paella.log.debug("TODO: implement volume() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - paella.log.debug("TODO: implement setPlaybackRate() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "playbackRate", - value: function playbackRate() { - paella.log.debug("TODO: implement playbackRate() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "getQualities", - value: function getQualities() { - return paella_DeferredNotImplemented(); - } - }, { - key: "setQuality", - value: function setQuality(index) { - return paella_DeferredNotImplemented(); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - return paella_DeferredNotImplemented(); - } - }, { - key: "unload", - value: function unload() { - this._callUnloadEvent(); - - return paella_DeferredNotImplemented(); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredNotImplemented(); // { width:X, height:Y } - } - }, { - key: "goFullScreen", - value: function goFullScreen() { - return paella_DeferredNotImplemented(); - } - }, { - key: "freeze", - value: function freeze() { - return paella_DeferredNotImplemented(); - } - }, { - key: "unFreeze", - value: function unFreeze() { - return paella_DeferredNotImplemented(); - } - }, { - key: "disable", - value: function disable(isMainAudioPlayer) { - console.log("Disable video requested"); - } - }, { - key: "enable", - value: function enable(isMainAudioPlayer) { - console.log("Enable video requested"); - } // Utility functions - - }, { - key: "setClassName", - value: function setClassName(className) { - this.domElement.className = className; - } - }, { - key: "_callReadyEvent", - value: function _callReadyEvent() { - paella.events.trigger(paella.events.singleVideoReady, { - sender: this - }); - } - }, { - key: "_callUnloadEvent", - value: function _callUnloadEvent() { - paella.events.trigger(paella.events.singleVideoUnloaded, { - sender: this - }); - } - }]); - - return VideoElementBase; - }(paella.VideoRect); - - paella.VideoElementBase = VideoElementBase; - - var EmptyVideo = /*#__PURE__*/function (_paella$VideoElementB) { - _inherits(EmptyVideo, _paella$VideoElementB); - - var _super12 = _createSuper(EmptyVideo); - - function EmptyVideo(id, stream, left, top, width, height) { - _classCallCheck(this, EmptyVideo); - - return _super12.call(this, id, stream, 'div', left, top, width, height); - } // Initialization functions - - - _createClass(EmptyVideo, [{ - key: "setPosterFrame", - value: function setPosterFrame(url) {} - }, { - key: "setAutoplay", - value: function setAutoplay(auto) {} - }, { - key: "load", - value: function load() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "play", - value: function play() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "pause", - value: function pause() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "isPaused", - value: function isPaused() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "duration", - value: function duration() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "currentTime", - value: function currentTime() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "volume", - value: function volume() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "playbackRate", - value: function playbackRate() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "unFreeze", - value: function unFreeze() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "freeze", - value: function freeze() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "unload", - value: function unload() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }]); - - return EmptyVideo; - }(paella.VideoElementBase); - - paella.EmptyVideo = EmptyVideo; - - var EmptyVideoFactory = /*#__PURE__*/function (_paella$VideoFactory) { - _inherits(EmptyVideoFactory, _paella$VideoFactory); - - var _super13 = _createSuper(EmptyVideoFactory); - - function EmptyVideoFactory() { - _classCallCheck(this, EmptyVideoFactory); - - return _super13.apply(this, arguments); - } - - _createClass(EmptyVideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return true; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - return new paella.EmptyVideo(id, streamData, rect.x, rect.y, rect.w, rect.h); - } - }]); - - return EmptyVideoFactory; - }(paella.VideoFactory); - - paella.videoFactories.EmptyVideoFactory = EmptyVideoFactory; - - var Html5Video = /*#__PURE__*/function (_paella$VideoElementB2) { - _inherits(Html5Video, _paella$VideoElementB2); - - var _super14 = _createSuper(Html5Video); - - function Html5Video(id, stream, left, top, width, height, streamName) { - var _this28; - - _classCallCheck(this, Html5Video); - - _this28 = _super14.call(this, id, stream, 'video', left, top, width, height); - _this28._currentQuality = null; - _this28._autoplay = false; - _this28._streamName = streamName || 'mp4'; - _this28._playbackRate = 1; - - if (_this28._stream.sources[_this28._streamName]) { - _this28._stream.sources[_this28._streamName].sort(function (a, b) { - return a.res.h - b.res.h; - }); - } - - _this28.video.preload = "auto"; - - _this28.video.setAttribute("playsinline", ""); //this.video.setAttribute("tabindex","-1"); - - - _this28._configureVideoEvents(_this28.video); - - return _this28; - } - - _createClass(Html5Video, [{ - key: "_configureVideoEvents", - value: function _configureVideoEvents(videoElement) { - var _this29 = this; - - function onProgress(event) { - if (!this._ready && this.video.readyState == 4) { - this._ready = true; - - if (this._initialCurrentTipe !== undefined) { - this.video.currentTime = this._initialCurrentTime; - delete this._initialCurrentTime; - } - - this._callReadyEvent(); - } - } - - var evtCallback = function evtCallback(event) { - onProgress.apply(_this29, [event]); - }; - - $(this.video).bind('progress', evtCallback); - $(this.video).bind('loadstart', evtCallback); - $(this.video).bind('loadedmetadata', evtCallback); - $(this.video).bind('canplay', evtCallback); - $(this.video).bind('oncanplay', evtCallback); // Save current time to resume video - - $(this.video).bind('timeupdate', function (evt) { - _this29._resumeCurrentTime = _this29.video.currentTime; - }); - $(this.video).bind('ended', function (evt) { - paella.events.trigger(paella.events.endVideo); - }); - $(this.video).bind('emptied', function (evt) { - if (_this29._resumeCurrentTime && !isNaN(_this29._resumeCurrentTime)) { - _this29.video.currentTime = _this29._resumeCurrentTime; - } - }); // Fix safari setQuelity bug - - if (paella.utils.userAgent.browser.Safari) { - $(this.video).bind('canplay canplaythrough', function (evt) { - _this29._resumeCurrentTime && (_this29.video.currentTime = _this29._resumeCurrentTime); - }); - } - } - }, { - key: "buffered", - get: function get() { - return this.video && this.video.buffered; - } - }, { - key: "video", - get: function get() { - if (this.domElementType == 'video') { - return this.domElement; - } else { - this._video = this._video || document.createElement('video'); - return this._video; - } - } - }, { - key: "ready", - get: function get() { - // Fix Firefox specific issue when video reaches the end - if (paella.utils.userAgent.browser.Firefox && this.video.currentTime == this.video.duration && this.video.readyState == 2) { - this.video.currentTime = 0; - } - - return this.video.readyState >= 3; - } // Synchronous functions: returns null if the resource is not loaded. Use only if - // the resource is loaded. - - }, { - key: "currentTimeSync", - get: function get() { - return this.ready ? this.video.currentTime : null; - } - }, { - key: "volumeSync", - get: function get() { - return this.ready ? this.video.volume : null; - } - }, { - key: "pausedSync", - get: function get() { - return this.ready ? this.video.paused : null; - } - }, { - key: "durationSync", - get: function get() { - return this.ready ? this.video.duration : null; - } - }, { - key: "_deferredAction", - value: function _deferredAction(action) { - var _this30 = this; - - return new Promise(function (resolve, reject) { - function processResult(actionResult) { - if (actionResult instanceof Promise) { - actionResult.then(function (p) { - return resolve(p); - }).catch(function (err) { - return reject(err); - }); - } else { - resolve(actionResult); - } - } - - if (_this30.ready) { - processResult(action()); - } else { - $(_this30.video).bind('canplay', function () { - processResult(action()); - $(_this30.video).unbind('canplay'); - $(_this30.video).unbind('loadedmetadata'); - }); - } - }); - } - }, { - key: "_getQualityObject", - value: function _getQualityObject(index, s) { - return { - index: index, - res: s.res, - src: s.src, - toString: function toString() { - return this.res.w == 0 ? "auto" : this.res.w + "x" + this.res.h; - }, - shortLabel: function shortLabel() { - return this.res.w == 0 ? "auto" : this.res.h + "p"; - }, - compare: function compare(q2) { - return this.res.w * this.res.h - q2.res.w * q2.res.h; - } - }; - } - }, { - key: "captureFrame", - value: function captureFrame() { - var _this31 = this; - - return new Promise(function (resolve) { - resolve({ - source: _this31.video, - width: _this31.video.videoWidth, - height: _this31.video.videoHeight - }); - }); - } - }, { - key: "supportsCaptureFrame", - value: function supportsCaptureFrame() { - return Promise.resolve(true); - } // Initialization functions - - }, { - key: "getVideoData", - value: function getVideoData() { - var _this32 = this; - - var This = this; - return new Promise(function (resolve, reject) { - _this32._deferredAction(function () { - resolve({ - duration: This.video.duration, - currentTime: This.video.currentTime, - volume: This.video.volume, - paused: This.video.paused, - ended: This.video.ended, - res: { - w: This.video.videoWidth, - h: This.video.videoHeight - } - }); - }); - }); - } - }, { - key: "setPosterFrame", - value: function setPosterFrame(url) { - this._posterFrame = url; - } - }, { - key: "setAutoplay", - value: function setAutoplay(auto) { - this._autoplay = auto; - - if (auto && this.video) { - this.video.setAttribute("autoplay", auto); - } - } - }, { - key: "videoCanvas", - value: function videoCanvas() { - var canvasType = this._stream.canvas || ["video"]; - return paella.getVideoCanvas(canvasType); - } - }, { - key: "webGlDidLoad", - value: function webGlDidLoad() { - return Promise.resolve(); - } - }, { - key: "load", - value: function load() { - var _this33 = this; - - return new Promise(function (resolve, reject) { - var sources = _this33._stream.sources[_this33._streamName]; - - if (_this33._currentQuality === null && _this33._videoQualityStrategy) { - _this33._currentQuality = _this33._videoQualityStrategy.getQualityIndex(sources); - } - - var stream = _this33._currentQuality < sources.length ? sources[_this33._currentQuality] : null; - _this33.video.innerText = ""; - - _this33.videoCanvas().then(function (CanvasClass) { - var canvasInstance = new CanvasClass(stream); - _this33._zoomAvailable = canvasInstance.allowZoom(); - - if (window.$paella_bg && bg.app && canvasInstance instanceof bg.app.WindowController) { - // WebGL canvas - _this33.domElementType = 'canvas'; - - if (stream) { - // WebGL engine load callback - return new Promise(function (webglResolve, webglReject) { - _this33.webGlDidLoad().then(function () { - _this33.canvasController = null; - var mainLoop = bg.app.MainLoop.singleton; - mainLoop.updateMode = bg.app.FrameUpdate.AUTO; - mainLoop.canvas = _this33.domElement; - mainLoop.run(canvasInstance); - return _this33.loadVideoStream(canvasInstance, stream); - }).then(function (canvas) { - webglResolve(canvas); - }).catch(function (err) { - return webglReject(err); - }); - }); - } else { - Promise.reject(new Error("Invalid stream data.")); - } - } else { - return _this33.loadVideoStream(canvasInstance, stream); - } - }).then(function (canvas) { - if (canvas && paella.WebGLCanvas && canvas instanceof paella.WebGLCanvas) { - _this33._video = canvas.video; - - _this33._video.pause(); - - _this33._configureVideoEvents(_this33.video); - } - - resolve(stream); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "loadVideoStream", - value: function loadVideoStream(canvasInstance, stream) { - return canvasInstance.loadVideo(this, stream); - } - }, { - key: "disable", - value: function disable(isMainAudioPlayer) {//if (isMainAudioPlayer) return; - //this._isDisabled = true; - //this._playState = !this.video.paused; - //this.video.pause(); - } - }, { - key: "enable", - value: function enable(isMainAudioPlayer) {//if (isMainAudioPlayer) return; - //this._isDisabled = false; - //if (this._playState) { - // this.video.play(); - //} - } - }, { - key: "getQualities", - value: function getQualities() { - var _this34 = this; - - return new Promise(function (resolve, reject) { - setTimeout(function () { - var result = []; - var sources = _this34._stream.sources[_this34._streamName]; - var index = -1; - sources.forEach(function (s) { - index++; - result.push(_this34._getQualityObject(index, s)); - }); - resolve(result); - }, 10); - }); - } - }, { - key: "setQuality", - value: function setQuality(index) { - var _this35 = this; - - return new Promise(function (resolve) { - var paused = _this35.video.paused; - var sources = _this35._stream.sources[_this35._streamName]; - _this35._currentQuality = index < sources.length ? index : 0; - var currentTime = _this35.video.currentTime; - var This = _this35; - - var onSeek = function onSeek() { - This.unFreeze().then(function () { - resolve(); - This.video.removeEventListener('seeked', onSeek, false); - }); - }; - - _this35.freeze().then(function () { - return _this35.load(); - }).then(function () { - if (!paused) { - _this35.play(); - } - - _this35.video.addEventListener('seeked', onSeek); - - _this35.video.currentTime = currentTime; - }); - }); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - var _this36 = this; - - return new Promise(function (resolve) { - resolve(_this36._getQualityObject(_this36._currentQuality, _this36._stream.sources[_this36._streamName][_this36._currentQuality])); - }); - } - }, { - key: "play", - value: function play() { - var _this37 = this; - - return this._deferredAction(function () { - if (!_this37._isDisabled) { - return _this37.video.play(); - } else { - return Promise.resolve(); - } - }); - } - }, { - key: "pause", - value: function pause() { - var _this38 = this; - - return this._deferredAction(function () { - if (!_this38._isDisabled) { - return _this38.video.pause(); - } else { - return Promise.resolve(); - } - }); - } - }, { - key: "isPaused", - value: function isPaused() { - var _this39 = this; - - return this._deferredAction(function () { - return _this39.video.paused; - }); - } - }, { - key: "duration", - value: function duration() { - var _this40 = this; - - return this._deferredAction(function () { - return _this40.video.duration; - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this41 = this; - - return this._deferredAction(function () { - (time == 0 || time) && !isNaN(time) && (_this41.video.currentTime = time); - }); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this42 = this; - - return this._deferredAction(function () { - return _this42.video.currentTime; - }); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - var _this43 = this; - - return this._deferredAction(function () { - _this43.video.volume = volume; - - if (volume == 0) { - _this43.video.setAttribute("muted", "muted"); - - _this43.video.muted = true; - } else { - _this43.video.removeAttribute("muted"); - - _this43.video.muted = false; - } - }); - } - }, { - key: "volume", - value: function volume() { - var _this44 = this; - - return this._deferredAction(function () { - return _this44.video.volume; - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - var _this45 = this; - - return this._deferredAction(function () { - _this45._playbackRate = rate; - _this45.video.playbackRate = rate; - }); - } - }, { - key: "playbackRate", - value: function playbackRate() { - var _this46 = this; - - return this._deferredAction(function () { - return _this46.video.playbackRate; - }); - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - var macOS10_12_safari = paella.utils.userAgent.system.MacOS && paella.utils.userAgent.system.Version.minor >= 12 && paella.utils.userAgent.browser.Safari; - var iOS = paella.utils.userAgent.system.iOS; // Autoplay does not work from Chrome version 64 - - var chrome_v64 = paella.utils.userAgent.browser.Chrome && paella.utils.userAgent.browser.Version.major == 64; - - if (macOS10_12_safari || iOS || chrome_v64) { - return false; - } else { - return true; - } - } - }, { - key: "goFullScreen", - value: function goFullScreen() { - var _this47 = this; - - return this._deferredAction(function () { - var elem = _this47.video; - - if (elem.requestFullscreen) { - elem.requestFullscreen(); - } else if (elem.msRequestFullscreen) { - elem.msRequestFullscreen(); - } else if (elem.mozRequestFullScreen) { - elem.mozRequestFullScreen(); - } else if (elem.webkitEnterFullscreen) { - elem.webkitEnterFullscreen(); - } - }); - } - }, { - key: "unFreeze", - value: function unFreeze() { - var _this48 = this; - - return this._deferredAction(function () { - var c = document.getElementById(_this48.video.id + "canvas"); - - if (c) { - $(c).remove(); - } - }); - } - }, { - key: "freeze", - value: function freeze() { - var This = this; - return this._deferredAction(function () { - var canvas = document.createElement("canvas"); - canvas.id = This.video.id + "canvas"; - canvas.className = "freezeFrame"; - canvas.width = This.video.videoWidth; - canvas.height = This.video.videoHeight; - canvas.style.cssText = This.video.style.cssText; - canvas.style.zIndex = 2; - var ctx = canvas.getContext("2d"); - ctx.drawImage(This.video, 0, 0, Math.ceil(canvas.width / 16) * 16, Math.ceil(canvas.height / 16) * 16); //Draw image - - This.video.parentElement.appendChild(canvas); - }); - } - }, { - key: "unload", - value: function unload() { - this._callUnloadEvent(); - - return paella_DeferredNotImplemented(); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredNotImplemented(); - } - }]); - - return Html5Video; - }(paella.VideoElementBase); - - paella.Html5Video = Html5Video; - - paella.Html5Video.IsAutoplaySupported = function () { - var debug = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return new Promise(function (resolve) { - // Create video element to test autoplay - var video = document.createElement('video'); - video.src = 'data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAC+htZGF0AAACqQYF//+l3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE1NSByMjkwMSA3ZDBmZjIyIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxOCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEgbWU9ZGlhIHN1Ym1lPTEgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MCBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTAgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9MCB0aHJlYWRzPTEgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTEga2V5aW50PTMyMCBrZXlpbnRfbWluPTMyIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByYz1jcmYgbWJ0cmVlPTAgY3JmPTQwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgcGJfcmF0aW89MS4zMCBhcT0xOjEuMDAAgAAAAJBliIQD/2iscx5avG2BdVkxRtUop8zs5zVIqfxQM03W1oVb8spYPP0yjO506xIxgVQ4iSPGOtcDZBVYGqcTatSa730A8XTpnUDpUSrpyaCe/P8eLds/XenOFYMh8UIGMBwzhVOniajqOPFOmmFC20nufGOpJw81hGhgFwCO6a8acwB0P6LNhZZoRD0y2AZMQfEA0AAHAAAACEGaIRiEP5eAANAABwDSGK8UmBURhUGyINeXiuMlXvJnPVVQKigqVGy8PAuVNiWY94iJ/jL/HeT+/usIfmc/dsQ/TV87CTfXhD8C/4xCP3V+DJP8UP3iJdT8okfAuRJF8zkPgh5/J7XzGT8o9pJ+tvlST+g3uwh1330Q9qd4IbnwOQ9dexCHf8mQfVJ57wET8acsIcn6UT6p7yoP2uQ97fFAhrNARXaou2QkEJxrmP6ZBa7TiE6Uqx04OcnChy+OrfwfRWfSYRbS2wmENdDIKUQSkggeXbLb10CIHL5BPgiBydo+HEEPILBbH9zZOdw/77EbN8euVRS/ZcjbZ/D63aLDh1MTme4vfGzFjXkw9r7U8EhcddAmwXGKjo9o53+/8Rnm1rnt6yh3hLD9/htcZnjjGcW9ZQlj6DKIGrrPo/l6C6NyeVr07mB/N6VlGb5fkLBZM42iUNiIGnMJzShmmlFtEsO0mr5CMcFiJdrZQjdIxsYwpU4xlzmD2+oPtjSLVZiDh2lHDRmHubAxXMROEt0z4GkcCYCk832HaXZSM+4vZbUwJa2ysgmfAQMTEM9gxxct7h5xLdrMnHUnB2bXMO2rEnqnnjWHyFYTrzmZTjJ3N4qP+Pv5VHYzZuAa9jnrg35h5hu/Q87uewVnjbJrtcOOm6b9lltPS6n/mkxgxSyqLJVzr/bYt039aTYyhmveJTdeiG7kLfmn9bqjXfxdfZoz53RDcxw+jP7n7TtT8BsB3jUvxe7n5Gbrm9/5QzQ3cxxl9s6ojDMDg3R7Bx//b5rwuSI84z2fuP8/nPxj/wvHNccSL3n77sCEv+AUwlVzHAFkYCkDkdRIORiUg5GJSDkYlIORgKQsjI9E1d0PUP5zV31MSkvI+AAAAAtBmkMYjP/4v5j6wQDGGK/rogCQL/+rZ+PHZ8R11ITSYLDLmXtUdt5a5V+63JHBE/z0/3cCf4av6uOAGtQmr8mCvCxwSI/c7KILm624qm/Kb4fKK5P1GWvX/S84SiSuyTIfk3zVghdRlzZpLZXgddiJjKTGb43OFQCup1nyCbjWgjmOozS6mXGEDsuoVDkSR7/Q8ErEhAZqgHJ5yCxkICvpE+HztDoOSTYiiBCW6shBKQM/Aw5DdbsGWUc/3XEIhH8HXJSDU8mZDApXSSZR+4fbKiOTUHmUgYd7HOLNG544Zy3F+ZPqxMwuGkCo/HxfLXrebdQakkweTwTqUgIDlwvPC181Z5eZ7cDTV905pDXGj/KiRAk3p+hlgHPvRW35PT4b163gUGkmIl0Ds4OBn6G64lkPsnQPNFs8AtwH4PSeYoz9s5uh/jFX0tlr7f+xzN6PuDvyOmKvYhdYK5FLAOkbJ6E/r7fxRZ1g63PPgeLsfir/0iq9K7IW+eWH4ONNCdL5oyV/TSILB+ob8z1ZWUf9p50jIFh6l64geGZ785/8OQanz95/ZPwGF03PMeYdkuH6x5Q/gcx5bg2RejM+RPQ6Vg6D43WOe+1fDKbVqr9P6Y5S9fuwD56fvq62ESHISopAae8/mbMD2la4/h/K9uSYuhxZDNszxgmQmd2kQDoEU6g46KneCXN/b9b5Ez/4iQOfBj4EuXyfp8MlAlFg8P486y4HT9H680pqN9xN164m7ReXPWHU7pw7F9Pw3FEDjQrHHnM3KfE8KWrl2JyxrdR90wr+HPPrkO5v1XT88+iU5MfGOeswl1uQxhiAGn4O62zaMJmDbSrMNY4LEV/jc+TjMQJRwOsUrW8aDyVoo87t8G+Qtfm6fOy6DNK9crM2f3KQJ0YEPc5JM0eSQsjYSFkZFIWRkUgcB1El5HwAAAAIAZ5iRCX/y4AA7liudRsNCYNGAb/ocSIJGilo13xUupVcYzmaVbkEY3nch7y9pfI1qxo3V9n9Q+r84e3e7dCfx+aLdD6S8dDaqzc6eqH9onVdingfJndPc1yaRhn4JD1jsj85o/le4m9cE2W1F8unegGNvOuknfzBmz4/Us9R+kC7xW5e9Z1Z9JsGeb/z6XkKkxiNh1C3Ns5jTVxB9x1poY49zmq+xsXNh0uy75DZf0JM9Uq8ghKrZiQDyAlHf4dqw48mtmlozgUMkh7VJ7vbIW1UNI81pRTT7C3WOOa3mw0RNjAoMLjtm1+VqQBEhHw+6VBvNTwCBkyvjU+kVMA1OU8elyGQX0xTlHRM8iPGg3CO8B5AzpOm2M7J75cG3PPGc42ztXyYzat3TyZ54CyDqZi1/Mn4B6T1fhMSD0uk5lKsOHIktX1Sfud/I3Ew+McUpwm3bxVdAy7uiGeiXWbe3cMBmCruk4yW18G6dEf9prnjcT6HUZG5bBSQGYSQscX2KCZoWxWkVS0w6IkwqdVJ+Akyey/Hl0MyrcAMI6Sgq3HMn95sBcc4ZadQLT31gNKo6qyebwmyK63HlMTK40Zj3FGuboBQ3Zsg87Jf3Gg1SDlG6fRVl2+5Cc6q+0OcUNRyCfLIG157ZHTSCwD9UpZtZDLki0BCLgAAAAhBmmQYiv+BgQDyne7dSHRhSQ/D31OEhh0h14FMQDwlvgJODIIYGxb7iHQo1mvJn3hOUUli9mTrUMuuPv/W2bsX3X7l9k7jtvT/Cuf4Kmbbhn0zmtjx7GWFyjrJfyHHxs5mxuTjdr2/drXoPhh1rb2XOnE9H3BdBqm1I+K5Sd1hYCevn6PbJcDyUHpysOZeLu+VoYklOlicG52cbxZbzvVeiS4jb+qyJoL62Ox+nSrUhOkCNMf8dz5iEi+C5iYZciyXk6gmIvSJVQDNTiO2i1a6pGORhiNVWGAMBHNHyHbmWtqB9AYbSdGR5qQzHnGF9HWaHfTzIqQMNEioRwE00KEllO+UcuPFmOs0Kl9lgy1DgKSKfGaaVFc7RNrn0nOddM6OfOG51GuoJSCnOpRjIvLAMAAAAA1NfU1+Ro9v/o+AANDABwAABedtb292AAAAbG12aGQAAAAA18kDNdfJAzUAAAPoAAAAowABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAGGlvZHMAAAAAEICAgAcAT////v7/AAACknRyYWsAAABcdGtoZAAAAAPXyQM118kDNQAAAAEAAAAAAAAAnwAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAOAAAACAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAJ8AABZEAAEAAAAAAgptZGlhAAAAIG1kaGQAAAAA18kDNdfJAzUAAV+QAAA3qlXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAG1bWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABdXN0YmwAAACYc3RzZAAAAAAAAAABAAAAiGF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAOAAgAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAyYXZjQwFNQAr/4QAaZ01ACuyiLy+AtQYBBkAAAATAAAEsI8SJZYABAAVo74OcgAAAABhzdHRzAAAAAAAAAAEAAAAFAAALIgAAABRzdHNzAAAAAAAAAAEAAAABAAAAEXNkdHAAAAAAIBAQGBAAAAAwY3R0cwAAAAAAAAAEAAAAAgAAFkQAAAABAAAhZgAAAAEAAAsiAAAAAQAAFkQAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAKHN0c3oAAAAAAAAAAAAAAAUAAANBAAAADAAAAA8AAAAMAAAADAAAACRzdGNvAAAAAAAAAAUAAAAwAAADdQAABhAAAAjPAAAKyQAAAlp0cmFrAAAAXHRraGQAAAAD18kDNdfJAzUAAAACAAAAAAAAAKMAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAABzAAAIQAABAAAAAAG+bWRpYQAAACBtZGhkAAAAANfJAzXXyQM1AACsRAAAHABVxAAAAAAAJWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABNb25vAAAAAXFtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAATVzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAAAAAAAAAABYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAAHAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAwc3RzegAAAAAAAAAAAAAABwAAAAQAAAAEAAACiwAAArAAAAHuAAABNwAAAAQAAAAsc3RjbwAAAAAAAAAHAAADcQAAA4EAAAOFAAAGHwAACNsAAArVAAAMDAAAABpzZ3BkAQAAAHJvbGwAAAACAAAAAf//AAAAHHNiZ3AAAAAAcm9sbAAAAAEAAAAHAAAAAQAAABR1ZHRhAAAADG5hbWVNb25vAAAAb3VkdGEAAABnbWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAA6aWxzdAAAADKpdG9vAAAAKmRhdGEAAAABAAAAAEhhbmRCcmFrZSAxLjEuMiAyMDE4MDkwNTAw'; - video.load(); //video.style.display = 'none'; - - if (debug) { - video.style = "position: fixed; top: 0px; right: 0px; z-index: 1000000;"; - document.body.appendChild(video); - } else { - video.style.display = 'none'; - } - - video.playing = false; - video.play().then(function (status) { - resolve(true); - }).catch(function (err) { - resolve(false); - }); - }); - }; - - var Html5VideoFactory = /*#__PURE__*/function () { - function Html5VideoFactory() { - _classCallCheck(this, Html5VideoFactory); - } - - _createClass(Html5VideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - try { - if (paella.videoFactories.Html5VideoFactory.s_instances > 0 && paella.utils.userAgent.system.iOS && paella.utils.userAgent.system.Version.major <= 10 && paella.utils.userAgent.system.Version.minor < 3) { - return false; - } - - for (var key in streamData.sources) { - if (key == 'mp4' || key == 'mp3') return true; - } - } catch (e) {} - - return false; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - ++paella.videoFactories.Html5VideoFactory.s_instances; - return new paella.Html5Video(id, streamData, rect.x, rect.y, rect.w, rect.h); - } - }]); - - return Html5VideoFactory; - }(); - - paella.videoFactories.Html5VideoFactory = Html5VideoFactory; - paella.videoFactories.Html5VideoFactory.s_instances = 0; - - var ImageVideo = /*#__PURE__*/function (_paella$VideoElementB3) { - _inherits(ImageVideo, _paella$VideoElementB3); - - var _super15 = _createSuper(ImageVideo); - - function ImageVideo(id, stream, left, top, width, height) { - var _this49; - - _classCallCheck(this, ImageVideo); - - _this49 = _super15.call(this, id, stream, 'img', left, top, width, height); - _this49._posterFrame = null; - _this49._currentQuality = null; - _this49._currentTime = 0; - _this49._duration = 0; - _this49._ended = false; - _this49._playTimer = null; - _this49._playbackRate = 1; - _this49._frameArray = null; - - _this49._stream.sources.image.sort(function (a, b) { - return a.res.h - b.res.h; - }); - - return _this49; - } - - _createClass(ImageVideo, [{ - key: "img", - get: function get() { - return this.domElement; - } - }, { - key: "imgStream", - get: function get() { - this._stream.sources.image[this._currentQuality]; - } - }, { - key: "_paused", - get: function get() { - return this._playTimer == null; - } - }, { - key: "_deferredAction", - value: function _deferredAction(action) { - var _this50 = this; - - return new Promise(function (_resolve) { - if (_this50.ready) { - _resolve(action()); - } else { - var _resolve = function resolve() { - _this50._ready = true; - - _resolve(action()); - }; - - $(_this50.video).bind('paella:imagevideoready', _resolve); - } - }); - } - }, { - key: "_getQualityObject", - value: function _getQualityObject(index, s) { - return { - index: index, - res: s.res, - src: s.src, - toString: function toString() { - return Number(this.res.w) + "x" + Number(this.res.h); - }, - shortLabel: function shortLabel() { - return this.res.h + "p"; - }, - compare: function compare(q2) { - return Number(this.res.w) * Number(this.res.h) - Number(q2.res.w) * Number(q2.res.h); - } - }; - } - }, { - key: "_loadCurrentFrame", - value: function _loadCurrentFrame() { - var This = this; - - if (this._frameArray) { - var frame = this._frameArray[0]; - - this._frameArray.some(function (f) { - if (This._currentTime < f.time) { - return true; - } else { - frame = f.src; - } - }); - - this.img.src = frame; - } - } // Initialization functions - - /*allowZoom:function() { - return false; - },*/ - - }, { - key: "getVideoData", - value: function getVideoData() { - var _this51 = this; - - return new Promise(function (resolve) { - _this51._deferredAction(function () { - var imgStream = _this51._stream.sources.image[_this51._currentQuality]; - var videoData = { - duration: _this51._duration, - currentTime: _this51._currentTime, - volume: 0, - paused: _this51._paused, - ended: _this51._ended, - res: { - w: imgStream.res.w, - h: imgStream.res.h - } - }; - resolve(videoData); - }); - }); - } - }, { - key: "setPosterFrame", - value: function setPosterFrame(url) { - this._posterFrame = url; - } - }, { - key: "setAutoplay", - value: function setAutoplay(auto) { - this._autoplay = auto; - - if (auto && this.video) { - this.video.setAttribute("autoplay", auto); - } - } - }, { - key: "load", - value: function load() { - var This = this; - var sources = this._stream.sources.image; - - if (this._currentQuality === null && this._videoQualityStrategy) { - this._currentQuality = this._videoQualityStrategy.getQualityIndex(sources); - } - - var stream = this._currentQuality < sources.length ? sources[this._currentQuality] : null; - - if (stream) { - this._frameArray = []; - - for (var key in stream.frames) { - var time = Math.floor(Number(key.replace("frame_", ""))); - - this._frameArray.push({ - src: stream.frames[key], - time: time - }); - } - - this._frameArray.sort(function (a, b) { - return a.time - b.time; - }); - - this._ready = true; - this._currentTime = 0; - this._duration = stream.duration; - - this._loadCurrentFrame(); - - paella.events.trigger("paella:imagevideoready"); - return this._deferredAction(function () { - return stream; - }); - } else { - return paella_DeferredRejected(new Error("Could not load video: invalid quality stream index")); - } - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return true; - } - }, { - key: "getQualities", - value: function getQualities() { - var _this52 = this; - - return new Promise(function (resolve) { - setTimeout(function () { - var result = []; - var sources = _this52._stream.sources[_this52._streamName]; - var index = -1; - sources.forEach(function (s) { - index++; - result.push(_this52._getQualityObject(index, s)); - }); - resolve(result); - }, 10); - }); - } - }, { - key: "setQuality", - value: function setQuality(index) { - var _this53 = this; - - return new Promise(function (resolve) { - var paused = _this53._paused; - var sources = _this53._stream.sources.image; - _this53._currentQuality = index < sources.length ? index : 0; - var currentTime = _this53._currentTime; - - _this53.load().then(function () { - this._loadCurrentFrame(); - - resolve(); - }); - }); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - var _this54 = this; - - return new Promise(function (resolve) { - resolve(_this54._getQualityObject(_this54._currentQuality, _this54._stream.sources.image[_this54._currentQuality])); - }); - } - }, { - key: "play", - value: function play() { - var This = this; - return this._deferredAction(function () { - This._playTimer = new paella.utils.Timer(function () { - This._currentTime += 0.25 * This._playbackRate; - - This._loadCurrentFrame(); - }, 250); - This._playTimer.repeat = true; - }); - } - }, { - key: "pause", - value: function pause() { - var This = this; - return this._deferredAction(function () { - This._playTimer.repeat = false; - This._playTimer = null; - }); - } - }, { - key: "isPaused", - value: function isPaused() { - var _this55 = this; - - return this._deferredAction(function () { - return _this55._paused; - }); - } - }, { - key: "duration", - value: function duration() { - var _this56 = this; - - return this._deferredAction(function () { - return _this56._duration; - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this57 = this; - - return this._deferredAction(function () { - _this57._currentTime = time; - - _this57._loadCurrentFrame(); - }); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this58 = this; - - return this._deferredAction(function () { - return _this58._currentTime; - }); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - return this._deferredAction(function () {// No audo sources in image video - }); - } - }, { - key: "volume", - value: function volume() { - return this._deferredAction(function () { - // No audo sources in image video - return 0; - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - var _this59 = this; - - return this._deferredAction(function () { - _this59._playbackRate = rate; - }); - } - }, { - key: "playbackRate", - value: function playbackRate() { - var _this60 = this; - - return this._deferredAction(function () { - return _this60._playbackRate; - }); - } - }, { - key: "goFullScreen", - value: function goFullScreen() { - var _this61 = this; - - return this._deferredAction(function () { - var elem = _this61.img; - - if (elem.requestFullscreen) { - elem.requestFullscreen(); - } else if (elem.msRequestFullscreen) { - elem.msRequestFullscreen(); - } else if (elem.mozRequestFullScreen) { - elem.mozRequestFullScreen(); - } else if (elem.webkitEnterFullscreen) { - elem.webkitEnterFullscreen(); - } - }); - } - }, { - key: "unFreeze", - value: function unFreeze() { - return this._deferredAction(function () {}); - } - }, { - key: "freeze", - value: function freeze() { - return this._deferredAction(function () {}); - } - }, { - key: "unload", - value: function unload() { - this._callUnloadEvent(); - - return paella_DeferredNotImplemented(); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredNotImplemented(); - } - }]); - - return ImageVideo; - }(paella.VideoElementBase); - - paella.ImageVideo = ImageVideo; - - var ImageVideoFactory = /*#__PURE__*/function () { - function ImageVideoFactory() { - _classCallCheck(this, ImageVideoFactory); - } - - _createClass(ImageVideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - try { - for (var key in streamData.sources) { - if (key == 'image') return true; - } - } catch (e) {} - - return false; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - return new paella.ImageVideo(id, streamData, rect.x, rect.y, rect.w, rect.h); - } - }]); - - return ImageVideoFactory; - }(); - - paella.videoFactories.ImageVideoFactory = ImageVideoFactory; -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ - - -(function () { - var BackgroundContainer = /*#__PURE__*/function (_paella$DomNode4) { - _inherits(BackgroundContainer, _paella$DomNode4); - - var _super16 = _createSuper(BackgroundContainer); - - function BackgroundContainer(id, image) { - var _this62; - - _classCallCheck(this, BackgroundContainer); - - _this62 = _super16.call(this, 'img', id, { - position: 'relative', - top: '0px', - left: '0px', - right: '0px', - bottom: '0px', - zIndex: GlobalParams.background.zIndex - }); - - _this62.domElement.setAttribute('src', image); - - _this62.domElement.setAttribute('alt', ''); - - _this62.domElement.setAttribute('width', '100%'); - - _this62.domElement.setAttribute('height', '100%'); - - return _this62; - } - - _createClass(BackgroundContainer, [{ - key: "setImage", - value: function setImage(image) { - this.domElement.setAttribute('src', image); - } - }]); - - return BackgroundContainer; - }(paella.DomNode); - - paella.BackgroundContainer = BackgroundContainer; - - var VideoOverlay = /*#__PURE__*/function (_paella$DomNode5) { - _inherits(VideoOverlay, _paella$DomNode5); - - var _super17 = _createSuper(VideoOverlay); - - function VideoOverlay() { - var _this63; - - _classCallCheck(this, VideoOverlay); - - var style = { - position: 'absolute', - left: '0px', - right: '0px', - top: '0px', - bottom: '0px', - overflow: 'hidden', - zIndex: 10 - }; - _this63 = _super17.call(this, 'div', 'overlayContainer', style); - - _this63.domElement.setAttribute("role", "main"); - - return _this63; - } - - _createClass(VideoOverlay, [{ - key: "size", - get: function get() { - if (!this._size) { - this._size = { - w: 1280, - h: 720 - }; - } - - return this._size; - } - }, { - key: "_generateId", - value: function _generateId() { - return Math.ceil(Date.now() * Math.random()); - } - }, { - key: "enableBackgroundMode", - value: function enableBackgroundMode() { - this.domElement.className = 'overlayContainer background'; - } - }, { - key: "disableBackgroundMode", - value: function disableBackgroundMode() { - this.domElement.className = 'overlayContainer'; - } - }, { - key: "clear", - value: function clear() { - this.domElement.innerText = ""; - } - }, { - key: "getVideoRect", - value: function getVideoRect(index) { - return paella.player.videoContainer.getVideoRect(index); - } - }, { - key: "addText", - value: function addText(text, rect, isDebug) { - var textElem = document.createElement('div'); - textElem.innerText = text; - textElem.className = "videoOverlayText"; - if (isDebug) textElem.style.backgroundColor = "red"; - return this.addElement(textElem, rect); - } - }, { - key: "addElement", - value: function addElement(element, rect) { - this.domElement.appendChild(element); - element.style.position = 'absolute'; - element.style.left = this.getHSize(rect.left) + '%'; - element.style.top = this.getVSize(rect.top) + '%'; - element.style.width = this.getHSize(rect.width) + '%'; - element.style.height = this.getVSize(rect.height) + '%'; - return element; - } - }, { - key: "getLayer", - value: function getLayer(id, zindex) { - id = id || this._generateId(); - return $(this.domElement).find("#" + id)[0] || this.addLayer(id, zindex); - } - }, { - key: "addLayer", - value: function addLayer(id, zindex) { - zindex = zindex || 10; - var element = document.createElement('div'); - element.className = "row"; - element.id = id || this._generateId(); - return this.addElement(element, { - left: 0, - top: 0, - width: 1280, - height: 720 - }); - } - }, { - key: "removeLayer", - value: function removeLayer(id) { - var elem = $(this.domElement).find("#" + id)[0]; - - if (elem) { - this.domElement.removeChild(elem); - } - } - }, { - key: "removeElement", - value: function removeElement(element) { - if (element) { - try { - this.domElement.removeChild(element); - } catch (e) {} - } - } - }, { - key: "getVSize", - value: function getVSize(px) { - return px * 100 / this.size.h; - } - }, { - key: "getHSize", - value: function getHSize(px) { - return px * 100 / this.size.w; - } - }]); - - return VideoOverlay; - }(paella.DomNode); - - paella.VideoOverlay = VideoOverlay; - - var VideoWrapper = /*#__PURE__*/function (_paella$DomNode6) { - _inherits(VideoWrapper, _paella$DomNode6); - - var _super18 = _createSuper(VideoWrapper); - - function VideoWrapper(id, left, top, width, height) { - var _this64; - - _classCallCheck(this, VideoWrapper); - - var relativeSize = new paella.RelativeVideoSize(); - var percentTop = relativeSize.percentVSize(top) + '%'; - var percentLeft = relativeSize.percentWSize(left) + '%'; - var percentWidth = relativeSize.percentWSize(width) + '%'; - var percentHeight = relativeSize.percentVSize(height) + '%'; - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute', - zIndex: GlobalParams.video.zIndex, - overflow: 'hidden' - }; - _this64 = _super18.call(this, 'div', id, style); - _this64._rect = { - left: left, - top: top, - width: width, - height: height - }; - _this64.domElement.className = "videoWrapper"; - return _this64; - } - - _createClass(VideoWrapper, [{ - key: "setRect", - value: function setRect(rect, animate) { - this._rect = JSON.parse(JSON.stringify(rect)); - var relativeSize = new paella.RelativeVideoSize(); - var percentTop = relativeSize.percentVSize(rect.top) + '%'; - var percentLeft = relativeSize.percentWSize(rect.left) + '%'; - var percentWidth = relativeSize.percentWSize(rect.width) + '%'; - var percentHeight = relativeSize.percentVSize(rect.height) + '%'; - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute' - }; - - if (animate) { - this.disableClassName(); - var thisClass = this; - $(this.domElement).animate(style, 400, function () { - thisClass.enableClassName(); - paella.events.trigger(paella.events.setComposition, { - video: thisClass - }); - }); - this.enableClassNameAfter(400); - } else { - $(this.domElement).css(style); - paella.events.trigger(paella.events.setComposition, { - video: this - }); - } - } - }, { - key: "getRect", - value: function getRect() { - return this._rect; - } - }, { - key: "disableClassName", - value: function disableClassName() { - this.classNameBackup = this.domElement.className; - this.domElement.className = ""; - } - }, { - key: "enableClassName", - value: function enableClassName() { - this.domElement.className = this.classNameBackup; - } - }, { - key: "enableClassNameAfter", - value: function enableClassNameAfter(millis) { - setTimeout("$('#" + this.domElement.id + "')[0].className = '" + this.classNameBackup + "'", millis); - } - }, { - key: "setVisible", - value: function setVisible(visible, animate) { - var _this65 = this; - - if (typeof visible == "string") { - visible = /true/i.test(visible) ? true : false; - } - - if (visible && animate) { - $(this.domElement).show(); - $(this.domElement).animate({ - opacity: 1.0 - }, 300); - } else if (visible && !animate) { - $(this.domElement).show(); - } else if (!visible && animate) { - $(this.domElement).animate({ - opacity: 0.0 - }, 300, function () { - return $(_this65.domElement).hide(); - }); - } else if (!visible && !animate) { - $(this.domElement).hide(); - } - } - }, { - key: "setLayer", - value: function setLayer(layer) { - this.domElement.style.zIndex = layer; - } - }]); - - return VideoWrapper; - }(paella.DomNode); - - paella.VideoWrapper = VideoWrapper; - paella.SeekType = { - FULL: 1, - BACKWARDS_ONLY: 2, - FORWARD_ONLY: 3, - DISABLED: 4 - }; // This function is used to manage the timer to enable and disable the click and double click events - // interaction with the video container timeout. - - function clearClickEventsTimeout() { - if (this._clickEventsTimeout) { - clearTimeout(this._clickEventsTimeout); - this._clickEventsTimeout = null; - } - } - - var VideoContainerBase = /*#__PURE__*/function (_paella$DomNode7) { - _inherits(VideoContainerBase, _paella$DomNode7); - - var _super19 = _createSuper(VideoContainerBase); - - function VideoContainerBase(id) { - var _this66; - - _classCallCheck(this, VideoContainerBase); - - var style = { - position: 'absolute', - left: '0px', - right: '0px', - top: '0px', - bottom: '0px', - overflow: 'hidden' - }; - _this66 = _super19.call(this, 'div', id, style); - _this66._trimming = { - enabled: false, - start: 0, - end: 0 - }; - _this66.timeupdateEventTimer = null; - _this66.timeupdateInterval = 250; - _this66.masterVideoData = null; - _this66.slaveVideoData = null; - _this66.currentMasterVideoData = null; - _this66.currentSlaveVideoData = null; - _this66._force = false; - _this66._clickEventsEnabled = true; - _this66._seekDisabled = false; - _this66._seekType = paella.SeekType.FULL; - _this66._seekTimeLimit = 0; - _this66._attenuationEnabled = false; - $(_this66.domElement).dblclick(function (evt) { - if (_this66._clickEventsEnabled) { - paella.player.isFullScreen() ? paella.player.exitFullScreen() : paella.player.goFullScreen(); - } - }); - var dblClickTimer = null; - $(_this66.domElement).click(function (evt) { - var doClick = function doClick() { - if (!_this66._clickEventsEnabled) return; - paella.player.videoContainer.paused().then(function (paused) { - // If some player needs mouse events support, the click is ignored - if (_this66.streamProvider.videoPlayers.some(function (p) { - return p.canvasData.mouseEventsSupport; - })) { - return; - } - - if (paused) { - paella.player.play(); - } else { - paella.player.pause(); - } - }); - }; // the dblClick timer prevents the single click from running when the user double clicks - - - if (dblClickTimer) { - clearTimeout(dblClickTimer); - dblClickTimer = null; - } else { - dblClickTimer = setTimeout(function () { - dblClickTimer = null; - doClick(); - }, 200); - } - }); - - _this66.domElement.addEventListener("touchstart", function (event) { - if (paella.player.controls) { - paella.player.controls.restartHideTimer(); - } - }); - - return _this66; - } - - _createClass(VideoContainerBase, [{ - key: "attenuationEnabled", - get: function get() { - return this._attenuationEnabled; - }, - set: function set(att) { - this._attenuationEnabled = att; - Array.from(paella.player.videoContainer.container.domElement.children).forEach(function (ch) { - if (ch.id == "overlayContainer") { - return; - } - - if (att) { - $(ch).addClass("dimmed-element"); - } else { - $(ch).removeClass("dimmed-element"); - } - }); - } - }, { - key: "seekType", - get: function get() { - return this._seekType; - }, - set: function set(type) { - switch (type) { - case paella.SeekType.FULL: - case paella.SeekType.BACKWARDS_ONLY: - case paella.SeekType.FORWARD_ONLY: - case paella.SeekType.DISABLED: - this._seekType = type; - paella.events.trigger(paella.events.seekAvailabilityChanged, { - type: type, - enabled: type == paella.SeekType.FULL, - disabled: type != paella.SeekType.FULL - }); - break; - - default: - throw new Error("Invalid seekType. Allowed seek types:\n\t\t\t\tpaella.SeekType.FULL\n\t\t\t\tpaella.SeekType.BACKWARDS_ONLY\n\t\t\t\tpaella.SeekType.FORWARD_ONLY\n\t\t\t\tpaella.SeekType.DISABLED"); - } - } - }, { - key: "triggerTimeupdate", - value: function triggerTimeupdate() { - var _this67 = this; - - var paused = 0; - var duration = 0; - this.paused().then(function (p) { - paused = p; - return _this67.duration(); - }).then(function (d) { - duration = d; - return _this67.currentTime(); - }).then(function (currentTime) { - if (!paused || _this67._force) { - _this67._seekTimeLimit = currentTime > _this67._seekTimeLimit ? currentTime : _this67._seekTimeLimit; - _this67._force = false; - paella.events.trigger(paella.events.timeupdate, { - videoContainer: _this67, - currentTime: currentTime, - duration: duration - }); - } - }); - } - }, { - key: "startTimeupdate", - value: function startTimeupdate() { - var _this68 = this; - - this.timeupdateEventTimer = new paella.utils.Timer(function (timer) { - _this68.triggerTimeupdate(); - }, this.timeupdateInterval); - this.timeupdateEventTimer.repeat = true; - } - }, { - key: "stopTimeupdate", - value: function stopTimeupdate() { - if (this.timeupdateEventTimer) { - this.timeupdateEventTimer.repeat = false; - } - - this.timeupdateEventTimer = null; - } - }, { - key: "enablePlayOnClick", - value: function enablePlayOnClick() { - var _this69 = this; - - var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - clearClickEventsTimeout.apply(this); - - if (timeout) { - this._clickEventsTimeout = setTimeout(function () { - _this69._clickEventsEnabled = true; - }, timeout); - } else { - this._clickEventsEnabled = true; - } - } - }, { - key: "disablePlayOnClick", - value: function disablePlayOnClick() { - clearClickEventsTimeout.apply(this); - this._clickEventsEnabled = false; - } - }, { - key: "isPlayOnClickEnabled", - value: function isPlayOnClickEnabled() { - return this._clickEventsEnabled; - } - }, { - key: "play", - value: function play() { - this.streamProvider.startVideoSync(this.audioPlayer); - this.startTimeupdate(); - setTimeout(function () { - return paella.events.trigger(paella.events.play); - }, 50); - } - }, { - key: "pause", - value: function pause() { - paella.events.trigger(paella.events.pause); - this.stopTimeupdate(); - this.streamProvider.stopVideoSync(); - } - }, { - key: "seekTo", - value: function seekTo(newPositionPercent) { - var _this70 = this; - - return new Promise(function (resolve, reject) { - var time = 0; - paella.player.videoContainer.currentTime().then(function (t) { - time = t; - return paella.player.videoContainer.duration(); - }).then(function (duration) { - if (_this70._seekTimeLimit > 0 && _this70._seekType == paella.SeekType.BACKWARDS_ONLY) { - time = _this70._seekTimeLimit; - } - - var currentPercent = time / duration * 100; - - switch (_this70._seekType) { - case paella.SeekType.FULL: - break; - - case paella.SeekType.BACKWARDS_ONLY: - if (newPositionPercent > currentPercent) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.FORWARD_ONLY: - if (newPositionPercent < currentPercent) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.DISABLED: - reject(new Error("Warning: Seek is disabled")); - return; - } - - _this70.setCurrentPercent(newPositionPercent).then(function (timeData) { - _this70._force = true; - - _this70.triggerTimeupdate(); - - paella.events.trigger(paella.events.seekToTime, { - newPosition: timeData.time - }); - paella.events.trigger(paella.events.seekTo, { - newPositionPercent: newPositionPercent - }); - resolve(); - }); - }); - }); - } - }, { - key: "seekToTime", - value: function seekToTime(time) { - var _this71 = this; - - return new Promise(function (resolve, reject) { - paella.player.videoContainer.currentTime().then(function (currentTime) { - if (_this71._seekTimeLimit && _this71._seekType == paella.SeekType.BACKWARDS_ONLY) { - currentTime = _this71._seekTimeLimit; - } - - switch (_this71._seekType) { - case paella.SeekType.FULL: - break; - - case paella.SeekType.BACKWARDS_ONLY: - if (time > currentTime) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.FORWARD_ONLY: - if (time < currentTime) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.DISABLED: - reject(new Error("Warning: Seek is disabled")); - return; - } - - _this71.setCurrentTime(time).then(function (timeData) { - _this71._force = true; - - _this71.triggerTimeupdate(); - - var percent = timeData.time * 100 / timeData.duration; - paella.events.trigger(paella.events.seekToTime, { - newPosition: timeData.time - }); - paella.events.trigger(paella.events.seekTo, { - newPositionPercent: percent - }); - }); - }); - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(params) { - paella.events.trigger(paella.events.setPlaybackRate, { - rate: params - }); - } - }, { - key: "mute", - value: function mute() {} - }, { - key: "unmute", - value: function unmute() {} - }, { - key: "setVolume", - value: function setVolume(params) {} - }, { - key: "volume", - value: function volume() { - return 1; - } - }, { - key: "trimStart", - value: function trimStart() { - var _this72 = this; - - return new Promise(function (resolve) { - resolve(_this72._trimming.start); - }); - } - }, { - key: "trimEnd", - value: function trimEnd() { - var _this73 = this; - - return new Promise(function (resolve) { - resolve(_this73._trimming.end); - }); - } - }, { - key: "trimEnabled", - value: function trimEnabled() { - var _this74 = this; - - return new Promise(function (resolve) { - resolve(_this74._trimming.enabled); - }); - } - }, { - key: "trimming", - value: function trimming() { - var _this75 = this; - - return new Promise(function (resolve) { - resolve(_this75._trimming); - }); - } - }, { - key: "enableTrimming", - value: function enableTrimming() { - this._trimming.enabled = true; - var cap = paella.captions.getActiveCaptions(); - if (cap !== undefined) paella.plugins.captionsPlugin.buildBodyContent(cap._captions, "list"); - paella.events.trigger(paella.events.setTrim, { - trimEnabled: this._trimming.enabled, - trimStart: this._trimming.start, - trimEnd: this._trimming.end - }); - } - }, { - key: "disableTrimming", - value: function disableTrimming() { - this._trimming.enabled = false; - var cap = paella.captions.getActiveCaptions(); - if (cap !== undefined) paella.plugins.captionsPlugin.buildBodyContent(cap._captions, "list"); - paella.events.trigger(paella.events.setTrim, { - trimEnabled: this._trimming.enabled, - trimStart: this._trimming.start, - trimEnd: this._trimming.end - }); - } - }, { - key: "setTrimming", - value: function setTrimming(start, end) { - var _this76 = this; - - return new Promise(function (resolve) { - var currentTime = 0; - - _this76.currentTime(true).then(function (c) { - currentTime = c; - return _this76.duration(); - }).then(function (duration) { - _this76._trimming.start = Math.floor(start); - _this76._trimming.end = Math.floor(end); - - if (_this76._trimming.enabled) { - if (currentTime < _this76._trimming.start) { - _this76.setCurrentTime(0); - } - - if (currentTime > _this76._trimming.end) { - _this76.setCurrentTime(duration); - } - - var cap = paella.captions.getActiveCaptions(); - if (cap !== undefined) paella.plugins.captionsPlugin.buildBodyContent(cap._captions, "list"); - } - - paella.events.trigger(paella.events.setTrim, { - trimEnabled: _this76._trimming.enabled, - trimStart: _this76._trimming.start, - trimEnd: _this76._trimming.end - }); - resolve(); - }); - }); - } - }, { - key: "setTrimmingStart", - value: function setTrimmingStart(start) { - return this.setTrimming(start, this._trimming.end); - } - }, { - key: "setTrimmingEnd", - value: function setTrimmingEnd(end) { - return this.setTrimming(this._trimming.start, end); - } - }, { - key: "setCurrentPercent", - value: function setCurrentPercent(percent) { - var _this77 = this; - - var duration = 0; - return new Promise(function (resolve) { - _this77.duration().then(function (d) { - duration = d; - return _this77.trimming(); - }).then(function (trimming) { - var position = 0; - - if (trimming.enabled) { - var start = trimming.start; - var end = trimming.end; - duration = end - start; - var trimedPosition = percent * duration / 100; - position = parseFloat(trimedPosition); - } else { - position = percent * duration / 100; - } - - return _this77.setCurrentTime(position); - }).then(function (timeData) { - resolve(timeData); - }); - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - paella.log.debug("VideoContainerBase.setCurrentTime(" + time + ")"); - } - }, { - key: "currentTime", - value: function currentTime() { - paella.log.debug("VideoContainerBase.currentTime()"); - return 0; - } - }, { - key: "duration", - value: function duration() { - paella.log.debug("VideoContainerBase.duration()"); - return 0; - } - }, { - key: "paused", - value: function paused() { - paella.log.debug("VideoContainerBase.paused()"); - return true; - } - }, { - key: "setupVideo", - value: function setupVideo(onSuccess) { - paella.log.debug("VideoContainerBase.setupVide()"); - } - }, { - key: "isReady", - value: function isReady() { - paella.log.debug("VideoContainerBase.isReady()"); - return true; - } - }, { - key: "onresize", - value: function (_onresize) { - function onresize() { - return _onresize.apply(this, arguments); - } - - onresize.toString = function () { - return _onresize.toString(); - }; - - return onresize; - }(function () { - _get(_getPrototypeOf(VideoContainerBase.prototype), "onresize", this).call(this, onresize); - }) - }, { - key: "ended", - value: function ended() { - var _this78 = this; - - return new Promise(function (resolve) { - var duration = 0; - - _this78.duration().then(function (d) { - duration = d; - return _this78.currentTime(); - }).then(function (currentTime) { - resolve(Math.floor(duration) <= Math.ceil(currentTime)); - }); - }); - } - }]); - - return VideoContainerBase; - }(paella.DomNode); - - paella.VideoContainerBase = VideoContainerBase; // Profile frame strategies - - var ProfileFrameStrategy = /*#__PURE__*/function () { - function ProfileFrameStrategy() { - _classCallCheck(this, ProfileFrameStrategy); - } - - _createClass(ProfileFrameStrategy, [{ - key: "valid", - value: function valid() { - return true; - } - }, { - key: "adaptFrame", - value: function adaptFrame(videoDimensions, frameRect) { - return frameRect; - } - }], [{ - key: "Factory", - value: function Factory() { - var config = paella.player.config; - - try { - var strategyClass = config.player.profileFrameStrategy; - var ClassObject = paella.utils.objectFromString(strategyClass); - var strategy = new ClassObject(); - - if (strategy instanceof paella.ProfileFrameStrategy) { - return strategy; - } - } catch (e) {} - - return null; - } - }]); - - return ProfileFrameStrategy; - }(); - - paella.ProfileFrameStrategy = ProfileFrameStrategy; - - var LimitedSizeProfileFrameStrategy = /*#__PURE__*/function (_ProfileFrameStrategy) { - _inherits(LimitedSizeProfileFrameStrategy, _ProfileFrameStrategy); - - var _super20 = _createSuper(LimitedSizeProfileFrameStrategy); - - function LimitedSizeProfileFrameStrategy() { - _classCallCheck(this, LimitedSizeProfileFrameStrategy); - - return _super20.apply(this, arguments); - } - - _createClass(LimitedSizeProfileFrameStrategy, [{ - key: "adaptFrame", - value: function adaptFrame(videoDimensions, frameRect) { - if (videoDimensions.width < frameRect.width || videoDimensions.height < frameRect.height) { - var frameRectCopy = JSON.parse(JSON.stringify(frameRect)); - frameRectCopy.width = videoDimensions.width; - frameRectCopy.height = videoDimensions.height; - var diff = { - w: frameRect.width - videoDimensions.width, - h: frameRect.height - videoDimensions.height - }; - frameRectCopy.top = frameRectCopy.top + diff.h / 2; - frameRectCopy.left = frameRectCopy.left + diff.w / 2; - return frameRectCopy; - } - - return frameRect; - } - }]); - - return LimitedSizeProfileFrameStrategy; - }(ProfileFrameStrategy); - - paella.LimitedSizeProfileFrameStrategy = LimitedSizeProfileFrameStrategy; - - function updateBuffers() { - // Initial implementation: use the mainStream buffered property - var mainBuffered = this.mainPlayer && this.mainPlayer.buffered; - - if (mainBuffered) { - this._bufferedData = []; - - for (var i = 0; i < mainBuffered.length; ++i) { - this._bufferedData.push({ - start: mainBuffered.start(i), - end: mainBuffered.end(i) - }); - } - } - } - - var StreamProvider = /*#__PURE__*/function () { - function StreamProvider(videoData) { - _classCallCheck(this, StreamProvider); - - this._mainStream = null; - this._videoStreams = []; - this._audioStreams = []; - this._mainPlayer = null; - this._audioPlayer = null; - this._videoPlayers = []; - this._audioPlayers = []; - this._players = []; - this._autoplay = paella.utils.parameters.get('autoplay') == 'true' || this.isLiveStreaming; - this._startTime = 0; - this._bufferedData = []; - var streamProvider = this; - this._buffered = { - start: function start(index) { - if (index < 0 || index >= streamProvider._bufferedData.length) { - throw new Error("Buffered index out of bounds."); - } - - return streamProvider._bufferedData[index].start; - }, - end: function end(index) { - if (index < 0 || index >= streamProvider._bufferedData.length) { - throw new Error("Buffered index out of bounds."); - } - - return streamProvider._bufferedData[index].end; - } - }; - Object.defineProperty(this._buffered, "length", { - get: function get() { - return streamProvider._bufferedData.length; - } - }); - } - - _createClass(StreamProvider, [{ - key: "buffered", - get: function get() { - updateBuffers.apply(this); - return this._buffered; - } - }, { - key: "init", - value: function init(videoData) { - var _this79 = this; - - if (videoData.length == 0) throw Error("Empty video data."); - this._videoData = videoData; - - if (!this._videoData.some(function (stream) { - return stream.role == "master"; - })) { - this._videoData[0].role = "master"; - } - - this._videoData.forEach(function (stream, index) { - stream.type = stream.type || 'video'; - - if (stream.role == 'master') { - _this79._mainStream = stream; - } - - if (stream.type == 'video') { - _this79._videoStreams.push(stream); - } else if (stream.type == 'audio') { - _this79._audioStreams.push(stream); - } - }); - - if (this._videoStreams.length == 0) { - throw new Error("No video streams found. Paella Player requires at least one video stream."); - } // Create video players - - - var autoplay = this.autoplay; - - this._videoStreams.forEach(function (videoStream, index) { - var rect = { - x: 0, - y: 0, - w: 1280, - h: 720 - }; - var player = paella.videoFactory.getVideoObject("video_".concat(index), videoStream, rect); - player.setVideoQualityStrategy(_this79._qualityStrategy); - player.setAutoplay(autoplay); - - if (videoStream == _this79._mainStream) { - _this79._mainPlayer = player; - _this79._audioPlayer = player; - } else { - player.setVolume(0); - } - - _this79._videoPlayers.push(player); - - _this79._players.push(player); - }); // Create audio player - - - this._audioStreams.forEach(function (audioStream, index) { - var player = paella.audioFactory.getAudioObject("audio_".concat(index), audioStream); - player.setAutoplay(autoplay); - - if (player) { - _this79._audioPlayers.push(player); - - _this79._players.push(player); - } - }); - } - }, { - key: "startVideoSync", - value: function startVideoSync(syncProviderPlayer) { - var _this80 = this; - - this._syncProviderPlayer = syncProviderPlayer; - this._audioPlayer = syncProviderPlayer; // The player that provides the synchronization is also used as main audio player. - - this.stopVideoSync(); - console.debug("Start sync to player:"); - console.debug(this._syncProviderPlayer); - var maxDiff = 0.1; - var totalTime = 0; - var numberOfSyncs = 0; - var syncFrequency = 0; - var maxSyncFrequency = 0.2; - - var sync = function sync() { - _this80._syncProviderPlayer.currentTime().then(function (t) { - _this80.players.forEach(function (player) { - if (player != syncProviderPlayer && player.currentTimeSync != null && Math.abs(player.currentTimeSync - t) > maxDiff) { - console.debug("Sync player current time: ".concat(player.currentTimeSync, " to time ").concat(t)); - console.debug(player); - ++numberOfSyncs; - player.setCurrentTime(t); - - if (syncFrequency > maxSyncFrequency) { - maxDiff *= 1.5; - console.log("Maximum syncrhonization frequency reached. Increasing max difference syncronization time to ".concat(maxDiff)); - } - } - }); - }); - - totalTime += 1000; - syncFrequency = numberOfSyncs / (totalTime / 1000); - _this80._syncTimer = setTimeout(function () { - return sync(); - }, 1000); - }; - - this._syncTimer = setTimeout(function () { - return sync(); - }, 1000); - } - }, { - key: "stopVideoSync", - value: function stopVideoSync() { - if (this._syncTimer) { - console.debug("Stop video sync"); - clearTimeout(this._syncTimer); - this._syncTimer = null; - } - } - }, { - key: "loadVideos", - value: function loadVideos() { - var promises = []; - - this._players.forEach(function (player) { - promises.push(player.load()); - }); - - return Promise.all(promises); - } - }, { - key: "startTime", - get: function get() { - return this._startTime; - }, - set: function set(s) { - this._startTime = s; - } - }, { - key: "isMonostream", - get: function get() { - return this._videoStreams.length == 1; - } - }, { - key: "mainStream", - get: function get() { - return this._mainStream; - } - }, { - key: "videoStreams", - get: function get() { - //return this._videoData; - return this._videoStreams; - } - }, { - key: "audioStreams", - get: function get() { - return this._audioStreams; - } - }, { - key: "streams", - get: function get() { - return this._videoStreams.concat(this._audioStreams); - } - }, { - key: "videoPlayers", - get: function get() { - return this._videoPlayers; - } - }, { - key: "audioPlayers", - get: function get() { - return this._audioPlayers; - } - }, { - key: "players", - get: function get() { - return this._videoPlayers.concat(this._audioPlayers); - } - }, { - key: "callPlayerFunction", - value: function callPlayerFunction(fnName) { - var _this81 = this; - - var promises = []; - var functionArguments = []; - - for (var i = 1; i < arguments.length; ++i) { - functionArguments.push(arguments[i]); - } - - this.players.forEach(function (player) { - promises.push(player[fnName].apply(player, functionArguments)); - }); - return new Promise(function (resolve, reject) { - Promise.all(promises).then(function () { - if (fnName == 'play' && !_this81._firstPlay) { - _this81._firstPlay = true; - - if (_this81._startTime) { - _this81.players.forEach(function (p) { - return p.setCurrentTime(_this81._startTime); - }); - } - } - - resolve(); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "mainVideoPlayer", - get: function get() { - return this._mainPlayer; - } - }, { - key: "mainAudioPlayer", - get: function get() { - return this._audioPlayer; - } - }, { - key: "mainPlayer", - get: function get() { - return this.mainVideoPlayer || this.mainAudioPlayer; - } - }, { - key: "isLiveStreaming", - get: function get() { - return paella.player.isLiveStream(); - } - }, { - key: "qualityStrategy", - get: function get() { - return this._qualityStrategy || null; - }, - set: function set(strategy) { - this._qualityStrategy = strategy; - - this._videoPlayers.forEach(function (player) { - player.setVideoQualityStrategy(strategy); - }); - } - }, { - key: "autoplay", - get: function get() { - return this.supportAutoplay && this._autoplay; - }, - set: function set(ap) { - if (!this.supportAutoplay || this.isLiveStreaming) return; - this._autoplay = ap; - - if (this.videoPlayers) { - this.videoPlayers.forEach(function (player) { - return player.setAutoplay(ap); - }); - this.audioPlayers.forEach(function (player) { - return player.setAutoplay(ap); - }); - } - } - }, { - key: "supportAutoplay", - get: function get() { - return this.videoPlayers.every(function (player) { - return player.supportAutoplay(); - }); - } - }]); - - return StreamProvider; - }(); - - paella.StreamProvider = StreamProvider; - - function addVideoWrapper(id, videoPlayer) { - var wrapper = new paella.VideoWrapper(id); - wrapper.addNode(videoPlayer); - this.videoWrappers.push(wrapper); - this.container.addNode(wrapper); - return wrapper; - } - - var VideoContainer = /*#__PURE__*/function (_paella$VideoContaine) { - _inherits(VideoContainer, _paella$VideoContaine); - - var _super21 = _createSuper(VideoContainer); - - function VideoContainer(id) { - var _this82; - - _classCallCheck(this, VideoContainer); - - _this82 = _super21.call(this, id); - _this82._streamProvider = new paella.StreamProvider(); - _this82._ready = false; - _this82._videoWrappers = []; - _this82._container = new paella.DomNode('div', 'playerContainer_videoContainer_container', { - position: 'relative', - display: 'block', - marginLeft: 'auto', - marginRight: 'auto', - width: '1024px', - height: '567px' - }); - - _this82._container.domElement.setAttribute('role', 'main'); - - _this82.addNode(_this82._container); - - _this82.overlayContainer = new paella.VideoOverlay(_this82.domElement); - - _this82.container.addNode(_this82.overlayContainer); - - _this82.setProfileFrameStrategy(paella.ProfileFrameStrategy.Factory()); - - _this82.setVideoQualityStrategy(paella.VideoQualityStrategy.Factory()); - - _this82._audioTag = paella.player.config.player.defaultAudioTag || paella.utils.dictionary.currentLanguage(); - _this82._audioPlayer = null; // Initial volume level - - _this82._volume = paella.utils.cookies.get("volume") ? Number(paella.utils.cookies.get("volume")) : 1; - - if (paella.player.startMuted) { - _this82._volume = 0; - } - - _this82._muted = false; - return _this82; - } // Playback and status functions - - - _createClass(VideoContainer, [{ - key: "streamProvider", - get: function get() { - return this._streamProvider; - } - }, { - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "isMonostream", - get: function get() { - return this._streamProvider.isMonostream; - } - }, { - key: "trimmingHandler", - get: function get() { - return this._trimmingHandler; - } - }, { - key: "videoWrappers", - get: function get() { - return this._videoWrappers; - } - }, { - key: "container", - get: function get() { - return this._container; - } - }, { - key: "profileFrameStrategy", - get: function get() { - return this._profileFrameStrategy; - } - }, { - key: "sourceData", - get: function get() { - return this._sourceData; - } - }, { - key: "play", - value: function play() { - var _this83 = this; - - return new Promise(function (resolve, reject) { - _this83.ended().then(function (ended) { - if (ended) { - _this83._streamProvider.startTime = 0; - - _this83.seekToTime(0); - } else { - _this83.streamProvider.startTime = _this83._startTime; - } - - return _this83.streamProvider.callPlayerFunction('play'); - }).then(function () { - _get(_getPrototypeOf(VideoContainer.prototype), "play", _this83).call(_this83); - - resolve(); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "pause", - value: function pause() { - var _this84 = this; - - return new Promise(function (resolve, reject) { - _this84.streamProvider.callPlayerFunction('pause').then(function () { - _get(_getPrototypeOf(VideoContainer.prototype), "pause", _this84).call(_this84); - - resolve(); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this85 = this; - - return new Promise(function (resolve, reject) { - _this85.trimming().then(function (trimmingData) { - if (trimmingData.enabled) { - time += trimmingData.start; - - if (time < trimmingData.start) { - time = trimmingData.start; - } - - if (time > trimmingData.end) { - time = trimmingData.end; - } - } - - return _this85.streamProvider.callPlayerFunction('setCurrentTime', time); - }).then(function () { - return _this85.duration(false); - }).then(function (duration) { - resolve({ - time: time, - duration: duration - }); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this86 = this; - - var ignoreTrimming = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return new Promise(function (resolve) { - var trimmingData = null; - var p = ignoreTrimming ? Promise.resolve({ - enabled: false - }) : _this86.trimming(); - p.then(function (t) { - trimmingData = t; - return _this86.masterVideo().currentTime(); - }).then(function (time) { - if (trimmingData.enabled) { - time = time - trimmingData.start; - } - - if (time < 0) time = 0; - resolve(time); - }); - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - this.streamProvider.callPlayerFunction('setPlaybackRate', rate); - - _get(_getPrototypeOf(VideoContainer.prototype), "setPlaybackRate", this).call(this, rate); - } - }, { - key: "mute", - value: function mute() { - var _this87 = this; - - return new Promise(function (resolve) { - _this87._muted = true; - - _this87._audioPlayer.setVolume(0).then(function () { - paella.events.trigger(paella.events.setVolume, { - master: 0 - }); - resolve(); - }); - }); - } - }, { - key: "unmute", - value: function unmute() { - var _this88 = this; - - return new Promise(function (resolve) { - _this88._muted = false; - - _this88._audioPlayer.setVolume(_this88._volume).then(function () { - paella.events.trigger(paella.events.setVolume, { - master: _this88._volume - }); - resolve(); - }); - }); - } - }, { - key: "muted", - get: function get() { - return this._muted; - } - }, { - key: "setVolume", - value: function setVolume(params) { - var _this89 = this; - - if (_typeof(params) == 'object') { - console.warn("videoContainer.setVolume(): set parameter as object is deprecated"); - return Promise.resolve(); - } else if (params == 0) { - return this.mute(); - } else { - return new Promise(function (resolve, reject) { - paella.utils.cookies.set("volume", params); - _this89._volume = params; - - _this89._audioPlayer.setVolume(params).then(function () { - paella.events.trigger(paella.events.setVolume, { - master: params - }); - resolve(params); - }).catch(function (err) { - reject(err); - }); - }); - } - } - }, { - key: "volume", - value: function volume() { - return this._audioPlayer.volume(); - } - }, { - key: "duration", - value: function duration() { - var _this90 = this; - - var ignoreTrimming = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return new Promise(function (resolve) { - var trimmingData = null; - var p = ignoreTrimming ? Promise.resolve({ - enabled: false - }) : _this90.trimming(); - p.then(function (t) { - trimmingData = t; - return _this90.masterVideo().duration(); - }).then(function (duration) { - if (trimmingData.enabled) { - duration = trimmingData.end - trimmingData.start; - } - - resolve(duration); - }); - }); - } - }, { - key: "paused", - value: function paused() { - return this.masterVideo().isPaused(); - } // Video quality functions - - }, { - key: "getQualities", - value: function getQualities() { - return this.masterVideo().getQualities(); - } - }, { - key: "setQuality", - value: function setQuality(index) { - var qualities = []; - var promises = []; - this.streamProvider.videoPlayers.forEach(function (player) { - var playerData = { - player: player, - promise: player.getQualities() - }; - qualities.push(playerData); - promises.push(playerData.promise); - }); - return new Promise(function (resolve) { - var resultPromises = []; - Promise.all(promises).then(function () { - qualities.forEach(function (data) { - data.promise.then(function (videoQualities) { - var videoQuality = videoQualities.length > index ? index : videoQualities.length - 1; - resultPromises.push(data.player.setQuality(videoQuality)); - }); - }); - return Promise.all(resultPromises); - }).then(function () { - //setTimeout(() => { - paella.events.trigger(paella.events.qualityChanged); - resolve(); //},10); - }); - }); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - return this.masterVideo().getCurrentQuality(); - } // Current audio functions - - }, { - key: "audioTag", - get: function get() { - return this._audioTag; - } - }, { - key: "audioPlayer", - get: function get() { - return this._audioPlayer; - } - }, { - key: "getAudioTags", - value: function getAudioTags() { - var _this91 = this; - - return new Promise(function (resolve) { - var lang = []; - var p = _this91.streamProvider.players; - p.forEach(function (player) { - if (player.stream.audioTag) { - lang.push(player.stream.audioTag); - } - }); - resolve(lang); - }); - } - }, { - key: "setAudioTag", - value: function setAudioTag(lang) { - var _this92 = this; - - this.streamProvider.stopVideoSync(); - return new Promise(function (resolve) { - var audioSet = false; - var firstAudioPlayer = null; - var promises = []; - - _this92.streamProvider.players.forEach(function (player) { - if (!firstAudioPlayer) { - firstAudioPlayer = player; - } - - if (!audioSet && player.stream.audioTag == lang) { - audioSet = true; - _this92._audioPlayer = player; - } - - promises.push(player.setVolume(0)); - }); // NOTE: The audio only streams must define a valid audio tag - - - if (!audioSet && _this92.streamProvider.mainVideoPlayer) { - _this92._audioPlayer = _this92.streamProvider.mainVideoPlayer; - } else if (!audioSet && firstAudioPlayer) { - _this92._audioPlayer = firstAudioPlayer; - } - - Promise.all(promises).then(function () { - return _this92._audioPlayer.setVolume(_this92._volume); - }).then(function () { - _this92._audioTag = _this92._audioPlayer.stream.audioTag; - paella.events.trigger(paella.events.audioTagChanged); - - _this92.streamProvider.startVideoSync(_this92.audioPlayer); - - resolve(); - }); - }); - } - }, { - key: "setProfileFrameStrategy", - value: function setProfileFrameStrategy(strategy) { - this._profileFrameStrategy = strategy; - } - }, { - key: "setVideoQualityStrategy", - value: function setVideoQualityStrategy(strategy) { - this.streamProvider.qualityStrategy = strategy; - } - }, { - key: "autoplay", - value: function autoplay() { - return this.streamProvider.autoplay; - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return this.streamProvider.supportAutoplay; - } - }, { - key: "setAutoplay", - value: function setAutoplay() { - var ap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - this.streamProvider.autoplay = ap; - return this.streamProvider.supportAutoplay; - } - }, { - key: "masterVideo", - value: function masterVideo() { - return this.streamProvider.mainVideoPlayer || this.audioPlayer; - } - }, { - key: "getVideoRect", - value: function getVideoRect(videoIndex) { - if (this.videoWrappers.length > videoIndex) { - return this.videoWrappers[videoIndex].getRect(); - } else { - throw new Error("Video wrapper with index ".concat(videoIndex, " not found")); - } - } - }, { - key: "setStreamData", - value: function setStreamData(videoData) { - var _this93 = this; - - var urlParamTime = paella.utils.parameters.get("time"); - var hashParamTime = paella.utils.hashParams.get("time"); - var timeString = hashParamTime ? hashParamTime : urlParamTime ? urlParamTime : "0s"; - var startTime = paella.utils.timeParse.timeToSeconds(timeString); - - if (startTime) { - this._startTime = startTime; - } - - videoData.forEach(function (stream) { - for (var type in stream.sources) { - var source = stream.sources[type]; - source.forEach(function (item) { - if (item.res) { - item.res.w = Number(item.res.w); - item.res.h = Number(item.res.h); - } - }); - } - }); - this._sourceData = videoData; - return new Promise(function (resolve, reject) { - _this93.streamProvider.init(videoData); - - var streamDataAudioTag = null; - videoData.forEach(function (video) { - if (video.audioTag && streamDataAudioTag == null) { - streamDataAudioTag = video.audioTag; - } - - if (video.audioTag == _this93._audioTag) { - streamDataAudioTag = _this93._audioTag; - } - }); - - if (streamDataAudioTag != _this93._audioTag && streamDataAudioTag != null) { - _this93._audioTag = streamDataAudioTag; - } - - _this93.streamProvider.videoPlayers.forEach(function (player, index) { - addVideoWrapper.apply(_this93, ['videoPlayerWrapper_' + index, player]); - player.setAutoplay(_this93.autoplay()); - }); - - _this93.streamProvider.loadVideos().catch(function (err) { - reject(err); - }).then(function () { - return _this93.setAudioTag(_this93.audioTag); - }).then(function () { - var endedTimer = null; - - var setupEndEventTimer = function setupEndEventTimer() { - _this93.stopTimeupdate(); - - if (endedTimer) { - clearTimeout(endedTimer); - endedTimer = null; - } - - endedTimer = setTimeout(function () { - paella.events.trigger(paella.events.ended); - }, 1000); - }; - - var eventBindingObject = _this93.masterVideo().video || _this93.masterVideo().audio; - - $(eventBindingObject).bind('timeupdate', function (evt) { - _this93.trimming().then(function (trimmingData) { - var current = evt.currentTarget.currentTime; - var duration = evt.currentTarget.duration; - - if (trimmingData.enabled) { - current -= trimmingData.start; - duration = trimmingData.end - trimmingData.start; - } - - if (current >= duration) { - _this93.streamProvider.callPlayerFunction('pause'); - - setupEndEventTimer(); - } - }); - }); - paella.events.bind(paella.events.endVideo, function (event) { - setupEndEventTimer(); - }); - _this93._ready = true; - paella.events.trigger(paella.events.videoReady); - var profileToUse = paella.utils.parameters.get('profile') || paella.utils.cookies.get('profile') || paella.profiles.getDefaultProfile(); - - if (paella.profiles.setProfile(profileToUse, false)) { - resolve(); - } else if (!paella.profiles.setProfile(paella.profiles.getDefaultProfile(), false)) { - resolve(); - } - }); - }); - } - }, { - key: "resizePortrait", - value: function resizePortrait() { - var width = paella.player.isFullScreen() == true ? $(window).width() : $(this.domElement).width(); - var relativeSize = new paella.RelativeVideoSize(); - var height = relativeSize.proportionalHeight(width); - this.container.domElement.style.width = width + 'px'; - this.container.domElement.style.height = height + 'px'; - var containerHeight = paella.player.isFullScreen() == true ? $(window).height() : $(this.domElement).height(); - var newTop = containerHeight / 2 - height / 2; - this.container.domElement.style.top = newTop + "px"; - } - }, { - key: "resizeLandscape", - value: function resizeLandscape() { - var height = paella.player.isFullScreen() == true ? $(window).height() : $(this.domElement).height(); - var relativeSize = new paella.RelativeVideoSize(); - var width = relativeSize.proportionalWidth(height); - this.container.domElement.style.width = width + 'px'; - this.container.domElement.style.height = height + 'px'; - this.container.domElement.style.top = '0px'; - } - }, { - key: "onresize", - value: function onresize() { - _get(_getPrototypeOf(VideoContainer.prototype), "onresize", this).call(this); - - var relativeSize = new paella.RelativeVideoSize(); - var aspectRatio = relativeSize.aspectRatio(); - var width = paella.player.isFullScreen() == true ? $(window).width() : $(this.domElement).width(); - var height = paella.player.isFullScreen() == true ? $(window).height() : $(this.domElement).height(); - var containerAspectRatio = width / height; - - if (containerAspectRatio > aspectRatio) { - this.resizeLandscape(); - } else { - this.resizePortrait(); - } //paella.profiles.setProfile(paella.player.selectedProfile,false) - - } // the duration and the current time are returned taking into account the trimming, for example: - // trimming: { enabled: true, start: 10, end: 110 } - // currentTime: 0, > the actual time is 10 - // duration: 100 > the actual duration is (at least) 110 - - }, { - key: "getVideoData", - value: function getVideoData() { - var _this94 = this; - - return new Promise(function (resolve, reject) { - var videoData = { - currentTime: 0, - volume: 0, - muted: _this94.muted, - duration: 0, - paused: false, - audioTag: _this94.audioTag, - trimming: { - enabled: false, - start: 0, - end: 0 - } - }; - - _this94.currentTime().then(function (currentTime) { - videoData.currentTime = currentTime; - return _this94.volume(); - }).then(function (v) { - videoData.volume = v; - return _this94.duration(); - }).then(function (d) { - videoData.duration = d; - return _this94.paused(); - }).then(function (p) { - videoData.paused = p; - return _this94.trimming(); - }).then(function (trimming) { - videoData.trimming = trimming; - resolve(videoData); - }).catch(function (err) { - return reject(err); - }); - }); - } - }]); - - return VideoContainer; - }(paella.VideoContainerBase); - - paella.VideoContainer = VideoContainer; -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may - obtain a copy of the License at - - http://www.osedu.org/licenses/ECL-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - or implied. See the License for the specific language governing - permissions and limitations under the License. -*/ - - -(function () { - var PluginManager = /*#__PURE__*/function () { - function PluginManager() { - var _this95 = this; - - _classCallCheck(this, PluginManager); - - this.targets = null; - this.pluginList = []; - this.eventDrivenPlugins = []; - this.enabledPlugins = []; - this.doResize = true; - this.targets = {}; - paella.events.bind(paella.events.loadPlugins, function (event) { - _this95.loadPlugins("paella.DeferredLoadPlugin"); - }); - var timer = new paella.utils.Timer(function () { - if (paella.player && paella.player.controls && _this95.doResize) paella.player.controls.onresize(); - }, 1000); - timer.repeat = true; - } - - _createClass(PluginManager, [{ - key: "setupPlugin", - value: function setupPlugin(plugin) { - plugin.setup(); - this.enabledPlugins.push(plugin); - - if (eval("plugin instanceof paella.UIPlugin")) { - plugin.checkVisibility(); - } - } - }, { - key: "checkPluginsVisibility", - value: function checkPluginsVisibility() { - this.enabledPlugins.forEach(function (plugin) { - if (eval("plugin instanceof paella.UIPlugin")) { - plugin.checkVisibility(); - } - }); - } - }, { - key: "setTarget", - value: function setTarget(pluginType, target) { - if (target.addPlugin) { - this.targets[pluginType] = target; - } - } - }, { - key: "getTarget", - value: function getTarget(pluginType) { - // PluginManager can handle event-driven events: - if (pluginType == "eventDriven") { - return this; - } else { - var target = this.targets[pluginType]; - return target; - } - } - }, { - key: "registerPlugin", - value: function registerPlugin(plugin) { - // Registra los plugins en una lista y los ordena - this.importLibraries(plugin); - this.pluginList.push(plugin); - this.pluginList.sort(function (a, b) { - return a.getIndex() - b.getIndex(); - }); - } - }, { - key: "importLibraries", - value: function importLibraries(plugin) { - plugin.getDependencies().forEach(function (lib) { - var script = document.createElement('script'); - script.type = "text/javascript"; - script.src = 'javascript/' + lib + '.js'; - document.head.appendChild(script); - }); - } // callback => function(plugin,pluginConfig) - - }, { - key: "loadPlugins", - value: function loadPlugins(pluginBaseClass) { - if (pluginBaseClass != undefined) { - var This = this; - this.foreach(function (plugin, config) { - // Prevent load a plugin twice - if (plugin.isLoaded()) return; - - if (eval("plugin instanceof " + pluginBaseClass)) { - if (config.enabled) { - paella.log.debug("Load plugin (" + pluginBaseClass + "): " + plugin.getName()); - plugin.config = config; - plugin.load(This); - } - } - }); - } - } - }, { - key: "foreach", - value: function foreach(callback) { - var enablePluginsByDefault = false; - var pluginsConfig = {}; - - try { - enablePluginsByDefault = paella.player.config.plugins.enablePluginsByDefault; - } catch (e) {} - - try { - pluginsConfig = paella.player.config.plugins.list; - } catch (e) {} - - this.pluginList.forEach(function (plugin) { - var name = plugin.getName(); - var config = pluginsConfig[name]; - - if (!config) { - config = { - enabled: enablePluginsByDefault - }; - } - - callback(plugin, config); - }); - } - }, { - key: "addPlugin", - value: function addPlugin(plugin) { - var _this96 = this; - - // Prevent add a plugin twice - if (plugin.__added__) return; - plugin.__added__ = true; - plugin.checkEnabled(function (isEnabled) { - if (plugin.type == "eventDriven" && isEnabled) { - paella.pluginManager.setupPlugin(plugin); - - _this96.eventDrivenPlugins.push(plugin); - - var events = plugin.getEvents(); - - var eventBind = function eventBind(event, params) { - plugin.onEvent(event.type, params); - }; - - for (var i = 0; i < events.length; ++i) { - var eventName = events[i]; - paella.events.bind(eventName, eventBind); - } - } - }); - } - }, { - key: "getPlugin", - value: function getPlugin(name) { - for (var i = 0; i < this.pluginList.length; ++i) { - if (this.pluginList[i].getName() == name) return this.pluginList[i]; - } - - return null; - } - }, { - key: "registerPlugins", - value: function registerPlugins() { - g_pluginCallbackList.forEach(function (pluginCallback) { - var PluginClass = pluginCallback(); - var pluginInstance = new PluginClass(); - - if (pluginInstance.getInstanceName()) { - paella.plugins = paella.plugins || {}; - paella.plugins[pluginInstance.getInstanceName()] = pluginInstance; - } - - paella.pluginManager.registerPlugin(pluginInstance); - }); - } - }]); - - return PluginManager; - }(); - - paella.PluginManager = PluginManager; - paella.pluginManager = new paella.PluginManager(); - var g_pluginCallbackList = []; - - paella.addPlugin = function (cb) { - g_pluginCallbackList.push(cb); - }; - - var Plugin = /*#__PURE__*/function () { - function Plugin() { - _classCallCheck(this, Plugin); - } - - _createClass(Plugin, [{ - key: "type", - get: function get() { - return ""; - } - }, { - key: "isLoaded", - value: function isLoaded() { - return this.__loaded__; - } - }, { - key: "getDependencies", - value: function getDependencies() { - return []; - } - }, { - key: "load", - value: function load(pluginManager) { - if (this.__loaded__) return; - this.__loaded__ = true; - var target = pluginManager.getTarget(this.type); - - if (target && target.addPlugin) { - target.addPlugin(this); - } - } - }, { - key: "getInstanceName", - value: function getInstanceName() { - return null; - } - }, { - key: "getRootNode", - value: function getRootNode(id) { - return null; - } - }, { - key: "checkEnabled", - value: function checkEnabled(onSuccess) { - onSuccess(true); - } - }, { - key: "setup", - value: function setup() {} - }, { - key: "getIndex", - value: function getIndex() { - return 0; - } - }, { - key: "getName", - value: function getName() { - return ""; - } - }]); - - return Plugin; - }(); - - paella.Plugin = Plugin; - - var FastLoadPlugin = /*#__PURE__*/function (_paella$Plugin) { - _inherits(FastLoadPlugin, _paella$Plugin); - - var _super22 = _createSuper(FastLoadPlugin); - - function FastLoadPlugin() { - _classCallCheck(this, FastLoadPlugin); - - return _super22.apply(this, arguments); - } - - return FastLoadPlugin; - }(paella.Plugin); - - var EarlyLoadPlugin = /*#__PURE__*/function (_paella$Plugin2) { - _inherits(EarlyLoadPlugin, _paella$Plugin2); - - var _super23 = _createSuper(EarlyLoadPlugin); - - function EarlyLoadPlugin() { - _classCallCheck(this, EarlyLoadPlugin); - - return _super23.apply(this, arguments); - } - - return EarlyLoadPlugin; - }(paella.Plugin); - - var DeferredLoadPlugin = /*#__PURE__*/function (_paella$Plugin3) { - _inherits(DeferredLoadPlugin, _paella$Plugin3); - - var _super24 = _createSuper(DeferredLoadPlugin); - - function DeferredLoadPlugin() { - _classCallCheck(this, DeferredLoadPlugin); - - return _super24.apply(this, arguments); - } - - return DeferredLoadPlugin; - }(paella.Plugin); - - paella.FastLoadPlugin = FastLoadPlugin; - paella.EarlyLoadPlugin = EarlyLoadPlugin; - paella.DeferredLoadPlugin = DeferredLoadPlugin; - - function addMenuItemTabindex(plugin) { - if (plugin.button.tabIndex > 0) { - paella.tabIndex.insertAfter(plugin.button, plugin.menuContent.children); - } - } - - function removeMenuItemTabindexplugin(plugin) { - if (plugin.button.tabIndex > 0) { - paella.tabIndex.removeTabIndex(plugin.menuContent.children); - } - } - - function _hideContainer(identifier, container, swapFocus) { - paella.events.trigger(paella.events.hidePopUp, { - container: container - }); - container.plugin.willHideContent(); - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton) { - removeMenuItemTabindexplugin(container.plugin); - } - - $(container.element).hide(); - $(this.domElement).css({ - width: '0px' - }); - container.button.className = container.button.className.replace(' selected', ''); - this.currentContainerId = -1; - container.plugin.didHideContent(); - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton && swapFocus) { - $(container.button).focus(); - } - } - - function _showContainer(identifier, container, button, swapFocus) { - paella.events.trigger(paella.events.showPopUp, { - container: container - }); - container.plugin.willShowContent(); - container.button.className = container.button.className + ' selected'; - $(container.element).show(); - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton) { - addMenuItemTabindex(container.plugin); - } - - var width = $(container.element).width(); - - if (container.plugin.getAlignment() == 'right') { - var right = $(button.parentElement).width() - $(button).position().left - $(button).width(); - $(this.domElement).css({ - width: width + 'px', - right: right + 'px', - left: '' - }); - } else { - var left = $(button).position().left; - $(this.domElement).css({ - width: width + 'px', - left: left + 'px', - right: '' - }); - } - - this.currentContainerId = identifier; - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton && container.plugin.menuContent.children.length > 0 && swapFocus) { - $(container.plugin.menuContent.children[0]).focus(); - } - - container.plugin.didShowContent(); - } - - var PopUpContainer = /*#__PURE__*/function (_paella$DomNode8) { - _inherits(PopUpContainer, _paella$DomNode8); - - var _super25 = _createSuper(PopUpContainer); - - function PopUpContainer(id, className) { - var _this97; - - _classCallCheck(this, PopUpContainer); - - var style = {}; - _this97 = _super25.call(this, 'div', id, style); - _this97.containers = null; - _this97.currentContainerId = -1; - _this97.domElement.className = className; - _this97.containers = {}; - return _this97; - } - - _createClass(PopUpContainer, [{ - key: "hideContainer", - value: function hideContainer(identifier, button) { - var swapFocus = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var container = this.containers[identifier]; - - if (container) { - _hideContainer.apply(this, [identifier, container, swapFocus]); - } - } - }, { - key: "showContainer", - value: function showContainer(identifier, button) { - var swapFocus = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var container = this.containers[identifier]; - - if (container && this.currentContainerId != identifier && this.currentContainerId != -1) { - var prevContainer = this.containers[this.currentContainerId]; - - _hideContainer.apply(this, [this.currentContainerId, prevContainer, swapFocus]); - - _showContainer.apply(this, [identifier, container, button, swapFocus]); - } else if (container && this.currentContainerId == identifier) { - _hideContainer.apply(this, [identifier, container, swapFocus]); - } else if (container) { - _showContainer.apply(this, [identifier, container, button, swapFocus]); - } - } - }, { - key: "registerContainer", - value: function registerContainer(identifier, domElement, button, plugin) { - var containerInfo = { - identifier: identifier, - button: button, - element: domElement, - plugin: plugin - }; - this.containers[identifier] = containerInfo; - - if (plugin.closeOnMouseOut && plugin.closeOnMouseOut()) { - var popUpId = identifier; - var btn = button; - $(domElement).mouseleave(function (evt) { - paella.player.controls.playbackControl().hidePopUp(popUpId, btn); - }); - } // this.domElement.appendChild(domElement); - - - $(domElement).hide(); - button.popUpIdentifier = identifier; - button.sourcePlugin = plugin; - $(button).click(function (event) { - if (!this.plugin.isPopUpOpen()) { - paella.player.controls.playbackControl().showPopUp(this.popUpIdentifier, this, false); - } else { - paella.player.controls.playbackControl().hidePopUp(this.popUpIdentifier, this, false); - } - }); - $(button).keypress(function (event) { - if (event.keyCode == 13 && !this.plugin.isPopUpOpen()) { - if (this.plugin.isPopUpOpen()) { - paella.player.controls.playbackControl().hidePopUp(this.popUpIdentifier, this, true); - } else { - paella.player.controls.playbackControl().showPopUp(this.popUpIdentifier, this, true); - } - } else if (event.keyCode == 27) { - paella.player.controls.playbackControl().hidePopUp(this.popUpIdentifier, this, true); - } - - event.preventDefault(); - }); - $(button).keyup(function (event) { - event.preventDefault(); - }); - plugin.containerManager = this; - } - }]); - - return PopUpContainer; - }(paella.DomNode); - - paella.PopUpContainer = PopUpContainer; - - var TimelineContainer = /*#__PURE__*/function (_paella$PopUpContaine) { - _inherits(TimelineContainer, _paella$PopUpContaine); - - var _super26 = _createSuper(TimelineContainer); - - function TimelineContainer() { - _classCallCheck(this, TimelineContainer); - - return _super26.apply(this, arguments); - } - - _createClass(TimelineContainer, [{ - key: "hideContainer", - value: function hideContainer(identifier, button) { - var container = this.containers[identifier]; - - if (container && this.currentContainerId == identifier) { - paella.events.trigger(paella.events.hidePopUp, { - container: container - }); - container.plugin.willHideContent(); - $(container.element).hide(); - container.button.className = container.button.className.replace(' selected', ''); - this.currentContainerId = -1; - $(this.domElement).css({ - height: '0px' - }); - container.plugin.didHideContent(); - } - } - }, { - key: "showContainer", - value: function showContainer(identifier, button) { - var height = 0; - var container = this.containers[identifier]; - - if (container && this.currentContainerId != identifier && this.currentContainerId != -1) { - var prevContainer = this.containers[this.currentContainerId]; - prevContainer.button.className = prevContainer.button.className.replace(' selected', ''); - container.button.className = container.button.className + ' selected'; - paella.events.trigger(paella.events.hidePopUp, { - container: prevContainer - }); - prevContainer.plugin.willHideContent(); - $(prevContainer.element).hide(); - prevContainer.plugin.didHideContent(); - paella.events.trigger(paella.events.showPopUp, { - container: container - }); - container.plugin.willShowContent(); - $(container.element).show(); - this.currentContainerId = identifier; - height = $(container.element).height(); - $(this.domElement).css({ - height: height + 'px' - }); - container.plugin.didShowContent(); - } else if (container && this.currentContainerId == identifier) { - paella.events.trigger(paella.events.hidePopUp, { - container: container - }); - container.plugin.willHideContent(); - $(container.element).hide(); - container.button.className = container.button.className.replace(' selected', ''); - $(this.domElement).css({ - height: '0px' - }); - this.currentContainerId = -1; - container.plugin.didHideContent(); - } else if (container) { - paella.events.trigger(paella.events.showPopUp, { - container: container - }); - container.plugin.willShowContent(); - container.button.className = container.button.className + ' selected'; - $(container.element).show(); - this.currentContainerId = identifier; - height = $(container.element).height(); - $(this.domElement).css({ - height: height + 'px' - }); - container.plugin.didShowContent(); - } - } - }]); - - return TimelineContainer; - }(paella.PopUpContainer); - - paella.TimelineContainer = TimelineContainer; - - var UIPlugin = /*#__PURE__*/function (_paella$DeferredLoadP) { - _inherits(UIPlugin, _paella$DeferredLoadP); - - var _super27 = _createSuper(UIPlugin); - - function UIPlugin() { - _classCallCheck(this, UIPlugin); - - return _super27.apply(this, arguments); - } - - _createClass(UIPlugin, [{ - key: "ui", - get: function get() { - return this._ui; - }, - set: function set(val) { - this._ui = val; - } - }, { - key: "checkVisibility", - value: function checkVisibility() { - var modes = this.config.visibleOn || [paella.PaellaPlayer.mode.standard, paella.PaellaPlayer.mode.fullscreen, paella.PaellaPlayer.mode.embed]; - var visible = false; - modes.forEach(function (m) { - if (m == paella.player.getPlayerMode()) { - visible = true; - } - }); - - if (visible) { - this.showUI(); - } else { - this.hideUI(); - } - } - }, { - key: "hideUI", - value: function hideUI() { - this.ui.setAttribute('aria-hidden', 'true'); - $(this.ui).hide(); - } - }, { - key: "showUI", - value: function showUI() { - var thisClass = this; - paella.pluginManager.enabledPlugins.forEach(function (p) { - if (p == thisClass) { - thisClass.ui.setAttribute('aria-hidden', 'false'); - $(thisClass.ui).show(); - } - }); - } - }]); - - return UIPlugin; - }(paella.DeferredLoadPlugin); - - paella.UIPlugin = UIPlugin; - - var ButtonPlugin = /*#__PURE__*/function (_paella$UIPlugin) { - _inherits(ButtonPlugin, _paella$UIPlugin); - - var _super28 = _createSuper(ButtonPlugin); - - function ButtonPlugin() { - var _this98; - - _classCallCheck(this, ButtonPlugin); - - _this98 = _super28.call(this); - _this98.subclass = ''; - _this98.container = null; - _this98.containerManager = null; - _this98._domElement = null; - return _this98; - } - - _createClass(ButtonPlugin, [{ - key: "type", - get: function get() { - return 'button'; - } - }, { - key: "getAlignment", - value: function getAlignment() { - return 'left'; // or right - } // Returns the button subclass. - - }, { - key: "getSubclass", - value: function getSubclass() { - return "myButtonPlugin"; - } - }, { - key: "getIconClass", - value: function getIconClass() { - return ""; - } - }, { - key: "addSubclass", - value: function addSubclass($subclass) { - $(this.container).addClass($subclass); - } - }, { - key: "removeSubclass", - value: function removeSubclass($subclass) { - $(this.container).removeClass($subclass); - } - }, { - key: "action", - value: function action(button) {// Implement this if you want to do something when the user push the plugin button - } - }, { - key: "getName", - value: function getName() { - return "ButtonPlugin"; - } - }, { - key: "getMinWindowSize", - value: function getMinWindowSize() { - return this.config.minWindowSize || 0; - } - }, { - key: "buildContent", - value: function buildContent(domElement) {// Override if your plugin - } - }, { - key: "getMenuContent", - value: function getMenuContent() { - return []; - } - }, { - key: "willShowContent", - value: function willShowContent() { - paella.log.debug(this.getName() + " willDisplayContent"); - } - }, { - key: "didShowContent", - value: function didShowContent() { - paella.log.debug(this.getName() + " didDisplayContent"); - } - }, { - key: "willHideContent", - value: function willHideContent() { - paella.log.debug(this.getName() + " willHideContent"); - } - }, { - key: "didHideContent", - value: function didHideContent() { - paella.log.debug(this.getName() + " didHideContent"); - } - }, { - key: "getButtonType", - value: function getButtonType() { - //return paella.ButtonPlugin.type.popUpButton; - //return paella.ButtonPlugin.type.timeLineButton; - //return paella.ButtonPlugin.type.menuButton; - return paella.ButtonPlugin.type.actionButton; - } - }, { - key: "getText", - value: function getText() { - return ""; - } - }, { - key: "getAriaLabel", - value: function getAriaLabel() { - return ""; - } - }, { - key: "setText", - value: function setText(text) { - this.container.innerHTML = '' + paella.AntiXSS.htmlEscape(text) + ''; - - if (this._i) { - this.container.appendChild(this._i); - } - } - }, { - key: "hideButton", - value: function hideButton() { - this.hideUI(); - } - }, { - key: "showButton", - value: function showButton() { - this.showUI(); - } // Utility functions: do not override - - }, { - key: "changeSubclass", - value: function changeSubclass(newSubclass) { - this.subclass = newSubclass; - this.container.className = this.getClassName(); - } - }, { - key: "changeIconClass", - value: function changeIconClass(newClass) { - this._i.className = 'button-icon ' + newClass; - } - }, { - key: "getClassName", - value: function getClassName() { - return paella.ButtonPlugin.kClassName + ' ' + this.getAlignment() + ' ' + this.subclass; - } - }, { - key: "getContainerClassName", - value: function getContainerClassName() { - if (this.getButtonType() == paella.ButtonPlugin.type.timeLineButton) { - return paella.ButtonPlugin.kTimeLineClassName + ' ' + this.getSubclass(); - } else if (this.getButtonType() == paella.ButtonPlugin.type.popUpButton) { - return paella.ButtonPlugin.kPopUpClassName + ' ' + this.getSubclass(); - } else if (this.getButtonType() == paella.ButtonPlugin.type.menuButton) { - return paella.ButtonPlugin.kPopUpClassName + ' menuContainer ' + this.getSubclass(); - } - } - }, { - key: "setToolTip", - value: function setToolTip(message) { - this.button.setAttribute("title", message); - this.button.setAttribute("aria-label", message); - } - }, { - key: "getDefaultToolTip", - value: function getDefaultToolTip() { - return ""; - } - }, { - key: "isPopUpOpen", - value: function isPopUpOpen() { - return this.button.popUpIdentifier == this.containerManager.currentContainerId; - } - }, { - key: "getExpandableContent", - value: function getExpandableContent() { - return null; - } - }, { - key: "expand", - value: function expand() { - if (this._expand) { - $(this._expand).show(); - } - } - }, { - key: "contract", - value: function contract() { - if (this._expand) { - $(this._expand).hide(); - } - } - }, { - key: "menuContent", - get: function get() { - return this._domElement; - }, - set: function set(domElem) { - this._domElement = domElem; - } - }, { - key: "rebuildMenu", - value: function rebuildMenu() { - var _this99 = this; - - function getButtonItem(itemData, plugin) { - var elem = document.createElement('div'); - elem.className = itemData.className + " menuItem"; - - if (itemData.default) { - elem.className += " selected"; - } - - elem.id = itemData.id; - elem.innerText = itemData.title; - - if (itemData.icon) { - elem.style.backgroundImage = "url(".concat(itemData.icon, ")"); - $(elem).addClass('icon'); - } - - elem.data = { - itemData: itemData, - plugin: plugin - }; - - function menuItemSelect(button, data, event) { - data.plugin.menuItemSelected(data.itemData); - var buttons = button.parentElement ? button.parentElement.children : []; - - for (var i = 0; i < buttons.length; ++i) { - $(buttons[i]).removeClass('selected'); - } - - $(button).addClass('selected'); - } - - $(elem).click(function (event) { - menuItemSelect(this, this.data, event); - }); - $(elem).keypress(function (event) { - if (event.keyCode == 13) { - menuItemSelect(this, this.data, event); - } - - event.preventDefault(); - }); - $(elem).keyup(function (event) { - if (event.keyCode == 27) { - paella.player.controls.hidePopUp(this.data.plugin.getName(), null, true); - } - - event.preventDefault(); - }); - return elem; - } - - var menuContent = this.getMenuContent(); - this.menuContent.innerHTML = ""; - menuContent.forEach(function (menuItem) { - _this99.menuContent.appendChild(getButtonItem(menuItem, _this99)); - }); - } - }], [{ - key: "BuildPluginButton", - value: function BuildPluginButton(plugin, id) { - plugin.subclass = plugin.getSubclass(); - var elem = document.createElement('div'); - var ariaLabel = plugin.getAriaLabel() || paella.utils.dictionary.translate(plugin.config.ariaLabel) || ""; - - if (ariaLabel != "") { - elem = document.createElement('button'); - } - - elem.className = plugin.getClassName(); - elem.id = id; - var buttonText = document.createElement('span'); - buttonText.className = "button-text"; - buttonText.innerHTML = paella.AntiXSS.htmlEscape(plugin.getText()); - buttonText.plugin = plugin; - elem.appendChild(buttonText); - - if (ariaLabel) { - var tabIndex = paella.tabIndex.next; - elem.setAttribute("tabindex", tabIndex); - elem.setAttribute("aria-label", ariaLabel); - } - - elem.setAttribute("alt", ""); - elem.plugin = plugin; - plugin.button = elem; - plugin.container = elem; - plugin.ui = elem; - plugin.setToolTip(plugin.getDefaultToolTip()); - var icon = document.createElement('i'); - icon.className = 'button-icon ' + plugin.getIconClass(); - icon.plugin = plugin; - elem.appendChild(icon); - plugin._i = icon; - - function onAction(self) { - paella.userTracking.log("paella:button:action", self.plugin.getName()); - self.plugin.action(self); - } - - $(elem).click(function (event) { - onAction(this); - }); - $(elem).keypress(function (event) { - onAction(this); - event.preventDefault(); - }); - $(elem).focus(function (event) { - plugin.expand(); - }); - return elem; - } - }, { - key: "BuildPluginExpand", - value: function BuildPluginExpand(plugin, id) { - var expandContent = plugin.getExpandableContent(); - - if (expandContent) { - var expand = document.createElement('span'); - expand.plugin = plugin; - expand.className = 'expandable-content ' + plugin.getClassName(); - plugin._expand = expand; - expand.appendChild(expandContent); - $(plugin._expand).hide(); - return expand; - } - - return null; - } - }, { - key: "BuildPluginPopUp", - value: function BuildPluginPopUp(parent, plugin, id) { - plugin.subclass = plugin.getSubclass(); - var elem = document.createElement('div'); - parent.appendChild(elem); - elem.className = plugin.getContainerClassName(); - elem.id = id; - elem.plugin = plugin; - plugin.buildContent(elem); - return elem; - } - }, { - key: "BuildPluginMenu", - value: function BuildPluginMenu(parent, plugin, id) { - plugin.subclass = plugin.getSubclass(); - var elem = document.createElement('div'); - parent.appendChild(elem); - elem.className = plugin.getContainerClassName(); - elem.id = id; - elem.plugin = plugin; - plugin.menuContent = elem; - plugin.rebuildMenu(elem); - return elem; - } - }]); - - return ButtonPlugin; - }(paella.UIPlugin); - - paella.ButtonPlugin = ButtonPlugin; - paella.ButtonPlugin.alignment = { - left: 'left', - right: 'right' - }; - paella.ButtonPlugin.kClassName = 'buttonPlugin'; - paella.ButtonPlugin.kPopUpClassName = 'buttonPluginPopUp'; - paella.ButtonPlugin.kTimeLineClassName = 'buttonTimeLine'; - paella.ButtonPlugin.type = { - actionButton: 1, - popUpButton: 2, - timeLineButton: 3, - menuButton: 4 - }; - - var VideoOverlayButtonPlugin = /*#__PURE__*/function (_paella$ButtonPlugin) { - _inherits(VideoOverlayButtonPlugin, _paella$ButtonPlugin); - - var _super29 = _createSuper(VideoOverlayButtonPlugin); - - function VideoOverlayButtonPlugin() { - _classCallCheck(this, VideoOverlayButtonPlugin); - - return _super29.apply(this, arguments); - } - - _createClass(VideoOverlayButtonPlugin, [{ - key: "type", - get: function get() { - return 'videoOverlayButton'; - } // Returns the button subclass. - - }, { - key: "getSubclass", - value: function getSubclass() { - return "myVideoOverlayButtonPlugin" + " " + this.getAlignment(); - } - }, { - key: "action", - value: function action(button) {// Implement this if you want to do something when the user push the plugin button - } - }, { - key: "getName", - value: function getName() { - return "VideoOverlayButtonPlugin"; - } - }, { - key: "tabIndex", - get: function get() { - return -1; - } - }]); - - return VideoOverlayButtonPlugin; - }(paella.ButtonPlugin); - - paella.VideoOverlayButtonPlugin = VideoOverlayButtonPlugin; - - var EventDrivenPlugin = /*#__PURE__*/function (_paella$EarlyLoadPlug) { - _inherits(EventDrivenPlugin, _paella$EarlyLoadPlug); - - var _super30 = _createSuper(EventDrivenPlugin); - - function EventDrivenPlugin() { - var _this100; - - _classCallCheck(this, EventDrivenPlugin); - - _this100 = _super30.call(this); - - var events = _this100.getEvents(); - - for (var i = 0; i < events.length; ++i) { - var event = events[i]; - - if (event == paella.events.loadStarted) { - _this100.onEvent(paella.events.loadStarted); - } - } - - return _this100; - } - - _createClass(EventDrivenPlugin, [{ - key: "type", - get: function get() { - return 'eventDriven'; - } - }, { - key: "getEvents", - value: function getEvents() { - return []; - } - }, { - key: "onEvent", - value: function onEvent(eventType, params) {} - }, { - key: "getName", - value: function getName() { - return "EventDrivenPlugin"; - } - }]); - - return EventDrivenPlugin; - }(paella.EarlyLoadPlugin); - - paella.EventDrivenPlugin = EventDrivenPlugin; -})(); - -(function () { - var VideoCanvas = /*#__PURE__*/function () { - function VideoCanvas(stream) { - _classCallCheck(this, VideoCanvas); - - this._stream = stream; - } - - _createClass(VideoCanvas, [{ - key: "loadVideo", - value: function loadVideo(videoPlugin, stream) { - return Promise.reject(new Error("Not implemented")); - } - }, { - key: "allowZoom", - value: function allowZoom() { - return true; - } - }]); - - return VideoCanvas; - }(); - - paella.VideoCanvas = VideoCanvas; - - function initWebGLCanvas() { - if (!paella.WebGLCanvas) { - var WebGLCanvas = /*#__PURE__*/function (_bg$app$WindowControl) { - _inherits(WebGLCanvas, _bg$app$WindowControl); - - var _super31 = _createSuper(WebGLCanvas); - - function WebGLCanvas(stream) { - var _this101; - - _classCallCheck(this, WebGLCanvas); - - _this101 = _super31.call(this); - _this101._stream = stream; - return _this101; - } - - _createClass(WebGLCanvas, [{ - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "video", - get: function get() { - return this.texture ? this.texture.video : null; - } - }, { - key: "camera", - get: function get() { - return this._camera; - } - }, { - key: "texture", - get: function get() { - return this._texture; - } - }, { - key: "loaded", - value: function loaded() { - var _this102 = this; - - return new Promise(function (resolve) { - var checkLoaded = function checkLoaded() { - if (_this102.video) { - resolve(_this102); - } else { - setTimeout(checkLoaded, 100); - } - }; - - checkLoaded(); - }); - } - }, { - key: "loadVideo", - value: function loadVideo(videoPlugin, stream) { - return Promise.reject(new Error("Not implemented")); - } - }, { - key: "allowZoom", - value: function allowZoom() { - return false; - } // WebGL engine functions - - }, { - key: "registerPlugins", - value: function registerPlugins() { - bg.base.Loader.RegisterPlugin(new bg.base.TextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VideoTextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VWGLBLoaderPlugin()); - } - }, { - key: "loadVideoTexture", - value: function loadVideoTexture() { - return bg.base.Loader.Load(this.gl, this.stream.src); - } - }, { - key: "buildVideoSurface", - value: function buildVideoSurface(sceneRoot, videoTexture) { - var sphere = bg.scene.PrimitiveFactory.Sphere(this.gl, 1, 50); - var sphereNode = new bg.scene.Node(this.gl); - sphereNode.addComponent(sphere); - sphere.getMaterial(0).texture = videoTexture; - sphere.getMaterial(0).lightEmission = 0; - sphere.getMaterial(0).lightEmissionMaskInvert = false; - sphere.getMaterial(0).cullFace = false; - sphereNode.addComponent(new bg.scene.Transform(bg.Matrix4.Scale(1, -1, 1))); - sceneRoot.addChild(sphereNode); - } - }, { - key: "buildCamera", - value: function buildCamera() { - var cameraNode = new bg.scene.Node(this.gl, "Camera"); - var camera = new bg.scene.Camera(); - cameraNode.addComponent(camera); - cameraNode.addComponent(new bg.scene.Transform()); - var projection = new bg.scene.OpticalProjectionStrategy(); - projection.far = 100; - projection.focalLength = 55; - camera.projectionStrategy = projection; - var oc = new bg.manipulation.OrbitCameraController(); - oc.maxPitch = 90; - oc.minPitch = -90; - oc.maxDistance = 0; - oc.minDistance = 0; - this._cameraController = oc; - cameraNode.addComponent(oc); - return cameraNode; - } - }, { - key: "buildScene", - value: function buildScene() { - var _this103 = this; - - this._root = new bg.scene.Node(this.gl, "Root node"); - this.registerPlugins(); - this.loadVideoTexture().then(function (texture) { - _this103._texture = texture; - - _this103.buildVideoSurface(_this103._root, texture); - }); - var lightNode = new bg.scene.Node(this.gl, "Light"); - var light = new bg.base.Light(); - light.ambient = bg.Color.White(); - light.diffuse = bg.Color.Black(); - light.specular = bg.Color.Black(); - lightNode.addComponent(new bg.scene.Light(light)); - - this._root.addChild(lightNode); - - var cameraNode = this.buildCamera(); - this._camera = cameraNode.component("bg.scene.Camera"); - - this._root.addChild(cameraNode); - } - }, { - key: "init", - value: function init() { - bg.Engine.Set(new bg.webgl1.Engine(this.gl)); - this.buildScene(); - this._renderer = bg.render.Renderer.Create(this.gl, bg.render.RenderPath.FORWARD); - this._inputVisitor = new bg.scene.InputVisitor(); - } - }, { - key: "frame", - value: function frame(delta) { - if (this.texture) { - this.texture.update(); - } - - this._renderer.frame(this._root, delta); - - this.postReshape(); - } - }, { - key: "display", - value: function display() { - this._renderer.display(this._root, this._camera); - } - }, { - key: "reshape", - value: function reshape(width, height) { - this._camera.viewport = new bg.Viewport(0, 0, width, height); - - if (!this._camera.projectionStrategy) { - this._camera.projection.perspective(60, this._camera.viewport.aspectRatio, 0.1, 100); - } - } - }, { - key: "mouseDrag", - value: function mouseDrag(evt) { - this._inputVisitor.mouseDrag(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseWheel", - value: function mouseWheel(evt) { - this._inputVisitor.mouseWheel(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "touchMove", - value: function touchMove(evt) { - this._inputVisitor.touchMove(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseDown", - value: function mouseDown(evt) { - this._inputVisitor.mouseDown(this._root, evt); - } - }, { - key: "touchStar", - value: function touchStar(evt) { - this._inputVisitor.touchStar(this._root, evt); - } - }, { - key: "mouseUp", - value: function mouseUp(evt) { - this._inputVisitor.mouseUp(this._root, evt); - } - }, { - key: "mouseMove", - value: function mouseMove(evt) { - this._inputVisitor.mouseMove(this._root, evt); - } - }, { - key: "mouseOut", - value: function mouseOut(evt) { - this._inputVisitor.mouseOut(this._root, evt); - } - }, { - key: "touchEnd", - value: function touchEnd(evt) { - this._inputVisitor.touchEnd(this._root, evt); - } - }]); - - return WebGLCanvas; - }(bg.app.WindowController); - - paella.WebGLCanvas = WebGLCanvas; - } - } - - function buildVideoCanvas(stream) { - if (!paella.WebGLCanvas) { - var WebGLCanvas = /*#__PURE__*/function (_bg$app$WindowControl2) { - _inherits(WebGLCanvas, _bg$app$WindowControl2); - - var _super32 = _createSuper(WebGLCanvas); - - function WebGLCanvas(stream) { - var _this104; - - _classCallCheck(this, WebGLCanvas); - - _this104 = _super32.call(this); - _this104._stream = stream; - return _this104; - } - - _createClass(WebGLCanvas, [{ - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "video", - get: function get() { - return this.texture ? this.texture.video : null; - } - }, { - key: "camera", - get: function get() { - return this._camera; - } - }, { - key: "texture", - get: function get() { - return this._texture; - } - }, { - key: "allowZoom", - value: function allowZoom() { - return false; - } - }, { - key: "loaded", - value: function loaded() { - var _this105 = this; - - return new Promise(function (resolve) { - var checkLoaded = function checkLoaded() { - if (_this105.video) { - resolve(_this105); - } else { - setTimeout(checkLoaded, 100); - } - }; - - checkLoaded(); - }); - } - }, { - key: "registerPlugins", - value: function registerPlugins() { - bg.base.Loader.RegisterPlugin(new bg.base.TextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VideoTextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VWGLBLoaderPlugin()); - } - }, { - key: "loadVideoTexture", - value: function loadVideoTexture() { - return bg.base.Loader.Load(this.gl, this.stream.src); - } - }, { - key: "buildVideoSurface", - value: function buildVideoSurface(sceneRoot, videoTexture) { - var sphere = bg.scene.PrimitiveFactory.Sphere(this.gl, 1, 50); - var sphereNode = new bg.scene.Node(this.gl); - sphereNode.addComponent(sphere); - sphere.getMaterial(0).texture = videoTexture; - sphere.getMaterial(0).lightEmission = 0; - sphere.getMaterial(0).lightEmissionMaskInvert = false; - sphere.getMaterial(0).cullFace = false; - sphereNode.addComponent(new bg.scene.Transform(bg.Matrix4.Scale(1, -1, 1))); - sceneRoot.addChild(sphereNode); - } - }, { - key: "buildCamera", - value: function buildCamera() { - var cameraNode = new bg.scene.Node(this.gl, "Camera"); - var camera = new bg.scene.Camera(); - cameraNode.addComponent(camera); - cameraNode.addComponent(new bg.scene.Transform()); - var projection = new bg.scene.OpticalProjectionStrategy(); - projection.far = 100; - projection.focalLength = 55; - camera.projectionStrategy = projection; - var oc = new bg.manipulation.OrbitCameraController(); - oc.maxPitch = 90; - oc.minPitch = -90; - oc.maxDistance = 0; - oc.minDistance = 0; - this._cameraController = oc; - cameraNode.addComponent(oc); - return cameraNode; - } - }, { - key: "buildScene", - value: function buildScene() { - var _this106 = this; - - this._root = new bg.scene.Node(this.gl, "Root node"); - this.registerPlugins(); - this.loadVideoTexture().then(function (texture) { - _this106._texture = texture; - - _this106.buildVideoSurface(_this106._root, texture); - }); - var lightNode = new bg.scene.Node(this.gl, "Light"); - var light = new bg.base.Light(); - light.ambient = bg.Color.White(); - light.diffuse = bg.Color.Black(); - light.specular = bg.Color.Black(); - lightNode.addComponent(new bg.scene.Light(light)); - - this._root.addChild(lightNode); - - var cameraNode = this.buildCamera(); - this._camera = cameraNode.component("bg.scene.Camera"); - - this._root.addChild(cameraNode); - } - }, { - key: "init", - value: function init() { - bg.Engine.Set(new bg.webgl1.Engine(this.gl)); - this.buildScene(); - this._renderer = bg.render.Renderer.Create(this.gl, bg.render.RenderPath.FORWARD); - this._inputVisitor = new bg.scene.InputVisitor(); - } - }, { - key: "frame", - value: function frame(delta) { - if (this.texture) { - this.texture.update(); - } - - this._renderer.frame(this._root, delta); - - this.postReshape(); - } - }, { - key: "display", - value: function display() { - this._renderer.display(this._root, this._camera); - } - }, { - key: "reshape", - value: function reshape(width, height) { - this._camera.viewport = new bg.Viewport(0, 0, width, height); - - if (!this._camera.projectionStrategy) { - this._camera.projection.perspective(60, this._camera.viewport.aspectRatio, 0.1, 100); - } - } - }, { - key: "mouseDrag", - value: function mouseDrag(evt) { - this._inputVisitor.mouseDrag(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseWheel", - value: function mouseWheel(evt) { - this._inputVisitor.mouseWheel(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "touchMove", - value: function touchMove(evt) { - this._inputVisitor.touchMove(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseDown", - value: function mouseDown(evt) { - this._inputVisitor.mouseDown(this._root, evt); - } - }, { - key: "touchStar", - value: function touchStar(evt) { - this._inputVisitor.touchStar(this._root, evt); - } - }, { - key: "mouseUp", - value: function mouseUp(evt) { - this._inputVisitor.mouseUp(this._root, evt); - } - }, { - key: "mouseMove", - value: function mouseMove(evt) { - this._inputVisitor.mouseMove(this._root, evt); - } - }, { - key: "mouseOut", - value: function mouseOut(evt) { - this._inputVisitor.mouseOut(this._root, evt); - } - }, { - key: "touchEnd", - value: function touchEnd(evt) { - this._inputVisitor.touchEnd(this._root, evt); - } - }]); - - return WebGLCanvas; - }(bg.app.WindowController); - - paella.WebGLCanvas = WebGLCanvas; - } - - return paella.WebGLCanvas; - } - - var g_canvasCallbacks = {}; - - paella.addCanvasPlugin = function (canvasType, webglSupport, mouseEventsSupport, canvasPluginCallback) { - g_canvasCallbacks[canvasType] = { - callback: canvasPluginCallback, - webglSupport: webglSupport, - mouseEventsSupport: mouseEventsSupport - }; - }; - - function loadWebGLDeps() { - return new Promise(function (resolve) { - if (!window.$paella_bg) { - paella.require("".concat(paella.baseUrl, "javascript/bg2e-es2015.js")).then(function () { - window.$paella_bg = bg; - buildVideoCanvas(); // loadWebGLDeps(); - - resolve(window.$paella_bg); - }); - } else { - resolve(window.$paella_bg); - } - }); - } - - function loadCanvasPlugin(canvasType) { - return new Promise(function (resolve, reject) { - var callbackData = g_canvasCallbacks[canvasType]; - - if (callbackData) { - (callbackData.webglSupport ? loadWebGLDeps() : Promise.resolve()).then(function () { - resolve(callbackData.callback()); - }).catch(function (err) { - reject(err); - }); - } else { - reject(new Error("No such canvas type: \"".concat(canvasType, "\""))); - } - }); - } - - paella.getVideoCanvas = function (type) { - return new Promise(function (resolve, reject) { - var canvasData = g_canvasCallbacks[type]; - - if (!canvasData) { - reject(new Error("No such canvas type: " + type)); - } else { - if (canvasData.webglSupport) { - loadWebGLDeps().then(function () { - resolve(canvasData.callback()); - }); - } else { - resolve(canvasData.callback()); - } - } - }); - }; - - paella.getVideoCanvasData = function (type) { - return g_canvasCallbacks[type]; - }; // Standard