...
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Whether the scene that is playing has finished getting ready, and what it is doing meanwhile.
/// Everything that needs to wait for a scene (the loading screen, the automated tests) waits on
/// <see cref="Ready"/> rather than on a guess in seconds.
/// </summary>
public static class Loading
{
/// <summary>True once the scene's world is built, its models are in and its sounds are warm.</summary>
public static bool Ready { get; internal set; }
/// <summary>What it is doing right now, for the loading screen.</summary>
public static string Step { get; internal set; } = "";
/// <summary>0 to 1.</summary>
public static float Progress { get; internal set; }
/// <summary>Seconds (real) the last load took.</summary>
public static float LastLoadSeconds { get; internal set; }
// An area change inside a scene (into a memory, down to the heart) can put the same screen up.
internal static string AreaTitle = "";
internal static float AreaUntil;
/// <summary>Shows the loading screen for an area change inside a scene, for at least this long.</summary>
public static void ShowArea( string title, float seconds = 0.8f )
{
AreaTitle = title ?? "";
AreaUntil = RealTime.Now + seconds;
}
public static bool AreaShowing => RealTime.Now < AreaUntil;
static readonly string[] Tips =
{
"Shake the mouse to get hands off you. It is undignified. It works.",
"The Fat Guy cannot be reasoned with. He has tried it himself.",
"Sprint builds a charge. A charge goes through people.",
"Hit them with a shoulder, not with your face.",
"Everyone down here broke on the way in. Be nice.",
"Stillness is not the same as giving up. Ask the white ones.",
"The orders never came. Stop checking.",
"A misfit is watching you read this.",
"If it dangles, it has physics.",
"Light, crowds, or being sat on. You only get one. Lucky you.",
};
internal static string Tip = "";
internal static void NewTip() => Tip = Tips[Game.Random.Next( Tips.Length )];
}
/// <summary>
/// Runs in every scene. While the scene gets ready it shows the loading screen and warms what
/// the scene will need (the lizard's model, its sounds), then lets go. It never touches the time
/// scale or input: it is a cover and a signal, nothing more.
/// </summary>
public sealed class LoadingSystem : GameObjectSystem
{
readonly List<(string Label, Func<bool> Done)> _steps = new();
readonly Queue<string> _sounds = new();
int _soundsTotal;
int _frames;
float _started;
bool _begun, _finished;
GameObject _screen;
/// <summary>Give up waiting on any one thing after this long, and start anyway.</summary>
const float PatienceSeconds = 25f;
public LoadingSystem( Scene scene ) : base( scene )
{
Listen( Stage.StartUpdate, -1000, Tick, "Loading" );
}
void Tick()
{
if ( Scene.IsEditor || !Game.IsPlaying ) return;
if ( !_begun ) Begin();
if ( _finished )
{
// Area changes reuse the screen.
if ( Loading.AreaShowing ) EnsureScreen(); else DropScreen();
return;
}
_frames++;
EnsureScreen();
// A few sounds a frame, so the first whack does not hitch.
for ( int i = 0; i < 10 && _sounds.Count > 0; i++ )
{
try { Sound.Preload( _sounds.Dequeue() ); } catch ( Exception ) { }
}
int done = 0;
string waiting = "";
foreach ( var (label, check) in _steps )
{
bool ok = false;
try { ok = check(); } catch ( Exception ) { ok = true; }
if ( ok ) done++; else if ( waiting == "" ) waiting = label;
}
float soundPart = _soundsTotal == 0 ? 1f : 1f - _sounds.Count / (float)_soundsTotal;
Loading.Progress = (_steps.Count == 0 ? 1f : done / (float)_steps.Count) * 0.75f + soundPart * 0.25f;
Loading.Step = waiting != "" ? waiting : _sounds.Count > 0 ? "Tuning the screams" : "Nearly";
bool patienceGone = RealTime.Now - _started > PatienceSeconds;
if ( patienceGone && waiting != "" ) Log.Warning( $"Loading gave up waiting on: {waiting}" );
if ( (done == _steps.Count && _sounds.Count == 0 && _frames >= 6) || patienceGone ) Finish();
}
void Begin()
{
_begun = true;
_started = RealTime.Now;
Loading.Ready = false;
Loading.Progress = 0f;
Loading.Step = "Waking up";
Loading.NewTip();
// What "ready" means depends on what is in the scene.
string sounds = null;
if ( Scene.GetAllComponents<StoryDirector>().Any() )
{
sounds = "sounds/opening";
_steps.Add( ("Hollowing out the asteroid", () => _frames >= 8) );
}
if ( Scene.GetAllComponents<StadiumGame>().Any() )
{
sounds = "sounds/stadium";
_steps.Add( ("Seating thirty thousand people", () => Scene.GetAllComponents<CrowdSpawner>().All( c => c.Total > 0 ) && _frames >= 4) );
}
if ( Scene.GetAllComponents<SumpBootstrap>().Any() )
{
sounds = "sounds/sump";
_steps.Add( ("Digging the Sump", () => SumpCavern.Ready) );
}
if ( Scene.GetAllComponents<RampageBootstrap>().Any() )
{
sounds = "sounds/rampage";
_steps.Add( ("Building a town to knock down", () => RampageWorld.Ready) );
}
_steps.Add( ("Assembling the lizard", () =>
{
var model = Model.Load( LizardRig.ModelPath );
return model is not null && !model.IsError;
}) );
if ( sounds is not null )
{
foreach ( var sound in ResourceLibrary.GetAll<SoundEvent>() )
{
string path = sound?.ResourcePath;
if ( !string.IsNullOrEmpty( path ) && path.StartsWith( sounds, StringComparison.OrdinalIgnoreCase ) ) _sounds.Enqueue( path );
}
_soundsTotal = _sounds.Count;
}
}
void Finish()
{
_finished = true;
Loading.Progress = 1f;
Loading.Step = "";
Loading.LastLoadSeconds = RealTime.Now - _started;
Loading.Ready = true;
DropScreen();
}
void EnsureScreen()
{
if ( _screen.IsValid() ) return;
_screen = new GameObject( true, "Loading Screen" );
_screen.Flags |= GameObjectFlags.NotSaved;
var panel = _screen.Components.Create<ScreenPanel>();
panel.ZIndex = 5000;
_screen.Components.Create<BingleUi.LoadingHud>();
}
void DropScreen()
{
if ( _screen.IsValid() ) _screen.Destroy();
_screen = null;
}
}