Skip to content

Commit

Permalink
Added more cars and best car testing in the virtual world scene
Browse files Browse the repository at this point in the history
  • Loading branch information
Selinux24 committed Aug 5, 2024
1 parent c1ef203 commit a217b50
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 46 deletions.
5 changes: 5 additions & 0 deletions Engine/Common/EngineShaderStageState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ public class EngineShaderStageState<T>(EngineDeviceContext deviceContext)
/// </summary>
public IEnumerable<T> GetResources()
{
if(resources.Count == 0)
{
return [];
}

int maxSlot = resources.Keys.Max();

T[] values = new T[maxSlot + 1];
Expand Down
10 changes: 6 additions & 4 deletions Samples/05 AISamples/Common/Agents/AgentFollower.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Engine;
using SharpDX;
using System;

namespace AISamples.Common.Agents
{
Expand All @@ -8,20 +9,21 @@ class AgentFollower(float distance, float height) : IFollower
private readonly float distance = distance;
private readonly float height = height;

public Car Car { get; set; }
public Func<Car> Car { get; set; }
public Vector3 Position { get; private set; }
public Vector3 Interest { get; private set; }
public float Velocity { get; set; }

public void Update(IGameTime gameTime)
{
if (Car == null)
var car = Car?.Invoke();
if (car == null)
{
return;
}

var p = Car.GetPosition();
var d = -Car.GetDirection();
var p = car.GetPosition();
var d = -car.GetDirection();

var d3 = new Vector3(d.X, 0f, d.Y) * distance;
d3.Y = height;
Expand Down
14 changes: 9 additions & 5 deletions Samples/05 AISamples/Common/Agents/Car.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class Car
public Sensor Sensor { get; }
public NeuralNetwork Brain { get; }
public bool Damaged { get; private set; } = false;
public float FittnessValue { get; set; } = 0;

public Car(float width, float height, float depth, AgentControlTypes controlType, float maxSpeed = 3f, float maxReverseSpeed = 1.5f)
{
Expand Down Expand Up @@ -143,9 +144,10 @@ private void Move(float time)
angle += rot * MathF.Sign(speed);
}

direction = new Vector2(MathF.Sin(angle), MathF.Cos(angle));
x += direction.X * speed;
y += direction.Y * speed;
direction = new Vector2(MathF.Sin(angle), MathF.Cos(angle)) * speed;
x += direction.X;
y += direction.Y;
FittnessValue += direction.LengthSquared();
}
private bool AssessDamage(Segment2[] roadBorders, Car[] traffic, bool damageTraffic)
{
Expand Down Expand Up @@ -219,9 +221,11 @@ public OrientedBoundingBox GetBox()
{
return trnBox;
}
public Matrix GetTransform()
public Matrix GetTransform(float height = 0)
{
return Matrix.Scaling(scale) * trnBox.Transformation;
var trn = Matrix.RotationY(angle) * Matrix.Translation(x, height, y);

return Matrix.Scaling(scale) * trn;
}
}
}
27 changes: 16 additions & 11 deletions Samples/05 AISamples/Common/World.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ class World(Graph graph, float height)
private GeometryDrawer<VertexPositionTexture> markingsDrawer2d = null;
private GeometryDrawer<VertexPositionTexture> markingsDrawer3d = null;

private Car bestCar = null;
private readonly List<Car> cars = [];
private Car bestCar = null;
private readonly Color4 bestCarColor = new Color(252, 212, 32, 255);
private readonly Color4 carColor = new Color(252, 222, 200, 255);

public Graph Graph { get => graph; }
public Guid Version { get; private set; } = Guid.NewGuid();
Expand Down Expand Up @@ -432,7 +434,7 @@ private void UpdateCars(IGameTime gameTime, ModelInstanced carDrawer)

for (int i = 0; i < maxCarCount; i++)
{
if (i >= cars.Count)
if (i >= cars.Count || cars[i].Damaged)
{
carDrawer[i].Manipulator.SetTransform(Matrix.Translation(Vector3.One * 10000000f));
carDrawer[i].TintColor = Color.Black;
Expand All @@ -444,9 +446,11 @@ private void UpdateCars(IGameTime gameTime, ModelInstanced carDrawer)

car.Update(gameTime, road, [], false);

carDrawer[i].Manipulator.SetTransform(car.GetTransform());
carDrawer[i].TintColor = car == bestCar ? Color.Yellow : Color.White;
carDrawer[i].Manipulator.SetTransform(car.GetTransform(height + hLayer));
carDrawer[i].TintColor = car == bestCar ? bestCarColor : carColor;
}

bestCar = cars.MaxBy(c => c.FittnessValue);
}
private void DrawMarkings()
{
Expand Down Expand Up @@ -592,18 +596,13 @@ public void RemoveMarking(Marking marking)
return (fStart.Position, fStart.Direction);
}

public void AddCar(Car car, bool isBestCar = false)
public void AddCar(Car car)
{
if (cars.Contains(car))
{
return;
}

if (isBestCar)
{
bestCar = car;
}

cars.Add(car);
}
public void RemoveCar(Car car)
Expand All @@ -626,10 +625,16 @@ public void Clear()
laneGuides.Clear();
markings.Clear();

cars.Clear();
ClearTraffic();

worldChanged = true;
Version = Guid.NewGuid();
}
public void ClearTraffic()
{
cars.Clear();

bestCar = null;
}
}
}
35 changes: 23 additions & 12 deletions Samples/05 AISamples/SceneCWRSelfDrivingCar/SelfDrivingCarScene.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class SelfDrivingCarScene : Scene
private GeometryColorDrawer<Triangle> roadDrawer = null;
private GeometryColorDrawer<Line3D> roadLaneDrawer = null;
private Model terrain = null;
private float carScale = 1f;
private ModelInstanced carModels = null;
private ModelInstanced trafficModels = null;

Expand Down Expand Up @@ -91,6 +92,8 @@ public SelfDrivingCarScene(Game game) : base(game)
Game.LockMouse = false;

GameEnvironment.Background = Color.Black;

Lights.SetAmbient(new SceneLightHemispheric("Ambient", Color3.White, Color3.Black, true));
}

public override void Initialize()
Expand Down Expand Up @@ -238,29 +241,34 @@ private async Task InitializeVisualizerDrawer()
}
private async Task InitializeCars()
{
var geo = GeometryUtil.CreateBox(Topology.TriangleList, carWidth, carHeight, carLength);
var mat = MaterialPhongContent.Default;
mat.IsTransparent = true;

var cDesc = new ModelInstancedDescription()
{
Instances = maxCarInstances,
CastShadow = ShadowCastingAlgorihtms.All,
Content = ContentDescription.FromContentData(ContentData.GenerateTriangleList(geo, mat)),
BlendMode = BlendModes.Alpha,
Content = ContentDescription.FromFile(Constants.TrafficResourcesFolder, Constants.TaxiModel),
BlendMode = BlendModes.OpaqueAlpha,
StartsVisible = false,
};
carModels = await AddComponentAgent<ModelInstanced, ModelInstancedDescription>("Cars", "Cars", cDesc);
carModels = await AddComponentAgent<ModelInstanced, ModelInstancedDescription>(
nameof(carModels),
nameof(carModels),
cDesc);

var tDesc = new ModelInstancedDescription()
{
Instances = maxTrafficInstances,
CastShadow = ShadowCastingAlgorihtms.All,
Content = ContentDescription.FromContentData(ContentData.GenerateTriangleList(geo, mat)),
BlendMode = BlendModes.Alpha,
Content = ContentDescription.FromFile(Constants.TrafficResourcesFolder, Constants.TaxiModel),
BlendMode = BlendModes.OpaqueAlpha,
StartsVisible = false,
};
trafficModels = await AddComponentAgent<ModelInstanced, ModelInstancedDescription>("Traffic", "Traffic", tDesc);
trafficModels = await AddComponentAgent<ModelInstanced, ModelInstancedDescription>(
nameof(trafficModels),
nameof(trafficModels),
tDesc);

var bbox = carModels[0].GetBoundingBox();
carScale = MathF.Max(MathF.Max(carWidth / bbox.Width, carHeight / bbox.Height), carLength / bbox.Depth);

cars = new Car[maxCarInstances];
traffic = new Car[maxTrafficInstances];
Expand Down Expand Up @@ -618,7 +626,7 @@ private void SelectBestCar()
if (c != null)
{
bestCar = c;
carFollower.Car = bestCar;
carFollower.Car = () => bestCar;
}
}

Expand Down Expand Up @@ -652,6 +660,7 @@ private void StartSimulation()
for (int i = 0; i < cars.Length; i++)
{
cars[i] = new(carWidth, carHeight, carLength, AgentControlTypes.AI, 1, 0.5f);
cars[i].SetScale(carScale);

if (!mutate)
{
Expand All @@ -666,11 +675,13 @@ private void StartSimulation()

cars[i].Brain.Mutate(0.1f);
}
carFollower.Car = bestCar = cars[0];
bestCar = cars[0];
carFollower.Car = () => bestCar;

for (int i = 0; i < traffic.Length; i++)
{
traffic[i] = new(carWidth, carHeight, carLength, AgentControlTypes.Dummy, 0.5f, 0.25f);
traffic[i].SetScale(carScale);

var lanePos = road.GetLaneCenter(i % traffic.Length);
lanePos.Y = Helper.RandomGenerator.NextFloat(0, 3) * -(carLength * 3);
Expand Down
Loading

0 comments on commit a217b50

Please sign in to comment.