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
Expand Up @@ -111,6 +111,47 @@ public void ConvertsTransportBindingsAndDriverOverrides()
Assert.That(catalogOnlyDefinition.Diagnostics, Has.Exactly(1).Contains("no curated driver override"));
}

private const string CompatibilityJson = @"{
'format': 'pinmame-machine-definition',
'schema_version': 2,
'machine': { 'id': 'test.compatibility.2026', 'name': 'Test Compatibility' },
'coverage': { 'status': 'partial', 'completion_score': 50 },
'drivers': [
{ 'id': 'test_l1', 'description': 'Test (L-1)', 'physical_compatibility': 'identical' },
{ 'id': 'test_l2', 'description': 'Test (L-2)', 'physical_compatibility': 'identical' },
{ 'id': 'test_f1', 'description': 'Test (Fix 1)', 'physical_compatibility': 'compatible' },
{ 'id': 'test_x1', 'description': 'Test (Other hardware)', 'physical_compatibility': 'different' },
{ 'id': 'test_u1', 'description': 'Test (Unknown)', 'physical_compatibility': 'unknown' }
],
'catalogDrivers': [
{ 'id': 'test_p1', 'description': 'Test (Prototype)' }
]
}";

[Test]
public void ListsCompatibleRomsBestMatchFirst()
{
var roms = PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_l2");

Assert.That(roms.Select(rom => rom.Id), Is.EqualTo(new[] { "test_l1", "test_f1", "test_p1", "test_u1" }));
Assert.That(roms.Select(rom => rom.Compatibility), Is.EqualTo(new[] {
PinMameRomCompatibility.Identical, PinMameRomCompatibility.Compatible, PinMameRomCompatibility.Unverified, PinMameRomCompatibility.Unverified
}));
Assert.That(roms[0].Description, Is.EqualTo("Test (L-1)"));
Assert.That(PinMameGameDefinitionConverter.Convert(CompatibilityJson, "test_l2").CompatibleRoms.Select(rom => rom.Id), Is.EqualTo(roms.Select(rom => rom.Id)));
}

[Test]
public void KeepsDifferentRomsApartFromCompatibleOnes()
{
Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_x1"), Is.Empty);
Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_f1").Select(rom => rom.Compatibility),
Has.None.EqualTo(PinMameRomCompatibility.Identical));
Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_u1").Select(rom => rom.Compatibility),
Is.All.EqualTo(PinMameRomCompatibility.Unverified));
Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "other_l1"), Is.Empty);
}

[Test]
public void SkipsAmbiguousOrDuplicateDevicesWithDiagnostics()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<Compile Include="..\VisualPinball.Engine.PinMAME.Unity\Editor\PinMameGameDefinitionCatalogClient.cs" Link="PinMameGameDefinitionCatalogClient.cs" />
<Compile Include="..\VisualPinball.Engine.PinMAME.Unity\Editor\PinMameGameDefinitionConverter.cs" Link="PinMameGameDefinitionConverter.cs" />
<Compile Include="..\VisualPinball.Engine.PinMAME.Unity\Editor\PinMameSpatialMatcher.cs" Link="PinMameSpatialMatcher.cs" />
<Compile Include="..\VisualPinball.Engine.PinMAME.Unity\Runtime\PinMameCompatibleRom.cs" Link="PinMameCompatibleRom.cs" />
<Compile Include="..\VisualPinball.Engine.PinMAME.Unity\Runtime\PinMameLegacyAliasResolver.cs" Link="PinMameLegacyAliasResolver.cs" />
<Compile Include="..\VisualPinball.Engine.PinMAME.Unity\Runtime\PinMameOutputModel.cs" Link="PinMameOutputModel.cs" />
<Compile Include="../VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameTimeFence.cs" Link="PinMameTimeFence.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Visual Pinball Engine
// Copyright (C) 2026 freezy and VPE Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// ReSharper disable CheckNamespace

using System;
using System.Linq;
using System.Threading;
using UnityEditor;
using UnityEngine;

namespace VisualPinball.Engine.PinMAME.Editor
{
/// <summary>
/// Looks up the ROMs compatible with a table's ROM in the machine catalog when the table is
/// exported, so the player can offer them when the table's ROM isn't there.
/// </summary>
[InitializeOnLoad]
internal static class PinMameCompatibleRomsExport
{
// the export waits for it; a cached catalog answers at once
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15);

static PinMameCompatibleRomsExport()
{
PinMameGamelogicEngine.ResolveCompatibleRoms = Resolve;
}

private static PinMameCompatibleRom[] Resolve(PinMameGamelogicEngine engine)
{
if (!engine || string.IsNullOrWhiteSpace(engine.machineId) || string.IsNullOrWhiteSpace(engine.romId)) {
return null;
}
try {
using var cancellation = new CancellationTokenSource(Timeout);
PinMameGameDefinitionCatalogClient.EnsureCacheRoot();
var catalog = PinMameGameDefinitionCatalogClient.GetCatalogAsync(false, cancellation.Token)
.ConfigureAwait(false).GetAwaiter().GetResult().Value;
var machine = catalog.Machines.FirstOrDefault(entry => string.Equals(entry.Id, engine.machineId, StringComparison.Ordinal));
if (machine == null || string.IsNullOrWhiteSpace(machine.Detail)) {
return null;
}
var definition = PinMameGameDefinitionCatalogClient.GetDefinitionAsync(machine, false, cancellation.Token)
.ConfigureAwait(false).GetAwaiter().GetResult();
var roms = PinMameGameDefinitionConverter.ReadCompatibleRoms(definition.Value, engine.romId);
Debug.Log($"[PinMAME] Exporting {roms.Length} ROM(s) compatible with {engine.romId}: {string.Join(", ", roms.Select(rom => rom.Id))}.");
return roms;
} catch (Exception exception) {
Debug.LogWarning($"[PinMAME] Could not look up the ROMs compatible with {engine.romId} in the machine catalog; exporting the {engine.CompatibleRoms.Count} saved with the table. {exception.Message}");
return null;
}
}
}
}

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 @@ -33,11 +33,16 @@ public sealed class PinMameGameDefinition
public PinMameSpatialPlacement[] SpatialCoils { get; }
public PinMameSpatialPlacement[] SpatialLamps { get; }
public string[] Diagnostics { get; }
/// <summary>
/// The machine's other ROMs that run a table made for the selected ROM, best match first.
/// </summary>
public PinMameCompatibleRom[] CompatibleRoms { get; }
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

public PinMameGameDefinition(string machineId, string name, string coverageStatus, int completionScore,
PinMameRomDefinition[] roms, string defaultRomId, GamelogicEngineSwitch[] switches, GamelogicEngineCoil[] coils,
GamelogicEngineLamp[] lamps, GamelogicEngineWire[] wires, PinMameSpatialPlacement[] spatialSwitches,
PinMameSpatialPlacement[] spatialCoils, PinMameSpatialPlacement[] spatialLamps, string[] diagnostics)
PinMameSpatialPlacement[] spatialCoils, PinMameSpatialPlacement[] spatialLamps, string[] diagnostics,
PinMameCompatibleRom[] compatibleRoms = null)
{
MachineId = machineId;
Name = name;
Expand All @@ -53,6 +58,7 @@ public PinMameGameDefinition(string machineId, string name, string coverageStatu
SpatialCoils = spatialCoils ?? Array.Empty<PinMameSpatialPlacement>();
SpatialLamps = spatialLamps ?? Array.Empty<PinMameSpatialPlacement>();
Diagnostics = diagnostics ?? Array.Empty<string>();
CompatibleRoms = compatibleRoms ?? Array.Empty<PinMameCompatibleRom>();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,66 @@ public static PinMameGameDefinition Convert(string json, string selectedRomId =
ConvertOutputs(root["outputs"] as JArray, overrides, coils, lamps, spatialCoils, spatialLamps, diagnostics);
var wires = ConvertFlipperWires(root["inputs"] as JArray, root["outputs"] as JArray, overrides, diagnostics);

var compatibleRoms = CompatibleRoms(sourceDrivers, roms, string.IsNullOrWhiteSpace(selectedRomId) ? defaultRomId : selectedRomId);

return new PinMameGameDefinition(machineId, name, coverageStatus, completionScore, roms, defaultRomId,
switches.ToArray(), coils.ToArray(), lamps.ToArray(), wires, spatialSwitches.ToArray(),
spatialCoils.ToArray(), spatialLamps.ToArray(), diagnostics.ToArray());
spatialCoils.ToArray(), spatialLamps.ToArray(), diagnostics.ToArray(), compatibleRoms);
}

/// <summary>
/// The machine's other ROMs that run a table made for <paramref name="romId"/>, best match
/// first, read from a machine definition of the catalog.
/// </summary>
public static PinMameCompatibleRom[] ReadCompatibleRoms(string json, string romId)
{
if (string.IsNullOrWhiteSpace(json) || string.IsNullOrWhiteSpace(romId)) {
return Array.Empty<PinMameCompatibleRom>();
}
var root = JObject.Parse(json);
if (!string.Equals(root.Value<string>("format"), ExpectedFormat, StringComparison.Ordinal)) {
throw new InvalidDataException($"Expected {ExpectedFormat}, got {root.Value<string>("format") ?? "no format"}.");
}
var sourceDrivers = (root["drivers"] as JArray)?.OfType<JObject>().ToArray() ?? Array.Empty<JObject>();
return CompatibleRoms(sourceDrivers, ReadRoms(root, sourceDrivers), romId);
}

/// <summary>
/// The catalog marks how each curated ROM relates to the physical machine. Two ROMs both
/// "identical" to it are revisions of each other; "identical" or "compatible" ones run the
/// same machine; "different" ones need modified hardware, so they don't run a table made for
/// another ROM, and nothing else runs a table made for them. ROMs without a mark, or marked
/// "unknown", are offered as unverified.
/// </summary>
private static PinMameCompatibleRom[] CompatibleRoms(IEnumerable<JObject> sourceDrivers, PinMameRomDefinition[] roms, string selectedRomId)
{
// a ROM the machine doesn't list may not even run it
if (string.IsNullOrWhiteSpace(selectedRomId) || !roms.Any(rom => string.Equals(rom.Id, selectedRomId, StringComparison.OrdinalIgnoreCase))) {
return Array.Empty<PinMameCompatibleRom>();
}
var marks = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var driver in sourceDrivers) {
var id = driver.Value<string>("id");
if (!string.IsNullOrWhiteSpace(id)) marks[id] = driver.Value<string>("physical_compatibility");
}
string Mark(string id) => marks.TryGetValue(id, out var mark) ? mark : null;
static bool RunsMachine(string mark) => mark is "identical" or "compatible";

var selected = Mark(selectedRomId);
if (selected == "different") {
return Array.Empty<PinMameCompatibleRom>();
}
return roms
.Where(rom => !string.Equals(rom.Id, selectedRomId, StringComparison.OrdinalIgnoreCase))
.Select(rom => (rom, mark: Mark(rom.Id)))
.Where(entry => entry.mark != "different")
.Select(entry => new PinMameCompatibleRom(entry.rom.Id, entry.rom.Description,
selected == "identical" && entry.mark == "identical" ? PinMameRomCompatibility.Identical
: RunsMachine(selected) && RunsMachine(entry.mark) ? PinMameRomCompatibility.Compatible
: PinMameRomCompatibility.Unverified))
.OrderBy(rom => rom.Compatibility)
.ThenBy(rom => rom.Id, StringComparer.OrdinalIgnoreCase)
.ToArray();
}

private static GamelogicEngineWire[] ConvertFlipperWires(JArray inputs, JArray outputs, IReadOnlyDictionary<string, JObject> overrides,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ private static PinMameGameDefinition Apply(PinMameGamelogicEngine gle, TableComp
Undo.RecordObject(tableComponent, "Populate PinMAME hardware");
gle.SetMachineSelection(machineId, !string.IsNullOrWhiteSpace(romId) ? romId : definition.DefaultRomId);
gle.SetAvailableHardware(definition.Switches, definition.Coils, definition.Lamps, definition.Wires);
gle.SetCompatibleRoms(definition.CompatibleRoms);
tableComponent.RepopulateHardware(gle);
gle.MarkMappingsPopulated();
EditorUtility.SetDirty(gle);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ private async System.Threading.Tasks.Task SelectMachine(int selectedGameIndex, s
}
// candidates for the manager dropdowns; the table's mappings stay until Populate Hardware
_gle.SetAvailableHardware(_definition.Switches, _definition.Coils, _definition.Lamps, _definition.Wires);
_gle.SetCompatibleRoms(_definition.CompatibleRoms);
EditorUtility.SetDirty(_gle);
} else if (!string.IsNullOrWhiteSpace(preferredRomId) && selectedRomId == null) {
_loadWarning = CombineWarnings(_loadWarning, $"The saved ROM '{preferredRomId}' is not listed for {selectedMachine.Name}; the saved component value was left unchanged.");
Expand All @@ -229,8 +230,28 @@ private async System.Threading.Tasks.Task SelectMachine(int selectedGameIndex, s
// The selection and the table's mappings stay as they are.
if (forceRefresh) Undo.RecordObject(_gle, "Refresh PinMAME hardware candidates");
_gle.SetAvailableHardware(_definition.Switches, _definition.Coils, _definition.Lamps, _definition.Wires);
_gle.SetCompatibleRoms(CompatibleRomsOf(selectedRomId));
EditorUtility.SetDirty(_gle);
} else if (fillCandidates && selectedRomId != null && !SameCompatibleRoms(_gle.CompatibleRoms, CompatibleRomsOf(selectedRomId))) {
// tables saved before the compatible ROMs were kept, or the catalog learned more since
Undo.RecordObject(_gle, "Update compatible PinMAME ROMs");
_gle.SetCompatibleRoms(CompatibleRomsOf(selectedRomId));
EditorUtility.SetDirty(_gle);
}
}

private PinMameCompatibleRom[] CompatibleRomsOf(string romId)
=> string.IsNullOrWhiteSpace(_definitionJson) ? Array.Empty<PinMameCompatibleRom>() : PinMameGameDefinitionConverter.ReadCompatibleRoms(_definitionJson, romId);

private static bool SameCompatibleRoms(IReadOnlyList<PinMameCompatibleRom> current, IReadOnlyList<PinMameCompatibleRom> updated)
{
if (current.Count != updated.Count) return false;
for (var i = 0; i < current.Count; i++) {
if (!string.Equals(current[i].Id, updated[i].Id, StringComparison.OrdinalIgnoreCase)
|| !string.Equals(current[i].Description ?? string.Empty, updated[i].Description ?? string.Empty, StringComparison.Ordinal)
|| current[i].Compatibility != updated[i].Compatibility) return false;
}
return true;
}

private static string CombineWarnings(string first, string second)
Expand Down Expand Up @@ -383,6 +404,7 @@ public override void OnInspectorGUI()
Undo.RecordObject(_tableComponent, "Populate PinMAME hardware");
_gle.SetMachineSelection(_definition.MachineId, _roms[_selectedRomIndex].Id);
_gle.SetAvailableHardware(_definition.Switches, _definition.Coils, _definition.Lamps, _definition.Wires);
_gle.SetCompatibleRoms(_definition.CompatibleRoms);
_tableComponent.RepopulateHardware(_gle);
_gle.MarkMappingsPopulated();
EditorUtility.SetDirty(_gle);
Expand Down Expand Up @@ -502,6 +524,7 @@ private void ChangeRom(int selectedRomIndex)
_gle.SetMachineSelection(definition.MachineId, selectedRomId);
// a ROM of the same machine: refresh the dropdown candidates, keep the mappings
_gle.SetAvailableHardware(definition.Switches, definition.Coils, definition.Lamps, definition.Wires);
_gle.SetCompatibleRoms(definition.CompatibleRoms);
_loadError = null;
_spatialAssignmentMessage = null;
EditorUtility.SetDirty(_gle);
Expand Down
53 changes: 53 additions & 0 deletions VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Visual Pinball Engine
// Copyright (C) 2026 freezy and VPE Team
//
// SPDX-License-Identifier: MIT
// Licensed under MIT. See https://opensource.org/license/mit.

using System;

namespace VisualPinball.Engine.PinMAME
{
/// <summary>
/// How closely a ROM matches the physical machine a table was made for, as the machine catalog
/// at games.visualpinball.org tells.
/// </summary>
public enum PinMameRomCompatibility
{
/// <summary>
/// Another revision of the same game: switches, coils, lamps and displays are wired the same.
/// </summary>
Identical = 0,

/// <summary>
/// Runs on the same machine, but isn't just a revision of the table's ROM, e.g. a community
/// fix or alternative firmware.
/// </summary>
Compatible = 1,

/// <summary>
/// A ROM of the same machine that nobody has confirmed runs it the same way.
/// </summary>
Unverified = 2,
}

/// <summary>
/// A ROM that can run a table in place of the one its author chose.
/// </summary>
[Serializable]
public struct PinMameCompatibleRom
{
public string Id;
public string Description;
public PinMameRomCompatibility Compatibility;

public PinMameCompatibleRom(string id, string description, PinMameRomCompatibility compatibility)
{
Id = id;
Description = description ?? string.Empty;
Compatibility = compatibility;
}

public override string ToString() => string.IsNullOrWhiteSpace(Description) ? Id : $"{Id} ({Description})";
}
}

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

Loading
Loading