diff --git a/docs/phases/14-health/77-health-conditions.md b/docs/phases/14-health/77-health-conditions.md index 023d48e..5693653 100644 --- a/docs/phases/14-health/77-health-conditions.md +++ b/docs/phases/14-health/77-health-conditions.md @@ -11,19 +11,19 @@ ## Задачи -- [ ] На человеке список медицинских условий: def, тяжесть, прогресс, метаданные старта -- [ ] Тик тяжести/стадий на потоке школы; пустой список = здоров -- [ ] Сейв вместе с человеком -- [ ] Нужды не удалять и не подменять одним «HP» -- [ ] Пока можно без ванильных DiseaseDef-вспышек — инфраструктура и тест на искусственное условие -- [ ] Детерминизм тика от сида человека и дня +- [x] На человеке список медицинских условий: def, тяжесть, прогресс, метаданные старта +- [x] Тик тяжести/стадий на потоке школы; пустой список = здоров +- [x] Сейв вместе с человеком +- [x] Нужды не удалять и не подменять одним «HP» +- [x] Пока можно без ванильных DiseaseDef-вспышек — инфраструктура и тест на искусственное условие +- [x] Детерминизм тика от сида человека и дня ## Тесты, без которых фаза не закрыта -- [ ] Условие с кривой тяжести меняется одинаково при том же сиде -- [ ] Сейв восстанавливает список -- [ ] Два условия на одном человеке не затирают друг друга -- [ ] Нужда голода по-прежнему тикает отдельно +- [x] Условие с кривой тяжести меняется одинаково при том же сиде +- [x] Сейв восстанавливает список +- [x] Два условия на одном человеке не затирают друг друга +- [x] Нужда голода по-прежнему тикает отдельно ## Критерий готовности diff --git a/docs/phases/14-health/README.md b/docs/phases/14-health/README.md index 35a1af8..a8ea6c7 100644 --- a/docs/phases/14-health/README.md +++ b/docs/phases/14-health/README.md @@ -12,7 +12,7 @@ | Фаза | Статус | Зачем | | --- | --- | --- | -| [77. Состояния здоровья](77-health-conditions.md) | 🔄 | Список условий, тяжесть, сейв, тик | +| [77. Состояния здоровья](77-health-conditions.md) | ✅ | Список условий, тяжесть, сейв, тик | **Этап B — болезни.** diff --git a/src/HSchool.People/HealthCondition.cs b/src/HSchool.People/HealthCondition.cs new file mode 100644 index 0000000..564eeaf --- /dev/null +++ b/src/HSchool.People/HealthCondition.cs @@ -0,0 +1,94 @@ +using System.Text.Json.Serialization; + +namespace HSchool.People; + +/// +/// One medical condition on a person (hediff-like). Needs stay separate — a disease may +/// later modify decay, but hunger is still a need. +/// +public sealed class HealthCondition +{ + public required string DefName { get; init; } + + /// 0…1. Stages and effects read this; DiseaseDef curves land in phase 78. + public float Severity { get; set; } + + /// Immunity / treatment progress 0…1. + public float Progress { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Source { get; init; } + + public DateTime StartedAt { get; init; } + + /// + /// Base severity change per game day before the person+day seed factor. + /// Artificial conditions carry this until DiseaseDef owns the curve (phase 78). + /// + public float SeverityPerDay { get; init; } + + /// Base progress change per game day before the person+day seed factor. + public float ProgressPerDay { get; init; } +} + +/// Mutates the sparse list and ticks severity deterministically. +public static class HealthConditions +{ + public static void Add(Person person, HealthCondition condition) + { + ArgumentNullException.ThrowIfNull(person); + ArgumentNullException.ThrowIfNull(condition); + + var list = person.Conditions; + if (list is null) + { + list = []; + person.Conditions = list; + } + + list.Add(condition); + } + + /// + /// Advances severity/progress for everyone with conditions. Same + /// , person id and yield the same curve. + /// + public static bool Tick(Person person, int peopleSeed, int dayNumber, double gameMinutes) + { + ArgumentNullException.ThrowIfNull(person); + var list = person.Conditions; + if (list is null || list.Count == 0 || gameMinutes <= 0) + { + return false; + } + + var daySeed = Seed.Mix(peopleSeed, person.Id, dayNumber, Seed.HealthSalt); + var unit = (daySeed & int.MaxValue) / (float)int.MaxValue; + var dayFactor = 0.5f + unit; + var days = gameMinutes / (24d * 60d); + var changed = false; + + foreach (var condition in list) + { + var severityDelta = (float)(condition.SeverityPerDay * dayFactor * days); + var progressDelta = (float)(condition.ProgressPerDay * dayFactor * days); + if (severityDelta == 0f && progressDelta == 0f) + { + continue; + } + + var nextSeverity = Math.Clamp(condition.Severity + severityDelta, 0f, 1f); + var nextProgress = Math.Clamp(condition.Progress + progressDelta, 0f, 1f); + if (nextSeverity == condition.Severity && nextProgress == condition.Progress) + { + continue; + } + + condition.Severity = nextSeverity; + condition.Progress = nextProgress; + changed = true; + } + + return changed; + } +} diff --git a/src/HSchool.People/Roster.cs b/src/HSchool.People/Roster.cs index 783e899..ce79764 100644 --- a/src/HSchool.People/Roster.cs +++ b/src/HSchool.People/Roster.cs @@ -81,6 +81,12 @@ public sealed record Person /// public List? LessonMarks { get; set; } + /// + /// Active medical conditions. Null when healthy (empty) so people.json stays compact. + /// Needs are not replaced by this list. + /// + public List? Conditions { get; set; } + public int AgeOn(DateTime asOf) => SchoolYears.AgeYears(BirthDate, asOf); } diff --git a/src/HSchool.People/Seed.cs b/src/HSchool.People/Seed.cs index 6cb7783..306b8f9 100644 --- a/src/HSchool.People/Seed.cs +++ b/src/HSchool.People/Seed.cs @@ -22,6 +22,7 @@ public static class Seed public const int ConflictSalt = 14; public const int HomeSalt = 15; public const int SummonSalt = 16; + public const int HealthSalt = 17; /// A stream that belongs to the school rather than to one family. public static int ForSchool(int schoolSeed, int salt) => Mix(schoolSeed, familyIndex: -1, salt); diff --git a/src/HSchool.Simulation/HealthConditionSystem.cs b/src/HSchool.Simulation/HealthConditionSystem.cs new file mode 100644 index 0000000..e3fe7c9 --- /dev/null +++ b/src/HSchool.Simulation/HealthConditionSystem.cs @@ -0,0 +1,26 @@ +using HSchool.People; + +namespace HSchool.Simulation; + +/// +/// Ticks medical condition severity on the roster. Contagion and DiseaseDef outbreaks are later phases. +/// +internal static class HealthConditionSystem +{ + public static bool Apply(School school, double gameMinutes) + { + if (gameMinutes <= 0 || school.Roster is null) + { + return false; + } + + var dayNumber = DateOnly.FromDateTime(school.Clock.Time).DayNumber; + var changed = false; + foreach (var person in school.Roster.People) + { + changed |= HealthConditions.Tick(person, school.PeopleSeed, dayNumber, gameMinutes); + } + + return changed; + } +} diff --git a/src/HSchool.Simulation/School.cs b/src/HSchool.Simulation/School.cs index e6aee17..abc2eb3 100644 --- a/src/HSchool.Simulation/School.cs +++ b/src/HSchool.Simulation/School.cs @@ -367,7 +367,7 @@ public sealed class School : IDisposable } } - /// Runs one fixed step of the school: calendar, yearly intake, applicant refresh, presence, actions, need decay, then apparel wear. + /// Runs one fixed step of the school: calendar, yearly intake, applicant refresh, presence, actions, need decay, apparel wear, then health conditions. /// when the roster, applicant pool or wardrobe changed this step. public bool Tick(double deltaTime, double gameMinutesPerRealSecond) { @@ -465,6 +465,7 @@ public sealed class School : IDisposable peopleChanged |= AffinitySystem.Apply(this, talked); } + peopleChanged |= HealthConditionSystem.Apply(this, gameMinutes); peopleChanged |= RosterTalkDirty; RosterTalkDirty = false; return peopleChanged; diff --git a/tests/HSchool.People.Tests/HealthConditionTests.cs b/tests/HSchool.People.Tests/HealthConditionTests.cs new file mode 100644 index 0000000..f791e15 --- /dev/null +++ b/tests/HSchool.People.Tests/HealthConditionTests.cs @@ -0,0 +1,157 @@ +namespace HSchool.People.Tests; + +public class HealthConditionTests +{ + [Fact] + public void SameSeed_YieldsSameSeverityCurve() + { + var started = new DateTime(2012, 4, 3, 8, 0, 0, DateTimeKind.Utc); + var first = Blank("p1"); + var second = Blank("p1"); + HealthConditions.Add(first, Artificial(started, severity: 0.2f)); + HealthConditions.Add(second, Artificial(started, severity: 0.2f)); + + Assert.True(HealthConditions.Tick(first, peopleSeed: 7, dayNumber: 100, gameMinutes: 24 * 60)); + Assert.True(HealthConditions.Tick(second, peopleSeed: 7, dayNumber: 100, gameMinutes: 24 * 60)); + + Assert.Equal(first.Conditions![0].Severity, second.Conditions![0].Severity); + Assert.True(first.Conditions[0].Severity > 0.2f); + } + + [Fact] + public void DifferentDaySeed_ChangesTheCurve() + { + var started = new DateTime(2012, 4, 3, 8, 0, 0, DateTimeKind.Utc); + var a = Blank("p1"); + var b = Blank("p1"); + HealthConditions.Add(a, Artificial(started, severity: 0.2f)); + HealthConditions.Add(b, Artificial(started, severity: 0.2f)); + + HealthConditions.Tick(a, peopleSeed: 7, dayNumber: 100, gameMinutes: 24 * 60); + HealthConditions.Tick(b, peopleSeed: 7, dayNumber: 101, gameMinutes: 24 * 60); + + Assert.NotEqual(a.Conditions![0].Severity, b.Conditions![0].Severity); + } + + [Fact] + public void RosterJson_RoundTripsConditions_AndOmitsHealthy() + { + var roster = Fixtures.Generate(Fixtures.Classrooms(4)); + var pupil = roster.People.First(person => person.IsStudent && !person.IsParent); + var started = new DateTime(2012, 4, 3, 9, 0, 0, DateTimeKind.Utc); + HealthConditions.Add(pupil, Artificial(started, severity: 0.35f, defName: "TestCold")); + HealthConditions.Add( + pupil, + new HealthCondition + { + DefName = "TestStomach", + Severity = 0.15f, + Progress = 0.05f, + Source = "idiopathic", + StartedAt = started.AddHours(1), + SeverityPerDay = 0.05f, + ProgressPerDay = 0.02f, + }); + + var json = RosterJson.Serialize(RosterDocument.From(1, roster)); + Assert.Contains("\"conditions\"", json, StringComparison.Ordinal); + Assert.Contains("\"defName\": \"TestCold\"", json, StringComparison.Ordinal); + Assert.Contains("\"defName\": \"TestStomach\"", json, StringComparison.Ordinal); + + var healthy = roster.People.First(person => person.Conditions is null || person.Conditions.Count == 0); + var healthySlice = PersonJsonSlice(json, healthy.Id); + Assert.DoesNotContain("\"conditions\"", healthySlice, StringComparison.Ordinal); + + var loaded = RosterJson.Parse(json).ToRoster(); + var loadedPupil = loaded.People.First(person => person.Id.Equals(pupil.Id, StringComparison.Ordinal)); + Assert.NotNull(loadedPupil.Conditions); + Assert.Equal(2, loadedPupil.Conditions!.Count); + Assert.Equal("TestCold", loadedPupil.Conditions[0].DefName); + Assert.Equal(0.35f, loadedPupil.Conditions[0].Severity); + Assert.Equal("cold", loadedPupil.Conditions[0].Source); + Assert.Equal(started, loadedPupil.Conditions[0].StartedAt); + Assert.Equal("TestStomach", loadedPupil.Conditions[1].DefName); + Assert.Equal(0.15f, loadedPupil.Conditions[1].Severity); + } + + [Fact] + public void TwoConditions_DoNotOverwriteEachOther() + { + var person = Blank("p1"); + var started = new DateTime(2012, 4, 3, 8, 0, 0, DateTimeKind.Utc); + HealthConditions.Add(person, Artificial(started, severity: 0.4f, defName: "A")); + HealthConditions.Add(person, Artificial(started, severity: 0.1f, defName: "B")); + + Assert.Equal(2, person.Conditions!.Count); + Assert.Equal("A", person.Conditions[0].DefName); + Assert.Equal(0.4f, person.Conditions[0].Severity); + Assert.Equal("B", person.Conditions[1].DefName); + Assert.Equal(0.1f, person.Conditions[1].Severity); + + HealthConditions.Tick(person, peopleSeed: 3, dayNumber: 50, gameMinutes: 60); + Assert.Equal(2, person.Conditions.Count); + Assert.Equal("A", person.Conditions[0].DefName); + Assert.Equal("B", person.Conditions[1].DefName); + Assert.True(person.Conditions[0].Severity > 0.4f); + Assert.True(person.Conditions[1].Severity > 0.1f); + } + + private static HealthCondition Artificial( + DateTime started, + float severity, + string defName = "TestCold") => + new() + { + DefName = defName, + Severity = severity, + Progress = 0f, + Source = "cold", + StartedAt = DateTime.SpecifyKind(started, DateTimeKind.Utc), + SeverityPerDay = 0.2f, + ProgressPerDay = 0.1f, + }; + + private static string PersonJsonSlice(string json, string personId) + { + var marker = $"\"id\": \"{personId}\""; + var start = json.IndexOf(marker, StringComparison.Ordinal); + Assert.True(start >= 0); + var end = json.IndexOf("},", start, StringComparison.Ordinal); + if (end < 0) + { + end = json.Length; + } + + return json[start..end]; + } + + private static Person Blank(string id) + { + var cases = new CaseTable + { + Nom = id, + Gen = id, + Dat = id, + Acc = id, + Ins = id, + Pre = id, + }; + return new Person + { + Id = id, + FamilyId = "f", + Female = false, + BirthDate = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc), + Name = new PersonName(id, id, id, cases, cases, cases), + IsStudent = true, + IsStaff = false, + IsParent = false, + Numbers = new Dictionary(StringComparer.Ordinal), + Choices = new Dictionary(StringComparer.Ordinal), + Skills = new Dictionary(StringComparer.Ordinal), + Traits = [], + Needs = new Dictionary(StringComparer.Ordinal), + Opinions = new Dictionary(StringComparer.Ordinal), + }; + } +} diff --git a/tests/HSchool.Simulation.Tests/HealthConditionSystemTests.cs b/tests/HSchool.Simulation.Tests/HealthConditionSystemTests.cs new file mode 100644 index 0000000..06f16ca --- /dev/null +++ b/tests/HSchool.Simulation.Tests/HealthConditionSystemTests.cs @@ -0,0 +1,144 @@ +using Arch.Core; +using HSchool.Ai; +using HSchool.Content; +using HSchool.People; +using HSchool.Schedule; + +namespace HSchool.Simulation.Tests; + +public class HealthConditionSystemTests +{ + private static readonly DateTime TuesdayLesson = new(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc); + + [Fact] + public void SameSeed_SchoolTick_YieldsSameSeverity() + { + using var first = OpenStaffed(); + using var second = OpenStaffed(); + var pupilId = first.Roster!.People.First(person => person.IsStudent && !person.IsParent).Id; + HangArtificial(first, pupilId, severity: 0.25f); + HangArtificial(second, pupilId, severity: 0.25f); + + TickMinutes(first, 60); + TickMinutes(second, 60); + + var a = first.Roster.People.First(person => person.Id == pupilId).Conditions![0].Severity; + var b = second.Roster!.People.First(person => person.Id == pupilId).Conditions![0].Severity; + Assert.Equal(a, b); + Assert.True(a > 0.25f); + } + + [Fact] + public void Hunger_StillDecaysWhileConditionTicks() + { + using var school = OpenStaffed(); + AdvanceTo(school, TuesdayLesson); + var onCampus = school.CapturePresence().First(row => row.NodeId is not null); + var pupil = school.Roster!.People.First(person => person.Id.Equals(onCampus.PersonId, StringComparison.Ordinal)); + HangArtificial(school, pupil.Id, severity: 0.2f); + + var hungerBefore = ReadHunger(school, pupil.Id); + var severityBefore = pupil.Conditions![0].Severity; + + TickMinutes(school, 60); + + var hungerAfter = ReadHunger(school, pupil.Id); + var severityAfter = pupil.Conditions[0].Severity; + var catalogHunger = school.Catalog!.Needs["Hunger"]; + Assert.True(hungerAfter < hungerBefore); + Assert.Equal(hungerBefore - catalogHunger.DecayPerHour, hungerAfter, precision: 3); + Assert.True(severityAfter > severityBefore); + } + + private static void HangArtificial(School school, string personId, float severity) + { + var person = school.Roster!.People.First(row => row.Id.Equals(personId, StringComparison.Ordinal)); + HealthConditions.Add( + person, + new HealthCondition + { + DefName = "TestCold", + Severity = severity, + Progress = 0f, + Source = "dev", + StartedAt = school.Clock.Time, + SeverityPerDay = 0.5f, + ProgressPerDay = 0.1f, + }); + } + + private static float ReadHunger(School school, string personId) + { + var value = float.NaN; + var query = new QueryDescription().WithAll(); + school.World.Query( + in query, + (ref PersonIdentity identity, ref PersonNeeds needs) => + { + if (identity.Id.Equals(personId, StringComparison.Ordinal)) + { + value = needs.Values["Hunger"]; + } + }); + Assert.False(float.IsNaN(value)); + return value; + } + + private static void TickMinutes(School school, int minutes) + { + for (var i = 0; i < minutes; i++) + { + school.Tick(0.2d, 5d); + } + } + + private static void AdvanceTo(School school, DateTime until) + { + while (school.Clock.Time < until) + { + school.Tick(0.2d, 5d); + } + } + + private static School OpenStaffed() + { + var start = new DateTime(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc); + var (catalog, map) = Vanilla(); + var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", start); + var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", start); + var schoolClass = roster.Classes.First(row => + row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104"); + var school = School.Create(1, "Здоровье", start, catalog, map); + school.InstallPeople(roster, seed: 1, "Russia", pool); + school.SetTimetable(new Timetable( + [ + new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 1, Period: 1), + new LessonPlacement(schoolClass.Id, "PhysicalEducation", "t2", "gym-hall", Day: 1, Period: 2), + ], + [])); + school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); + return school; + } + + private static (DefCatalog Catalog, MapLayout Map) Vanilla() + { + var root = Path.Combine(AppContext.BaseDirectory, "vanilla"); + var documents = new List(); + foreach (var path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories)) + { + if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase) + && !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + var relative = Path.GetRelativePath(root, path).Replace('\\', '/'); + documents.Add(new ContentDocument(CatalogLoader.CorePackId, relative, File.ReadAllText(path))); + } + + var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents); + var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents); + Assert.NotNull(map); + return (catalog, map); + } +}