diff --git a/projects/smashkarts/StreamingAssets/aa/settings.json b/projects/smashkarts/StreamingAssets/aa/settings.json new file mode 100644 index 00000000..a37f8ac3 --- /dev/null +++ b/projects/smashkarts/StreamingAssets/aa/settings.json @@ -0,0 +1 @@ +{"m_buildTarget":"WebGL","m_SettingsHash":"012304eb5efa77226fa620375549d575","m_CatalogLocations":[{"m_Keys":["AddressablesMainContentCatalogRemoteHash"],"m_InternalId":"https://smashkartsgc.b-cdn.net/assetbundles/remote/webgl/catalog_2025.01.24.11.12.42.hash","m_Provider":"UnityEngine.ResourceManagement.ResourceProviders.TextDataProvider","m_Dependencies":[],"m_ResourceType":{"m_AssemblyName":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","m_ClassName":"System.String"},"SerializedData":[7,76,85,110,105,116,121,46,82,101,115,111,117,114,99,101,77,97,110,97,103,101,114,44,32,86,101,114,115,105,111,110,61,48,46,48,46,48,46,48,44,32,67,117,108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,110,117,108,108,75,85,110,105,116,121,69,110,103,105,110,101,46,82,101,115,111,117,114,99,101,77,97,110,97,103,101,109,101,110,116,46,82,101,115,111,117,114,99,101,80,114,111,118,105,100,101,114,115,46,80,114,111,118,105,100,101,114,76,111,97,100,82,101,113,117,101,115,116,79,112,116,105,111,110,115,50,0,0,0,123,0,34,0,109,0,95,0,73,0,103,0,110,0,111,0,114,0,101,0,70,0,97,0,105,0,108,0,117,0,114,0,101,0,115,0,34,0,58,0,116,0,114,0,117,0,101,0,125,0]},{"m_Keys":["AddressablesMainContentCatalogCacheHash"],"m_InternalId":"{UnityEngine.Application.persistentDataPath}/com.unity.addressables/catalog_2025.01.24.11.12.42.hash","m_Provider":"UnityEngine.ResourceManagement.ResourceProviders.TextDataProvider","m_Dependencies":[],"m_ResourceType":{"m_AssemblyName":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","m_ClassName":"System.String"},"SerializedData":[7,76,85,110,105,116,121,46,82,101,115,111,117,114,99,101,77,97,110,97,103,101,114,44,32,86,101,114,115,105,111,110,61,48,46,48,46,48,46,48,44,32,67,117,108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,110,117,108,108,75,85,110,105,116,121,69,110,103,105,110,101,46,82,101,115,111,117,114,99,101,77,97,110,97,103,101,109,101,110,116,46,82,101,115,111,117,114,99,101,80,114,111,118,105,100,101,114,115,46,80,114,111,118,105,100,101,114,76,111,97,100,82,101,113,117,101,115,116,79,112,116,105,111,110,115,50,0,0,0,123,0,34,0,109,0,95,0,73,0,103,0,110,0,111,0,114,0,101,0,70,0,97,0,105,0,108,0,117,0,114,0,101,0,115,0,34,0,58,0,116,0,114,0,117,0,101,0,125,0]},{"m_Keys":["AddressablesMainContentCatalog"],"m_InternalId":"{UnityEngine.AddressableAssets.Addressables.RuntimePath}/catalog.json","m_Provider":"UnityEngine.AddressableAssets.ResourceProviders.ContentCatalogProvider","m_Dependencies":["AddressablesMainContentCatalogRemoteHash","AddressablesMainContentCatalogCacheHash"],"m_ResourceType":{"m_AssemblyName":"Unity.Addressables, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null","m_ClassName":"UnityEngine.AddressableAssets.ResourceLocators.ContentCatalogData"},"SerializedData":[7,76,85,110,105,116,121,46,82,101,115,111,117,114,99,101,77,97,110,97,103,101,114,44,32,86,101,114,115,105,111,110,61,48,46,48,46,48,46,48,44,32,67,117,108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,110,117,108,108,75,85,110,105,116,121,69,110,103,105,110,101,46,82,101,115,111,117,114,99,101,77,97,110,97,103,101,109,101,110,116,46,82,101,115,111,117,114,99,101,80,114,111,118,105,100,101,114,115,46,80,114,111,118,105,100,101,114,76,111,97,100,82,101,113,117,101,115,116,79,112,116,105,111,110,115,50,0,0,0,123,0,34,0,109,0,95,0,73,0,103,0,110,0,111,0,114,0,101,0,70,0,97,0,105,0,108,0,117,0,114,0,101,0,115,0,34,0,58,0,116,0,114,0,117,0,101,0,125,0]}],"m_ProfileEvents":false,"m_LogResourceManagerExceptions":true,"m_ExtraInitializationData":[],"m_DisableCatalogUpdateOnStart":false,"m_IsLocalCatalogInBundle":false,"m_CertificateHandlerType":{"m_AssemblyName":"","m_ClassName":""},"m_AddressablesVersion":"1.22.3","m_maxConcurrentWebRequests":500,"m_CatalogRequestsTimeout":0} \ No newline at end of file diff --git a/projects/smashkarts/css/main.css b/projects/smashkarts/css/main.css new file mode 100644 index 00000000..18de9868 --- /dev/null +++ b/projects/smashkarts/css/main.css @@ -0,0 +1,361 @@ +html { + box-sizing: border-box; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} + +body { + margin: 0; + width: 100%; + height: 100%; + overflow: hidden; +} + +#xsolla-iframe { + position: absolute; + width: 80%; + height: 100%; + left: 50.5%; + display: none; + transform: translate(-50%, 0%); +} + + +#mainContainer { + display: flex; + width: 100vw; + height: 100vh; + padding: 0 env(safe-area-inset-right) 0 env(safe-area-inset-left); +} + +#mainContainerBg { + position: absolute; + z-index: -1; + margin: 0 calc(-1 * env(safe-area-inset-right)) 0 calc(-1 * env(safe-area-inset-left)); + transform: scale(1.1); /* used to remove white fade at the edges of screen */ + width: 100vw; + height: 100vh; + background: url("../images/menuBGTile.png"), #496486; + background-size: 10%; + background-repeat: repeat; + background-blend-mode: multiply; + filter: blur(4px); +} + +#leftContainer { + display: flex; + flex-direction: column; +} + +#gameContainer { + display: flex; + justify-content: center; +} + +#gameCanvas { + width: 100vw; /* initial value */ + height: 100vh; /* initial value */ +} + +#btmContainer { + display: none; /* initially hidden then if enabled set to flex */ + align-items: center; + justify-content: center; + padding: 0px; +} + +#btmAdPlaceholder { + align-items: center; + justify-content: center; + position: absolute; +} + +#btmAdPlaceholderBg { + background-color: #00000030; + position: absolute; + width: 100%; + height: 100%; + filter: blur(4px); + z-index: -1; +} + +#btmAdResText{ + color: white; + font-size: 40px; + font-family: 'Baloo 2'; + filter: drop-shadow(2px 2px 0px #2050A9); +} + +#btmAdBlockerContainer +{ + display: flex; + align-items: center; + height: 100%; +} + +#btmAdBlockerImg { + max-height: 90%; + margin-right: 20px; +} + +#btmAdBlockerText { + color: white; + font-family: 'Baloo 2'; + font-size: 35px; + filter: drop-shadow(2px 2px 0px #2050A9); +} + +#rightContainer { + display: none; /* initially hidden then if enabled set to flex */ + align-items: center; + justify-content: center; + padding: 0px; +} + +#rightAdPlaceholder { + align-items: center; + justify-content: center; + position: absolute; +} + +#rightAdPlaceholderBg { + background-color: #00000030; + position: absolute; + width: 100%; + height: 100%; + filter: blur(4px); + z-index: -1; +} + +#rightAdBlockerContainer +{ + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + width: 90%; + height: 100%; +} + +#rightAdBlockerImg { + max-width: 100%; +} + +#rightAdBlockerText { + color: white; + font-family: 'Baloo 2'; + font-size: 30px; + filter: drop-shadow(2px 2px 0px #2050A9); + line-height: 1; + text-align: center; +} + +#rightAdResText{ + color: white; + font-size: 40px; + font-family: 'Baloo 2'; + filter: drop-shadow(2px 2px 0px #2050A9); +} + +#adContainerDeath { + display: none; + --shown_display: flex; + position: absolute; + /* border: 1px solid red; */ + z-index: 100; + bottom: 0px; + right: 0px; /* removed on the fly to center for mobile */ + width: fit-content; + height: fit-content; + align-items: center; +} + +#adContainerLoadingLeft { + display: none; + --shown_display: block; + position: absolute; + transform-origin: left top; + transform: translate(0px, -50%); + /* border: 1px solid red; */ + z-index: 100; + top: 50%; + left: 10px; + width: auto; + height: auto; +} + +#adContainerMainMenu { + display: none; + --shown_display: block; + position: absolute; + transform-origin: right top; + transform: translate(0px, -50%); + /* border: 1px solid red; */ + z-index: 100; + top: 50%; + right: 10px; + width: auto; + height: auto; +} + +@media screen and (max-width: 600px) { + #smashkarts-io_300x250 { + /* border: 1px solid blue; */ + display: none; + } +} + + +/* #adContainerWin { + display: none; + --shown_display: block; + position: absolute; + transform-origin: right top; + transform: translate(0px, -50%); + z-index: 100; + top: 50%; + right: 10px; + width: auto; + height: auto; +} */ + +#adContainerWin { + display: none; + --shown_display: block; + position: absolute; + transform-origin: right bottom; + /* border: 1px solid red; */ + z-index: 100; + bottom: 10px; + right: 10px; + width: auto; + height: auto; +} + +#adContainerSpectate { + display: none; + --shown_display: block; + position: absolute; + transform-origin: right bottom; + /* border: 1px solid red; */ + z-index: 100; + bottom: 10px; + right: 10px; + width: auto; + height: auto; +} + +#pw-video-container { + width: 100%; + height: 100%; + position: absolute; + display: none; /* default to hidden */ +} + +#pw-video-placeholder { + width: 100%; + height: 100%; +} + +@media screen and (max-width: 600px) { + #smashkarts-io_300x250_2 { + /* border: 1px solid blue; */ + display: none; + } +} + +/* try to handle mobile dialog */ +canvas+* { + z-index: 2; +} + +.logo { + display: block; + width: 35vw; +} + +.progress { + margin: 1.5em; + border: 2px solid; + width: 25vw; + display: none; +} + +.progress .full { + margin: 2px; + background: white; + height: 1em; + transform-origin: top left; +} + +#loader { + position: absolute; + left: 0; + top: 0; + width: 100vw; + height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + background: #1b70f0; + background-image: url("../images/overlay.png"), url("../images/menuBGTile.png"); + background-size: cover, 13vw; + background-repeat: no-repeat, repeat; +} + +.spinner { + position: absolute; + left: 2vw; + bottom: 2vh; + border: 10px solid #f3f3f3; + border-top: 10px solid #3498db; + border-radius: 50%; + width: 10vh; + height: 10vh; + animation: spin 1s linear infinite; +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } +} + + +/* for all screens */ +#rotate-landscape { + display: none; +} + +/* only when orientation is in portrait mode */ +@media all and (orientation:portrait) { + #rotate-landscape { + position: absolute; + left: 0; + top: 0; + width: 100vw; + height: 100vh; + display: block; + background: #1b70f0; + background-image: url("../images/overlay.png"), url("../images/menuBGTile.png"); + background-size: cover, 13vw; + background-repeat: no-repeat, repeat; + } +} + +.center { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 90vw; +} diff --git a/projects/smashkarts/css/readme.md b/projects/smashkarts/css/readme.md new file mode 100644 index 00000000..bef7f4ae --- /dev/null +++ b/projects/smashkarts/css/readme.md @@ -0,0 +1 @@ +ja diff --git a/projects/smashkarts/images/SmashKartsBackground.jpg b/projects/smashkarts/images/SmashKartsBackground.jpg deleted file mode 100644 index 58160269..00000000 Binary files a/projects/smashkarts/images/SmashKartsBackground.jpg and /dev/null differ diff --git a/projects/smashkarts/images/SmashKartsPoster.jpg b/projects/smashkarts/images/SmashKartsPoster.jpg deleted file mode 100644 index 0d5f843b..00000000 Binary files a/projects/smashkarts/images/SmashKartsPoster.jpg and /dev/null differ diff --git a/projects/smashkarts/images/favicon.png b/projects/smashkarts/images/favicon.png deleted file mode 100644 index 21c3ea60..00000000 Binary files a/projects/smashkarts/images/favicon.png and /dev/null differ diff --git a/projects/smashkarts/images/icon-144.png b/projects/smashkarts/images/icon-144.png deleted file mode 100644 index bd92b638..00000000 Binary files a/projects/smashkarts/images/icon-144.png and /dev/null differ diff --git a/projects/smashkarts/images/icon-512.png b/projects/smashkarts/images/icon-512.png deleted file mode 100644 index f6e21239..00000000 Binary files a/projects/smashkarts/images/icon-512.png and /dev/null differ diff --git a/projects/smashkarts/images/readme.md b/projects/smashkarts/images/readme.md new file mode 100644 index 00000000..bef7f4ae --- /dev/null +++ b/projects/smashkarts/images/readme.md @@ -0,0 +1 @@ +ja diff --git a/projects/smashkarts/images/turnoffadblock.png b/projects/smashkarts/images/turnoffadblock.png new file mode 100644 index 00000000..f62c5b7a Binary files /dev/null and b/projects/smashkarts/images/turnoffadblock.png differ diff --git a/projects/smashkarts/index.html b/projects/smashkarts/index.html index 47a0278f..ffef2f55 100644 --- a/projects/smashkarts/index.html +++ b/projects/smashkarts/index.html @@ -1,492 +1,405 @@ - - - Smash Karts | 3kh0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Smash Karts | 3kh0 - - - - - - - - - - - AdinPlay Ads - - - - - - -
- -
- -
-
-
-
- -
- - - -
-
-
-
-
- -
- - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Smash Karts + + + + + + + +
+
+
+
+ + + +
+
+
+
+
+ + +
+ +
+
+
+
+ + +
+ +
+
+
+
+
+ + +
+
+ + +
+ +
+
+
+
+
+
+ +

Disable AdBlock for extra XP

+
+
+

unset

+
+
+
+
+
+ +
+
+
+
+
+ +

Disable AdBlock for extra XP

+
+
+

unset

+
+
+
+ +
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + diff --git a/projects/smashkarts/manifest.json b/projects/smashkarts/manifest.json index 9f3681ef..bfb5c55f 100644 --- a/projects/smashkarts/manifest.json +++ b/projects/smashkarts/manifest.json @@ -1,22 +1,22 @@ { - "name": "Smash Karts", - "short_name": "Smash Karts", - "theme_color": "#2196f3", - "background_color": "#2196f3", - "display": "fullscreen", - "orientation": "landscape", - "scope": ".", - "icons": [ - { - "src": "images/icon-144.png", - "sizes": "144x144", - "type": "image/png" - }, - { - "src": "images/icon-512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "start_url": "./" -} + "name": "Smash Karts", + "short_name": "Smash Karts", + "theme_color": "#2196f3", + "background_color": "#2196f3", + "display": "fullscreen", + "orientation": "landscape", + "scope": ".", + "icons": [ + { + "src": "images/icon-144.png", + "sizes": "144x144", + "type": "image/png" + }, + { + "src": "images/icon-512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "start_url": "./" + } \ No newline at end of file diff --git a/projects/smashkarts/scripts/ads-adinplay-display.js b/projects/smashkarts/scripts/ads-adinplay-display.js new file mode 100644 index 00000000..2541b817 --- /dev/null +++ b/projects/smashkarts/scripts/ads-adinplay-display.js @@ -0,0 +1,185 @@ +'use strict'; + +/////////////////////////// +//ad tags +const adTagLoadingBanner = "smashkarts-io_300x600_2"; +const adTagMainMenuBanner = "smashkarts-io_300x250"; +const adTagWinCeremonyBanner = "smashkarts-io_300x250_2"; +const adTagSpectateBanner = "smashkarts-io_300x250_3"; +const adTagDeathBannerWeb = "smashkarts-io_728x90-new"; +const adTagDeathBannerMobile = "smashkarts-io_320x100"; + +var currShownAdElementIds = []; + +const officialFullscreenIFramedProxies = [ + "https://schoolkarts.com/", + "https://www.gstatic.com/" +] + +function hasAdContent(adElementId) +{ + const ad = document.getElementById(adElementId); + + return (ad != null && ad.innerHTML); +} + +function showAd(adElementId) +{ + const ad = document.getElementById(adElementId); + + if(ad != null) + { + ad.style.display = "block"; + } +} + +function requestAd(adElementId, adShownTimestamp) +{ + if(currShownAdElementIds.includes(adElementId)) + return; + + if(Date.now() >= (adShownTimestamp.val + bannerMinRefreshDelayMillisecs) || !hasAdContent(adElementId)) + { + adShownTimestamp.val = Date.now(); + + destroyAd(adElementId); + + currShownAdElementIds.push(adElementId); + + aiptag.cmd.display.push(function() + { + aipDisplayTag.display(adElementId); + showAd(adElementId); + }); + } +} + +function hideAd(adElementId) +{ + if(currShownAdElementIds.includes(adElementId)) + { + //for adinplay we dont distingush between hiding and destroying + destroyAd(adElementId); + + //if we were hiding you would need to reset the currShownAdElement + //currShownAdElementId = null; + } +} + +function destroyAd(adElementId) +{ + const ad = document.getElementById(adElementId); + + if(ad != null) + { + ad.style.display = "none"; + //ad.innerHTML = ""; + aiptag.cmd.display.push(function() + { + aipDisplayTag.destroy(adElementId); + }); + } + + const indexToRemove = currShownAdElementIds.indexOf(adElementId); + + if(indexToRemove >= 0) + { + currShownAdElementIds.splice(indexToRemove, 1); + } +} + +function requestLoadingAd() +{ + requestAd(adTagLoadingBanner, loadingBannerShownTimestamp); + + //@podonnell: breaking rev - Dec 11th + //if(!isIFramed() || isOfficialFullscreenIFramedProxy()) + // { + // requestAd(adTagLoadingBanner, loadingBannerShownTimestamp); + // } +} + +function hideLoadingAd() +{ + hideAd(adTagLoadingBanner); +} + +function requestMainMenuAd() +{ + requestAd(adTagMainMenuBanner, mainMenuBannerShownTimestamp); + + //@podonnell: breaking rev - Dec 11th + // if(!isIFramed() || isOfficialFullscreenIFramedProxy()) + // { + // requestAd(adTagMainMenuBanner, mainMenuBannerShownTimestamp); + // } +} + +function hideMainMenuAd() +{ + hideAd(adTagMainMenuBanner); +} + +function requestWinCeremonyAd() +{ + requestAd(adTagWinCeremonyBanner, winCeremonyBannerShownTimestamp); +} + +function hideWinCeremonyAd() +{ + hideAd(adTagWinCeremonyBanner); +} + +function requestSpectateAd() +{ + requestAd(adTagSpectateBanner, spectateBannerShownTimestamp); +} + +function hideSpectateAd() +{ + hideAd(adTagSpectateBanner); +} + +function requestDeathAd() +{ + if(isMobile()) + { + requestAd(adTagDeathBannerMobile, deathBannerShownTimestamp); + } + else + { + requestAd(adTagDeathBannerWeb, deathBannerShownTimestamp); + } +} + +function hideDeathAd() +{ + hideAd(adTagDeathBannerMobile); + hideAd(adTagDeathBannerWeb); +} + +function requestOffCanvasAd(adResArrayToHide, adTagIdToShow) +{ + hideOffCanvasAds(adResArrayToHide); + + currShownAdElementIds.push(adTagIdToShow); + + aiptag.cmd.display.push(function() + { + aipDisplayTag.display(adTagIdToShow); + showAd(adTagIdToShow); + }); +} + +function hideOffCanvasAds(adResArray) +{ + adResArray.forEach(adRes => { + destroyAd(adRes.adId); + }); +} + +function isOfficialFullscreenIFramedProxy() +{ + const url = document.referrer; + return url != null && officialFullscreenIFramedProxies.includes(url); +} diff --git a/projects/smashkarts/scripts/ads-adinplay-video.js b/projects/smashkarts/scripts/ads-adinplay-video.js new file mode 100644 index 00000000..1d22fd1f --- /dev/null +++ b/projects/smashkarts/scripts/ads-adinplay-video.js @@ -0,0 +1,178 @@ +'use strict'; + +let aipRewardedAdAvailable = false; + +function aipVideoPlayerInitialised() +{ + return (typeof aiptag.adplayer !== 'undefined'); +} + +function showInterstitial(audioOn, interstitialType, interstitialName) +{ + if (!isVideoAdPlaying && firebase.auth().currentUser != null) + { + //check if the adslib is loaded correctly or blocked by adblockers etc. + if (aipVideoPlayerInitialised()) + { + isVideoAdPlaying = true; + + interstitialStart(false); + + aiptag.cmd.player.push(function() + { + aiptag.adplayer.startPreRoll(); + }); + } + else + { + //Adlib didnt load this could be due to an adblocker, timeout etc. + //Please add your script here that starts the content, this usually is the same script as added in AIP_COMPLETE. + console.log("Ad Could not be loaded, load your content here"); + + isVideoAdPlaying = false; + + interstitialError(false); + } + } +} + +function onInterstitialComplete(evt) +{ + /******************* + ***** WARNING ***** + ******************* + Please do not remove the PREROLL_ELEM + from the page, it will be hidden automaticly. + */ + console.log("onInterstitialComplete: " + evt); + + isVideoAdPlaying = false; + + if(evt === "video-ad-completed") + { + interstitialComplete(false); + } + else if(evt === "video-ad-skipped") + { + interstitialSkipped(false); + } + else + { + interstitialError(false); + } +} + +function tryInitRewardedInterstitial(audioOn) +{ + if(!window.adblockDetected) + { + if(aipVideoPlayerInitialised()) + { + initRewardedInterstitial(); + } + else + { + //poll until video player is ready + const checkVideoPlayerInterval = setInterval(() => { + //player isnt ready => do nothing + if (!aipVideoPlayerInitialised()) + return; + + //player is ready => stop polling and send message to unity + clearInterval(checkVideoPlayerInterval); + initRewardedInterstitial(); + }, 1000); + } + } +} + +function initRewardedInterstitial() +{ + if(!aipRewardedAdAvailable) + { + //It's important the EventListener rewardedSlotReady is added only once. + if(aipAPItag.rewardedSlotEventListener !== true) + { + aipAPItag.rewardedSlotEventListener = true; + + aiptag.events.addEventListener("rewardedSlotReady", function (e) + { + if(e.detail.isEmpty !== true) + { + //rewarded ad is ready to show + console.log("rewarded ad is ready to show"); + aipRewardedAdAvailable = true; + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "RewardedInterstitialAvailable"); + } + else + { + //There is no rewarded ad available + console.log("rewarded ad not available"); + aipRewardedAdAvailable = false; + } + }, false); + } + + //set the preload flag to true to use preloading of the rewarded ad + aiptag.cmd.player.push(function() { aiptag.adplayer.startRewardedAd({preload: true, showLoading: false}); }); + } + else + { + //rewarded ad already preloaded + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "RewardedInterstitialAvailable"); + } +} + +function tryShowRewardedInterstitial(audioOn) +{ + if(!aipVideoPlayerInitialised() || !aipRewardedAdAvailable) + { + interstitialNoFill(true); + return; + } + + if (!isVideoAdPlaying && firebase.auth().currentUser != null) + { + isVideoAdPlaying = true; + + interstitialStart(true); + + aiptag.adplayer.showRewardedAd(); + + aipRewardedAdAvailable = false; + + // aiptag.cmd.player.push(function() + // { + // + // aiptag.adplayer.startRewardedAd(); + // }); + } +} + +function onRewardedInterstitialGranted() +{ + console.log("Reward Granted"); + + isVideoAdPlaying = false; + + interstitialComplete(true); +} + +function onRewardedInterstitialComplete(evt) +{ + //evt can be: timeout, empty or closed + console.log("Rewarded Ad Completed: " + evt); + + isVideoAdPlaying = false; + + if(evt === "closed") + { + //skipped by the user + interstitialSkipped(true); + } + else + { + //timeout or empty + interstitialNoFill(true); + } +} diff --git a/projects/smashkarts/scripts/ads-adsbygoogle-v2.js b/projects/smashkarts/scripts/ads-adsbygoogle-v2.js deleted file mode 100644 index 7f4e7fb5..00000000 --- a/projects/smashkarts/scripts/ads-adsbygoogle-v2.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -function requestMainMenuBanner() -{ - if(!isMobile()) - { - aiptag.cmd.display.push(function() { aipDisplayTag.display('smashkarts-io_300x250')}); - } -} - -function requestWinCeremonyBanner(interstialRequested) -{ - if(!isMobile()) - { - aiptag.cmd.display.push(function() { aipDisplayTag.display('smashkarts-io_300x250_2')}); - } -} - - -function requestLongBanner() -{ - if(!isMobile()) - { - //aiptag.cmd.display.push(function() { aipDisplayTag.display('smashkarts-io_728x90')}); - aiptag.cmd.display.push(function() { aipDisplayTag.display('smashkarts-io_970x250')}); - } - else - { - //aiptag.cmd.display.push(function() { aipDisplayTag.display('smashkarts-io_320x100')}); - } -} - -function showInterstitial(unusedParam, interstitialType, interstitialName) -{ - // var audioOnStr = audioOn ? 'on' : 'off'; - // adConfig({ - // sound: audioOnStr, - // }); - - if(adBreak != null) - { - adBreak({ - - type: interstitialType, // ad shows at start of next level - name: interstitialName, - beforeBreak: interstitialStart, - afterBreak: interstitialComplete - }); - } -} - - -var onShowRewardedVideoClicked = null; - -function tryInitRewardedInterstitial(unusedParam) -{ - if(adBreak != null) - { - adBreak({ - type: 'reward', // The type of this placement - name: 'rewardedxpboost', // A descriptive name for this placement - beforeAd: () => {interstitialStart();}, // Prepare for the ad. Mute and pause the game flow - afterAd: () => {console.log("tryInitRewardedInterstitials afterAd");}, // Resume the game and re-enable sound - beforeReward: (showAdFn) => { console.log("set onShowRewardedVideoClicked"); rewardedInterstitialAvailable(); onShowRewardedVideoClicked = showAdFn }, // Show reward prompt (call showAdFn() if clicked) - adDismissed: () => {interstitialSkipped();}, // Player dismissed the ad before it finished. - adViewed: () => {interstitialComplete();}, // Player watched the ad–give them the reward. - adBreakDone: (placementInfo) => {console.log("tryInitRewardedInterstitials adBreakDone");}, // Always called (if provided) even if an ad didn’t show - }); - } -} - -function tryShowRewardedInterstitial(unusedParam) -{ - if(onShowRewardedVideoClicked != null) - { - onShowRewardedVideoClicked(); - } -} - -function rewardedInterstitialAvailable() -{ - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "RewardedInterstitialAvailable"); -} diff --git a/projects/smashkarts/scripts/ads-common-logic.js b/projects/smashkarts/scripts/ads-common-logic.js new file mode 100644 index 00000000..ed2ea928 --- /dev/null +++ b/projects/smashkarts/scripts/ads-common-logic.js @@ -0,0 +1,510 @@ +'use strict'; + +//inject bait script +var baitScript = document.createElement('script'); +baitScript.setAttribute('src',baitScriptSrc); +baitScript.async = false; +document.head.appendChild(baitScript); + +//globals +var bannerMinRefreshDelayMillisecs = 0; //can be overwritten depending on ad provider, 0 defaults to requesting a new ad each time + +var loadingBannerShownTimestamp = {val: -1}; //wrap in object to pass by ref +const divIdLoadingBanner = "adContainerLoadingLeft"; + +var mainMenuBannerShownTimestamp = {val: -1}; //wrap in object to pass by ref +const divIdMainMenuBanner = "adContainerMainMenu"; + +var winCeremonyBannerShownTimestamp = {val: -1}; //wrap in object to pass by ref +const divIdWinCeremonyBanner = "adContainerWin"; + +var spectateBannerShownTimestamp = {val: -1}; //wrap in object to pass by ref +const divIdSpectateBanner = "adContainerSpectate"; + +var deathBannerShownTimestamp = {val: -1}; //wrap in object to pass by ref +const divIdDeathBanner = "adContainerDeath"; + +const testBaitDelay = 1000; +var adblockDetectedType; +var pendingAdblockDetectedMessage; + +var isVideoAdPlaying; //used internally in ad provider scripts + +const loadingAdBannerPollDelay = 100; +var loadingAdBannerIntervalId; + +function createAdBlockBaitDiv(divId, classList) +{ + var div = document.getElementById(divId); + + if(div == null) + { + div = document.createElement("div"); + + div.id = divId; + + if(classList != null) + { + div.classList.add(classList); + + } + + div.style.display = "block"; + div.style.backgroundColor = 'transparent'; + div.style.height = '10px'; + div.style.width = '10px'; + div.style.position = 'fixed'; + div.style.bottom = '-100px'; + div.style.left = '-100px'; + + div.innerHTML = ' '; + + document.body.appendChild(div); + } + + return div; +} + +function wasAdBlockDivRemoved(div) +{ + return getComputedStyle(div).display === "none" || div.getBoundingClientRect().height === 0; +} + +function onUpdateAdBlockDetectedComplete(detectionType) +{ + if(!window.adblockDetected) + { + adblockDetectedType = detectionType; + + window.adblockDetected = (detectionType != null); + + if(window.adblockDetected) + { + console.log(`Adblock detected: ${detectionType}`); + } + + pendingAdblockDetectedMessage = true; + trySendAdBlockDetectedMessage(); + } +} + +function trySendAdBlockDetectedMessage() +{ + if(window.unityGame != null && pendingAdblockDetectedMessage) + { + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnUpdateAdBlockDetectedComplete", adblockDetectedType != null ? adblockDetectedType : ""); + + pendingAdblockDetectedMessage = false; + } +} + +function updateAdBlockDetected() +{ + if(window.adblockDetected) + return; + + var imgUrlTestPassed = true; //should be false but disabling temporarily as previous img src url has been removed + var fbDivTestPassed = false; + + //nested function + function checkAllAsyncTestsComplete() + { + if(imgUrlTestPassed && fbDivTestPassed) + { + onUpdateAdBlockDetectedComplete(null); + } + } + + //test local div ad bait + var localAdBlockDiv = createAdBlockBaitDiv("AdBanner", ['adLeaderboard', 'adBanner', 'leaderboard_ad']); + + //delay testing bait divs to let adblockers do their thing + setTimeout(() => + { + //test local script bait + if(document.getElementById('sklocalscriptbait') == null) + { + onUpdateAdBlockDetectedComplete("Local Script"); + return; + } + + //test local div bait + if(wasAdBlockDivRemoved(localAdBlockDiv)) + { + onUpdateAdBlockDetectedComplete("Local Div"); + return; + } + + //disabling temporarily as previous img src url has been removed + // //test image pixel ad bait detection + // var img = new Image(); + // + // img.onload = () => + // { + // imgUrlTestPassed = true; + // checkAllAsyncTestsComplete(); + // } + // + // img.onerror = () => + // { + // onUpdateAdBlockDetectedComplete("Img Url Test"); + // return; + // }; + // + // img.src = 'https://px.moatads.com/pixel.gif'; + + //test bait divs from firebase ids + if (typeof firebase !== 'undefined' && firebase.database() != null && firebase.auth() != null) + { + try + { + const dbRef = firebase.database().ref(); + + dbRef.child("adblock").once("value").then((snapshot) => + { + if (snapshot.exists()) + { + var adblockDivIds = snapshot.val(); + + if(Array.isArray(adblockDivIds)) + { + var adblockDivs = []; + + adblockDivIds.forEach(divId => + { + const div = createAdBlockBaitDiv(divId); + adblockDivs.push(div); + }); + + //delay testing bait divs to let adblockers do their thing + setTimeout(() => + { + //check bait divs + for (let i = 0; i < adblockDivs.length; i++) + { + const div = adblockDivs[i]; + + if(wasAdBlockDivRemoved(div)) + { + onUpdateAdBlockDetectedComplete("Firebase Div"); + return; + } + } + + fbDivTestPassed = true; + checkAllAsyncTestsComplete(); + }, testBaitDelay); + } + } + }); + } + catch(e) + { + console.log(`updateAdBlockDetected error: ${e}`); + } + } + }, testBaitDelay); +} + +function setElementSize(identifier, x, y, w, h) +{ + const el = document.getElementById(identifier); + if(el != null) + { + el.style.left = x + "px"; + el.style.top = y + "px"; + el.style.width = w + "px"; + el.style.height = h + "px"; + } +} + +function hideAdContainer(adElementId) +{ + const ad = document.getElementById(adElementId); + + if(ad != null) + { + ad.style.display = "none"; + } +} + +function showAdContainer(adElementId) +{ + const ad = document.getElementById(adElementId); + + if(ad != null) + { + ad.style.position = "absolute"; + ad.style.display = getComputedStyle(ad).getPropertyValue("--shown_display"); + } +} + +function hideLoadingBanner() +{ + if(!offCanvasAdsEnabled) + { + hideAdContainer(divIdLoadingBanner); + hideLoadingAd(); + } +} + +function showLoadingBanner() +{ + if(!offCanvasAdsEnabled) + { + //check for adblock specifically for main menu banner as we show our own disable blocker panel + if(!isMobile() && !window.adblockDetected) + { + showAdContainer(divIdLoadingBanner); + requestLoadingAd(); + } + } +} + +//Used by playwire to ensure everything still gets initialised correctly for season pass holders +function showDummyMainMenuBanner() +{ + if(!offCanvasAdsEnabled) + { + hideWinCeremonyBanner(); + hideLongBanner(); + hideMainMenuBanner(); + hideSpectateBanner(); + + showAdContainer(divIdMainMenuBanner); + + requestDummyMainMenuAd(); + } +} + +function hideMainMenuBanner() +{ + if(!offCanvasAdsEnabled) + { + hideAdContainer(divIdMainMenuBanner); + hideMainMenuAd(); + } +} + +function showMainMenuBanner() +{ + if(!offCanvasAdsEnabled) + { + hideWinCeremonyBanner(); + hideLongBanner(); + hideSpectateBanner(); + + //check for adblock specifically for main menu banner as we show our own disable blocker panel + if(!isMobile() && !window.adblockDetected) + { + showAdContainer(divIdMainMenuBanner); + requestMainMenuAd(); + } + } +} + +function hideWinCeremonyBanner() +{ + if(!offCanvasAdsEnabled) + { + hideAdContainer(divIdWinCeremonyBanner); + hideWinCeremonyAd(); + } +} + +function showWinCeremonyBanner() +{ + if(!offCanvasAdsEnabled) + { + hideLongBanner(); + hideMainMenuBanner(); + hideSpectateBanner(); + + showAdContainer(divIdWinCeremonyBanner); + requestWinCeremonyAd(); + } +} + +function hideSpectateBanner() +{ + if(!offCanvasAdsEnabled) + { + hideAdContainer(divIdSpectateBanner); + hideSpectateAd(); + } +} + +function showSpectateBanner() +{ + if(!offCanvasAdsEnabled) + { + hideLongBanner(); + hideMainMenuBanner(); + hideWinCeremonyBanner(); + + showAdContainer(divIdSpectateBanner); + requestSpectateAd(); + } +} + +function hideLongBanner() +{ + if(offCanvasAdsEnabled) + { + if(onlyShowOffCanvasAdsOnDeath) + { + hideBtmAdContainer(); + hideRightAdContainer(); + updateGameCanvasSize(); + } + else if(!showBtmAd) + { + //not showing off canvas btm ad so destroy standard on canvas death banner + hideAdContainer(divIdDeathBanner); + hideDeathAd(); + } + } + else + { + hideAdContainer(divIdDeathBanner); + hideDeathAd(); + } +} + +function showLongBanner() +{ + if(offCanvasAdsEnabled) + { + if(onlyShowOffCanvasAdsOnDeath) + { + if(showBtmAd) + { + updateBtmAdContainer(); + } + + if(showRightAd) + { + updateRightAdContainer(); + } + + updateGameCanvasSize(); + } + else if(!showBtmAd) + { + //not showing off canvas btm ad so show standard on canvas death banner + hideWinCeremonyBanner(); + hideMainMenuBanner(); + + showAdContainer(divIdDeathBanner); + requestDeathAd(); + } + } + else + { + hideWinCeremonyBanner(); + hideMainMenuBanner(); + + showAdContainer(divIdDeathBanner); + requestDeathAd(); + } +} + +function showNonRewardedInterstitial(audioOn, interstitialType, interstitialName) +{ + if(!window.adblockDetected) + { + //showInterstitial(audioOn, 'start', 'pregame'); + //showInterstitial(audioOn, 'next', 'winceremony') + showInterstitial(audioOn, interstitialType, interstitialName) + } + else + { + interstitialError(false); + } +} + +function interstitialStart(rewarded) +{ + isVideoAdPlaying = true; + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialStart", rewarded ? 1 : 0); + + if(offCanvasAdsEnabled) + { + hideAllOffCanvasAds(); + } +} + +function interstitialError(rewarded) +{ + isVideoAdPlaying = false; + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialFailed", rewarded ? 1 : 0); + + if(offCanvasAdsEnabled) + { + refreshAllOffCanvasAds(); + } +} + +function interstitialSkipped(rewarded) +{ + isVideoAdPlaying = false; + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialSkipped", rewarded ? 1 : 0); + + if(offCanvasAdsEnabled) + { + refreshAllOffCanvasAds(); + } +} + +function interstitialNoFill(rewarded) +{ + isVideoAdPlaying = false; + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialNoFill", rewarded ? 1 : 0); + + if(offCanvasAdsEnabled) + { + refreshAllOffCanvasAds(); + } +} + +function interstitialComplete(rewarded) +{ + isVideoAdPlaying = false; + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialComplete", rewarded ? 1 : 0); + + if(offCanvasAdsEnabled) + { + refreshAllOffCanvasAds(); + } +} + +function canShowLoadingAdBanner() +{ + return (!window.adblockDetected && + (loadingState === "None" || loadingState === "Closing" || loadingState === "Closed") && + (userNoAdsEndTimestamp != null && userNoAdsEndTimestamp <= Date.now()) && + !isMobile()); +} + +function updateLoadingAdBanner() +{ + //poll to determine if we can show a loading ad or not + loadingAdBannerIntervalId = setInterval(() => + { + if(canShowLoadingAdBanner()) + { + showLoadingBanner(); + showMainMenuBanner(); + clearInterval(loadingAdBannerIntervalId); + } + else if(userNoAdsEndTimestamp != null) + { + clearInterval(loadingAdBannerIntervalId); + } + }, loadingAdBannerPollDelay); +} diff --git a/projects/smashkarts/scripts/ads-init.js b/projects/smashkarts/scripts/ads-init.js new file mode 100644 index 00000000..bb63af28 --- /dev/null +++ b/projects/smashkarts/scripts/ads-init.js @@ -0,0 +1,173 @@ +'use strict'; + +//Keep these in global scope +let adBreak; +let adConfig; + +//PLAYWIRE +if(isPlaywireEnabled()) +{ + //PLAYWIRE RAMP v1.0 + // var ramp = {config: '//config.playwire.com/1024690/v2/websites/73592/banner.json' }; + // + // var playwireScript = document.createElement("script"); + // playwireScript.id = "ramp"; + // playwireScript.type = "text/javascript"; + // playwireScript.async = true; + // playwireScript.src = "//cdn.intergient.com/ramp.js"; + // document.head.appendChild(playwireScript); + + //PLAYWIRE RAMP v2.0 + window.ramp = window.ramp || {}; + window.ramp.que = window.ramp.que || []; + window.ramp.passiveMode = true; + window.ramp.onReady = function() + { + playwireRampInitialised = true; + + //ads stealing focus bugfix + const handleSlotRenderEnded = () => { + let hasFocus = true; + let intervalId; + + const handleBlur = () => { + hasFocus = false; + }; + + const handleFocus = () => { + hasFocus = true; + }; + + window.addEventListener('blur', handleBlur); + window.addEventListener('focus', handleFocus); + + intervalId = setInterval(() => { + if (!hasFocus) { + window.focus(); + clearInterval(intervalId); + window.removeEventListener('blur', handleBlur); + window.removeEventListener('focus', handleFocus); + } else { + clearInterval(intervalId); + window.removeEventListener('blur', handleBlur); + window.removeEventListener('focus', handleFocus); + } + }, 1000); + }; + + window.googletag.pubads().addEventListener('slotRenderEnded', handleSlotRenderEnded); + }; + + window._pwGA4PageviewId = ''.concat(Date.now()); + window.dataLayer = window.dataLayer || []; + window.gtag = window.gtag || function () { + dataLayer.push(arguments); + }; + gtag('js', new Date()); + gtag('config', 'G-F2WLE0BJLM', { 'send_page_view': false, 'cookie_flags': 'samesite=none;secure' }); + gtag( + 'event', + 'ramp_js', + { + 'send_to': 'G-F2WLE0BJLM', + 'pageview_id': window._pwGA4PageviewId + } + ); + + var playwireScript = document.createElement("script"); + playwireScript.type = "text/javascript"; + playwireScript.async = true; + playwireScript.src = "//cdn.intergient.com/1024690/73592/ramp.js"; + document.head.appendChild(playwireScript); + + //PLAYWIRE PRECONNECTS + addPreconnectLink("https://cdn.intergi.com", true); + addPreconnectLink("https://cdn.intergient.com", true); + addPreconnectLink("https://securepubads.g.doubleclick.net", true); + addPreconnectLink("https://cdn.playwire.com", true); + addPreconnectLink("https://z.moatads.com", true); + + function addPreconnectLink(preconnectUrl, crossOriginEnabled) + { + var link = document.createElement('link'); + link.rel = 'preconnect'; + link.href = preconnectUrl; + + if(crossOriginEnabled) + { + link.crossOrigin = 'anonymous'; + } + + document.head.appendChild(link); + } +} + +//ADINPLAY +if(isAdinPlayEnabled()) +{ + window.aiptag = window.aiptag || {cmd: []}; + aiptag.cmd.display = aiptag.cmd.display || []; + aiptag.cmd.player = aiptag.cmd.player || []; + + //CMP tool settings + aiptag.cmp = { + show: true, + position: "bottom", //centered, bottom + button: false, + buttonText: "Privacy settings", + buttonPosition: "bottom-left" //bottom-left, bottom-right, top-left, top-right + } + + //init video player + if(videoAdProvider === AdProviderAdinplay) + { + aiptag.cmd.player.push(function() { + aiptag.adplayer = new aipPlayer({ + AD_WIDTH: 960, + AD_HEIGHT: 540, + AD_DISPLAY: 'fullscreen', //default, fullscreen, center, fill + LOADING_TEXT: 'loading advertisement', + PREROLL_ELEM: function(){return document.getElementById('preroll');}, + AIP_COMPLETE: function(evt){onInterstitialComplete(evt);}, + AIP_REWARDEDCOMPLETE: function(evt){onRewardedInterstitialComplete(evt);}, + AIP_REWARDEDGRANTED: function(){onRewardedInterstitialGranted();} + }); + }); + } + + var adinplayScript = document.createElement("script"); + adinplayScript.type = "text/javascript"; + adinplayScript.async = true; + adinplayScript.src = "//api.adinplay.com/libs/aiptag/pub/SHK/smashkarts.io/tag.min.js"; + document.head.appendChild(adinplayScript); +} + +//GOOGLE H5 GAMES +if(isGoogleH5GamesEnabled()) +{ + window.googletag = window.googletag || { cmd: [] }; + googletag.cmd.push(() => + { + var url = (window.location != window.parent.location) ? document.referrer : document.location.href; + if (url.startsWith("https://smashkarts.io/") || url.startsWith("http://smashkarts.io/") || + url.startsWith("https://www.smashkarts.io/") || url.startsWith("http://www.smashkarts.io/") + || url.includes("smashkarts-dev.firebaseapp.com")) + { + (function () + { + var afgads = document.createElement('script'); + afgads.setAttribute("async", true); + afgads.setAttribute("type", "text/javascript"); + afgads.setAttribute("data-ad-frequency-hint", "30s"); + afgads.setAttribute("data-ad-client", "ca-pub-1463476156508236"); + afgads.setAttribute("src", "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"); + var node = document.getElementsByTagName('script')[0]; + node.parentNode.insertBefore(afgads, node); + })(); + + window.adsbygoogle = window.adsbygoogle || []; + adBreak = adConfig = function (o) { adsbygoogle.push(o); }; + adConfig({ preloadAdBreaks: "on", sound: "on" }); + } + }); +} diff --git a/projects/smashkarts/scripts/ads-injector.js b/projects/smashkarts/scripts/ads-injector.js new file mode 100644 index 00000000..36ca3eb8 --- /dev/null +++ b/projects/smashkarts/scripts/ads-injector.js @@ -0,0 +1,49 @@ +'use strict'; + +//PLAYWIRE +if(isPlaywireEnabled()) +{ + var pwCommonScript = document.createElement("script"); + pwCommonScript.src = pwCommonScriptSrc; + document.body.appendChild(pwCommonScript); + + if(displayAdProvider === AdProviderPlaywire) + { + var pwDisplayScript = document.createElement("script"); + pwDisplayScript.src = pwDisplayScriptSrc; + document.body.appendChild(pwDisplayScript); + } + + if(videoAdProvider === AdProviderPlaywire) + { + var pwVideoScript = document.createElement("script"); + pwVideoScript.src = pwVideoScriptSrc; + document.body.appendChild(pwVideoScript); + } +} + +//ADINPLAY +if(isAdinPlayEnabled()) +{ + if(displayAdProvider === AdProviderAdinplay) + { + var adinplayDisplayScript = document.createElement("script"); + adinplayDisplayScript.src = adinplayDisplayScriptSrc; + document.body.appendChild(adinplayDisplayScript); + } + + if(videoAdProvider === AdProviderAdinplay) + { + var adinplayVideoScript = document.createElement("script"); + adinplayVideoScript.src = adinplayVideoScriptSrc; + document.body.appendChild(adinplayVideoScript); + } +} + +//GOOGLE H5 GAMES +if(isGoogleH5GamesEnabled()) +{ + var googleH5GamesVideoScript = document.createElement("script"); + googleH5GamesVideoScript.src = googleH5GamesVideoScriptSrc; + document.body.appendChild(googleH5GamesVideoScript); +} diff --git a/projects/smashkarts/scripts/ads-offcanvas-logic.js b/projects/smashkarts/scripts/ads-offcanvas-logic.js new file mode 100644 index 00000000..db59da93 --- /dev/null +++ b/projects/smashkarts/scripts/ads-offcanvas-logic.js @@ -0,0 +1,519 @@ +'use strict'; + +function displayingBtmAd() +{ + return currBtmAdIndex >= 0; +} + +function displayingRightAd() +{ + return currRightAdIndex >= 0; +} + +function sortAdResArrays() +{ + btmAdResolutions.sort(sortRightAdResArrays); + rightAdResolutions.sort(sortBtmAdResArrays); + btmAdResolutionsMobile.sort(sortRightAdResArrays); + rightAdResolutionsMobile.sort(sortBtmAdResArrays); +} + +function sortBtmAdResArrays(adResObj1, adResObj2) +{ + if(adResObj1.w === adResObj2.w) + { + if(adResObj1.h === adResObj2.h) + { + return 0; + } + else if(adResObj1.h > adResObj2.h) + { + return -1; + } + else + { + return 1; + } + } + else if(adResObj1.w > adResObj2.w) + { + return -1; + } + else + { + return 1; + } +} + +function sortRightAdResArrays(adResObj1, adResObj2) +{ + if(adResObj1.h === adResObj2.h) + { + if(adResObj1.w === adResObj2.w) + { + return 0; + } + else if(adResObj1.w > adResObj2.w) + { + return -1; + } + else + { + return 1; + } + } + else if(adResObj1.h > adResObj2.h) + { + return -1; + } + else + { + return 1; + } +} + +function updateOffCanvasAdContainers() +{ + if(onlyShowOffCanvasAdsOnDeath) + { + if(displayingBtmAd()) + { + updateBtmAdContainer(); + } + else + { + hideBtmAdContainer(); + } + + if(displayingRightAd()) + { + updateRightAdContainer(); + } + else + { + hideRightAdContainer(); + } + } + else + { + updateBtmAdContainer(); + updateRightAdContainer(); + } +} + +function updateOffCanvasBorderCorner() +{ + //border corner + if(displayingBtmAd() && displayingRightAd()) + { + gameContainer.style.borderBottomRightRadius = offCanvasBorderBtmRightCornerRadiusStyle; + } + else + { + gameContainer.style.borderBottomRightRadius = "0px"; + } +} + +function updateBtmAdContainer() +{ + if (offCanvasAdsEnabled && showBtmAd) + { + //padding + //main container + var mainContainerStyle = getComputedStyle(mainContainer); + var mainContainerPadLeft = parseInt(mainContainerStyle.getPropertyValue("padding-left")); + var mainContainerPadRight = parseInt(mainContainerStyle.getPropertyValue("padding-right")); + var mainContainerPadTop = parseInt(mainContainerStyle.getPropertyValue("padding-top")); + var mainContainerPadBtm = parseInt(mainContainerStyle.getPropertyValue("padding-bottom")); + + //ad container + var btmAdContainerStyle = getComputedStyle(btmAdContainer); + var btmAdContainerPadLeft = parseInt(btmAdContainerStyle.getPropertyValue("padding-left")); + var btmAdContainerPadRight = parseInt(btmAdContainerStyle.getPropertyValue("padding-right")); + var btmAdContainerPadTop = parseInt(btmAdContainerStyle.getPropertyValue("padding-top")); + var btmAdContainerPadBtm = parseInt(btmAdContainerStyle.getPropertyValue("padding-bottom")); + + //calc max ad sizes + var maxAdWidth = window.innerWidth - mainContainerPadLeft - mainContainerPadRight - btmAdContainerPadLeft - btmAdContainerPadRight - rightAdContainer.getBoundingClientRect().width; + var maxAdHeight = (window.innerHeight * maxAdHeightPercentage) - mainContainerPadTop - mainContainerPadBtm - btmAdContainerPadTop - btmAdContainerPadBtm; + + //calc best ad size + var bestAdWidth = 0; + var bestAdHeight = 0; + + var tempBtmAdIndex = -1; + var btmAdResArray = isMobile() ? btmAdResolutionsMobile : btmAdResolutions; + + for (let i = 0; i < btmAdResArray.length; i++) + { + const adRes = btmAdResArray[i]; + + const adWidth = adRes.w; + const adHeight = adRes.h; + + if (adHeight <= maxAdHeight && adHeight >= bestAdHeight && adWidth <= maxAdWidth && adWidth >= bestAdWidth) + { + tempBtmAdIndex = i; + + bestAdWidth = adWidth; + bestAdHeight = adHeight; + } + } + + // console.log(`windowWidth: ${window.innerWidth} maxAdWidth: ${maxAdWidth} closestAdWidth: ${closestAdWidth}`); + + if (tempBtmAdIndex >= 0) + { + gameContainer.style.borderBottom = offCanvasBorderStyle; + + var containerHeight = bestAdHeight + btmAdContainerPadTop + btmAdContainerPadBtm + "px"; + btmAdContainer.style.display = "flex"; + btmAdContainer.style.minHeight = containerHeight; + btmAdContainer.style.height = containerHeight; + + btmAdPlaceholder.style.display = "flex"; + btmAdPlaceholder.style.width = bestAdWidth + "px"; + btmAdPlaceholder.style.height = bestAdHeight + "px"; + + if(debugAdContainers) + { + btmAdResText.style.display = "block"; + btmAdResText.innerHTML = `${bestAdWidth}x${bestAdHeight}`; + } + else + { + btmAdResText.style.display = "none"; + } + + //if we arent already showing an ad then request one + if(currBtmAdIndex != tempBtmAdIndex) + { + currBtmAdIndex = tempBtmAdIndex; + + const adTagIdToShow = btmAdResArray[currBtmAdIndex].adId; + + requestOffCanvasAd(btmAdResArray, adTagIdToShow); + } + } + else + { + hideBtmAdContainer(); + } + } + else + { + hideBtmAdContainer(); + } +} + +function hideBtmAdContainer() +{ + gameContainer.style.borderBottom = "0px"; + + btmAdContainer.style.display = "none"; + btmAdPlaceholder.style.display = "none"; + btmAdResText.style.display = "none"; + + hideOffCanvasAds(btmAdResolutions); + hideOffCanvasAds(btmAdResolutionsMobile); + + currBtmAdIndex = -1; +} + +function updateRightAdContainer() +{ + if (offCanvasAdsEnabled && showRightAd) + { + //padding + //main container + var mainContainerStyle = getComputedStyle(mainContainer); + var mainContainerPadLeft = parseInt(mainContainerStyle.getPropertyValue("padding-left")); + var mainContainerPadRight = parseInt(mainContainerStyle.getPropertyValue("padding-right")); + var mainContainerPadTop = parseInt(mainContainerStyle.getPropertyValue("padding-top")); + var mainContainerPadBtm = parseInt(mainContainerStyle.getPropertyValue("padding-bottom")); + + //ad container + var rightAdContainerStyle = getComputedStyle(rightAdContainer); + var rightAdContainerPadLeft = parseInt(rightAdContainerStyle.getPropertyValue("padding-left")); + var rightAdContainerPadRight = parseInt(rightAdContainerStyle.getPropertyValue("padding-right")); + var rightAdContainerPadTop = parseInt(rightAdContainerStyle.getPropertyValue("padding-top")); + var rightAdContainerPadBtm = parseInt(rightAdContainerStyle.getPropertyValue("padding-bottom")); + + //calc max ad sizes + var maxAdWidth = (window.innerWidth * maxAdWidthPercentage) - mainContainerPadLeft - mainContainerPadRight - rightAdContainerPadLeft - rightAdContainerPadRight; + var maxAdHeight = window.innerHeight - mainContainerPadTop - mainContainerPadBtm - rightAdContainerPadTop - rightAdContainerPadBtm; + + //calc closest ad width + var bestAdWidth = 0; + var bestAdHeight = 0; + + var tempRightAdIndex = -1; + var rightAdResArray = isMobile() ? rightAdResolutionsMobile : rightAdResolutions; + + for (let i = 0; i < rightAdResArray.length; i++) + { + const adRes = rightAdResArray[i]; + + const adWidth = adRes.w; + const adHeight = adRes.h; + + if (adWidth <= maxAdWidth && adWidth >= bestAdWidth && adHeight <= maxAdHeight && adHeight >= bestAdHeight) + { + tempRightAdIndex = i; + + bestAdWidth = adWidth; + bestAdHeight = adHeight; + } + } + + // console.log(`windowHeight: ${window.innerHeight} maxAdHeight: ${maxAdHeight} closestAdHeight: ${closestAdHeight}`); + + //set ad container sizes + if (tempRightAdIndex >= 0) + { + gameContainer.style.borderRight = offCanvasBorderStyle; + + var containerWidth = bestAdWidth + rightAdContainerPadLeft + rightAdContainerPadRight + "px"; + rightAdContainer.style.display = "flex"; + rightAdContainer.style.minWidth = containerWidth; + rightAdContainer.style.width = containerWidth; + + rightAdPlaceholder.style.display = "flex"; + rightAdPlaceholder.style.width = bestAdWidth + "px"; + rightAdPlaceholder.style.height = bestAdHeight + "px"; + + if(debugAdContainers) + { + rightAdResText.style.display = "block"; + rightAdResText.innerHTML = `${bestAdWidth}x${bestAdHeight}`; + } + else + { + //rightAdPlaceholder.style.display = "none"; + rightAdResText.style.display = "none"; + } + + //if we arent already showing an ad then request one + if(currRightAdIndex != tempRightAdIndex) + { + currRightAdIndex = tempRightAdIndex; + + const adTagIdToShow = rightAdResArray[currRightAdIndex].adId; + + requestOffCanvasAd(rightAdResArray, adTagIdToShow); + } + } + else + { + hideRightAdContainer(); + } + } + else + { + hideRightAdContainer(); + } +} + +function hideRightAdContainer() +{ + gameContainer.style.borderRight = "0px"; + + rightAdContainer.style.display = "none"; + rightAdPlaceholder.style.display = "none"; + rightAdResText.style.display = "none"; + + hideOffCanvasAds(rightAdResolutions); + hideOffCanvasAds(rightAdResolutionsMobile); + + currRightAdIndex = -1; +} + +function hideAllOffCanvasAds() +{ + //bottom + hideOffCanvasAds(btmAdResolutions); + hideOffCanvasAds(btmAdResolutionsMobile); + currBtmAdIndex = -1; + + //right + hideOffCanvasAds(rightAdResolutions); + hideOffCanvasAds(rightAdResolutionsMobile); + currRightAdIndex = -1; +} + +function refreshAllOffCanvasAds() +{ + updateOffCanvasAdContainers(); +} + +function updateAdBlockerContainer() +{ + if(!window.adblockDetected) + { + document.getElementById("btmAdBlockerContainer").style.display = "none"; + document.getElementById("rightAdBlockerContainer").style.display = "none"; + } +} + +function createOffCanvasAdDivs() +{ + //bottom + var btmAdResArray = isMobile() ? btmAdResolutionsMobile : btmAdResolutions; + + btmAdResArray.forEach(btmAdRes => { + var adDiv = document.createElement("div"); + adDiv.id = btmAdRes.adId; + + if(setOffCanvasAdDivDimensions) + { + adDiv.style.width = btmAdRes.w + "px"; + adDiv.style.height = btmAdRes.h + "px"; + } + + btmAdPlaceholder.appendChild(adDiv); + }); + + //right + var rightAdResArray = isMobile() ? rightAdResolutionsMobile : rightAdResolutions; + + rightAdResArray.forEach(rightAdRes => { + var adDiv = document.createElement("div"); + adDiv.id = rightAdRes.adId; + + if(setOffCanvasAdDivDimensions) + { + adDiv.style.width = rightAdRes.w + "px"; + adDiv.style.height = rightAdRes.h + "px"; + } + + rightAdPlaceholder.appendChild(adDiv); + }); +} + +function offCanvasAdsOnLoad() +{ + createOffCanvasAdDivs(); + resizeOffCanvasAdContainers(); + updateAdBlockerContainer(); +} + +function offCanvasAdsOnResize() +{ + resizeOffCanvasAdContainers(); +} + +function resizeOffCanvasAdContainers() +{ + updateOffCanvasAdContainers(); + updateOffCanvasBorderCorner(); +} + +sortAdResArrays(); + +window.addEventListener("load", offCanvasAdsOnLoad); +window.addEventListener("resize", offCanvasAdsOnResize); + + +// //CHEAT KEYS +// function handleCheatKey(keyboardEvent) +// { +// var key = keyboardEvent.key; + +// if (key == "b" || key == "B") +// { +// //Toggle bottom ad +// showBtmAd = !showBtmAd; + +// resizeContainers(); + +// console.log(`Toggle showBtmAd: ${showBtmAd}`); +// } +// else if (key == "r" || key == "R") +// { +// //Toggle right ad +// showRightAd = !showRightAd; + +// resizeContainers(); + +// console.log(`Toggle showRightAd: ${showRightAd}`); +// } +// else if (key == "=") +// { +// cheatCyclePadding(true); + +// console.log("Inc padding"); +// } +// else if (key == "-") +// { +// cheatCyclePadding(false); + +// console.log("Dec padding"); +// } +// else if (key == "x" || key == "X") +// { +// onlyShowOffCanvasAdsOnDeath = !onlyShowOffCanvasAdsOnDeath; + +// if(onlyShowOffCanvasAdsOnDeath) +// { +// currRightAdIndex = -1; +// currBtmAdIndex = -1; +// } + +// resizeContainers(); + +// console.log(`Toggle onlyShowOffCanvasAdsOnDeath: ${onlyShowOffCanvasAdsOnDeath}`); +// } +// } + +// window.addEventListener("keypress", handleCheatKey) + +// function cheatCyclePadding(increasePadding) +// { +// const maxPadding = 150; +// const paddingInc = 10; + +// //bottom padding +// var btmAdContainerStyle = getComputedStyle(btmAdContainer); +// var btmAdContainerPadLeft = parseInt(btmAdContainerStyle.getPropertyValue("padding-left")); +// var btmAdContainerPadRight = parseInt(btmAdContainerStyle.getPropertyValue("padding-right")); +// var btmAdContainerPadTop = parseInt(btmAdContainerStyle.getPropertyValue("padding-top")); +// var btmAdContainerPadBtm = parseInt(btmAdContainerStyle.getPropertyValue("padding-bottom")); + +// //right padding +// var rightAdContainerStyle = getComputedStyle(rightAdContainer); +// var rightAdContainerPadLeft = parseInt(rightAdContainerStyle.getPropertyValue("padding-left")); +// var rightAdContainerPadRight = parseInt(rightAdContainerStyle.getPropertyValue("padding-right")); +// var rightAdContainerPadTop = parseInt(rightAdContainerStyle.getPropertyValue("padding-top")); +// var rightAdContainerPadBtm = parseInt(rightAdContainerStyle.getPropertyValue("padding-bottom")); + +// if(increasePadding) +// { +// //btm +// btmAdContainer.style.paddingLeft = Math.min(btmAdContainerPadLeft + paddingInc, maxPadding) + "px"; +// btmAdContainer.style.paddingRight = Math.min(btmAdContainerPadRight + paddingInc, maxPadding) + "px"; +// btmAdContainer.style.paddingTop = Math.min(btmAdContainerPadTop + paddingInc, maxPadding) + "px"; +// btmAdContainer.style.paddingBottom = Math.min(btmAdContainerPadBtm + paddingInc, maxPadding) + "px"; + +// //right +// rightAdContainer.style.paddingLeft = Math.min(rightAdContainerPadLeft + paddingInc, maxPadding) + "px"; +// rightAdContainer.style.paddingRight = Math.min(rightAdContainerPadRight + paddingInc, maxPadding) + "px"; +// rightAdContainer.style.paddingTop = Math.min(rightAdContainerPadTop + paddingInc, maxPadding) + "px"; +// rightAdContainer.style.paddingBottom = Math.min(rightAdContainerPadBtm + paddingInc, maxPadding) + "px"; +// } +// else +// { +// //btm +// btmAdContainer.style.paddingLeft = Math.max(btmAdContainerPadLeft - paddingInc, 0) + "px"; +// btmAdContainer.style.paddingRight = Math.max(btmAdContainerPadRight - paddingInc, 0) + "px"; +// btmAdContainer.style.paddingTop = Math.max(btmAdContainerPadTop - paddingInc, 0) + "px"; +// btmAdContainer.style.paddingBottom = Math.max(btmAdContainerPadBtm - paddingInc, 0) + "px"; + +// //right +// rightAdContainer.style.paddingLeft = Math.max(rightAdContainerPadLeft - paddingInc, 0) + "px"; +// rightAdContainer.style.paddingRight = Math.max(rightAdContainerPadRight - paddingInc, 0) + "px"; +// rightAdContainer.style.paddingTop = Math.max(rightAdContainerPadTop - paddingInc, 0) + "px"; +// rightAdContainer.style.paddingBottom = Math.max(rightAdContainerPadBtm - paddingInc, 0) + "px"; +// } + +// resizeContainers(); +// } diff --git a/projects/smashkarts/scripts/ads-positioning-logic.js b/projects/smashkarts/scripts/ads-positioning-logic.js new file mode 100644 index 00000000..c2e42ea5 --- /dev/null +++ b/projects/smashkarts/scripts/ads-positioning-logic.js @@ -0,0 +1,169 @@ +'use strict'; + +var gameContainer; +function updateAdSizes() +{ + if(gameContainer == null) + { + gameContainer = document.getElementById('gameContainer'); + } + + if(gameContainer != null) + { + updateLongBanner(); + + if(!offCanvasAdsEnabled) + { + updateMainMenuBanner(); + updateWinBanner(); + updateSpectateBanner(); + } + } +} + +var mainMenuBanner; +const defaultMainMenuScaleStr = "scale(100%, 100%)"; +const defaultMainMenuTranslateStr = "translate(0px, -50%)"; +function updateMainMenuBanner() +{ + if(mainMenuBanner == null) + { + mainMenuBanner = document.getElementById(divIdMainMenuBanner); + } + + if(mainMenuBanner != null && mainMenuBanner.style.display !== "none") + { + var adContainerW = mainMenuBanner.offsetWidth; + var adContainerH = mainMenuBanner.offsetHeight; + var gameContainerH = gameContainer.offsetHeight; + + if(adContainerH/gameContainerH > 0.75) + { + var newHeight = gameContainerH * 0.75; + var newScale = newHeight / adContainerH; + var scaleString = "scale( " + newScale + "," + newScale + ")"; + mainMenuBanner.style.transform = `${scaleString} ${defaultMainMenuTranslateStr}`; + } + else + { + mainMenuBanner.style.transform = `${defaultMainMenuScaleStr} ${defaultMainMenuTranslateStr}` + } + } +} + +var winBanner; +const defaultWinCeremonyScaleStr = "scale(100%, 100%)"; +const defaultWinCeremonyTranslateStr = "translate(0px, 0px)"; //"translate(0px, -50%)" +function updateWinBanner() +{ + if(winBanner == null) + { + winBanner = document.getElementById(divIdWinCeremonyBanner); + } + + if(winBanner != null && winBanner.style.display !== "none") + { + var adContainerW = winBanner.offsetWidth; + var adContainerH = winBanner.offsetHeight; + var gameContainerH = gameContainer.offsetHeight; + + if(adContainerH/gameContainerH > 0.75) + { + var newHeight = gameContainerH * 0.75; + var newScale = newHeight / adContainerH; + var scaleString = "scale( " + newScale + "," + newScale + ")"; + winBanner.style.transform = `${scaleString} ${defaultWinCeremonyTranslateStr}`; + } + else + { + winBanner.style.transform = `${defaultWinCeremonyScaleStr} ${defaultWinCeremonyTranslateStr}` + } + } +} + +var spectateBanner; +const defaultSpectateScaleStr = "scale(100%, 100%)"; +const defaultSpectateTranslateStr = "translate(0px, 0px)"; //"translate(0px, -50%)" +function updateSpectateBanner() +{ + if(spectateBanner == null) + { + spectateBanner = document.getElementById(divIdSpectateBanner); + } + + if(spectateBanner != null && spectateBanner.style.display !== "none") + { + var adContainerW = spectateBanner.offsetWidth; + var adContainerH = spectateBanner.offsetHeight; + var gameContainerH = gameContainer.offsetHeight; + + if(adContainerH/gameContainerH > 0.75) + { + var newHeight = gameContainerH * 0.75; + var newScale = newHeight / adContainerH; + var scaleString = "scale( " + newScale + "," + newScale + ")"; + spectateBanner.style.transform = `${scaleString} ${defaultSpectateTranslateStr}`; + } + else + { + spectateBanner.style.transform = `${defaultSpectateScaleStr} ${defaultSpectateTranslateStr}` + } + } +} + +var longBanner; +function updateLongBanner() +{ + if(longBanner == null) + { + longBanner = document.getElementById(divIdDeathBanner); + + if(isMobile() && longBanner != null) + { + //revert from right to center for mobile + longBanner.style.right = "auto"; + } + } + + if(longBanner != null && longBanner.style.display !== "none") + { + longBanner.style.bottom = 0 + "px"; + //longBanner.style.width = 100 + "vw"; + //longBanner.style.width = gameContainer.offsetWidth + "px"; + + var adContainerW = longBanner.offsetWidth; + var adContainerH = longBanner.offsetHeight; + var gameContainerH = gameContainer.offsetHeight; + + if(isMobile()) + { + longBanner.style.top = (gameContainerH - adContainerH) + "px"; + longBanner.style.transform = "scale( 1, 1) translate(0px, -10px)"; + } + else + { + //reserve 30% screen height for horizontal ads, 75% for vertical ads + let heightPercentage = (adContainerW > adContainerH) ? 0.3 : 0.75; + + if(adContainerH/gameContainerH > heightPercentage) + { + const newHeight = gameContainerH * heightPercentage; + const newScale = newHeight / adContainerH; + const scaleString = "scale( " + newScale + "," + newScale + ")"; + //const offsetX = 0; + const offsetX = (adContainerW - adContainerW*newScale)/2 - 10; + const offsetY = (adContainerH - adContainerH*newScale)/2 - 10; + const translateString = "translate(" + offsetX + "px, " + offsetY + "px)"; + longBanner.style.transform = translateString + " " + scaleString; + } + else + { + longBanner.style.transform = "scale( 1, 1) translate(-10px, -10px)"; + } + } + } +} + +//window.addEventListener("load", updateAdSizes); +//window.addEventListener("resize", updateAdSizes); +setInterval(updateAdSizes, 500); diff --git a/projects/smashkarts/scripts/ads-v2.js b/projects/smashkarts/scripts/ads-v2.js deleted file mode 100644 index 709bd132..00000000 --- a/projects/smashkarts/scripts/ads-v2.js +++ /dev/null @@ -1,286 +0,0 @@ -'use strict'; - -var gameContainer; -function updateAdSizes() -{ - if(gameContainer == null) - { - gameContainer = document.getElementById('gameContainer'); - } - - if(gameContainer != null) - { - updateMainMenuBanner(); - updateLongBanner(); - updateWinBanner(); - } -} - -function adBlockerActive() -{ - var active = (document.getElementById('nbAIVXTtpUxM') == null); - return active; -} - -var mainMenuBanner; -function updateMainMenuBanner() -{ - if(mainMenuBanner == null) - { - mainMenuBanner = document.getElementById('adContainer'); - } - - if(mainMenuBanner != null && mainMenuBanner.display != "none") - { - var adContainerW = mainMenuBanner.offsetWidth; - var adContainerH = mainMenuBanner.offsetHeight; - var gameContainerH = gameContainer.offsetHeight; - - if(adContainerH/gameContainerH > 0.8) - { - var newHeight = gameContainerH * 0.8; - var newScale = newHeight / adContainerH; - var scaleString = "scale( " + newScale + "," + newScale + ")"; - var offsetX = (adContainerW - (adContainerW*newScale))/2 - 10; - var offsetY = 10 - (adContainerH - adContainerH*newScale)/2; - var translateString = "translate(" + offsetX + "px, " + offsetY + "px)"; - mainMenuBanner.style.transform = translateString + " " + scaleString; - } - else - { - mainMenuBanner.style.transform = "scale( 1, 1) translate(-10px, 10px)"; - } - } -} - -var winBanner; -function updateWinBanner() -{ - if(winBanner == null) - { - winBanner = document.getElementById('adContainer2'); - } - - if(winBanner != null && winBanner.display != "none") - { - var adContainerW = winBanner.offsetWidth; - var adContainerH = winBanner.offsetHeight; - var gameContainerH = gameContainer.offsetHeight; - - if(adContainerH/gameContainerH > 0.65) - { - var newHeight = gameContainerH * 0.65; - var newScale = newHeight / adContainerH; - var scaleString = "scale( " + newScale + "," + newScale + ")"; - var offsetX = (adContainerW - (adContainerW*newScale))/2 - 10; - var offsetY = gameContainerH/2 - adContainerH/2; - var translateString = "translate(" + offsetX + "px, " + offsetY + "px)"; - winBanner.style.transform = translateString + " " + scaleString; - } - else - { - var offsetY = gameContainerH/2 - adContainerH/2; - winBanner.style.transform = "scale( 1, 1) translate(-10px, " + offsetY + "px)"; - } - } -} - -var longBanner; -function updateLongBanner() -{ - if(longBanner == null) - { - longBanner = document.getElementById('adLongContainer'); - } - - if(longBanner != null && longBanner.display != "none") - { - if(isMobile()) - { - longBanner.style.left = "50%"; - longBanner.style.marginRight = "-50%"; - - var p = window.innerHeight - longBanner.offsetHeight; - - longBanner.style.top = p + "px"; - longBanner.style.transform = "scale( 1, 1) translate(-50%, -10px)"; - } - else - { - longBanner.style.bottom = 0 + "px"; - longBanner.style.width = 100 + "vw"; - - var adContainerH = longBanner.offsetHeight; - var gameContainerH = gameContainer.offsetHeight; - - if(adContainerH/gameContainerH > 0.3) - { - var newHeight = gameContainerH * 0.3; - var newScale = newHeight / adContainerH; - var scaleString = "scale( " + newScale + "," + newScale + ")"; - var offsetX = 0; - var offsetY = (adContainerH - adContainerH*newScale)/2 - 10; - var translateString = "translate(" + offsetX + "px, " + offsetY + "px)"; - longBanner.style.transform = translateString + " " + scaleString; - } - else - { - longBanner.style.transform = "scale( 1, 1) translate(0px, -10px)"; - } - } - - if(isMobile()) - { - var p = window.innerHeight - longBanner.offsetHeight; - longBanner.style.top = p + "px"; - } - else - { - longBanner.style.bottom = 0 + "px"; - } - } -} - -setInterval(updateAdSizes, 500); - -function showMainMenuBanner() -{ - hideWinCeremonyBanner(); - hideLongBanner(); - - const ad = document.querySelector("#adContainer"); - ad.style.display = "block"; - updateAdSizes(); - - requestMainMenuBanner(); -} - -function hideMainMenuBanner() -{ - const ad = document.querySelector("#adContainer"); - if(ad != null) ad.style.display = "none"; - - const ad2 = document.querySelector("#adContainerMainMenu"); - if(ad2 != null) ad2.style.display = "none"; -} - -function showWinCeremonyBanner(interstialRequested) -{ - hideLongBanner(); - hideMainMenuBanner(); - - const ad = document.querySelector("#adContainer2"); - ad.style.display = "block"; - updateAdSizes(); - - requestWinCeremonyBanner(interstialRequested); -} - - -function hideWinCeremonyBanner() -{ - const ad = document.querySelector("#adContainer2"); - if(ad != null) ad.style.display = "none"; - - const ad2 = document.querySelector("#adContainerWin"); - if(ad2 != null) ad2.style.display = "none"; -} - -function showLongBanner() -{ - hideWinCeremonyBanner(); - hideMainMenuBanner(); - - const ad = document.querySelector("#adLongContainer"); - ad.style.display = "flex"; - updateAdSizes(); - - requestLongBanner(); -} - - -function hideLongBanner() -{ - const ad = document.querySelector("#adLongContainer"); - if(ad != null) ad.style.display = "none"; - - const ad2 = document.querySelector("#adLongContainer2"); - if(ad2 != null) ad2.style.display = "none"; -} - -function showLongBanner2() -{ - hideWinCeremonyBanner(); - hideMainMenuBanner(); - - const ad = document.querySelector("#adLongContainer2"); - ad.style.position = "absolute"; - ad.style.display = "block"; - requestLongBanner2(); -} - -function showMainMenuBanner2() -{ - hideWinCeremonyBanner(); - hideLongBanner(); - - const ad = document.querySelector("#adContainerMainMenu"); - ad.style.position = "absolute"; - ad.style.display = "block"; - requestMainMenuBanner2(); -} - -function showWinCeremonyBanner2(interstialRequested) -{ - hideLongBanner(); - hideMainMenuBanner(); - - const ad = document.querySelector("#adContainerWin"); - ad.style.position = "absolute"; - ad.style.display = "block"; - requestWinCeremonyBanner2(interstialRequested); -} - - -function setElementSize(identifier, x, y, w, h) -{ - const el = document.getElementById(identifier); - if(el != null) - { - el.style.left = x + "px"; - el.style.top = y + "px"; - el.style.width = w + "px"; - el.style.height = h + "px"; - } -} - -function showPreGameInterstitial(audioOn) -{ - showInterstitial(audioOn, 'start', 'pregame'); -} - -function showWinCeremonyInterstitial(audioOn) -{ - showInterstitial(audioOn, 'next', 'winceremony') -} - -function interstitialStart() -{ - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialStart"); -} - -function interstitialError() -{ - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialFailed"); -} - -function interstitialSkipped() -{ - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialSkipped"); -} - - -function interstitialComplete() -{ - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "InterstitialComplete"); -} diff --git a/projects/smashkarts/scripts/auth-v3.js b/projects/smashkarts/scripts/auth-v3.js deleted file mode 100644 index 310cc305..00000000 --- a/projects/smashkarts/scripts/auth-v3.js +++ /dev/null @@ -1,260 +0,0 @@ -'use strict'; - -var unityFirebaseGameOjbectName = 'JavascriptMessageReceiver'; - -function onAuthStateChanged(user) { - if(!user) - { - signInAnonymously(); - } - else - { - sendAuthDataToUnity(); - } -} - -function signInAnonymously() -{ - firebase.auth().signInAnonymously().catch(function(error) { - var errorCode = error.code; - console.log("error logging in " + errorCode); - console.error(error); - }); -} - -function signInWithEmail(email, password) -{ - firebase.auth().signInWithEmailAndPassword(email, password) - .then((userCredential) => { - console.log("signInWithEmailAndPassword Success"); - }) - .catch(function(error) - { - console.log("error logging in " + error.code); - console.error(error); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); - }); -} - -function linkUserWithEmail(email, password) -{ - if(firebase.auth().currentUser != null && firebase.auth().currentUser.isAnonymous) - { - var credential = firebase.auth.EmailAuthProvider.credential(email, password); - firebase.auth().currentUser.linkWithCredential(credential).then(function(user) { - console.log("Anonymous account successfully upgraded", user); - sendAuthDataToUnity(); - }, function(error) { - console.log("Error upgrading anonymous account", error); - console.error(error); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); - }); - } -} - -function checkForRedirect() -{ - firebase.auth().getRedirectResult().then(function(result) - { - console.log("linkOrSignInWithGoogle:success"); - sendAuthDataToUnity(); - }, function(error) - { - if(error.code == "auth/credential-already-in-use") - { - console.log("linkOrSignInWithGoogle:fail auth/credential-already-in-use try signInWithCredential"); - firebase.auth().signInWithCredential(error.credential).catch(function(error) - { - console.log("signInWithCredential:: Error logging in " + error.code); - console.error(error); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); - }); - } - else - { - console.log("linkOrSignInWithGoogle:: Error logging in " + error.code); - console.error(error); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); - } - }); -} - -function linkOrSignInWithGoogle() -{ - var provider = new firebase.auth.GoogleAuthProvider(); - - if(firebase.auth().currentUser != null && firebase.auth().currentUser.isAnonymous) - { - var isSafariBrowser = (navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') <= -1); - if(isMobile() || isSafariBrowser) - { - firebase.auth().currentUser.linkWithRedirect(provider); - } - else - { - firebase.auth().currentUser.linkWithPopup(provider).then((result) => - { - console.log("linkOrSignInWithGoogle:: Success"); - sendAuthDataToUnity(); - }).catch((error) => - { - if(error.code == "auth/credential-already-in-use") - { - firebase.auth().signInWithCredential(error.credential).catch(function(error) - { - console.log("signInWithCredential:: Error logging in " + error.code); - console.error(error); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); - }); - } - else - { - console.log("linkOrSignInWithGoogle:: Error logging in " + error.code); - console.error(error); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); - } - }); - } - } -} - -function signOut() -{ - firebase.auth().signOut(); -} - -function sendAuthDataToUnity() -{ - if(window.unityGame != null && firebase.auth().currentUser != null) - { - var firebaseUid = firebase.auth().currentUser.uid; - var isAnon = firebase.auth().currentUser.isAnonymous; - var data = {authToken:"",uid:firebaseUid,isAnonymous:isAnon}; - var dataJson = JSON.stringify(data); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, 'SetAuthToken', dataJson); - } -} - -function sendPasswordResetEmail(emailAddress) -{ - firebase.auth().sendPasswordResetEmail(emailAddress).then(function() { - console.log("sendPasswordResetEmail:: Success"); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "SendPasswordResetEmailSuccess"); - }).catch(function(error) { - console.log("sendPasswordResetEmail:: Failed "); - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "SendPasswordResetEmailFailed", error.message); - console.error(error); - }); -} - -function getValueTT(nodeKey) -{ - if(firebase.auth().currentUser != null) - { - const dbRef = firebase.database().ref(); - dbRef.child(nodeKey).once('value').then((snapshot) => { - if (snapshot.exists()) - { - var valJsonStr = JSON.stringify(snapshot.val()); - SendDataToUnity("OnGetValueSuccess", nodeKey, valJsonStr); - } - else - { - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnGetValueEmptySuccess", nodeKey); - } - }).catch((error) => - { - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnGetValueError", nodeKey, error.message); - console.error(error); - }); - } -} - -function SendDataToUnity(functionName, nk, ds) -{ - var obj = - { - nodeKey: nk, - dataStr: ds - } - - window.unityGame.SendMessage(unityFirebaseGameOjbectName, functionName, JSON.stringify(obj)); -} - -function setValueTT(nodeKey, jsonData) -{ - if(firebase.auth().currentUser != null) - { - const dbRef = firebase.database().ref(); - var jsonObj = JSON.parse(jsonData); - dbRef.child(nodeKey).set(jsonObj, (error) => { - if (error) { - console.log("auth.js::setValue - Error " + nodeKey); - SendDataToUnity("OnSetValueError", nodeKey, error.message); - } else { - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnSetValueSuccess", nodeKey); - } - }); - } -} - -function removeValueTT(nodeKey) -{ - if(firebase.auth().currentUser != null) - { - const dbRef = firebase.database().ref(); - dbRef.child(nodeKey).remove() - .then(function(){ - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnRemoveValueSuccess", nodeKey); - }) - .catch(function(error){ - console.log("auth.js::removeValueTT error"); - SendDataToUnity("OnRemoveValueError", nodeKey, error.message); - }); - } -} - -function updateValueTT(nodeKey, jsonData) -{ - if(firebase.auth().currentUser != null) - { - const dbRef = firebase.database().ref(); - var jsonObj = JSON.parse(jsonData); - dbRef.child(nodeKey).update(jsonObj, (error) => { - if (error) { - console.log("auth.js::updateValue Error " + nodeKey); - SendDataToUnity( "OnUpdateValueError", nodeKey, error.message); - } else { - window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnUpdateValueSuccess", nodeKey); - } - }); - } -} - -function getCurrentUserId() -{ - if(firebase.auth().currentUser != null) - { - return firebase.auth().currentUser.uid; - } - return ""; -} - -function getCurrentUserIsAnon() -{ - if(firebase.auth().currentUser != null) - { - return firebase.auth().currentUser.isAnonymous; - } - return true; -} - -window.addEventListener('load', function() { - console.log('Init Auth'); - if (typeof firebase !== 'undefined' && firebase.auth() != null) - { - firebase.auth().onAuthStateChanged(onAuthStateChanged); - checkForRedirect(); - } -}, false); - diff --git a/projects/smashkarts/scripts/auth.js b/projects/smashkarts/scripts/auth.js new file mode 100644 index 00000000..731f41c9 --- /dev/null +++ b/projects/smashkarts/scripts/auth.js @@ -0,0 +1,516 @@ +'use strict'; + +var unityFirebaseGameOjbectName = 'JavascriptMessageReceiver'; + +var firstLoad = true; + +function onAuthStateChanged(user) { + if(!user) + { + if(firstLoad) + { + if(window.customAuthToken != null) + { + signInWithCustomToken(window.customAuthToken); + } + else + { + signInAnonymously(); + } + } + } + else + { + getUserNoAdsEndTimestamp(); + sendAuthDataToUnity(); + } + firstLoad = false; +} + +function signInWithCustomToken(token) +{ + firebase.auth().signInWithCustomToken(token) + .then((userCredential) => { + console.log("signInWithCustomToken Success"); + }) + .catch(function(error) + { + console.log("error logging in " + error.code); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); + }); +} + +function signInAnonymously() +{ + firebase.auth().signInAnonymously().catch(function(error) { + var errorCode = error.code; + console.log("error logging in " + errorCode); + console.error(error); + }); +} + +function signInWithEmail(email, password) +{ + firebase.auth().signInWithEmailAndPassword(email, password) + .then((userCredential) => { + console.log("signInWithEmailAndPassword Success"); + }) + .catch(function(error) + { + console.log("error logging in " + error.code); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); + }); +} + +function linkUserWithEmail(email, password) +{ + if(firebase.auth().currentUser != null && firebase.auth().currentUser.isAnonymous) + { + var credential = firebase.auth.EmailAuthProvider.credential(email, password); + firebase.auth().currentUser.linkWithCredential(credential).then(function(user) { + console.log("Anonymous account successfully upgraded", user); + sendAuthDataToUnity(); + }, function(error) { + console.log("Error upgrading anonymous account", error); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); + }); + } +} + +//@podonnell: Turn off linkWithRedirect for mobile etc. as this was previously only being used because linkWithPopup was causing issues +//These seem to have been fixed at some stage probably some upgrade of firebase +// function checkForRedirect() +// { +// firebase.auth().getRedirectResult().then(function(result) +// { +// console.log("linkOrSignInWithGoogle:success"); +// sendAuthDataToUnity(); +// }, function(error) +// { +// if(error.code == "auth/credential-already-in-use") +// { +// console.log("linkOrSignInWithGoogle:fail auth/credential-already-in-use try signInWithCredential"); +// firebase.auth().signInWithCredential(error.credential).catch(function(error) +// { +// console.log("signInWithCredential:: Error logging in " + error.code); +// console.error(error); +// window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); +// }); +// } +// else +// { +// console.log("linkOrSignInWithGoogle:: Error logging in " + error.code); +// console.error(error); +// window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); +// } +// }); +// } + +function linkOrSignInWithGoogle() +{ + var provider = new firebase.auth.GoogleAuthProvider(); + + if(firebase.auth().currentUser != null && firebase.auth().currentUser.isAnonymous) + { + //@podonnell: Turn off linkWithRedirect for mobile etc. as this was previously only being used because linkWithPopup was causing issues + //These seem to have been fixed at some stage probably some upgrade of firebase + // var isSafariBrowser = (navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') <= -1); + // if(isMobile() || isSafariBrowser) + // { + // firebase.auth().currentUser.linkWithRedirect(provider); + // } + // else + { + firebase.auth().currentUser.linkWithPopup(provider).then((result) => + { + console.log("linkOrSignInWithGoogle:: Success"); + sendAuthDataToUnity(); + }).catch((error) => + { + if(error.code == "auth/credential-already-in-use") + { + firebase.auth().signInWithCredential(error.credential).catch(function(error) + { + console.log("signInWithCredential:: Error logging in " + error.code); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); + }); + } + else + { + console.log("linkOrSignInWithGoogle:: Error logging in " + error.code); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); + } + }); + } + } +} + +function linkOrSignInWithApple() +{ + var provider = new firebase.auth.OAuthProvider('apple.com'); + + if(firebase.auth().currentUser != null && firebase.auth().currentUser.isAnonymous) + { + //@podonnell: Turn off linkWithRedirect for mobile etc. as this was previously only being used because linkWithPopup was causing issues + //These seem to have been fixed at some stage probably some upgrade of firebase + // var isSafariBrowser = (navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') <= -1); + // if(isMobile() || isSafariBrowser) + // { + // firebase.auth().currentUser.linkWithRedirect(provider); + // } + // else + { + firebase.auth().currentUser.linkWithPopup(provider).then((result) => + { + console.log("linkOrSignInWithApple:: Success"); + sendAuthDataToUnity(); + }).catch((error) => + { + if(error.code == "auth/credential-already-in-use") + { + firebase.auth().signInWithCredential(error.credential).catch(function(error) + { + console.log("signInWithCredential:: Error logging in " + error.code); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseSignInWithEmailFailed", error.message); + }); + } + else + { + console.log("linkOrSignInWithApple:: Error logging in " + error.code); + console.error(error); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "firebaseLinkUserWithEmailFailed", error.message); + } + }); + } + } +} + +function signOut() +{ + firebase.auth().signOut().then(function() { + console.log("signOut:: Success"); + signInAnonymously(); + }).catch(function(error) { + console.log("signOut:: Failed "); + console.error(error); + }); +} + +function sendAuthDataToUnity() +{ + if(window.unityGame != null && firebase.auth().currentUser != null) + { + var firebaseUid = firebase.auth().currentUser.uid; + var isAnon = firebase.auth().currentUser.isAnonymous; + var data = {authToken:"",uid:firebaseUid,isAnonymous:isAnon}; + var dataJson = JSON.stringify(data); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, 'SetAuthToken', dataJson); + } +} + +function sendPasswordResetEmail(emailAddress) +{ + firebase.auth().sendPasswordResetEmail(emailAddress).then(function() { + console.log("sendPasswordResetEmail:: Success"); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "SendPasswordResetEmailSuccess"); + }).catch(function(error) { + console.log("sendPasswordResetEmail:: Failed "); + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "SendPasswordResetEmailFailed", error.message); + console.error(error); + }); +} + +function getValueTT(nodeKey) +{ + const dbRef = firebase.database().ref(); + dbRef.child(nodeKey).once('value').then((snapshot) => { + if (snapshot.exists()) + { + var valJsonStr = JSON.stringify(snapshot.val()); + SendDataToUnity("OnGetValueSuccess", nodeKey, valJsonStr); + } + else + { + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnGetValueEmptySuccess", nodeKey); + } + }).catch((error) => + { + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnGetValueError", nodeKey, error.message); + console.error(error); + }); +} + +function SendDataToUnity(functionName, nk, ds) +{ + var obj = + { + nodeKey: nk, + dataStr: ds + } + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, functionName, JSON.stringify(obj)); +} + + +function SendResponseToUnity(functionName, k, resonseData) +{ + resonseData["key"] = k; + + window.unityGame.SendMessage(unityFirebaseGameOjbectName, functionName, JSON.stringify(resonseData)); +} + +function setValueTT(nodeKey, jsonData) +{ + if(firebase.auth().currentUser != null) + { + const dbRef = firebase.database().ref(); + var jsonObj = JSON.parse(jsonData); + dbRef.child(nodeKey).set(jsonObj, (error) => { + if (error) { + console.log("auth.js::setValue - Error " + nodeKey); + SendDataToUnity("OnSetValueError", nodeKey, error.message); + } else { + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnSetValueSuccess", nodeKey); + } + }); + } +} + +function removeValueTT(nodeKey) +{ + if(firebase.auth().currentUser != null) + { + const dbRef = firebase.database().ref(); + dbRef.child(nodeKey).remove() + .then(function(){ + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnRemoveValueSuccess", nodeKey); + }) + .catch(function(error){ + console.log("auth.js::removeValueTT error"); + SendDataToUnity("OnRemoveValueError", nodeKey, error.message); + }); + } +} + +function updateValueTT(nodeKey, jsonData) +{ + if(firebase.auth().currentUser != null) + { + const dbRef = firebase.database().ref(); + var jsonObj = JSON.parse(jsonData); + dbRef.child(nodeKey).update(jsonObj, (error) => { + if (error) { + console.log("auth.js::updateValue Error " + nodeKey); + SendDataToUnity( "OnUpdateValueError", nodeKey, error.message); + } else { + window.unityGame.SendMessage(unityFirebaseGameOjbectName, "OnUpdateValueSuccess", nodeKey); + } + }); + } +} + +var cloudFunctionSuccess = 0; +var cloudFunctionFail = 0; + +var regions = ["us-central1", "us-east1", "europe-west1"]; +var lastError = "internal"; + +async function callCloudFunction(functionId, jsonData, key) +{ + var success = false; + for(var i=0;i + { + if (setValueError) + { + console.log("logCloudFunctionError setValueError:: " + setValueError.message); + } else + { + var debugErrorWriteSuccessNode = "cferror/" + debugErrorRootNode + "/" + firebaseUid + "/" + functionId + "/" + currentTime + "/successTime"; + var successTime = new Date().getTime(); + dbRef.child(debugErrorWriteSuccessNode).set(successTime); + //console.log("logCloudFunctionError Success"); + } + }); + } + else + { + console.log("logCloudFunctionError:: " + debugErrorRootNode + " " + message); + } +} + +function logCloudFunctionSuccess(debugErrorRootNode, jsonData, functionId) +{ + var firebaseUid = firebase.auth().currentUser.uid; + var currentTime = new Date().getTime(); + var debugErrorNode = "cferror/" + debugErrorRootNode + "/" + firebaseUid + "/" + functionId + "/" + currentTime; + const dbRef = firebase.database().ref(); + + dbRef.child(debugErrorNode).set({ + errorData: jsonData, + os: getOS(), + time : currentTime, + successCount : cloudFunctionSuccess, + failCount : cloudFunctionFail, + }, (setValueError) => { + if (setValueError) { + console.log("logCloudFunctionSuccess setValueError:: " + setValueError.message); + + } else { + console.log("logCloudFunctionSuccess Success "); + } + } + ); +} + +function getCurrentUserId() +{ + if(firebase.auth().currentUser != null) + { + return firebase.auth().currentUser.uid; + } + return ""; +} + +function getCurrentUserIsAnon() +{ + if(firebase.auth().currentUser != null) + { + return firebase.auth().currentUser.isAnonymous; + } + return true; +} + +var userNoAdsEndTimestamp; +function getUserNoAdsEndTimestamp() +{ + if (typeof firebase !== 'undefined' && firebase.database() != null && firebase.auth() != null) + { + try + { + var uid = getCurrentUserId(); + + if(uid != null && uid !== "") + { + const dbRef = firebase.database().ref(); + + dbRef.child(`users/${uid}/udro/noAdsEndTimestamp`).once("value").then((snapshot) => + { + if (snapshot.exists()) + { + userNoAdsEndTimestamp = snapshot.val(); + } + else + { + userNoAdsEndTimestamp = 0; + } + }); + } + } + catch (e) + { + console.log(e); + } + } +} + +window.addEventListener('load', function() { + console.log('Init Auth'); + if (typeof firebase !== 'undefined' && firebase.auth() != null) + { + firebase.auth().onAuthStateChanged(onAuthStateChanged); + + //@podonnell: Turn off linkWithRedirect for mobile etc. as this was previously only being used because linkWithPopup was causing issues + //These seem to have been fixed at some stage probably some upgrade of firebase + //checkForRedirect(); + } +}, false); + + +function getBrowser() +{ + return window.navigator.userAgent; +} + +function getBrowserVisibilityState() +{ + return document.visibilityState; +} diff --git a/projects/smashkarts/scripts/ad-blocker.js b/projects/smashkarts/scripts/banger.js similarity index 54% rename from projects/smashkarts/scripts/ad-blocker.js rename to projects/smashkarts/scripts/banger.js index a308309c..d2fb7fd7 100644 --- a/projects/smashkarts/scripts/ad-blocker.js +++ b/projects/smashkarts/scripts/banger.js @@ -1,4 +1,5 @@ +// Used for detecting if ad blockers are enabled var e=document.createElement('div'); -e.id='nbAIVXTtpUxM'; +e.id='sklocalscriptbait'; e.style.display='none'; document.body.appendChild(e); diff --git a/projects/smashkarts/scripts/cc.js b/projects/smashkarts/scripts/cc.js new file mode 100644 index 00000000..26800c69 --- /dev/null +++ b/projects/smashkarts/scripts/cc.js @@ -0,0 +1,44 @@ +"use strict"; + +if(typeof(Worker) !== "undefined") +{ + const checkTimeDelay = 500; + let consoleOpen = false; + let checkTimestamp = Date.now(); + + const consoleCheckerThread = new Worker(ccWorkerScriptSrc); + + consoleCheckerThread.addEventListener("message", (msg) => + { + checkTimestamp = msg.data; + }); + + setInterval(() => + { + const wasConsoleOpen = consoleOpen; + consoleOpen = (Date.now() - checkTimestamp > checkTimeDelay); + + if(consoleOpen && !wasConsoleOpen) + { + console.log("%cSTOP!", "color:red; font-style:heavy; font-size:75px; font-weight:900; text-shadow:2px 2px 0 rgb(0,0,0)"); + console.log("%cThis is a browser feature intended for developers. If someone told you to copy and paste something here, there is a good chance that they are attempting to gain access to your account and personal information!", "font-size:20px;"); + } + }, checkTimeDelay); + + ////Alternative just to pause lock up debugger when console is open + // (function pauseGameWhenConsoleOpen() + // { + // try + // { + // (function pauseDebugger() + // { + // debugger; + // pauseDebugger() + // })() + // } + // catch (e) + // { + // setTimeout(pauseGameWhenConsoleOpen, 5000) + // } + // })() +} diff --git a/projects/smashkarts/scripts/ccWorker.js b/projects/smashkarts/scripts/ccWorker.js new file mode 100644 index 00000000..1b44cd0e --- /dev/null +++ b/projects/smashkarts/scripts/ccWorker.js @@ -0,0 +1,7 @@ +"use strict"; + +setInterval(() => +{ + self.postMessage(Date.now()); + debugger; +}, self.checkTimeDelay); diff --git a/projects/smashkarts/scripts/constants.js b/projects/smashkarts/scripts/constants.js new file mode 100644 index 00000000..66ee73fe --- /dev/null +++ b/projects/smashkarts/scripts/constants.js @@ -0,0 +1,73 @@ +'use strict'; + +let enableFirebaseAnalytics = true; + +//ADS +const AdProviderPlaywire = "Playwire"; +const AdProviderGoogleH5Games = "GoogleH5Games"; +const AdProviderAdinplay = "AdinPlay"; +var displayAdProvider = AdProviderAdinplay; +var videoAdProvider = AdProviderAdinplay; + +var playwireRampInitialised = false; + +var pwCommonScriptSrc = "scripts/ads-pw-common.js"; +var pwDisplayScriptSrc = "scripts/ads-pw-display.js"; +var pwVideoScriptSrc = "scripts/ads-pw-video.js"; +var adinplayDisplayScriptSrc = "scripts/ads-adinplay-display.js"; +var adinplayVideoScriptSrc = "scripts/ads-adinplay-video.js"; +var googleH5GamesVideoScriptSrc = "scripts/ads-google-h5-games-video.js"; + +function isPlaywireEnabled() +{ + return displayAdProvider === AdProviderPlaywire || videoAdProvider === AdProviderPlaywire; +} + +function isAdinPlayEnabled() +{ + return displayAdProvider === AdProviderAdinplay || videoAdProvider === AdProviderAdinplay; +} + +function isGoogleH5GamesEnabled() +{ + return videoAdProvider === AdProviderGoogleH5Games; +} + +//OFF CANVAS ADS +var debugAdContainers = false; +var offCanvasAdsEnabled = false; +var showBtmAd = false; +var showRightAd = true; +var setOffCanvasAdDivDimensions = false; //false by default, true for crazygames +var onlyShowOffCanvasAdsOnDeath = false; + +var maxAdWidthPercentage = 0.25; +var maxAdHeightPercentage = 0.25; +var offCanvasBorderSize = "5"; +var offCanvasBorderStyle = `#99c7fc ${offCanvasBorderSize}px solid`; +var offCanvasBorderBtmRightCornerRadiusStyle = "8px"; + +var btmAdResolutions = [ + { w: 970, h: 250, adId: "smashkarts-io_970x250_2" }, + { w: 970, h: 90, adId: "smashkarts-io_970x90" }, + { w: 728, h: 90, adId: "smashkarts-io_728x90_2" }, +]; + +var rightAdResolutions = [ + { w: 336, h: 1050, adId: "smashkarts-io_336x1050" }, + { w: 300, h: 600, adId: "smashkarts-io_300x600" }, + { w: 160, h: 600, adId: "smashkarts-io_160x600" }, +]; + +var btmAdResolutionsMobile = [ + { w: 320, h: 50, adId: "smashkarts-io_320x50" }, +]; + +var rightAdResolutionsMobile = [ +]; + +var currBtmAdIndex = -1; +var currRightAdIndex = -1; + +var baitScriptSrc = "scripts/banger.js"; +var ccWorkerScriptSrc = "scripts/ccWorker.js"; diff --git a/projects/smashkarts/scripts/main-v2.js b/projects/smashkarts/scripts/main.js similarity index 70% rename from projects/smashkarts/scripts/main-v2.js rename to projects/smashkarts/scripts/main.js index c7d751cd..6bd90662 100644 --- a/projects/smashkarts/scripts/main-v2.js +++ b/projects/smashkarts/scripts/main.js @@ -8,14 +8,6 @@ function setV(val2) } } -function getReferrerUrl() -{ - var url = (window.location != window.parent.location) - ? document.referrer - : document.location.href; - return url; -} - function isMobile() { var isMobile = RegExp(/Android|webOS|iPhone|iPod|iPad/i).test(navigator.userAgent); @@ -118,18 +110,29 @@ window.copyText = function (text) { function firebaseLogEvent(eventName) { - if(firebaseSupported) firebase.analytics().logEvent(eventName); + if(enableFirebaseAnalytics && firebase.analytics != null) + firebase.analytics().logEvent(eventName); } function firebaseSetScreen(screenName) { - if(firebaseSupported) firebase.analytics().setCurrentScreen(screenName); - if(firebaseSupported) firebase.analytics().logEvent("screen_view", { "screen_name": screenName}) + if(enableFirebaseAnalytics && firebase.analytics != null) + { + firebase.analytics().setCurrentScreen(screenName); + firebase.analytics().logEvent("screen_view", { "screen_name": screenName}) + } } function firebaseLogEventWithParam(eventName, p, v) { - if(firebaseSupported) firebase.analytics().logEvent(eventName, { [p]: v}); + if(enableFirebaseAnalytics && firebase.analytics != null) + firebase.analytics().logEvent(eventName, { [p]: v}); +} + +function firebaseLogEventWithParamDict(eventName, paramsDict) +{ + if(enableFirebaseAnalytics && firebase.analytics != null) + firebase.analytics().logEvent(eventName, paramsDict); } var fs = false; @@ -142,8 +145,8 @@ function toggleFullscreen() } else { - console.log("setElementFullScreen"); - var elem = document.getElementById("mainContainer"); + console.log("setElementFullScreen"); + var elem = document.documentElement; //document.getElementById("mainContainer"); setElementFullScreen(elem); } fs = !fs; @@ -173,6 +176,25 @@ function isFullscreen() }); } + function openPrivacyUrl() + { + onNextMouseUp(function () { + console.log("openPrivacyUrl onNextMouseUp"); + if(isPlaywireEnabled()) + { + window.open("https://smashkarts.io/privacy/privacyPW.html", "_blank"); + } + else if(isAdinPlayEnabled()) + { + window.open("https://smashkarts.io/privacy/privacyAdinplay.html", "_blank"); + } + else + { + window.open("https://smashkarts.io/privacy/privacy.html", "_blank"); + } + }); + } + function setElementFullScreen(el) { onNextMouseUp(function () { var request = el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen || el.msRequestFullscreen; @@ -208,3 +230,39 @@ function isFullscreen() { location.reload(); } + + var loadingState = "None"; + function updateLoadingState(state) + { + loadingState = state; + } + + function onLoadingToMainMenuComplete(isCG) + { + hideLoadingBanner(); + + if(isCG && !cgEnvDisabled) + { + window.CrazyGames.SDK.game.sdkGameLoadingStop(); + } + } + +function isIFramed() +{ + try + { + // Check if the current window is not the top-level window + if (window.self !== window.top) + { + return true; + } + } + catch (e) + { + // If a cross-origin error occurs, assume the content is iframed + return true; + } + + // Default case: Not iframed + return false; +} diff --git a/projects/smashkarts/scripts/readme.md b/projects/smashkarts/scripts/readme.md new file mode 100644 index 00000000..bef7f4ae --- /dev/null +++ b/projects/smashkarts/scripts/readme.md @@ -0,0 +1 @@ +ja diff --git a/projects/smashkarts/scripts/shop.js b/projects/smashkarts/scripts/shop.js new file mode 100644 index 00000000..7c050834 --- /dev/null +++ b/projects/smashkarts/scripts/shop.js @@ -0,0 +1,90 @@ +'use strict'; + +var currentOrderId = ""; +var currentProductId = ""; +var completedOrderId = ""; +var sandbox = false; +var shopUrl = (sandbox ? "https://sandbox-secure.xsolla.com" : "https://secure.xsolla.com"); + +async function buyProduct(productId) +{ + console.log("buyProduct " + productId); + + var functionRef = firebase.app().functions().httpsCallable("getXsollaTokenForItemMulti"); + + var response = await functionRef(productId); + if(response != null && response.data != null) + { + var url = shopUrl + "/paystation3/?access_token=" + response.data.token; + currentOrderId = response.data.order_id; + currentProductId = productId; + openStoreWindowInFrame(url); + } +} + +async function openStoreWindoWithToken(productId, token, orderId) +{ + var url = shopUrl + "/paystation3/?access_token=" + token; + currentOrderId = orderId; + currentProductId = productId; + openStoreWindowInFrame(url); +} + + +async function openStoreWindowInFrame(url) +{ + var elem = document.getElementById("xsolla-iframe"); + elem.src = url; + elem.style.display = "block"; +} + +window.addEventListener("message", (event) => { + if (event.origin == shopUrl) + { + if(event.data != null) + { + var jsonData = JSON.parse(event.data); + if(jsonData != null) + { + if(jsonData.data != null) + { + if(jsonData.data.action == "change-status" && jsonData.data.value == "done") + { + completedOrderId = jsonData.data.purchase_invoice_id; + } + else if (jsonData.data.action == "close-widget") + { + purchaseComplete(); + } + } + + if(jsonData.command == "return" || jsonData.command == "close-widget") + { + purchaseComplete(); + } + + } + } + console.log("Window event " + event.data); + } +}, false); + + function purchaseComplete() + { + if(currentOrderId != "") + { + var elem = document.getElementById("xsolla-iframe"); + elem.style.display = "none"; + + var obj = + { + orderId: currentOrderId.toString(), + productId: currentProductId + } + const functionName = (completedOrderId != "") ? "PurchaseComplete" : "PurchaseCanceled"; + window.unityGame.SendMessage(unityFirebaseGameOjbectName, functionName, JSON.stringify(obj)); + completedOrderId = ""; + currentProductId = ""; + currentOrderId = ""; + } + } diff --git a/projects/smashkarts/service-worker2.js b/projects/smashkarts/service-worker2.js new file mode 100644 index 00000000..cef090af --- /dev/null +++ b/projects/smashkarts/service-worker2.js @@ -0,0 +1,27 @@ +const PRECACHE = 'precache-v1'; + +// A list of local resources we always want to be cached. +const PRECACHE_URLS = [ +]; + +// The install handler takes care of precaching the resources we always need. +self.addEventListener('install', event => { + event.waitUntil( + caches.open(PRECACHE) + .then(cache => cache.addAll(PRECACHE_URLS)) + .then(self.skipWaiting()) + ); +}); + +// The activate handler takes care of cleaning up old caches. +self.addEventListener('activate', event => { + return null; +}); + +// The fetch handler serves responses for same-origin resources from a cache. +// If no response is found, it populates the runtime cache with the response +// from the network before returning it to the page. +self.addEventListener('fetch', event => { + // Skip cross-origin requests, like those for Google Analytics. + return null; +}); diff --git a/projects/smashkarts/xmlhttprequest-length-computable.min.js b/projects/smashkarts/xmlhttprequest-length-computable.min.js index ae5325fb..01c1ecf2 100644 --- a/projects/smashkarts/xmlhttprequest-length-computable.min.js +++ b/projects/smashkarts/xmlhttprequest-length-computable.min.js @@ -1,6 +1 @@ -(function(){var g={CONTENT_ENCODING_MULTIPLE:1.5,DEFAULT_CONTENT_LENGTH:1048576,DECOMPRESSED_CONTENT_LENGTH_HEADER:"x-decompressed-content-length"};if(window.Proxy){var h=XMLHttpRequest,k=function(a,c){var b=0;a["decompressed-content-length"]&&(b=a["decompressed-content-length"]);try{if(!b){var d=c.target.getResponseHeader(a.DECOMPRESSED_CONTENT_LENGTH_HEADER);void 0!=d&&(b=parseInt(d))}if(!b){var e=c.target.getResponseHeader("content-length");if(e){e=parseInt(e);var f=c.target.getResponseHeader("content-encoding"); -b=f&&"identity"!=f?e*a.CONTENT_ENCODING_MULTIPLE|0:e*a.CONTENT_ENCODING_MULTIPLE}}}catch(p){}b||(b=a.DEFAULT_CONTENT_LENGTH);return b},l=function(a,c){var b=0;return function(d){if(d&&(d instanceof ProgressEvent||a.no_type_check)&&("progress"==d.type||"load"==d.type||"loadend"==d.type))if(0==d.lengthComputable){var e=d;d=new Proxy(d,{get:function(c,d){return"lengthComputable"==d?!0:"loaded"==d?(b||(b=k(a,e)),a.loadFinished?b:Math.min(e.loaded,b-1)):"total"==d?(b||(b=k(a,e)),b):c[d]}})}else a.lengthComputable=!0;a.latestProgress= -d;c&&c(d)}},n={set:function(a,c,b){a.xmlHTTPRequestLengthComputable&&0==c.indexOf("on")&&a.xmlHTTPRequestLengthComputable.listeners[c.substr(2)]?(a.xmlHTTPRequestLengthComputable.listeners[c.substr(2)].on&&delete a.xmlHTTPRequestLengthComputable.listeners[c.substr(2)].on,b?(a[c]=l(a.xmlHTTPRequestLengthComputable,b),a.xmlHTTPRequestLengthComputable.listeners[c.substr(2)].on=b):a[c]=b):a[c]=b;return!0},get:function(a,c){return"addEventListener"==c?function(){if(a.xmlHTTPRequestLengthComputable.listeners[arguments[0]]){var b= -l(a.xmlHTTPRequestLengthComputable,arguments[1]);a.xmlHTTPRequestLengthComputable.listeners[arguments[0]].listeners.push([b,arguments[1]]);return a[c].call(a,arguments[0],b,arguments[2],arguments[3])}return a[c].apply(a,arguments)}:"removeEventListener"==c?function(){if(a.xmlHTTPRequestLengthComputable.listeners[arguments[0]])for(var b=a.xmlHTTPRequestLengthComputable.listeners[arguments[0]].listeners,d=0;d