Framework/Players/WorldMap.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;

namespace RoleplayFramework.Players;

/// <summary>
/// Loads cloud map packages into the world scene's MapInstance. The host sets the map name before the lobby
/// exists, so the networked MapInstance reaches joining clients already pointing at the right map.
/// </summary>
public static class WorldMap
{
	public const float LoadTimeoutSeconds = 300;

	/// <summary>The world's MapInstance, including a disabled one (it stays disabled until a map is chosen).</summary>
	public static MapInstance Find( Scene scene ) =>
		scene?.GetAllObjects( true ).SelectMany( o => o.Components.GetAll<MapInstance>( FindMode.EverythingInSelf ) ).FirstOrDefault();

	/// <summary>Host/offline: checks the package, then loads it. Returns null on success, else a user-facing error.</summary>
	public static async Task<string> LoadAsync( Scene scene, string mapIdent )
	{
		var instance = Find( scene );
		if ( instance is null ) return "This world scene has no MapInstance to load a cloud map into.";

		RpLog.Info( "map", $"Loading cloud map '{mapIdent}'..." );
		var started = RealTime.Now;

		Package package;
		try { package = await Package.FetchAsync( mapIdent, false ); }
		catch ( Exception e ) { return $"Could not look up map '{mapIdent}': {e.Message}"; }

		if ( package is null ) return $"Map '{mapIdent}' was not found on sbox.game.";
		if ( !string.Equals( package.TypeName, "map", StringComparison.OrdinalIgnoreCase ) )
			return $"'{mapIdent}' is a {package.TypeName} package, not a map.";

		instance.UseMapFromLaunch = false;
		instance.MapName = mapIdent;
		instance.Enabled = true;
		instance.GameObject.Enabled = true;

		var error = await WaitLoaded( instance );
		if ( error is not null ) return error;

		RpLog.Info( "map", $"Map '{package.Title}' ({mapIdent}) loaded in {RealTime.Now - started:F0}s, {scene.GetAllComponents<SpawnPoint>().Count()} spawn points" );
		return null;
	}

	/// <summary>Client: waits until the world's map (if any) has finished loading. Returns null when ready.</summary>
	public static async Task<string> WaitForSceneMap( Scene scene )
	{
		var instance = Find( scene );
		if ( instance is null || string.IsNullOrEmpty( instance.MapName ) || instance.IsLoaded ) return null;
		RpLog.Info( "map", $"Waiting for map '{instance.MapName}' to load..." );
		return await WaitLoaded( instance );
	}

	static async Task<string> WaitLoaded( MapInstance instance )
	{
		var started = RealTime.Now;
		while ( instance.IsValid() && !instance.IsLoaded )
		{
			if ( RealTime.Now - started > LoadTimeoutSeconds )
				return $"Map '{instance.MapName}' did not finish loading within {LoadTimeoutSeconds:F0}s.";
			await GameTask.DelayRealtimeSeconds( 0.25f );
		}
		return instance.IsValid() ? null : "The map was unloaded while loading.";
	}
}