Builds the world for a flashback scene: a scrapbook arena of tinted boxes, balls, lights, signs, crowd people and a FatGuy cameo, all spawned unsaved under one root at Sump.FlashbackOrigin and mirrored from a per-misfit seed. Also holds the arena frame helpers (P, Yaw, Local, Near, InRect), line of sight checks, and the Watcher class that walks a CrowdPerson round a patrol route, notices the player and hands over to the crowd AI when told to chase.
using System;
using System.Collections.Generic;
/// <summary>How one human in a flashback is dressed: the stadium crowd's body, by tint and accessory only.</summary>
public sealed class HumanLook
{
public Color? Shirt, Trousers, Hat, Coat;
public bool WideHat;
/// <summary>Running speed when it comes for you, in inches per second.</summary>
public float RunSpeed = 140f;
/// <summary>Walking speed on its rounds.</summary>
public float WalkSpeed = 70f;
}
/// <summary>
/// The place a flashback happens in, and the tools to build it. Everything made here is unsaved
/// and sits under <see cref="Root"/>, far from the hub at <see cref="Sump.FlashbackOrigin"/>, so
/// destroying the root removes the whole memory.
/// Positions are given in the arena's own frame: inches from its middle, +X forward, +Y left,
/// Z up from the floor. Each misfit's seed may mirror the arena left to right (see <see cref="Flip"/>),
/// which is why everything goes through <see cref="P(float,float,float)"/>.
/// </summary>
public sealed class FlashbackArena
{
public GameObject Root { get; }
public Vector3 Origin { get; }
public MisfitProfile Profile { get; }
public ReptileController Player { get; }
public BodyHandling Body { get; }
public FlashbackCrowd Crowd { get; }
/// <summary>The way round the arena's walls, for everybody who walks. Tell it when a door opens or shuts.</summary>
public FlashbackNav Nav { get; }
/// <summary>Random numbers from the misfit's seed: the same misfit always gets the same memory.</summary>
public Random Rng { get; }
/// <summary>1, or -1 when this memory is mirrored left to right.</summary>
public float Flip { get; }
public float FloorZ => Origin.z;
public AmbientLight Ambient { get; private set; }
public DirectionalLight Sun { get; private set; }
/// <summary>The far walls and lid that stand in for a sky; tint them to change the time of day.</summary>
public readonly List<ModelRenderer> Sky = new();
public readonly List<CrowdPerson> People = new();
public FatGuy FatGuy { get; private set; }
/// <summary>How easily the player is seen right now (multiplies how far eyes reach). The flashback sets it every frame.</summary>
public float Visibility { get; set; } = 1f;
readonly Model _box, _sphere;
public FlashbackArena( MisfitProfile profile, ReptileController player, BodyHandling body, int salt )
{
Profile = profile;
Player = player;
Body = body;
Origin = Sump.FlashbackOrigin;
Rng = new Random( unchecked(profile.Seed * 31 + salt * 977 + 5) );
Flip = Rng.Next( 2 ) == 0 ? 1f : -1f;
_box = Model.Load( "models/dev/box.vmdl" ); // a 50 unit cube
_sphere = Model.Load( "models/dev/sphere.vmdl" ); // radius 32
Root = Sump.Spawn( "Flashback Arena", Origin );
Crowd = Root.Components.Create<FlashbackCrowd>();
Crowd.Centre = Origin;
Crowd.FloorZ = Origin.z;
Crowd.GripFactor = body.Grip;
// It samples the floor by itself on the first physics tick, once the genre has built the place.
Nav = Root.Components.Create<FlashbackNav>();
Nav.Crowd = Crowd;
Nav.Player = player.IsValid() ? player.GameObject : null;
}
// ---- Places ---------------------------------------------------------------------------------
/// <summary>A point in the arena's frame, as a world position.</summary>
public Vector3 P( float x, float y, float z = 0f ) => Origin + new Vector3( x, y * Flip, z );
public Vector3 P( Vector3 local ) => P( local.x, local.y, local.z );
/// <summary>A yaw in the arena's frame (degrees), as a world yaw.</summary>
public float Yaw( float yaw ) => Flip > 0f ? yaw : -yaw;
/// <summary>A world position back in the arena's frame.</summary>
public Vector3 Local( Vector3 world )
{
var d = world - Origin;
return new Vector3( d.x, d.y * Flip, d.z );
}
public Vector3 PlayerLocal => Player.IsValid() ? Local( Player.WorldPosition ) : Vector3.Zero;
public float PlayerSpeed => Player.IsValid() ? Player.Velocity.Length : 0f;
/// <summary>True while the player's feet are within a flat distance of an arena point.</summary>
public bool Near( Vector3 local, float radius )
{
if ( !Player.IsValid() ) return false;
var d = PlayerLocal - local;
return d.WithZ( 0f ).Length < radius && MathF.Abs( d.z ) < 140f;
}
/// <summary>True while the player's feet are inside a rectangle of the floor plan.</summary>
public bool InRect( float x0, float x1, float y0, float y1 )
{
var p = PlayerLocal;
return p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1;
}
// ---- Building blocks ------------------------------------------------------------------------
public GameObject Group( string name, GameObject parent = null )
{
var go = new GameObject( parent ?? Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = Origin;
return go;
}
/// <summary>A tinted box by its middle and size (arena frame, never turned). Solid unless said otherwise.</summary>
public GameObject Block( string name, Vector3 centre, Vector3 size, Color tint, bool solid = true, GameObject parent = null, bool shadows = true )
{
var go = new GameObject( parent ?? Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( centre );
go.WorldScale = size / 50f;
var renderer = go.Components.Create<ModelRenderer>();
renderer.Model = _box;
renderer.Tint = tint;
if ( !shadows ) renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
if ( solid ) AddBoxCollider( go );
return go;
}
/// <summary>A box by its extents: from (x0, y0, z0) to (x1, y1, z1).</summary>
public GameObject Slab( string name, float x0, float x1, float y0, float y1, float z0, float z1, Color tint, bool solid = true, GameObject parent = null, bool shadows = true ) =>
Block( name, new Vector3( (x0 + x1) * 0.5f, (y0 + y1) * 0.5f, (z0 + z1) * 0.5f ),
new Vector3( MathF.Abs( x1 - x0 ), MathF.Abs( y1 - y0 ), MathF.Abs( z1 - z0 ) ), tint, solid, parent, shadows );
/// <summary>Something solid that is not drawn (the edge of the memory).</summary>
public GameObject Barrier( string name, float x0, float x1, float y0, float y1, float z0, float z1 )
{
var go = new GameObject( Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( (x0 + x1) * 0.5f, (y0 + y1) * 0.5f, (z0 + z1) * 0.5f );
go.WorldScale = new Vector3( MathF.Abs( x1 - x0 ), MathF.Abs( y1 - y0 ), MathF.Abs( z1 - z0 ) ) / 50f;
AddBoxCollider( go );
return go;
}
static void AddBoxCollider( GameObject go )
{
var collider = go.Components.Create<BoxCollider>();
collider.Scale = new Vector3( 50f, 50f, 50f );
collider.Static = true;
}
/// <summary>A tinted ball by its middle and radii. Never solid.</summary>
public GameObject Ball( string name, Vector3 centre, Vector3 radii, Color tint, GameObject parent = null, bool shadows = false )
{
var go = new GameObject( parent ?? Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( centre );
go.WorldScale = radii / 32f;
var renderer = go.Components.Create<ModelRenderer>();
renderer.Model = _sphere;
renderer.Tint = tint;
if ( !shadows ) renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
return go;
}
/// <summary>A box or ball hung on another object, placed in that object's own frame (a dog's leg, a camera's lens).</summary>
public GameObject Part( GameObject parent, string name, bool ball, Vector3 localPosition, Vector3 size, Color tint )
{
var go = new GameObject( parent, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.LocalPosition = localPosition;
go.LocalScale = ball ? size / 64f : size / 50f;
var renderer = go.Components.Create<ModelRenderer>();
renderer.Model = ball ? _sphere : _box;
renderer.Tint = tint;
renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
return go;
}
/// <summary>An empty object at an arena point, facing a yaw, to hang parts on and move about.</summary>
public GameObject Holder( string name, Vector3 at, float yaw = 0f )
{
var go = new GameObject( Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( at );
go.WorldRotation = Rotation.FromYaw( Yaw( yaw ) );
return go;
}
public static void Tint( GameObject go, Color tint )
{
if ( !go.IsValid() ) return;
var renderer = go.Components.Get<ModelRenderer>();
if ( renderer.IsValid() ) renderer.Tint = tint;
}
// ---- Light and air --------------------------------------------------------------------------
/// <summary>A point light. Brightness multiplies the colour.</summary>
public PointLight Lamp( string name, Vector3 at, Color color, float radius, float brightness = 1f, GameObject parent = null )
{
var go = new GameObject( parent ?? Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( at );
var light = go.Components.Create<PointLight>();
light.LightColor = (color * brightness).WithAlpha( 1f );
light.Radius = radius;
light.Shadows = false;
return light;
}
/// <summary>A spot light at a point, aimed at another point.</summary>
public SpotLight Spot( string name, Vector3 at, Vector3 aimAt, Color color, float cone, float brightness = 1f, bool shadows = false )
{
var go = new GameObject( Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
var from = P( at );
var to = P( aimAt );
go.WorldPosition = from;
var direction = (to - from).Normal;
go.WorldRotation = Rotation.LookAt( direction, MathF.Abs( direction.z ) > 0.98f ? Vector3.Forward : Vector3.Up );
var light = go.Components.Create<SpotLight>();
light.LightColor = (color * brightness).WithAlpha( 1f );
light.ConeOuter = cone;
light.ConeInner = cone * 0.6f;
light.Radius = from.Distance( to ) + 400f;
light.Shadows = shadows;
go.Tags.Add( PlayerPhobia.BrightTag ); // a hard light: the player's own fear of light notices it
return light;
}
/// <summary>The air of the place: ambient light, distance fog, and optionally a sun or moon.</summary>
public void Air( Color ambient, Color fog, float fogStart, float fogEnd, Color? sun = null, Angles? sunAngles = null )
{
var air = Group( "Air" );
Ambient = air.Components.Create<AmbientLight>();
Ambient.Color = ambient;
SumpFog.Create( air, fog, fogStart, fogEnd ); // the cavern uses the same fog; keep the two alike
if ( sun is not { } sunColor ) return;
var sky = Group( "Sun" );
sky.WorldRotation = (sunAngles ?? new Angles( 55f, 40f, 0f )).ToRotation();
Sun = sky.Components.Create<DirectionalLight>();
Sun.LightColor = sunColor;
Sun.Shadows = true;
}
/// <summary>Flat ground: one big slab whose top is the arena's floor.</summary>
public GameObject Ground( float halfX, float halfY, Color tint )
{
Crowd.HalfX = halfX;
Crowd.HalfY = halfY;
return Slab( "Ground", -halfX, halfX, -halfY, halfY, -60f, 0f, tint );
}
/// <summary>
/// Walls and a lid far outside the arena, to be looked at as sky, plus unseen walls at the
/// arena's edge so nobody walks out of the memory.
/// </summary>
public void Surround( float halfX, float halfY, float height, Color sky )
{
float far = MathF.Max( halfX, halfY ) + 900f;
float top = height + 900f;
var group = Group( "Sky" );
Sky.Add( Slab( "Sky N", -far, far, far, far + 40f, -80f, top, sky, false, group, false ).Components.Get<ModelRenderer>() );
Sky.Add( Slab( "Sky S", -far, far, -far - 40f, -far, -80f, top, sky, false, group, false ).Components.Get<ModelRenderer>() );
Sky.Add( Slab( "Sky E", far, far + 40f, -far, far, -80f, top, sky, false, group, false ).Components.Get<ModelRenderer>() );
Sky.Add( Slab( "Sky W", -far - 40f, -far, -far, far, -80f, top, sky, false, group, false ).Components.Get<ModelRenderer>() );
Sky.Add( Slab( "Sky Lid", -far, far, -far, far, top, top + 40f, sky, false, group, false ).Components.Get<ModelRenderer>() );
Barrier( "Edge N", -halfX, halfX, halfY, halfY + 60f, -20f, height );
Barrier( "Edge S", -halfX, halfX, -halfY - 60f, -halfY, -20f, height );
Barrier( "Edge E", halfX, halfX + 60f, -halfY, halfY, -20f, height );
Barrier( "Edge W", -halfX - 60f, -halfX, -halfY, halfY, -20f, height );
Barrier( "Edge Lid", -halfX, halfX, -halfY, halfY, height, height + 60f );
}
public void TintSky( Color tint )
{
foreach ( var renderer in Sky )
if ( renderer.IsValid() ) renderer.Tint = tint;
}
/// <summary>Words in the world (a sign), facing along a yaw. Returns the object; use <see cref="SetSign"/> to change it.</summary>
public GameObject Sign( string text, Vector3 at, float yaw, float size, Color color )
{
var go = new GameObject( Root, true, "Sign" );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( at );
go.WorldRotation = Rotation.FromYaw( Yaw( yaw ) );
var words = go.Components.Create<TextRenderer>();
words.Text = text;
words.FontSize = 64f;
words.Scale = size / 64f;
words.Color = color;
return go;
}
public static void SetSign( GameObject sign, string text, Color color )
{
if ( !sign.IsValid() ) return;
var words = sign.Components.Get<TextRenderer>();
if ( !words.IsValid() ) return;
if ( words.Text != text ) words.Text = text;
words.Color = color;
}
// ---- People ---------------------------------------------------------------------------------
/// <summary>
/// One human: the stadium's <see cref="CrowdPerson"/>, hosted by this arena's crowd. Passive
/// people stand or walk their rounds; clear <see cref="CrowdPerson.Passive"/> and they come
/// for the player, grab a limb and hang on, exactly as in the stadium.
/// </summary>
public CrowdPerson Human( string name, Vector3 at, float yaw, HumanLook look, bool passive = true )
{
var go = new GameObject( Root, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( at ) + Vector3.Up;
go.WorldRotation = Rotation.FromYaw( Yaw( yaw ) );
var person = go.Components.Create<CrowdPerson>();
person.Host = Crowd;
person.GrabberChance = 1f; // anybody here will take hold of you, once they are after you
person.LeaveThroughExit = false;
person.Passive = passive;
person.RunSpeed = look.RunSpeed;
person.PassiveSpeed = look.WalkSpeed;
person.ShirtTint = look.Shirt;
person.TrouserTint = look.Trousers;
person.HatTint = look.Hat;
person.CoatTint = look.Coat;
person.WideHat = look.WideHat;
person.Steer = Nav.Agent().Steer; // round the walls, not into them
People.Add( person );
return person;
}
/// <summary>Sends every human after the player, or stands them all down.</summary>
public void EveryoneChases( bool chase )
{
foreach ( var person in People )
if ( person.IsValid() ) person.Passive = !chase;
}
/// <summary>
/// The Fat Guy's walk-on part: the real one from the stadium, in cameo mode. He harms nobody,
/// but he is solid, so he can be in the way. Once per flashback.
/// </summary>
public FatGuy FatGuyCameo( Vector3 at, float yaw, bool seated, Color? suit = null )
{
var go = new GameObject( Root, true, "Fat Guy (cameo)" );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = P( at );
go.WorldRotation = Rotation.FromYaw( Yaw( yaw ) );
var guy = go.Components.Create<FatGuy>();
guy.CameoOnly = true;
guy.CameoSeated = seated;
if ( suit is { } color ) guy.SuitColor = color;
var collider = go.Components.Create<BoxCollider>();
collider.Scale = new Vector3( 96f, 108f, 110f );
collider.Center = new Vector3( 0f, 0f, 55f );
go.Tags.Add( PlayerPhobia.HeavyTag ); // the player's fear of weight knows him anywhere
FatGuy = guy;
return guy;
}
/// <summary>
/// The human object the misfit clings to, lying where it found it: a small bright thing with
/// a warm light on it. Returns its object; the flashback decides what touching it does.
/// </summary>
public GameObject Keepsake( Vector3 at )
{
var group = Group( "Clung Object" );
group.WorldPosition = P( at );
var gold = new Color( 1f, 0.82f, 0.35f );
Block( "Keepsake", at + Vector3.Up * 7f, new Vector3( 12f, 8f, 5f ), gold, false, group, false );
Ball( "Keepsake Knob", at + new Vector3( 3f, 0f, 12f ), new Vector3( 3.5f ), Color.Lerp( gold, Color.White, 0.5f ), group );
Lamp( "Keepsake Glow", at + Vector3.Up * 26f, gold, 170f, 0.9f, group );
return group;
}
/// <summary>A thing to collect: a glowing shard on the ground. Destroy its object when it is taken.</summary>
public GameObject Pickup( string name, Vector3 at, Color color )
{
var group = Group( name );
group.WorldPosition = P( at );
Block( name + " Body", at + Vector3.Up * 9f, new Vector3( 16f, 10f, 12f ), color, false, group, false );
Block( name + " Fin", at + new Vector3( 4f, 0f, 20f ), new Vector3( 5f, 14f, 10f ), Color.Lerp( color, Color.White, 0.4f ), false, group, false );
Lamp( name + " Glow", at + Vector3.Up * 30f, color, 200f, 0.8f, group );
return group;
}
// ---- Eyes -----------------------------------------------------------------------------------
/// <summary>True if nothing solid is between two world points (people do not count).</summary>
public bool ClearLine( Vector3 from, Vector3 to )
{
if ( !Player.IsValid() ) return false;
var trace = Player.Scene.Trace.Ray( from, to )
.IgnoreGameObjectHierarchy( Player.GameObject )
.WithoutTags( "crowd", "fatguy", "debris" )
.Run();
return !trace.Hit;
}
/// <summary>
/// Can an eye at a world point, looking along a direction, see the player? The reach is
/// multiplied by <see cref="Visibility"/>; a half-angle of 180 looks all round.
/// </summary>
public bool Sees( Vector3 eye, Vector3 forward, float halfAngle, float range )
{
if ( !Player.IsValid() ) return false;
var target = Player.WorldPosition + Vector3.Up * 12f;
var to = target - eye;
float distance = to.Length;
if ( distance > range * Visibility ) return false;
if ( halfAngle < 179f && distance > 1f )
{
var flat = to.WithZ( 0f );
var ahead = forward.WithZ( 0f );
if ( flat.Length > 1f && ahead.Length > 0.01f
&& Vector3.Dot( flat.Normal, ahead.Normal ) < MathF.Cos( halfAngle * MathF.PI / 180f ) ) return false;
}
return ClearLine( eye, target );
}
}
/// <summary>
/// A human with eyes and a round to walk: a farmer, an orderly, a parent. Wraps one
/// <see cref="CrowdPerson"/>. While passive it walks its route and looks; told to
/// <see cref="Chase"/>, the crowd AI takes over and it comes to grab.
/// </summary>
public sealed class Watcher
{
public CrowdPerson Person;
public string Name = "";
/// <summary>World points walked in a loop. Empty: it stands at its post.</summary>
public Vector3[] Route = Array.Empty<Vector3>();
/// <summary>Where it starts, and returns to (world).</summary>
public Vector3 Post;
public float PostYaw;
/// <summary>How far and how wide (half-angle, degrees) it sees ahead.</summary>
public float Range = 600f, HalfAngle = 35f;
/// <summary>Anything this close is noticed whichever way it faces.</summary>
public float NearRange = 100f;
/// <summary>Seconds it stops at each point of its round.</summary>
public float Pause = 2f;
/// <summary>True this frame if it can see the player.</summary>
public bool Sees { get; private set; }
/// <summary>Seconds since it last saw the player.</summary>
public float LostFor { get; private set; } = 100f;
/// <summary>While set it stops where it is and faces this world point (taking aim, staring).</summary>
public Vector3? Aim;
int _next;
float _pauseUntil, _legStarted, _investigateUntil;
Vector3? _investigate;
public bool Alive => Person.IsValid() && Person.State != CrowdState.Dead;
public bool Chasing => Alive && !Person.Passive;
public Vector3 Position => Person.IsValid() ? Person.WorldPosition : Post;
public Vector3 Eye => Position + Vector3.Up * 60f;
public Vector3 Forward => Person.IsValid() ? Person.WorldRotation.Forward : Vector3.Forward;
public void Update( FlashbackArena arena, float dt )
{
if ( !Alive ) { Sees = false; return; }
Sees = Person.State != CrowdState.Down
&& (arena.Sees( Eye, Forward, HalfAngle, Range ) || arena.Sees( Eye, Forward, 180f, NearRange ));
LostFor = Sees ? 0f : LostFor + dt;
if ( !Person.Passive ) return; // after the player: the crowd AI is driving
float now = Time.Now;
if ( Aim is { } aim )
{
Person.GoTo = null;
Person.LookAt = aim;
return;
}
if ( _investigate is { } spot )
{
Person.GoTo = spot;
if ( Person.AtGoal || now > _investigateUntil ) { _investigate = null; _pauseUntil = now + 2.5f; Person.GoTo = null; }
return;
}
if ( Route.Length == 0 )
{
// Back to the post, and face the way it was put.
bool away = (Position - Post).WithZ( 0f ).Length > 40f;
Person.GoTo = away ? Post : null;
Person.LookAt = Post + Rotation.FromYaw( PostYaw ).Forward * 200f;
return;
}
Person.LookAt = null;
if ( now < _pauseUntil ) { Person.GoTo = null; return; }
if ( Person.GoTo is null ) _legStarted = now;
Person.GoTo = Route[_next];
// Arrived, or been trying for far too long (something is in the way): on to the next point.
if ( Person.AtGoal || now - _legStarted > 40f )
{
_next = (_next + 1) % Route.Length;
_pauseUntil = now + Pause;
Person.GoTo = null;
}
}
/// <summary>Goes to look at a spot, then picks its round up again.</summary>
public void Investigate( Vector3 where, float seconds = 14f )
{
_investigate = where;
_investigateUntil = Time.Now + seconds;
}
public void Chase()
{
if ( Person.IsValid() ) Person.Passive = false;
}
public void StandDown()
{
if ( Person.IsValid() ) Person.Passive = true;
}
/// <summary>Put back at its post, calm, as if nothing had happened (a rewind).</summary>
public void Reset()
{
_investigate = null;
Aim = null;
_next = 0;
_pauseUntil = 0f;
LostFor = 100f;
Sees = false;
if ( !Person.IsValid() ) return;
Person.Passive = true;
Person.GoTo = null;
if ( Person.State == CrowdState.Dead ) return;
Person.WorldPosition = Post + Vector3.Up * 2f;
Person.WorldRotation = Rotation.FromYaw( PostYaw );
var body = Person.Components.Get<Rigidbody>();
if ( body.IsValid() ) { body.Velocity = Vector3.Zero; body.AngularVelocity = Vector3.Zero; }
}
}