Skip to content

Commit

Permalink
Merge branch '6000.0' into 6000.0-4gb-memory-limit
Browse files Browse the repository at this point in the history
  • Loading branch information
JohannesDeml committed Dec 18, 2024
2 parents 2a2dca4 + 1a07693 commit 1e4e83a
Show file tree
Hide file tree
Showing 6 changed files with 227 additions and 94 deletions.
15 changes: 11 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ on:
push:
tags:
- '*'
branches:
- master

jobs:
variables:
Expand All @@ -28,7 +30,12 @@ jobs:
- name: Set tag
id: set_tag
run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT
run: |
if [[ $GITHUB_REF == refs/tags/* ]]; then
echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT
else
echo "VERSION=${{ steps.set_unity_version.outputs.VERSION }}-webgl2-master" >> $GITHUB_OUTPUT
fi
- name: Set target name
id: set_build_name
Expand Down Expand Up @@ -62,8 +69,8 @@ jobs:
buildProject:
name: Create Unity WebGL Build 🏗
# only build with additional parameters, the tag alone should only create a release draft
if: ${{ needs.variables.outputs.TAG != needs.variables.outputs.UNITY_VERSION }}
# Build if it's a master push or if the tag is not just the unity version
if: ${{ github.ref == 'refs/heads/master' || needs.variables.outputs.TAG != needs.variables.outputs.UNITY_VERSION }}
needs: [ variables ]
runs-on: ubuntu-latest
strategy:
Expand Down Expand Up @@ -112,7 +119,7 @@ jobs:
createRelease:
name: Create Github release 🐙
# only run for the pure tag without build parameters
if: ${{ needs.variables.outputs.TAG == needs.variables.outputs.UNITY_VERSION }}
if: ${{ github.ref_type == 'tag' && needs.variables.outputs.TAG == needs.variables.outputs.UNITY_VERSION }}
needs: [ variables ]
runs-on: ubuntu-latest
steps:
Expand Down
80 changes: 80 additions & 0 deletions Assets/Plugins/WebGL/WebBridge/CommonCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using Supyrb.Attributes;
using UnityEngine;
Expand Down Expand Up @@ -274,5 +275,84 @@ public void LogShaderCompilation(int enabled)
GraphicsSettings.logWhenShaderIsCompiled = enabled == 1;
Debug.Log($"GraphicsSettings.logWhenShaderIsCompiled: {GraphicsSettings.logWhenShaderIsCompiled}");
}

/// <summary>
/// Copy text to clipboard using the browser's clipboard API
/// </summary>
/// <param name="text">Text to copy to clipboard</param>
[WebCommand(Description = "Copy text to clipboard")]
public void CopyToClipboard(string text)
{
WebToolPlugins.CopyToClipboard(text);
}

/// <summary>
/// Check if the browser has an internet connection
/// </summary>
[WebCommand(Description = "Check if browser is online")]
public void CheckOnlineStatus()
{
bool isOnline = WebToolPlugins.IsOnline();
Debug.Log($"<color=#4D65A4>Online Status:</color> {(isOnline ? "<color=#3bb508>Connected</color>" : "<color=#b50808>Disconnected</color>")}");
}

/// <summary>
/// Captures the current screen and saves it as a PNG file.
/// </summary>
[WebCommand(Description = "Save current screen as PNG")]
public void SaveScreenshot()
{
SaveScreenshotSuperSize(1);
}

/// <summary>
/// Captures the current screen and saves it as a PNG file.
/// </summary>
/// <param name="superSize">1 for normal size, 2 for double size, 4 for quadruple size</param>
[WebCommand(Description = "Save current screen as PNG with variable super size")]
public void SaveScreenshotSuperSize(int superSize)
{
StartCoroutine(CaptureScreenshot(superSize));
}

private IEnumerator CaptureScreenshot(int superSize)
{
// Wait for the end of frame to ensure everything is rendered
yield return new WaitForEndOfFrame();

string filename = "screenshot.png";
try
{
// Capture the screen
Texture2D screenshot = ScreenCapture.CaptureScreenshotAsTexture(superSize);

try
{
// Convert to PNG
byte[] pngData = screenshot.EncodeToPNG();

// Download through browser
WebToolPlugins.DownloadBinaryFile(filename, pngData, "image/png");

Debug.Log($"Screenshot saved as {filename} ({screenshot.width}x{screenshot.height}) with size {pngData.Length} bytes");
}
finally
{
// Clean up the texture
if (Application.isPlaying)
{
Destroy(screenshot);
}
else
{
DestroyImmediate(screenshot);
}
}
}
catch (System.Exception e)
{
Debug.LogError($"Failed to save screenshot: {e.Message}");
}
}
}
}
16 changes: 14 additions & 2 deletions Assets/Plugins/WebGL/WebBridge/WebBridge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ public void Help()
{
sb.AppendLine($"<b>---{webCommand.GetType().Name}---</b>");
MethodInfo[] methods = webCommand.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
Array.Sort(methods, (a, b) => string.Compare(a.Name, b.Name));

for (int i = 0; i < methods.Length; i++)
{
Expand All @@ -123,11 +124,11 @@ public void Help()
var parameter = parameters[j];
if (parameter.ParameterType == typeof(string))
{
sb.Append($", \"{parameter.ParameterType} {parameter.Name}\"");
sb.Append($", \"{GetFriendlyTypeName(parameter.ParameterType)} {parameter.Name}\"");
}
else
{
sb.Append($", {parameter.ParameterType} {parameter.Name}");
sb.Append($", {GetFriendlyTypeName(parameter.ParameterType)} {parameter.Name}");
}
}

Expand All @@ -140,5 +141,16 @@ public void Help()
sb.AppendLine($"\nRun a command with 'runUnityCommand(\"COMMAND_NAME\",PARAMETER);'");
Debug.Log(sb.ToString());
}

private string GetFriendlyTypeName(Type type)
{
if (type == typeof(int)) return "int";
if (type == typeof(long)) return "long";
if (type == typeof(float)) return "float";
if (type == typeof(double)) return "double";
if (type == typeof(bool)) return "bool";
if (type == typeof(string)) return "string";
return type.Name;
}
}
}
136 changes: 80 additions & 56 deletions Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,14 @@ public static class WebToolPlugins
[DllImport("__Internal")]
private static extern uint _GetTotalMemorySize();
[DllImport("__Internal")]
private static extern uint _GetStaticMemorySize();
private static extern bool _CopyToClipboard(string text);
[DllImport("__Internal")]
private static extern uint _GetDynamicMemorySize();
private static extern int _IsOnline();
[DllImport("__Internal")]
private static extern void _DownloadFile(string filename, string content);
[DllImport("__Internal")]
private static extern void _DownloadBlob(string filename, byte[] byteArray, int byteLength, string mimeType);

#endif

private static bool _infoPanelVisible = false;
Expand Down Expand Up @@ -154,106 +159,125 @@ public static bool IsMobileDevice()
userAgent.Contains("Android");
}

/// <summary>
/// Get the total memory size used by the application in MB
/// </summary>
/// <returns>Size in MB</returns>
public static float GetTotalMemorySize()
{
#if UNITY_WEBGL && !UNITY_EDITOR
var bytes = _GetTotalMemorySize();
return GetMegaBytes(bytes);
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetTotalMemorySize)} called");
return -1f;
#else
return -1f;
#endif
}

/// <summary>
/// Log all current memory data in MB
/// </summary>
public static void LogMemory()
{
#if UNITY_WEBGL && !UNITY_EDITOR
var managed = GetManagedMemorySize();
var native = GetNativeMemorySize();
var total = GetTotalMemorySize();
Debug.Log($"Memory stats:\nManaged: {managed:0.00}MB\nNative: {native:0.00}MB\nTotal: {total:0.00}MB");
Debug.Log($"Memory stats:\nManaged: {managed:0.00}MB\nTotal: {total:0.00}MB");
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(LogMemory)} called");
#endif
}

/// <summary>
/// Get the static memory size used by the application in MB
/// Get the total memory size used by the application in MB
/// </summary>
/// <returns>Size in MB</returns>
public static float GetStaticMemorySize()
public static float GetTotalMemorySize()
{
#if UNITY_WEBGL && !UNITY_EDITOR
var bytes = _GetStaticMemorySize();
var bytes = _GetTotalMemorySize();
return GetMegaBytes(bytes);
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetStaticMemorySize)} called");
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetTotalMemorySize)} called");
return -1f;
#else
return -1f;
#endif
}

/// <summary>
/// Get the dynamic memory size used by the application in MB
/// Get the managed memory size used by the application in MB
/// </summary>
/// <returns>Size in MB</returns>
public static float GetDynamicMemorySize()
public static float GetManagedMemorySize()
{
#if UNITY_WEBGL && !UNITY_EDITOR
var bytes = _GetStaticMemorySize();
var bytes = (uint)GC.GetTotalMemory(false);
return GetMegaBytes(bytes);
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetDynamicMemorySize)} called");
return -1f;
#else
return -1f;
#endif
}

/// <summary>
/// Get the native memory size used by the application in MB (Static + Dynamic memory)
/// Converts bytes (B) to mega bytes (MB)
/// </summary>
/// <returns>Size in MB</returns>
public static float GetNativeMemorySize()
/// <param name="bytes">bytes to convert</param>
/// <returns>bytes / (1024 * 1024)</returns>
private static float GetMegaBytes(uint bytes)
{
#if UNITY_WEBGL && !UNITY_EDITOR
return GetDynamicMemorySize() + GetStaticMemorySize();
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetNativeMemorySize)} called");
return -1f;
#else
return -1f;
#endif
return (float)bytes / (1024 * 1024);
}

/// <summary>
/// Get the managed memory size used by the application in MB
/// Copies the specified text to the system clipboard using the browser's clipboard API.
/// Only works in WebGL builds and requires clipboard-write permission in modern browsers.
/// </summary>
/// <returns>Size in MB</returns>
public static float GetManagedMemorySize()
/// <param name="text">The text to copy to the clipboard</param>
/// <returns>True if the copy operation was successful, false otherwise</returns>
public static void CopyToClipboard(string text)
{
var bytes = (uint)GC.GetTotalMemory(false);
return GetMegaBytes(bytes);
#if UNITY_WEBGL && !UNITY_EDITOR
_CopyToClipboard(text);
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(CopyToClipboard)} called with: {text}");
#endif
}

/// <summary>
/// Converts bytes (B) to mega bytes (MB)
/// Checks if the browser currently has an internet connection using the navigator.onLine property.
/// </summary>
/// <param name="bytes">bytes to convert</param>
/// <returns>bytes / (1024 * 1024)</returns>
private static float GetMegaBytes(uint bytes)
/// <returns>True if the browser is online, false if it's offline</returns>
public static bool IsOnline()
{
return (float)bytes / (1024 * 1024);
#if UNITY_WEBGL && !UNITY_EDITOR
return _IsOnline() == 1;
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(IsOnline)} called");
return true;
#else
return true;
#endif
}

/// <summary>
/// Downloads a text file through the browser with the specified filename and content.
/// Creates a temporary anchor element to trigger the download.
/// </summary>
/// <param name="filename">The name of the file to be downloaded</param>
/// <param name="content">The text content to be saved in the file</param>
public static void DownloadTextFile(string filename, string content)
{
#if UNITY_WEBGL && !UNITY_EDITOR
_DownloadFile(filename, content);
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(DownloadTextFile)} called with filename: {filename}");
#endif
}

/// <summary>
/// Downloads a binary file through the browser with the specified filename and data.
/// Creates a Blob with the specified MIME type and triggers the download.
/// </summary>
/// <param name="filename">The name of the file to be downloaded</param>
/// <param name="data">The binary data to be saved in the file</param>
/// <param name="mimeType">The MIME type of the file (defaults to "application/octet-stream")</param>
/// <example>
/// <code>
/// // Example: Save a Texture2D as PNG
/// Texture2D texture;
/// byte[] pngData = texture.EncodeToPNG();
/// WebToolPlugins.DownloadBinaryFile("texture.png", pngData, "image/png");
/// </code>
/// </example>
public static void DownloadBinaryFile(string filename, byte[] data, string mimeType = "application/octet-stream")
{
#if UNITY_WEBGL && !UNITY_EDITOR
_DownloadBlob(filename, data, data.Length, mimeType);
#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS
Debug.Log($"{nameof(WebToolPlugins)}.{nameof(DownloadBinaryFile)} called with filename: {filename}");
#endif
}
}
}
Loading

0 comments on commit 1e4e83a

Please sign in to comment.