Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// Visual Pinball Engine
// Copyright (C) 2026 freezy and VPE Team
// https://github.com/freezy/VisualPinball.Engine
//
// SPDX-License-Identifier: GPL-3.0-or-later

using System;
using System.Collections;
using System.IO;
using System.Text;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using VisualPinball.Unity.Editor;
using Object = UnityEngine.Object;

namespace VisualPinball.Unity.Test
{
public class LightPackagingTests
{
/// <summary>
/// A lamp's light sources keep their own settings through a runtime load, although glTFast
/// puts the spot on rotated helper children that shift the other lights' sibling indices.
/// </summary>
[UnityTest]
public IEnumerator LampLightSourcesKeepTheirSettingsBesideASpot()
{
var path = Path.Combine(Path.GetTempPath(), $"vpe-lamp-lights-{Guid.NewGuid():N}.vpe");
var source = new GameObject("Table");
GameObject imported = null;
try {
source.AddComponent<TableComponent>();
var lampGo = new GameObject("Lamp");
lampGo.transform.SetParent(source.transform, false);
var spot = lampGo.AddComponent<Light>();
spot.type = LightType.Spot;
spot.range = 0.33f;
AddLight(lampGo.transform, "A", LightType.Point, 0.11f);
AddLight(lampGo.transform, "B", LightType.Spot, 0.22f);
AddLight(lampGo.transform, "C", LightType.Point, 0.44f);
// A hidden bulb mesh isn't exported, but the lamp's saved light paths count it. Last,
// so it can't cancel out the helper the spot prepends to the lamp's children.
var bulb = new GameObject("Bulb");
bulb.transform.SetParent(lampGo.transform, false);
bulb.SetActive(false);
lampGo.AddComponent<LightComponent>();

new PackageWriter(source).WritePackageSync(path);
var load = new RuntimePackageReader(path).ImportIntoScene();
while (!load.IsCompleted) {
yield return null;
}
imported = load.GetAwaiter().GetResult();

var lamp = imported.GetComponentInChildren<LightComponent>(true);
Assert.That(lamp, Is.Not.Null);
var hierarchy = Dump(lamp.transform);
AssertLight(lamp.transform, null, LightType.Spot, 0.33f, hierarchy);
AssertLight(lamp.transform, "A", LightType.Point, 0.11f, hierarchy);
AssertLight(lamp.transform, "B", LightType.Spot, 0.22f, hierarchy);
AssertLight(lamp.transform, "C", LightType.Point, 0.44f, hierarchy);
} finally {
if (imported) { Object.DestroyImmediate(imported); }
Object.DestroyImmediate(source);
File.Delete(path);
}
}

private static void AddLight(Transform parent, string name, LightType type, float range)
{
var go = new GameObject(name);
go.transform.SetParent(parent, false);
var light = go.AddComponent<Light>();
light.type = type;
light.range = range;
}

private static void AssertLight(Transform lamp, string name, LightType type, float range, string hierarchy)
{
var node = name == null ? lamp : lamp.Find(name);
Assert.That(node, Is.Not.Null, $"{name} is missing: {hierarchy}");
var light = VpeLightRestore.FindLight(node);
Assert.That(light, Is.Not.Null, $"{node.name} has no light: {hierarchy}");
Assert.That(light.type, Is.EqualTo(type), $"{node.name} took another light's type: {hierarchy}");
Assert.That(light.range, Is.EqualTo(range).Within(0.0001f), $"{node.name} took another light's settings: {hierarchy}");
}

private static string Dump(Transform node)
{
var text = new StringBuilder();
Dump(node, 0, text);
return text.ToString();
}

private static void Dump(Transform node, int depth, StringBuilder text)
{
var light = node.GetComponent<Light>();
text.Append(' ', depth * 2).Append(node.name);
if (light) {
text.Append($" [{light.type} range={light.range:0.###}]");
}
text.Append(" | ");
foreach (Transform child in node) {
Dump(child, depth + 1, text);
}
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,11 @@ public IEnumerator PackagedInsertUsesGlbMeshAndRestoresLampInRuntimeReader()
var light = insertGo.AddComponent<InsertLightComponent>();
light.Intensity = 0.6f;
light.ExtraBulbs[0].Intensity = 0.4f;
var spillGo = new GameObject("Insert Spill Light");
spillGo.transform.SetParent(insertGo.transform, false);
var spill = spillGo.AddComponent<Light>();
spill.type = LightType.Spot;
light.SpillLight = spill;
staleBake = ScriptableObject.CreateInstance<InsertBakeData>();
staleBake.Hash = "stale-bake";
insert.SetBake(staleBake);
Expand Down Expand Up @@ -197,6 +202,14 @@ public IEnumerator PackagedInsertUsesGlbMeshAndRestoresLampInRuntimeReader()
var restoredLight = restoredInsert.GetComponent<InsertLightComponent>();
Assert.That(restoredLight.Intensity, Is.EqualTo(0.6f));
Assert.That(restoredLight.ExtraBulbs[0].Intensity, Is.EqualTo(0.4f));
// glTFast puts the spot below orientation helpers, not on the spill's own node: a
// reference that missed it left the spill lit whatever the lamp did.
var restoredSpillNode = restoredInsert.transform.Find("Insert Spill Light");
Assert.That(restoredSpillNode, Is.Not.Null);
Assert.That(restoredSpillNode.GetComponent<Light>(), Is.Null);
Assert.That(restoredLight.SpillLight, Is.Not.Null, "the spill reference must find the spot below glTFast's helpers");
Assert.That(restoredLight.SpillLight.type, Is.EqualTo(LightType.Spot));
Assert.That(restoredLight.SpillLight.transform.IsChildOf(restoredSpillNode), Is.True);
} finally {
if (source) { Object.DestroyImmediate(source); }
if (imported) { Object.DestroyImmediate(imported); }
Expand Down Expand Up @@ -349,6 +362,46 @@ public void InsertLightStateAndSpillReferenceRoundTrip()
}
}

[Test]
public void SpillReferenceFindsTheSpotBelowGltfOrientationHelpers()
{
// What a runtime load of a package makes of a spot: the light two rotated helpers below
// the node the reference names, one from the export and one from the instantiation.
var go = new GameObject("Insert Lamp");
go.SetActive(false);
var spillGo = new GameObject("Spill");
spillGo.transform.SetParent(go.transform);
var exported = new GameObject("Spill_Orientation");
exported.transform.SetParent(spillGo.transform);
var instantiated = new GameObject("Spill_Orientation_Orientation");
instantiated.transform.SetParent(exported.transform);
// An authored light whose name looks like a helper is not one: helpers are named after their parent.
var other = new GameObject("Fill_Orientation");
other.transform.SetParent(spillGo.transform);
other.transform.SetAsFirstSibling();
try {
other.AddComponent<Light>();
var spot = instantiated.AddComponent<Light>();
var insertLight = go.AddComponent<InsertLightComponent>();
var refs = new PackagedRefs(go.transform);
refs.SetNodeIdsForWrite(new Dictionary<Transform, string> {
[go.transform] = "insert-node",
[spillGo.transform] = "spill-node",
});
refs.SetNodeIdsForRead(new Dictionary<string, Transform> {
["insert-node"] = go.transform,
["spill-node"] = spillGo.transform,
});
var referenceData = PackageApi.Packer.Pack(new InsertLightReferencesPackable { SpillLightNodeId = "spill-node" });

insertLight.UnpackReferences(referenceData, go.transform, refs, null);

Assert.That(insertLight.SpillLight, Is.SameAs(spot));
} finally {
Object.DestroyImmediate(go);
}
}

[Test]
public void UnavailableAuthoringDependenciesDoNotAbortSidecarCapture()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,10 @@ await _files.UnpackAssetsRuntime(cancellationToken, (processed, total) => {
foreach (var slingshot in slingshots) {
slingshot.ValidateAfterUnpack();
}
// After the items, as the editor import does: the lights payload finds each light by
// its node id, while a lamp's own light sources go by sibling paths that glTFast's
// orientation helpers and the export's skipped inactive objects shift.
VpeLightRestore.RestoreLightProfiles(_table, _tableFolder, id => _transformByNodeId.GetValueOrDefault(id));
readRefsStopwatch.Stop();
LoadAttempt.Current?.Mark("references");
Logger.Debug($"RuntimePackageReader: Restored references in {readRefsStopwatch.ElapsedMilliseconds}ms.");
Expand Down Expand Up @@ -414,7 +418,6 @@ private async Task<GameObject> ImportModels(
var fixupStopwatch = Stopwatch.StartNew();
ClearGeneratedTangents(table, meshesWithoutTangents);
VpeLightRestore.NormalizeImportedLightIntensities(table);
VpeLightRestore.RestoreLightProfiles(table, _tableFolder, id => _transformByNodeId.GetValueOrDefault(id));
fixupStopwatch.Stop();
Logger.Debug(
$"RuntimePackageReader: glb stages: load={loadStopwatch.ElapsedMilliseconds}ms, " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,32 @@ public static void RestoreLightProfiles(GameObject table, IPackageFolder tableFo
}
}

/// <summary>
/// The light a packaged node stands for. glTF spots and directional lights point the other
/// way than Unity's, so glTFast puts them on a rotated <c>*_Orientation</c> child, once when
/// exporting and again when instantiating, each named after its parent: at runtime the light
/// sits two helpers below the node its id names. The editor import folds them back into the
/// prefab's light.
/// </summary>
public static Light FindLight(Transform node)
{
while (node) {
if (node.TryGetComponent<Light>(out var light)) {
return light;
}
var helperName = node.name + "_Orientation";
Transform helper = null;
foreach (Transform child in node) {
if (child.name == helperName) {
helper = child;
break;
}
}
node = helper;
}
return null;
}

private static Light ResolveLightProfileTarget(
LightSourcePackable profile,
IReadOnlyList<Light> lights,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ public static void UnpackReferences(byte[] bytes, InsertLightComponent light, Pa
{
var data = PackageApi.Packer.Unpack<InsertLightReferencesPackable>(bytes);
var node = refs.GetNode(data.SpillLightNodeId);
light.SpillLight = node ? node.GetComponent<Light>() : null;
// At runtime the spot sits on glTFast's orientation helpers below the node. Missing it
// leaves the spill as it was exported, lit whatever the lamp does.
light.SpillLight = VpeLightRestore.FindLight(node);
}
}

Expand Down
Loading