Skip to content

Commit

Permalink
Merge branch 'develop' into enhancement/Maroon-470_FieldCalculation
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianGlawogger committed Jan 23, 2025
2 parents fae6ab7 + 6aece34 commit 293d79a
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public class WebGlReceiver : MonoBehaviour, GlobalEntity

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Properties, Getters and Setters
public string MostRecentData { get; private set; }

// -------------------------------------------------------------------------------------------------------------
// Singleton
Expand Down Expand Up @@ -68,6 +69,7 @@ private void Awake()
public void GetDataFromJavaScript(string data)
{
Debug.Log("Received Data: " + data);
MostRecentData = data;
OnIncomingData.Invoke(data);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ public class ParameterLoader : MonoBehaviour
/// </summary>
public UnityEvent<ExperimentParameters> parametersLoaded = new UnityEvent<ExperimentParameters>();

/// <summary>
/// Invoked when ExperimentParameters have been loaded, which are custom (e.g. received from Javascript WebGL).
/// </summary>
public UnityEvent CustomParametersLoaded = new UnityEvent();

/// <summary>
/// Invoked when the JSON files have been initialized.
/// </summary>
Expand All @@ -48,6 +53,11 @@ public ExperimentParameters MostRecentParameters
private set;
}

/// <summary>
/// Used to know whether there was already an experiment which potentially used the URL fragment parameters on WebGL already
/// </summary>
private static bool firstExperimentDefaultParametersLoaded = false;

#region Singleton
private static ParameterLoader _instance;
public static ParameterLoader Instance
Expand All @@ -68,9 +78,12 @@ private void Start()

#if UNITY_WEBGL && !UNITY_EDITOR
// Listener for external json data (sent e.g. via a Javascript button from a website where Maroon is embedded)
WebGlReceiver.Instance.OnIncomingData.AddListener((string jsonData) => { LoadJsonFromString(jsonData); });
WebGlReceiver.Instance.OnIncomingData.AddListener((string jsonData) => {
LoadJsonFromString(jsonData);
CustomParametersLoaded?.Invoke();
});
#endif

if (_automaticiallyDetectJsonFiles)
{
#if UNITY_WEBGL && !UNITY_EDITOR
Expand Down Expand Up @@ -140,8 +153,22 @@ public void InitJsonFiles(List<TextAsset> jsonFiles)
/// </summary>
/// <param name="file">File to load</param>
/// <returns>The loaded ExperimentParameters</returns>
public ExperimentParameters LoadJsonFromFileIndex(int index)
public ExperimentParameters LoadJsonFromFileIndex(int index, bool firstDefaultParametersLoad = false)
{
#if UNITY_WEBGL
/*
* Initial config received from Javascript (originating from the URL Fragment config) will be received before the requested experiment is loaded,
* thus if on WebGL and the WebGlReceiver.Instance.MostRecentData is not null and this it the first experiment, load instead the WebGlReceiver.Instance.MostRecentData instead of the requested default file.
*/
if (firstDefaultParametersLoad && !firstExperimentDefaultParametersLoaded && !string.IsNullOrWhiteSpace(WebGlReceiver.Instance.MostRecentData))
{
firstExperimentDefaultParametersLoaded = true;
CustomParametersLoaded?.Invoke();
return LoadJsonFromString(WebGlReceiver.Instance.MostRecentData);
}
#endif


if (index >= _jsonFile.Count)
{
Debug.LogError("Index " + index + " is greater or equal the number of files " + _jsonFile.Count);
Expand All @@ -158,7 +185,7 @@ public ExperimentParameters LoadJsonFromFileIndex(int index)
/// </summary>
/// <param name="name">Name of the file to load</param>
/// <returns>The loaded ExperimentParameters</returns>
public ExperimentParameters LoadJsonFromFileName(string name)
public ExperimentParameters LoadJsonFromFileName(string name, bool firstDefaultParametersLoad = false)
{
int index = IndexOfJson(name);
if (index == -1)
Expand All @@ -167,7 +194,7 @@ public ExperimentParameters LoadJsonFromFileName(string name)
return null;
}

return LoadJsonFromFileIndex(index);
return LoadJsonFromFileIndex(index, firstDefaultParametersLoad);
}

/// <summary>
Expand All @@ -177,7 +204,16 @@ public ExperimentParameters LoadJsonFromFileName(string name)
/// <returns>The loaded ExperimentParameters</returns>
public ExperimentParameters LoadJsonFromString(string data)
{
Debug.Log("Trying to load ExperimentParameters from JSON String.");
MostRecentParameters = ConvertJsonToExperimentParameters(data);
if (MostRecentParameters == null)
{
Debug.LogError("Loaded ExperimentParameters are null.");
}
else
{
Debug.Log("Successfully parsed ExperimentParameters: " + MostRecentParameters.GetType());
}
parametersLoaded?.Invoke(MostRecentParameters);
return MostRecentParameters;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,22 +126,22 @@ public void OnFilesLoadedInital()
#if UNITY_WEBGL && !UNITY_EDITOR
if (BootstrappingManager.Instance.UrlParameters.TryGetValue(WebGlUrlParameter.Config, out string config))
{
if (!ApplyConfig(config)) ApplyConfig("Default");
if (!ApplyConfig(config)) ApplyConfig("Default", true);
}
else
#endif
{
ApplyConfig("Default");
ApplyConfig("Default", true);
}

ParameterLoader.Instance.OnFilesInitialized.RemoveListener(OnFilesLoadedInital);
}

public bool ApplyConfig(string configName)
public bool ApplyConfig(string configName, bool firstDefaultParametersLoad = false)
{
_currentConfigIndex = ParameterLoader.Instance.IndexOfJson(configName);
dropdown.SetValueWithoutNotify(_currentConfigIndex);
var parameters = ParameterLoader.Instance.LoadJsonFromFileName(configName);
var parameters = ParameterLoader.Instance.LoadJsonFromFileName(configName, firstDefaultParametersLoad);

return parameters != null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ private void Start()
_em = ExperimentManager.Instance;
_camControls = mainCamera.GetComponent<CameraControls>();

parameterLoader.LoadJsonFromFileIndex(0);
parameterLoader.LoadJsonFromFileIndex(0, true);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Maroon.Physics.Optics.TableObject.LightComponent;
using Maroon.Physics.Optics.TableObject.OpticalComponent;
using Maroon.Physics.Optics.Util;
using Maroon.ReusableScripts.ExperimentParameters;
using TMPro;
using UnityEngine;
using Math = System.Math;
Expand Down Expand Up @@ -97,7 +98,14 @@ public OpticalComponent SelectedOc
private void Awake()
{
if (Instance == null)
{
Instance = this;

ParameterLoader.Instance.CustomParametersLoaded.AddListener(() => {
// When OpticsParameters config JSON gets sent via Javascript, set the preset Dropdown to index 0, as that's representing an 'undefined' preset
presetDropdown.SetValueWithoutNotify(0);
});
}
else
{
Debug.LogError("SHOULD NOT OCCUR - Destroyed UIManager");
Expand All @@ -110,12 +118,6 @@ private void Start()
_cauchyModel = cauchyModelDropdown.GetComponent<TMP_Dropdown>();
_lensModel = lensModelDropdown.GetComponent<TMP_Dropdown>();
_focalLengthText = focalLengthDisplay.GetComponent<TMP_Text>();
#if UNITY_WEBGL
WebGlReceiver.Instance.OnIncomingData.AddListener((string _jsonData) => {
// When OpticsParameters config JSON gets sent via Javascript, set the preset Dropdown to index 0, as that's representing an 'undefined' preset
presetDropdown.SetValueWithoutNotify(0);
});
#endif
}

// ----------------------------------- Light Components -----------------------------------
Expand Down
51 changes: 51 additions & 0 deletions unity/Assets/WebGLTemplates/MaroonWeb/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
row_progress.style.display = "none";
row_game.style.display = "flex";
enableFitGame();
parseUrlFragment();
}
}

Expand Down Expand Up @@ -76,6 +77,56 @@
fitGame();
window.addEventListener('resize', fitGame);
}

function parseUrlFragment()
{
// Access the URL fragment (after the #)
const fragment = window.location.hash.substr(1); // Remove the '#' symbol
const fragmentParams = new URLSearchParams(fragment);
const config = fragmentParams.get('config');

if (!config)
{
console.log("URL Fragment Config is empty.");
}
else
{
console.log("URL Fragment Config: ", config);
sendConfig(config);
}
}

function sendConfig(config) {
try {
// Send configuration to Maroon.
sendDataToUnity(config);
} catch (e) {
alert('Check the syntax of the input. ' + e);
}
}

async function sendDataToUnity(data){
console.log("Send Data to Unity");

if (!unityInstance)
{
console.log("UnityInstance is null, waiting...");
}
await waitForNonNullUnityInstance();

unityInstance.SendMessage("WebGL Receiver", "GetDataFromJavaScript", data);
}

async function waitForNonNullUnityInstance() {
return new Promise(resolve => {
const checkInterval = setInterval(() => {
if (unityInstance !== null) {
clearInterval(checkInterval);
resolve(unityInstance); // Resolves once unityInstance is no longer null
}
}, 100); // Check every 100ms
});
}

</script>

Expand Down

0 comments on commit 293d79a

Please sign in to comment.