From 33cdd6dfa7a585b528410e91e4781d58074699ca Mon Sep 17 00:00:00 2001 From: josh Date: Fri, 27 Nov 2026 22:24:17 -0500 Subject: [PATCH] Make Soundings voyages playable with ship operations and guided tips --- .../Soundings/Editor/EconomyVerification.cs | 88 ++- Assets/Soundings/Editor/SoundingsBuild.cs | 8 +- Assets/Soundings/Resources/HarborWater.shader | 18 +- Assets/Soundings/Resources/Passage.uss | 136 +++++ Assets/Soundings/Resources/Passage.uss.meta | 12 + .../Soundings/Resources/ServiceControls.uss | 31 ++ .../Resources/ServiceControls.uss.meta | 12 + Assets/Soundings/Resources/Shipwork.uss | 11 + Assets/Soundings/Runtime/Company.cs | 38 +- Assets/Soundings/Runtime/ConstructionPages.cs | 78 ++- Assets/Soundings/Runtime/DeckPassengers.cs | 522 ++++++++++++++++++ .../Soundings/Runtime/DeckPassengers.cs.meta | 2 + Assets/Soundings/Runtime/FirstVoyageGuide.cs | 20 +- Assets/Soundings/Runtime/Harbor.cs | 254 ++++++++- Assets/Soundings/Runtime/LedgerPage.cs | 7 + Assets/Soundings/Runtime/Market.cs | 13 +- Assets/Soundings/Runtime/OnboardEconomy.cs | 247 +++++++++ .../Soundings/Runtime/OnboardEconomy.cs.meta | 2 + Assets/Soundings/Runtime/OnboardSystems.cs | 143 +++++ .../Soundings/Runtime/OnboardSystems.cs.meta | 2 + Assets/Soundings/Runtime/OperationsPage.cs | 6 +- Assets/Soundings/Runtime/PassageInterface.cs | 292 ++++++++++ .../Runtime/PassageInterface.cs.meta | 2 + Assets/Soundings/Runtime/PassageWeather.cs | 187 +++++++ .../Soundings/Runtime/PassageWeather.cs.meta | 2 + Assets/Soundings/Runtime/ServiceControls.cs | 126 +++++ .../Soundings/Runtime/ServiceControls.cs.meta | 2 + Assets/Soundings/Runtime/ServiceDeckModel.cs | 207 +++++++ .../Runtime/ServiceDeckModel.cs.meta | 2 + Assets/Soundings/Runtime/SoundingsApp.cs | 43 +- Assets/Soundings/Runtime/VisualSmoke.cs | 92 ++- .../Soundings/Runtime/VoyagePresentation.cs | 206 +++++-- Docs/Design.md | 9 +- Packages/manifest.json | 3 +- Packages/packages-lock.json | 6 + ProjectSettings/ProjectSettings.asset | 10 +- README.md | 21 +- 37 files changed, 2734 insertions(+), 126 deletions(-) create mode 100644 Assets/Soundings/Resources/Passage.uss create mode 100644 Assets/Soundings/Resources/Passage.uss.meta create mode 100644 Assets/Soundings/Resources/ServiceControls.uss create mode 100644 Assets/Soundings/Resources/ServiceControls.uss.meta create mode 100644 Assets/Soundings/Runtime/DeckPassengers.cs create mode 100644 Assets/Soundings/Runtime/DeckPassengers.cs.meta create mode 100644 Assets/Soundings/Runtime/OnboardEconomy.cs create mode 100644 Assets/Soundings/Runtime/OnboardEconomy.cs.meta create mode 100644 Assets/Soundings/Runtime/OnboardSystems.cs create mode 100644 Assets/Soundings/Runtime/OnboardSystems.cs.meta create mode 100644 Assets/Soundings/Runtime/PassageInterface.cs create mode 100644 Assets/Soundings/Runtime/PassageInterface.cs.meta create mode 100644 Assets/Soundings/Runtime/PassageWeather.cs create mode 100644 Assets/Soundings/Runtime/PassageWeather.cs.meta create mode 100644 Assets/Soundings/Runtime/ServiceControls.cs create mode 100644 Assets/Soundings/Runtime/ServiceControls.cs.meta create mode 100644 Assets/Soundings/Runtime/ServiceDeckModel.cs create mode 100644 Assets/Soundings/Runtime/ServiceDeckModel.cs.meta diff --git a/Assets/Soundings/Editor/EconomyVerification.cs b/Assets/Soundings/Editor/EconomyVerification.cs index 151e079..e13d4af 100644 --- a/Assets/Soundings/Editor/EconomyVerification.cs +++ b/Assets/Soundings/Editor/EconomyVerification.cs @@ -10,7 +10,9 @@ namespace Soundings.Editor VerifyUsedStartAndProfit(); VerifyFinancedStartAndConstruction(); VerifyFlagshipCampaign(); - Debug.Log("Soundings economy verification passed: both starts, pricing, fuel, accounting, saves and flagship progression."); + VerifyLiveCrossingSettlement(); + VerifyStormAndShipSystems(); + Debug.Log("Soundings economy verification passed: both starts, pricing, fuel, accounting, saves, flagship progression, live settlement, weather and ship systems."); } private static void VerifyUsedStartAndProfit() @@ -99,6 +101,90 @@ namespace Soundings.Editor Debug.Log($"Global circuit returned to Miami on day {company.Day} with ${company.Cash:N0} cash."); } + private static void VerifyLiveCrossingSettlement() + { + Company company = Company.Start(false); + Ship ship = company.ActiveShip; + Voyage booking = company.Forecast(ship, 1); + int startingCash = company.Cash; + int startingFuel = ship.Fuel; + var live = new OnboardSession(ship, booking); + int initialDemand = live.Get(OnboardService.Meals).Requested; + int initialPrice = live.GetPrice(OnboardService.Meals); + live.ChangePrice(OnboardService.Meals, 10); + Require(live.Get(OnboardService.Meals).Requested < initialDemand, "meal requests respond to live prices"); + Require(live.StartSpecial(OnboardService.Meals) && live.EffectivePrice(OnboardService.Meals) < live.GetPrice(OnboardService.Meals), + "specials reduce the effective price immediately"); + live.AdvanceTo(.30f); + Require(live.CurrentEvent.HasValue && live.CanAcceptEvent, "an event opens with a meaningful budget"); + int eventCost = live.CurrentEvent.Value.Cost; + int beforeDecision = live.Happiness; + live.ResolveEvent(true); + Require(live.Expenses == eventCost && live.Happiness > beforeDecision, "event decision affects the crossing"); + live.AdvanceTo(.46f); + Require(company.Voyages == 0 && ship.Port == 0 && company.Cash == startingCash && ship.Fuel == startingFuel, + "onboard simulation does not move the company before arrival"); + live.AdvanceTo(1); + Require(company.Sail(ship, 1, live) == null, "complete live crossing"); + Voyage arrival = company.History[0]; + Require(arrival.Guests == booking.Guests && arrival.TicketSales == booking.TicketSales, "departed manifest stays fixed"); + Require(arrival.Day == booking.Day && ship.Fuel == startingFuel - booking.FuelBurn, "live arrival settles time and fuel"); + Require(company.Cash == startingCash + arrival.CashChange && company.LifetimeProfit == arrival.NetIncome, + "live voyage accounting balances"); + var reloaded = JsonUtility.FromJson(JsonUtility.ToJson(company)); + Require(reloaded.CanLoad() && reloaded.History[0].OnboardSales == arrival.OnboardSales + && reloaded.History[0].Onboard.Happiness == arrival.Onboard.Happiness + && reloaded.ActiveShip.ServicePrices[(int)OnboardService.Meals] == initialPrice + 10, + "live earnings, survey and future prices survive a save round-trip"); + Require(company.Sail(ship, 1, live) != null && company.Voyages == 1, "the live crossing cannot settle twice"); + } + + private static void VerifyStormAndShipSystems() + { + Company company = Company.Start(false); + Ship ship = company.ActiveShip; + Voyage booking = company.Forecast(ship, 1); + ship.Fuel = booking.RequiredFuel; + var speed = new OnboardSession(ship, booking); + Require(!speed.CanSetEngineMode(2), "full power cannot consume the arrival reserve"); + speed.SetEngineMode(0); + Require(speed.SpeedFactor < 1 && speed.ProjectedFuelBurn < booking.FuelBurn, "economy power trades time for fuel"); + ship.Fuel = ship.Tank; + speed.SetEngineMode(2); + Require(speed.SpeedFactor > 1 && speed.ProjectedFuelBurn > booking.FuelBurn + && speed.ProjectedFuelBurn + booking.Reserve <= ship.Fuel, "full power uses spare fuel without consuming reserve"); + + var calm = new OnboardSession(ship, booking); + Voyage stormBooking = company.Forecast(ship, 1); + stormBooking.Weather = WeatherCondition.Storm; + var storm = new OnboardSession(ship, stormBooking); + Require(calm.Get(OnboardService.Amenities).Capacity > 0 + && storm.Get(OnboardService.Amenities).Capacity == 0 + && storm.Get(OnboardService.Amenities).Served == 0, "storm closes outdoor amenities"); + Require(storm.Get(OnboardService.Drinks).Requested > calm.Get(OnboardService.Drinks).Requested, + "storm sends more guests to indoor venues"); + storm.AdvanceTo(.30f); + Require(storm.CurrentEvent.HasValue && storm.CurrentEvent.Value.Title == "Outdoor decks closed", "storm presents a weather-specific decision"); + + // Keep the same manifest on a longer crossing to stress the ship's service and utility capacity. + booking.Days = 7; + var baseline = new OnboardSession(ship, booking) { Assisted = false }; + baseline.AdvanceTo(1); + OnboardReport baselineReport = baseline.Report(); + Require(company.Build(ship, 0, 8, Facility.Galley) == null + && company.Build(ship, 0, 9, Facility.Stores) == null + && company.Build(ship, 0, 10, Facility.Water) == null + && company.Build(ship, 0, 11, Facility.Waste) == null + && company.Build(ship, 1, 0, Facility.Stores) == null, "service and utility modules fit spare berths"); + var upgraded = new OnboardSession(ship, booking) { Assisted = false }; + upgraded.AdvanceTo(1); + Require(baselineReport.Provisions == 0 && upgraded.ProvisionsRemaining > 0 + && upgraded.WaterPercent > baselineReport.WaterPercent + && upgraded.SewagePercent < baselineReport.SewagePercent + && upgraded.Health > baselineReport.Health + && upgraded.Happiness > baselineReport.Happiness, "upgraded resources sustain guest health and happiness on a long crossing"); + } + private static void Complete(Company company, Ship ship, int destination) { Voyage quote = company.Forecast(ship, destination); diff --git a/Assets/Soundings/Editor/SoundingsBuild.cs b/Assets/Soundings/Editor/SoundingsBuild.cs index 4d24f8b..297bf71 100644 --- a/Assets/Soundings/Editor/SoundingsBuild.cs +++ b/Assets/Soundings/Editor/SoundingsBuild.cs @@ -24,10 +24,10 @@ namespace Soundings.Editor EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(ScenePath, true) }; PlayerSettings.companyName = "Soundings"; PlayerSettings.productName = "Soundings"; - PlayerSettings.bundleVersion = "0.2.0"; - PlayerSettings.defaultScreenWidth = 1600; - PlayerSettings.defaultScreenHeight = 900; - PlayerSettings.fullScreenMode = FullScreenMode.Windowed; + PlayerSettings.bundleVersion = "0.3.0"; + PlayerSettings.defaultScreenWidth = 1920; + PlayerSettings.defaultScreenHeight = 1080; + PlayerSettings.fullScreenMode = FullScreenMode.FullScreenWindow; PlayerSettings.resizableWindow = true; PlayerSettings.runInBackground = true; PlayerSettings.SetApplicationIdentifier(NamedBuildTarget.Standalone, "game.soundings.simulator"); diff --git a/Assets/Soundings/Resources/HarborWater.shader b/Assets/Soundings/Resources/HarborWater.shader index f368d59..ada0adc 100644 --- a/Assets/Soundings/Resources/HarborWater.shader +++ b/Assets/Soundings/Resources/HarborWater.shader @@ -6,6 +6,7 @@ Shader "Soundings/Harbor Water" _BackdropCrop ("Harbor crop", Vector) = (1,1,0,0) _HullSpan ("Hull length and beam", Vector) = (71,7,0,0) _Underway ("Open water blend", Range(0,1)) = 0 + _WeatherSeverity ("Sea conditions", Range(0,1)) = 0 } SubShader { @@ -21,7 +22,7 @@ Shader "Soundings/Harbor Water" sampler2D _Backdrop; float4 _BackdropCrop, _HullSpan; - float _Underway; + float _Underway, _WeatherSeverity; struct Output { float4 clip : SV_POSITION; float4 screen : TEXCOORD0; float2 world : TEXCOORD1; }; Output vert(appdata_base input) @@ -40,7 +41,8 @@ Shader "Soundings/Harbor Water" float waterMask = 1 - smoothstep(.55,.69,uv.y); float2 p = input.world - _HullSpan.zw; float t = _Time.y; - float textureWave = sin(p.y * 1.94 + p.x * .30 + sin(p.x * .44 - t * .30)) * .0015; + float textureWave = sin(p.y * 1.94 + p.x * .30 + sin(p.x * .44 - t * (.30 + 1.2 * _WeatherSeverity))) + * (.0015 + .003 * _WeatherSeverity); uv += waterMask * float2(textureWave, textureWave * .14); float3 color = tex2D(_Backdrop, uv).rgb; if (_Underway > 0) @@ -53,7 +55,19 @@ Shader "Soundings/Harbor Water" float west = pow(1 - screen.x, 1.65); float3 horizon = lerp(float3(.45,.53,.59), float3(.83,.60,.46), west); float3 sky = lerp(horizon, float3(.13,.24,.38), twilight); + float cloud = .76 + .24 * sin(screen.x * 18 + screen.y * 8 + sin(screen.x * 41 - t * .2)); + float3 stormSky = lerp(float3(.37,.45,.49), float3(.10,.15,.20), twilight) * cloud; + sky = lerp(sky, stormSky, _WeatherSeverity); + float chop = sin(p.y * .83 + p.x * .45 - t * 2.4) * sin(p.x * .48 + p.y * 2.2 + t * 1.6); + openWater = lerp(openWater, openWater * .56 + float3(.055,.082,.09), _WeatherSeverity); + openWater += max(0, chop - .70) * .19 * _WeatherSeverity; color = lerp(color, lerp(openWater, sky, skyBand), _Underway); + if (_WeatherSeverity > .75) + { + float2 rainGrid = float2(screen.x * 160 + screen.y * 42, screen.y * 22 + t * 15); + float rain = step(.973, frac(rainGrid.x + floor(rainGrid.y) * .381)) * step(.58, frac(rainGrid.y)); + color += rain * .22 * _Underway * float3(.55,.69,.77); + } waterMask = lerp(waterMask, 1 - skyBand, _Underway); } diff --git a/Assets/Soundings/Resources/Passage.uss b/Assets/Soundings/Resources/Passage.uss new file mode 100644 index 0000000..ca1414e --- /dev/null +++ b/Assets/Soundings/Resources/Passage.uss @@ -0,0 +1,136 @@ +.voyage-overlay { + position: absolute; + left: 0; + right: 0; + top: 0; + bottom: 0; +} +.voyage-business { + position: absolute; + left: 30px; + top: 84px; + width: 284px; +} +.voyage-business-opener { align-items: flex-start; } +.action.voyage-drawer-toggle { + background-color: #203642; + color: #f2ddad; + height: 34px; + min-height: 34px; + padding: 0 12px; + border-width: 1px; + border-color: #866e48; + border-radius: 3px 3px 0 0; +} +.voyage-business-book { + padding: 9px 11px 7px; + background-color: rgba(8, 22, 29, .94); + border-width: 1px; + border-color: #796d55; + border-left-width: 2px; + border-left-color: #c4a369; +} +.voyage-business-metrics { flex-direction: row; justify-content: space-between; margin-bottom: 4px; } +.voyage-business-metric { flex-grow: 1; } +.voyage-caption { font-size: 9px; letter-spacing: 1px; color: #dcca9f; -unity-font-style: bold; } +.voyage-business-value { color: #f5deae; font-size: 25px; } +.voyage-provisions { margin-bottom: 4px; color: #aac4bf; font-size: 11px; } +.voyage-service { + border-top-width: 1px; + border-top-color: #41565a; + padding-top: 4px; + padding-bottom: 4px; +} +.voyage-service-line { flex-direction: row; justify-content: space-between; align-items: center; } +.voyage-service-name { font-size: 13px; color: #f3f1db; -unity-font-style: bold; } +.voyage-service-demand { font-size: 11px; color: #b9e0ca; } +.voyage-service-demand.voyage-demand-short { color: #e6bf86; } +.voyage-service-included { color: #a6bbba; font-size: 10px; margin-top: 2px; } +.voyage-price-row { flex-direction: row; align-items: center; margin-top: 3px; } +.action.voyage-price-step { + width: 26px; + min-width: 26px; + min-height: 24px; + height: 24px; + padding: 0; + color: #e6ca91; +} +.voyage-service-price { min-width: 43px; color: #f2d9a6; -unity-text-align: middle-center; font-size: 13px; } +.action.voyage-special { + margin-left: 7px; + min-height: 25px; + height: 25px; + padding: 0 6px; + color: #eacb8d; + background-color: #223a42; + font-size: 11px; +} +.voyage-metric-help { color: #a7babb; font-size: 10px; margin-top: 6px; } +.voyage-event-host { position: absolute; top: 84px; right: 30px; width: 294px; } +.voyage-event { + background-color: rgba(12, 25, 32, .96); + padding: 11px 13px; + border-width: 1px; + border-color: #af8e5a; + border-top-width: 2px; + border-top-color: #d8b47c; +} +.voyage-event-title { color: #f1ddb0; font-size: 27px; margin: 2px 0 5px; } +.voyage-event-copy { color: #e4ebdf; white-space: normal; font-size: 13px; } +.voyage-event-impact { color: #bfd2cc; white-space: normal; font-size: 11px; margin-top: 7px; } +.voyage-event-clock { color: #eacb8d; font-size: 11px; margin-top: 8px; } +.action.voyage-event-accept { background-color: #d8b680; color: #1b302f; border-color: #e8c992; margin-top: 8px; min-height: 32px; } +.action.voyage-event-decline { margin-top: 5px; min-height: 30px; } +.voyage-event-result { border-top-width: 1px; padding: 8px 10px; } +.voyage-deckbar { + position: absolute; + bottom: 100px; + left: 7%; + right: 7%; + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + align-items: center; +} +.voyage-deck-caption { margin-right: 8px; } +.action.voyage-view-button { + background-color: rgba(10, 26, 35, .95); + color: #e7d4a6; + border-color: #77857c; + height: 30px; + min-height: 30px; + padding: 0 9px; + font-size: 12px; + margin: 0 3px; +} +.action.voyage-view-button:hover, .action.voyage-view-button:focus { border-color: #e5c990; } +.action.voyage-control-active { background-color: #d8b680; border-color: #e8c992; color: #1b302f; } +.action.voyage-reset { margin-left: 7px; } +.voyage-rail { + position: absolute; + left: 5%; + right: 5%; + bottom: 18px; + min-height: 70px; + padding: 7px 11px; + flex-direction: row; + align-items: center; + background-color: rgba(7, 21, 29, .95); + border-width: 1px; + border-color: #796d55; + border-top-width: 2px; + border-top-color: #c4a369; +} +.voyage-route { flex-grow: 1; min-width: 0; margin-right: 15px; } +.voyage-route-context { flex-direction: row; align-items: center; } +.voyage-conditions { margin-left: 9px; color: #a9c7bd; font-size: 10px; } +.voyage-conditions.voyage-conditions-warning { color: #efab87; } +.voyage-route-name { font-size: 27px; color: #f5deae; } +.voyage-remaining { font-size: 11px; color: #bfcfcb; } +.voyage-progress { height: 3px; background-color: #40585d; margin-top: 4px; } +.voyage-progress-fill { height: 3px; background-color: #d8b680; } +.voyage-speed { margin-right: 15px; align-items: flex-start; } +.voyage-speed-buttons { flex-direction: row; margin-top: 5px; } +.voyage-camera { margin-right: 15px; } +.voyage-camera-help { color: #c4d4cf; font-size: 11px; margin-top: 5px; } +.action.voyage-skip { flex-shrink: 0; } diff --git a/Assets/Soundings/Resources/Passage.uss.meta b/Assets/Soundings/Resources/Passage.uss.meta new file mode 100644 index 0000000..9f4d803 --- /dev/null +++ b/Assets/Soundings/Resources/Passage.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f7a02a05e40fd7cc1929dee801b9c4c9 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Assets/Soundings/Resources/ServiceControls.uss b/Assets/Soundings/Resources/ServiceControls.uss new file mode 100644 index 0000000..08e317e --- /dev/null +++ b/Assets/Soundings/Resources/ServiceControls.uss @@ -0,0 +1,31 @@ +.service-stations { + position: absolute; + top: 75px; + left: 19%; + right: 24%; + flex-direction: row; + justify-content: center; + padding: 4px; + background-color: rgba(10, 21, 27, .92); + border-width: 1px; + border-color: #7e7866; +} +.service-station { min-height: 29px; margin: 0 2px; padding: 2px 7px; font-size: 12px; flex-grow: 1; } +.service-selected { color: #f5d89d; background-color: #3a4947; border-color: #cfa873; } +.service-console { + position: absolute; + bottom: 151px; + left: 26px; + width: 291px; + padding: 12px; + background-color: rgba(11, 25, 32, .94); + border-width: 1px; + border-left-width: 2px; + border-color: #927e5d; +} +.service-title { font-size: 28px; color: #f0dfbb; margin-bottom: 4px; } +.service-metrics { white-space: normal; font-size: 13px; margin: 3px 0 8px; color: #d4e4e1; } +.service-engines { flex-direction: row; } +.service-engines .action { flex-grow: 1; padding: 3px 7px; margin-right: 4px; min-height: 29px; } +.service-tip { white-space: normal; font-size: 11px; color: #a6bcb8; margin-top: 5px; } +.service-operate, .service-assist { margin-top: 5px; min-height: 30px; } diff --git a/Assets/Soundings/Resources/ServiceControls.uss.meta b/Assets/Soundings/Resources/ServiceControls.uss.meta new file mode 100644 index 0000000..4d5e051 --- /dev/null +++ b/Assets/Soundings/Resources/ServiceControls.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 41b8dfcd54fe12ffaa79ebd161b12d5e +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Assets/Soundings/Resources/Shipwork.uss b/Assets/Soundings/Resources/Shipwork.uss index 5494ac3..153a5b1 100644 --- a/Assets/Soundings/Resources/Shipwork.uss +++ b/Assets/Soundings/Resources/Shipwork.uss @@ -124,6 +124,8 @@ .work-berth.work-room-2 { background-color: #55523d; border-color: #9e8f5e; } .work-berth.work-room-3 { background-color: #54415b; border-color: #9a7ea2; } .work-berth.work-room-4 { background-color: #394e64; border-color: #7592ad; } +.work-berth.work-room-5 { background-color: #664439; border-color: #bd8d79; } +.work-berth.work-room-6 { background-color: #3c5947; border-color: #89a877; } .work-berth:hover, .work-berth:focus { background-color: #39626b; border-color: #d8ecdb; @@ -262,3 +264,12 @@ } .work-primary:hover { background-color: #edd49c; border-color: #f3dbb0; } .work-overhaul { color: #e5c995; border-color: #807255; border-radius: 2px; } + +.work-fit-modes { flex-direction: row; margin: 0 0 6px; } +.work-fit-modes .action { min-height: 26px; font-size: 12px; margin-right: 6px; padding: 2px 9px; } +.work-fit-modes .work-selected { border-color: #caad74; color: #f0d3a7; background-color: #30494b; } +.work-berth.work-room-7 { background-color: #5b4b3c; border-color: #ad936e; } +.work-berth.work-room-8 { background-color: #50563e; border-color: #979e6d; } +.work-berth.work-room-9 { background-color: #325761; border-color: #77a9b3; } +.work-berth.work-room-10 { background-color: #34594c; border-color: #7fa98b; } +.work-berth.work-room-11 { background-color: #60553c; border-color: #baab79; } diff --git a/Assets/Soundings/Runtime/Company.cs b/Assets/Soundings/Runtime/Company.cs index 4ac9b5a..1e0895b 100644 --- a/Assets/Soundings/Runtime/Company.cs +++ b/Assets/Soundings/Runtime/Company.cs @@ -15,6 +15,7 @@ namespace Soundings { public string Name; public int HullIndex, Port, Condition, Fare, Fuel; + public int[] ServicePrices; public double FuelValue; public List Decks = new List(); @@ -23,6 +24,12 @@ namespace Soundings public int Meals => Count(Facility.Dining) * Market.Facilities[(int)Facility.Dining].Capacity * 3; public int Entertainment => Count(Facility.Entertainment) * Market.Facilities[(int)Facility.Entertainment].Capacity; public int Capacity => Math.Min(Beds, Meals); + public int GalleyCapacity => 168 + HullIndex * 72 + Count(Facility.Galley) * Market.Facilities[(int)Facility.Galley].Capacity; + public int FoodCapacity => 1500 + HullIndex * 640 + Count(Facility.Stores) * Market.Facilities[(int)Facility.Stores].Capacity; + public int WaterCapacity => 16000 + HullIndex * 7600 + Count(Facility.Water) * Market.Facilities[(int)Facility.Water].Capacity; + public int WaterProduction => 9000 + HullIndex * 3900 + Count(Facility.Water) * 6000; + public int WasteCapacity => 12000 + HullIndex * 6800 + Count(Facility.Waste) * Market.Facilities[(int)Facility.Waste].Capacity; + public int WasteTreatment => 5500 + HullIndex * 3400 + Count(Facility.Waste) * 7000; public int Tank => Hull.Tank + Count(Facility.Tank) * Market.Facilities[(int)Facility.Tank].Capacity; public double BurnPerMile => Hull.TonsPerMile * (1 + (100 - Condition) * .003); public int SafeRange => Math.Max(0, (int)Math.Floor(Math.Min(Fuel - 6, Fuel * 100 / 112) / BurnPerMile)); @@ -41,10 +48,12 @@ namespace Soundings [Serializable] public sealed class Voyage { - public int Origin, Destination, Miles, Days, Day, Fare, Guests, Capacity, FuelBurn, Reserve, + public int Origin, Destination, Miles, Days, Day, Fare, Guests, RoomDemand, Capacity, FuelBurn, Reserve, TicketSales, OnboardSales, Crew, Catering, PortFees, FuelExpense, LoanInterest, Principal, ReputationChange; public string ShipName; - public int OperatingCash => Crew + Catering + PortFees; + public OnboardReport Onboard; + public WeatherCondition Weather; + public int OperatingCash => Crew + Catering + PortFees + (Onboard?.Expenses ?? 0); public int NetIncome => TicketSales + OnboardSales - OperatingCash - FuelExpense - LoanInterest; public int CashChange => TicketSales + OnboardSales - OperatingCash - LoanInterest - Principal; public int RequiredFuel => FuelBurn + Reserve; @@ -179,6 +188,8 @@ namespace Soundings ship.Decks[1].Cells[1] = Facility.Dining; ship.Decks[1].Cells[2] = Facility.Entertainment; ship.Decks[1].Cells[4] = Facility.Dining; + ship.Decks[1].Cells[5] = Facility.Bar; + ship.Decks[1].Cells[8] = Facility.Amenity; } return ship; } @@ -314,7 +325,8 @@ namespace Soundings double entertainment = Math.Min(1, (double)ship.Entertainment / Math.Max(1, ship.Capacity)); double marketDemand = (150 + ship.Capacity * .50) * from.MarketSize * to.Appeal * season * saturation; double product = (.66 + Reputation * .006 + entertainment * .20) * (.8 + ship.Condition * .002); - int guests = Market.Clamp((int)Math.Round(marketDemand * fareFactor * product), 0, ship.Capacity); + int roomDemand = Math.Max(0, (int)Math.Round(marketDemand * fareFactor * product)); + int guests = Math.Min(roomDemand, ship.Capacity); double unitCost = ship.Fuel > 0 ? ship.FuelValue / ship.Fuel : Market.FuelPrice(ship.Port, Day); return new Voyage @@ -327,6 +339,7 @@ namespace Soundings Miles = miles, Fare = ship.Fare, Guests = guests, + RoomDemand = roomDemand, Capacity = ship.Capacity, FuelBurn = fuel, Reserve = reserve, @@ -366,16 +379,29 @@ namespace Soundings return null; } - public string Sail(Ship ship, int destination) + public string Sail(Ship ship, int destination, OnboardSession live = null) { - Voyage quote = Forecast(ship, destination); + Voyage quote = live?.Quote ?? Forecast(ship, destination); + if (live != null && (live.Ship != ship || quote.Origin != ship.Port || quote.Destination != destination)) + return "This sailing has already been settled or belongs to another ship."; string block = DepartureBlock(ship, quote); if (block != null) return block; + if (live != null) + { + live.AdvanceTo(1); + quote.Onboard = live.Report(); + quote.OnboardSales = quote.Onboard.Revenue; + quote.FuelBurn = quote.Onboard.FuelBurn; + quote.FuelExpense = (int)Math.Round(quote.FuelBurn * ship.FuelValue / ship.Fuel); + quote.ReputationChange += (int)Math.Round((quote.Onboard.Happiness - 74) / 10.0); + live.SavePrices(); + } + ship.FuelValue *= (double)(ship.Fuel - quote.FuelBurn) / ship.Fuel; ship.Fuel -= quote.FuelBurn; - ship.Condition = Math.Max(24, ship.Condition - Math.Max(1, quote.Days / 2)); + ship.Condition = Market.Clamp(ship.Condition - Math.Max(1, quote.Days / 2) + (quote.Onboard?.Repair ?? 0), 24, 100); ship.Port = quote.Destination; Day = quote.Day; Cash += quote.CashChange; diff --git a/Assets/Soundings/Runtime/ConstructionPages.cs b/Assets/Soundings/Runtime/ConstructionPages.cs index 2c490f8..ff69ba1 100644 --- a/Assets/Soundings/Runtime/ConstructionPages.cs +++ b/Assets/Soundings/Runtime/ConstructionPages.cs @@ -8,6 +8,8 @@ namespace Soundings private static readonly (int HullIndex, bool Used)[] Offers = { (0, true), (0, false), (1, true), (1, false), (2, false) }; + private bool systemTools; + private static readonly Color DraftGrid = new Color(.37f, .62f, .65f, .19f); private static readonly Color DraftFine = new Color(.47f, .75f, .74f, .42f); private static readonly Color DraftInk = new Color(.64f, .89f, .82f, .88f); @@ -112,16 +114,31 @@ namespace Soundings var fittings = Add(work, "work-fittings"); var gauges = Add(fittings, "work-capacity-strip"); - AddText(gauges, $"{ship.Beds:N0} berths", "work-capacity"); - AddText(gauges, $"{ship.Meals:N0} meal covers", "work-capacity"); - AddText(gauges, $"{ship.Entertainment:N0} show seats", "work-capacity"); - AddText(gauges, $"{ship.Tank:N0} t bunker capacity", "work-capacity"); - AddText(gauges, $"{ship.Capacity:N0} guests per sailing", "work-capacity work-capacity-emphasis"); - - var tools = Add(fittings, "work-tool-tray"); - for (int i = 1; i <= Market.Facilities.Count; i++) + if (systemTools) { - Facility option = (Facility)(i % Market.Facilities.Count); + AddText(gauges, $"{ship.GalleyCapacity:N0} galley covers", "work-capacity"); + AddText(gauges, $"{ship.FoodCapacity:N0} stored portions", "work-capacity"); + AddText(gauges, $"{ship.WaterCapacity:N0} L freshwater", "work-capacity"); + AddText(gauges, $"{ship.WasteCapacity:N0} L sewage buffer", "work-capacity"); + } + else + { + AddText(gauges, $"{ship.Beds:N0} berths", "work-capacity"); + AddText(gauges, $"{ship.Meals:N0} meal covers", "work-capacity"); + AddText(gauges, $"{ship.Entertainment:N0} show seats", "work-capacity"); + AddText(gauges, $"{ship.Tank:N0} t bunker capacity", "work-capacity"); + AddText(gauges, $"{ship.Capacity:N0} guests per sailing", "work-capacity work-capacity-emphasis"); + } + + var toolMode = Add(fittings, "work-fit-modes"); + toolMode.Add(Action("Guest facilities", () => ChangeBuildTools(false), systemTools ? "" : "work-selected", "facility-guests")); + toolMode.Add(Action("Ship systems", () => ChangeBuildTools(true), systemTools ? "work-selected" : "", "facility-systems")); + var tools = Add(fittings, "work-tool-tray"); + int start = systemTools ? (int)Facility.Galley : 1; + int end = systemTools ? Market.Facilities.Count : (int)Facility.Galley; + for (int i = start; i <= end; i++) + { + Facility option = i == end ? Facility.Empty : (Facility)i; FacilitySpec spec = Market.Facilities[(int)option]; Button button = Action("", () => { @@ -135,11 +152,21 @@ namespace Soundings var copy = Add(button, "work-tool-copy"); copy.pickingMode = PickingMode.Ignore; AddText(copy, spec.Name, "work-tool-name"); - AddText(copy, option == Facility.Empty ? spec.Details : Money(spec.Price), "work-tool-cost"); + AddText(copy, option == Facility.Empty ? "25% refund" : Money(spec.Price), "work-tool-cost"); tools.Add(button); } } + private void ChangeBuildTools(bool systems) + { + if (systemTools == systems) + return; + systemTools = systems; + tool = systems ? Facility.Galley : Facility.Cabin; + Notify(null); + Render(); + } + private static string PlacementInstruction(Facility selected) { FacilitySpec spec = Market.Facilities[(int)selected]; @@ -211,6 +238,37 @@ namespace Soundings Line(6,11,18,11); Line(6,16,18,16); break; + case Facility.Bar: + Segment(4,5,20,5,12,13,4,5); + Segment(12,13,12,20,7,20); + Line(12,20,17,20); + Line(8,8,16,8); + break; + case Facility.Amenity: + Segment(4,11,6,7,10,5,14,5,18,7,20,11,4,11); + Line(12,11,12,17); + Segment(3,19,6,17,9,19,12,17,15,19,18,17,21,19); + break; + case Facility.Galley: + Segment(3,13,17,13,15,18,5,18,3,13); + Line(17,13,22,11); + Line(8,10,8,6); + Line(12,10,12,5); + break; + case Facility.Stores: + Segment(4,5,20,5,20,19,4,19,4,5); + Line(4,11,20,11); + Line(8,8,16,8); + Line(8,15,16,15); + break; + case Facility.Water: + case Facility.Waste: + Segment(12,3,18,11,19,15,17,19,12,21,7,19,5,15,6,11,12,3); + Line(8,16,16,16); + break; + case Facility.Workshop: + Segment(6,19,15,10,14,7,18,5,20,7,19,10,16,11,8,21,6,19); + break; default: Line(6,6,18,18); Line(6,18,18,6); diff --git a/Assets/Soundings/Runtime/DeckPassengers.cs b/Assets/Soundings/Runtime/DeckPassengers.cs new file mode 100644 index 0000000..66ba605 --- /dev/null +++ b/Assets/Soundings/Runtime/DeckPassengers.cs @@ -0,0 +1,522 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Soundings +{ + internal sealed class DeckPassengers : IDisposable + { + private const float BaseFloor = 5.38f; + private const float FloorSpacing = 1.88f; + private static readonly string[] Paint = + { + "142C3F", "E1DBCA", "B88754", "8A613C", "283846", "678B93", "B45944", "497975", + "D3A064", "688566", "354B64", "54435D", "AAD4D4", "D7906C", "ECE4D7", "337F9A", + "573B2E", "A46C50", "DFAB86", "40577D", "BF7756", "D3B973", "76ADA8", "A684AB", "E3DED0" + }; + + private readonly Transform shipRoot; + private readonly Ship ship; + private readonly float length, beam; + private readonly Shader shader; + private readonly Dictionary paint = new(); + private readonly List meshes = new(); + private readonly Layout[] decks; + private readonly Layout promenade; + private Layout bridge; + private Mesh clothes, head; + private int activeIndex = -1; + private bool bridgeView; + private float animationTime; + + private sealed class Layout + { + public readonly GameObject Room, Crowd; + public readonly List People = new(); + + public Layout(string name, Transform parent) + { + Room = Piece(name, parent); + Crowd = Piece("Passenger activity", Room.transform); + } + } + + private sealed class Passenger + { + public Transform Body; + public Vector3 Position; + public int Slot, Service; + public float Yaw, Phase, Travel; + public bool Seated; + } + + public DeckPassengers(Transform parent, Ship ship, float length, float beam, Shader surface) + { + shipRoot = parent; + this.ship = ship; + this.length = length; + this.beam = beam; + shader = surface; + decks = new Layout[ship.Decks.Count]; + BuildPeopleMeshes(); + promenade = BuildPromenade(); + promenade.Crowd.SetActive(false); + } + + public float FloorHeight(int index) => BaseFloor + index * FloorSpacing + .08f; + + public Vector3 WalkOrigin(int index) + { + float aisle = ship.Hull.Rows == 3 ? -beam * .34f : 0; + return new Vector3(-length * .34f, FloorHeight(index) + 1.57f, aisle); + } + + private float BridgeHeight => BaseFloor + ship.Decks.Count * FloorSpacing; + + public Vector3 BridgeOrigin() => new(BridgeCenter - 1.2f, BridgeHeight + 1.65f, 0); + + public Vector3 ClampBridgePosition(Vector3 position) + { + position.x = Mathf.Clamp(position.x, BridgeCenter - 3.2f, BridgeCenter + 1.3f); + position.z = Mathf.Clamp(position.z, -beam * .44f, beam * .44f); + position.y = BridgeHeight + 1.65f; + return position; + } + + public void Select(int index) + { + if (activeIndex >= 0 && decks[activeIndex] != null) + decks[activeIndex].Room.SetActive(false); + if (bridgeView) + bridge.Room.SetActive(false); + bridgeView = false; + activeIndex = index; + promenade.Room.SetActive(index == -1); + if (index < 0) + return; + if (decks[index] == null) + decks[index] = BuildDeck(index); + decks[index].Room.SetActive(true); + } + + public void SelectBridge() + { + if (activeIndex >= 0 && decks[activeIndex] != null) + decks[activeIndex].Room.SetActive(false); + promenade.Room.SetActive(false); + activeIndex = -1; + if (bridge == null) + bridge = BuildBridge(); + bridgeView = true; + bridge.Room.SetActive(true); + } + + public void HideRooms() + { + if (activeIndex >= 0 && decks[activeIndex] != null) + decks[activeIndex].Room.SetActive(false); + if (bridgeView) + bridge.Room.SetActive(false); + bridgeView = false; + activeIndex = -1; + promenade.Room.SetActive(false); + } + + public void HidePassengers() + { + promenade.Crowd.SetActive(false); + foreach (Layout deck in decks) + deck?.Crowd.SetActive(false); + } + + public void Tick(OnboardSession session, float delta) + { + if (bridgeView || session == null) + return; + animationTime += Mathf.Max(0, delta); + Layout layout = activeIndex < 0 ? promenade : decks[activeIndex]; + if (!layout.Crowd.activeSelf) + layout.Crowd.SetActive(true); + + int guests = Math.Max(1, session.Quote.Guests); + foreach (Passenger person in layout.People) + { + float proportion = person.Service < 0 ? Mathf.Clamp01(guests / 100f) + : Mathf.Clamp01(session.Get((OnboardService)person.Service).Served / (float)guests); + bool appears = guests >= 10 && (person.Slot == 0 ? proportion > 0 : (person.Slot == 1 ? proportion > .2f : proportion > .48f)); + if (person.Body.gameObject.activeSelf != appears) + person.Body.gameObject.SetActive(appears); + if (!appears) + continue; + + float time = animationTime + person.Phase; + Vector3 point = person.Position; + if (person.Travel > 0) + { + float drift = Mathf.Sin(time * .65f); + point.x += drift * person.Travel; + point.y += Mathf.Abs(Mathf.Sin(time * 8)) * .105f; + person.Body.localRotation = Quaternion.Euler(0, Mathf.Cos(time * .65f) >= 0 ? 90 : -90, 0); + } + else + { + point.y += Mathf.Sin(time * 2.9f) * .035f; + person.Body.localRotation = Quaternion.Euler(person.Seated ? 7f : 0, person.Yaw + Mathf.Sin(time * 2.1f) * 6f, 0); + } + person.Body.localPosition = point; + } + } + + private Layout BuildPromenade() + { + var layout = new Layout("Open promenade", shipRoot); + float y = BridgeHeight + .04f; + float width = beam * (.82f - (ship.Decks.Count - 1) * .044f); + for (int i = 0; i < 16; i++) + { + float z = (i % 2 == 0 ? -1 : 1) * width * .76f; + float x = length * Mathf.Lerp(-.32f, .23f, i / 15f); + AddPerson(layout, new Vector3(x, y, z), -1, i % 3, i, i % 5 == 0 ? 0 : 1.2f, false); + } + AddPerson(layout, new Vector3(-1.5f, y, -2.0f), (int)OnboardService.Amenities, 0, 16, 0, false, 0); + AddPerson(layout, new Vector3(3.0f, y, 1.95f), (int)OnboardService.Drinks, 1, 17, 0, false, 180); + return layout; + } + + private Layout BuildDeck(int index) + { + var layout = new Layout($"Deck {index + 1} cutaway", shipRoot); + float y = FloorHeight(index); + var structure = new Geometry(this, layout.Room.transform); + Vector2[] outline = Outline(.97f, beam * .98f); + structure.Mesh(0).Loft(outline, Vector2.zero, false, + new Vector3(.93f, -1.2f, .69f), new Vector3(.99f, 0, .95f), + new Vector3(1f, 2.0f, 1f), new Vector3(1f, y - .20f, 1f)); + structure.Mesh(1).Loft(outline, Vector2.zero, false, + new Vector3(1.002f, y - .21f, 1.003f), new Vector3(1.003f, y, 1.003f)); + structure.Mesh(2).Loft(outline, Vector2.zero, true, + new Vector3(.998f, y - .01f, .998f), new Vector3(.998f, y + .01f, .998f)); + structure.Mesh(8).Loft(outline, Vector2.zero, false, + new Vector3(1.003f, 3.3f, 1.004f), new Vector3(1.003f, 3.37f, 1.004f)); + + for (int i = 0; i < outline.Length; i++) + { + Vector2 a = outline[i], b = outline[(i + 1) % outline.Length]; + structure.Mesh(1).Rod(HarborMesh.Point(a, y + .52f), HarborMesh.Point(b, y + .52f), .031f); + structure.Mesh(1).Rod(HarborMesh.Point(a, y), HarborMesh.Point(a, y + .52f), .035f); + } + + float total = length * .68f; + int columns = ship.Hull.Columns, rows = ship.Hull.Rows; + float cellWidth = total / columns; + float rowDepth = beam * 1.48f / rows; + for (int i = 0; i < 3; i++) + structure.Box(3, new Vector3(-length * .025f, y + .013f, (i - 1) * .28f), new Vector3(total + 5, .014f, .025f)); + for (int col = 0; col < columns; col++) + { + float x = -.025f * length - total * .5f + (col + .5f) * cellWidth; + for (int row = 0; row < rows; row++) + { + int slot = row * columns + col; + float z = (row - (rows - 1) * .5f) * (rowDepth + .47f); + var center = new Vector3(x, y + .026f, z); + Facility facility = ship.Decks[index].Cells[slot]; + Room(structure, layout, facility, center, cellWidth - .60f, rowDepth - .21f, index * 70 + slot); + } + } + AddPerson(layout, new Vector3(-length * .30f, y + .021f, rows == 3 ? beam * .36f : .03f), -1, 0, index * 6, 1.1f, false); + AddPerson(layout, new Vector3(length * .29f, y + .021f, rows == 3 ? -beam * .36f : -.03f), -1, 1, index * 6 + 1, 1.2f, false); + structure.Finish(); + return layout; + } + + private void Room(Geometry shape, Layout layout, Facility facility, Vector3 pos, float width, float depth, int seed) + { + int floor = facility switch + { + Facility.Cabin => 5, Facility.Dining => 6, Facility.Entertainment => 11, Facility.Bar => 7, + Facility.Amenity => 9, Facility.Tank => 4, Facility.Galley => 6, Facility.Stores => 5, + Facility.Water => 15, Facility.Waste => 11, Facility.Workshop => 7, _ => 3 + }; + void Box(int color, float x, float y, float z, float w, float height, float d) + => shape.Box(color, pos + new Vector3(x, y, z), new Vector3(w, height, d)); + Box(floor, 0, .006f, 0, width, .045f, depth); + if (facility == Facility.Empty) + { + Box(8, 0, .04f, depth * .48f, width, .025f, .045f); + return; + } + + Box(1, 0, .20f, depth * .49f, width, .36f, .12f); + Box(1, -width * .48f, .21f, 0, .12f, .40f, depth); + Box(1, width * .48f, .21f, 0, .12f, .40f, depth); + int service = -1; + switch (facility) + { + case Facility.Cabin: + for (int side = -1; side <= 1; side += 2) + { + Box(4, width * .25f * side, .23f, depth * .018f, 1.07f, .40f, 1.63f); + Box(14, width * .25f * side, .49f, depth * .018f, 1.04f, .18f, 1.58f); + Box(12, width * .25f * side, .61f, -depth * .11f, 1.02f, .06f, 1.02f); + Box(14, width * .25f * side, .62f, depth * .23f, .83f, .07f, .29f); + } + Box(8, 0, .35f, depth * .23f, .72f, .64f, .57f); + service = (int)OnboardService.Rooms; + break; + case Facility.Dining: + for (int side = -1; side <= 1; side += 2) + { + float x = side * width * .24f; + Box(3, x, .34f, 0, .22f, .54f, .19f); + Box(14, x, .67f, 0, 1.16f, .15f, .94f); + Box(13, x, .77f, -.13f, .36f, .06f, .27f); + Chair(shape, pos + new Vector3(x, 0, -depth * .31f), 4); + Chair(shape, pos + new Vector3(x, 0, depth * .27f), 4); + } + service = (int)OnboardService.Meals; + break; + case Facility.Bar: + Box(3, 0, .47f, depth * .28f, width * .80f, .88f, .73f); + Box(8, 0, .96f, depth * .28f, width * .83f, .13f, .78f); + for (int i = -1; i <= 1; i++) + { + float x = i * width * .21f; + Box(11, x, 1.09f, depth * .28f, .12f, .20f, .16f); + Chair(shape, pos + new Vector3(x, .17f, -depth * .10f), 6); + } + service = (int)OnboardService.Drinks; + break; + case Facility.Entertainment: + Box(4, 0, .30f, depth * .28f, width * .82f, .52f, .66f); + Box(13, 0, .88f, depth * .42f, width * .80f, .68f, .13f); + for (int i = -1; i <= 1; i++) + Chair(shape, pos + new Vector3(i * width * .23f, 0, -depth * .23f), 10); + AddPerson(layout, pos + new Vector3(0, .55f, depth * .23f), (int)OnboardService.Shows, 0, seed + 41, 0, false, 180); + service = (int)OnboardService.Shows; + break; + case Facility.Amenity: + Box(14, 0, .18f, depth * .16f, width * .66f, .30f, depth * .44f); + Box(15, 0, .35f, depth * .16f, width * .55f, .04f, depth * .34f); + Box(8, -width * .29f, .25f, -depth * .26f, 1.38f, .42f, .43f); + Box(8, width * .29f, .25f, -depth * .26f, 1.38f, .42f, .43f); + service = (int)OnboardService.Amenities; + break; + case Facility.Tank: + var start = pos + new Vector3(-width * .32f, .61f, 0); + shape.Mesh(5).Rod(start, pos + new Vector3(width * .32f, .61f, 0), .49f, 12); + Box(8, 0, .94f, -.12f, .29f, .22f, .24f); + return; + case Facility.Galley: + Box(3, 0, .45f, depth * .23f, width * .82f, .88f, .76f); + Box(14, 0, .94f, depth * .23f, width * .84f, .11f, .87f); + for (int i = -1; i <= 1; i++) + Box(4, i * width * .24f, 1.02f, depth * .23f, .55f, .06f, .50f); + Box(14, 0, 1.53f, depth * .32f, width * .78f, .34f, .55f); + break; + case Facility.Stores: + for (int shelf = 1; shelf <= 2; shelf++) + { + float y = shelf * .53f; + Box(8, 0, y, depth * .28f, width * .82f, .09f, .60f); + for (int i = -1; i <= 1; i++) + Box(i == 0 ? 6 : 5, i * width * .24f, y + .21f, depth * .28f, width * .19f, .34f, .47f); + } + break; + case Facility.Water: + case Facility.Waste: + for (int side = -1; side <= 1; side += 2) + { + var foot = pos + new Vector3(side * width * .24f, .18f, depth * .17f); + shape.Mesh(facility == Facility.Water ? 15 : 11).Rod(foot, foot + Vector3.up * 1.15f, .39f, 12); + Box(3, side * width * .24f, .12f, depth * .17f, .94f, .22f, .92f); + } + Box(14, 0, .99f, depth * .34f, width * .53f, .15f, .13f); + break; + case Facility.Workshop: + Box(3, 0, .47f, depth * .28f, width * .83f, .88f, .72f); + Box(8, 0, .97f, depth * .28f, width * .86f, .12f, .79f); + Box(4, 0, 1.42f, depth * .46f, width * .78f, .77f, .12f); + Box(7, width * .24f, 1.10f, depth * .27f, .47f, .20f, .34f); + break; + } + + if (service < 0) + return; + bool seats = facility is Facility.Dining or Facility.Bar or Facility.Entertainment or Facility.Amenity; + float sittingZ = facility == Facility.Bar ? -depth * .10f : -depth * .26f; + for (int i = 0; i < (seats ? 3 : 2); i++) + { + float x = (i - (seats ? 1f : .5f)) * width * .23f; + AddPerson(layout, pos + new Vector3(x, seats ? .23f : .03f, sittingZ), service, i, seed + i, 0, seats); + } + } + + private Layout BuildBridge() + { + var layout = new Layout("Bridge interior", shipRoot); + var geometry = new Geometry(this, layout.Room.transform); + float y = BridgeHeight; + float x = BridgeCenter; + float extent = beam * .65f; + geometry.Box(2, new Vector3(x, y, 0), new Vector3(8.8f, .18f, extent * 2)); + geometry.Box(4, new Vector3(x + 3.5f, y + .46f, 0), new Vector3(.30f, .88f, extent * 2)); + geometry.Box(1, new Vector3(x + 3.5f, y + 2.62f, 0), new Vector3(.28f, .33f, extent * 2)); + geometry.Box(1, new Vector3(x, y + 2.85f, 0), new Vector3(8.9f, .26f, extent * 2)); + geometry.Box(4, new Vector3(x - 4.15f, y + 1.45f, 0), new Vector3(.25f, 2.9f, extent * 2)); + for (int i = -2; i <= 2; i++) + { + float z = i * extent * .48f; + geometry.Mesh(1).Rod(new Vector3(x + 3.56f, y + .78f, z), new Vector3(x + 3.18f, y + 2.52f, z), .088f, 6); + } + + for (int side = -1; side <= 1; side += 2) + { + float z = side * extent; + geometry.Box(4, new Vector3(x, y + .48f, z), new Vector3(8.8f, .95f, .28f)); + for (int i = -1; i <= 1; i++) + geometry.Box(1, new Vector3(x + i * 3.4f, y + 1.8f, z), new Vector3(.15f, 1.75f, .18f)); + } + for (int column = -1; column <= 1; column++) + { + float z = column * extent * .57f; + geometry.Box(4, new Vector3(x + 1.8f, y + .54f, z), new Vector3(1.02f, 1.03f, 1.96f)); + geometry.Box(10, new Vector3(x + 1.76f, y + 1.16f, z), new Vector3(.85f, .26f, 2.1f)); + geometry.Box(15, new Vector3(x + 1.45f, y + 1.36f, z + .42f), new Vector3(.13f, .41f, .63f)); + geometry.Box(12, new Vector3(x + 1.37f, y + 1.37f, z + .42f), new Vector3(.02f, .26f, .46f)); + for (int button = 0; button < 4; button++) + geometry.Box(button == 2 ? 13 : 12, new Vector3(x + 1.54f, y + 1.31f, z - .55f + button * .14f), new Vector3(.11f, .035f, .10f)); + Chair(geometry, new Vector3(x + .6f, y, z), 10); + } + Vector3 fore = new(length * .355f, y - .28f, 0); + geometry.Mesh(2).Loft(new[] + { + new Vector2(fore.x - 8, -beam * .70f), new Vector2(fore.x + length * .11f, 0), + new Vector2(fore.x - 8, beam * .70f) + }, new Vector2(fore.x - 2f, 0), true, new Vector3(1f, y - .4f, 1f), new Vector3(1, y - .28f, 1f)); + geometry.Finish(); + return layout; + } + + private float BridgeCenter => length * (.190f - ship.Decks.Count * .014f); + + private void BuildPeopleMeshes() + { + var body = new HarborMesh(); + body.Rod(new Vector3(0, .54f, 0), new Vector3(0, 1.15f, 0), .20f, 7); + body.Rod(new Vector3(-.094f, .05f, .025f), new Vector3(-.090f, .57f, 0), .074f, 6); + body.Rod(new Vector3(.094f, .045f, -.035f), new Vector3(.090f, .57f, 0), .074f, 6); + body.Rod(new Vector3(-.28f, .71f, .07f), new Vector3(-.16f, 1.08f, 0), .066f, 6); + body.Rod(new Vector3(.28f, .76f, .13f), new Vector3(.16f, 1.08f, 0), .066f, 6); + var face = new HarborMesh(); + face.Radome(new Vector3(0, 1.29f, .025f), .151f); + clothes = Bake(body); + head = Bake(face); + } + + private void AddPerson(Layout layout, Vector3 position, int service, int slot, int seed, float travel, bool seated, float yaw = 0) + { + GameObject person = Piece(service < 0 ? "Walking passenger" : OnboardSession.ServiceLabel((OnboardService)service), layout.Crowd.transform); + person.transform.localPosition = position; + person.transform.localScale = new Vector3(1, seated ? .74f : 1, 1) * (1f + seed % 3 * .045f); + RenderMesh("Outfit", person.transform, clothes, MaterialFor(19 + seed % 6)); + RenderMesh("Head", person.transform, head, MaterialFor(16 + seed % 3)); + layout.People.Add(new Passenger { Body = person.transform, Position = position, Phase = seed * 1.37f, Slot = slot, + Service = service, Travel = travel, Yaw = yaw, Seated = seated }); + person.SetActive(false); + } + + private static void Chair(Geometry shape, Vector3 at, int color) + { + shape.Box(color, at + new Vector3(0, .39f, 0), new Vector3(.42f, .12f, .39f)); + shape.Box(4, at + new Vector3(0, .19f, 0), new Vector3(.12f, .35f, .12f)); + } + + private Vector2[] Outline(float size, float width) + { + int steps = 22; + var points = new Vector2[steps * 2 + 2]; + for (int i = 0; i <= steps; i++) + { + float t = i / (float)steps; + float x = (t - .5f) * length * size; + float shape = t < .20f ? Mathf.Lerp(.66f, 1, 1f - Mathf.Pow(1f - t / .20f, 2)) + : t > .69f ? Mathf.Sqrt(Mathf.Clamp01(1f - Mathf.Pow((t - .69f) / .31f, 1.72f))) : 1f; + float z = Mathf.Max(.012f, width * shape); + points[i] = new Vector2(x, -z); + points[points.Length - 1 - i] = new Vector2(x, z); + } + return points; + } + + private Material MaterialFor(int id) + { + if (paint.TryGetValue(id, out Material material)) + return material; + ColorUtility.TryParseHtmlString("#" + Paint[id], out Color color); + material = new Material(shader) { color = color, name = "Deck fittings " + Paint[id] }; + material.SetFloat("_Roughness", .77f); + material.SetFloat("_Metal", id == 4 ? .4f : .03f); + material.SetFloat("_Emissive", id is 12 or 15 ? .24f : .025f); + paint.Add(id, material); + return material; + } + + private Mesh Bake(HarborMesh shape) + { + Mesh mesh = shape.Bake(); + meshes.Add(mesh); + return mesh; + } + + private static GameObject Piece(string name, Transform parent) + { + var result = new GameObject(name) { layer = 8 }; + result.transform.SetParent(parent, false); + return result; + } + + private static void RenderMesh(string name, Transform parent, Mesh mesh, Material material) + { + GameObject result = Piece(name, parent); + result.AddComponent().sharedMesh = mesh; + result.AddComponent().sharedMaterial = material; + } + + public void Dispose() + { + foreach (Mesh mesh in meshes) + UnityEngine.Object.Destroy(mesh); + foreach (Material material in paint.Values) + UnityEngine.Object.Destroy(material); + } + + private sealed class Geometry + { + private readonly Dictionary shapes = new(); + private readonly DeckPassengers owner; + private readonly Transform parent; + + public Geometry(DeckPassengers owner, Transform parent) + { + this.owner = owner; + this.parent = parent; + } + + public HarborMesh Mesh(int color) + { + if (!shapes.TryGetValue(color, out HarborMesh shape)) + shapes.Add(color, shape = new HarborMesh()); + return shape; + } + + public void Box(int color, Vector3 center, Vector3 size) => Mesh(color).Box(center, size); + + public void Finish() + { + foreach (var (color, shape) in shapes) + RenderMesh("Deck structure", parent, owner.Bake(shape), owner.MaterialFor(color)); + } + } + } +} diff --git a/Assets/Soundings/Runtime/DeckPassengers.cs.meta b/Assets/Soundings/Runtime/DeckPassengers.cs.meta new file mode 100644 index 0000000..51f02c2 --- /dev/null +++ b/Assets/Soundings/Runtime/DeckPassengers.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3998745d9bf0ce529afc60cc4577979b \ No newline at end of file diff --git a/Assets/Soundings/Runtime/FirstVoyageGuide.cs b/Assets/Soundings/Runtime/FirstVoyageGuide.cs index e17ef45..95167b0 100644 --- a/Assets/Soundings/Runtime/FirstVoyageGuide.cs +++ b/Assets/Soundings/Runtime/FirstVoyageGuide.cs @@ -7,7 +7,7 @@ namespace Soundings { private enum GuideStep { - Off, GetShip, Cabins, Dining, SetCourse, Bunker, Fare, CastOff, Review + Off, GetShip, Cabins, Dining, SetCourse, Bunker, Fare, CastOff, Review, AtSea } private const int StarterCabinModules = 4; @@ -40,8 +40,13 @@ namespace Soundings private void RefreshGuide() { guideContext = GuideStep.Off; - if (title || company == null || company.TutorialStep == 0 || underway != null) + if (title || company == null || company.TutorialStep == 0) return; + if (underway != null) + { + guideContext = GuideStep.AtSea; + return; + } Ship ship = Ship; if (guideFareShip != ship) @@ -148,7 +153,14 @@ namespace Soundings return ("Read the arrival statement", "Open the Logbook to see your voyage profit and cash change.", "nav-4"); if (ledgerAccounts) return ("Read the arrival statement", "Switch to Voyage records to review your latest crossing.", "log-voyages"); - return ("Check the passage", "Compare net profit and cash change. You can refit the ship in Deck Plans.", "voyage-0"); + return ("Check the passage", "Check the voyage profit and guest survey. You can refit the ship in Deck Plans.", "voyage-0"); + + case GuideStep.AtSea: + if (passageServiceArea >= 0) + return ("Run the service deck", "Inspect each station. You can switch between Assisted and Manual operations here.", "service-assist"); + if (passageBridge || passageExploring) + return ("Walk the ship", "Move with WASD and hold the right mouse button to look. Exterior returns to the ship view.", null); + return ("Make the crossing count", "Set onboard prices, offer specials, and watch for events. Choose Bridge or a deck view to look around.", "passage-business"); default: return GuideCourse(); @@ -159,6 +171,8 @@ namespace Soundings { if (page != 1) return (heading, "Open Deck Plans to lay out your ship.", "nav-1"); + if (systemTools) + return (heading, "Open Guest facilities to fit cabins and dining.", "facility-guests"); string facilityName = Market.Facilities[(int)facility].Name; if (tool != facility) diff --git a/Assets/Soundings/Runtime/Harbor.cs b/Assets/Soundings/Runtime/Harbor.cs index f50e5de..0578d70 100644 --- a/Assets/Soundings/Runtime/Harbor.cs +++ b/Assets/Soundings/Runtime/Harbor.cs @@ -24,6 +24,18 @@ namespace Soundings private float passage; private bool sailing; private Bounds hullBounds; + private DeckPassengers decks; + private Transform exteriorRoot; + private Ship displayedShip; + private ServiceDeckModel serviceDeck; + private int deckIndex = -1, serviceArea; + private float vesselBeam = 6.65f; + private CameraMode cameraMode; + private float freeYaw, freePitch, freeFov = 47f; + private Vector3 freePosition; + private float walkHeight; + + private enum CameraMode { Orbit, Flight, DeckWalk, Bridge, Service } public RenderTexture Frame { get; private set; } @@ -61,20 +73,44 @@ namespace Soundings public void Orbit(Vector2 drag) { - targetYaw = Mathf.Clamp(targetYaw - drag.x * .18f, 3f, 72f); - targetPitch = Mathf.Clamp(targetPitch + drag.y * .13f, 12f, 30f); + if (cameraMode != CameraMode.Orbit) + return; + targetYaw = sailing ? (targetYaw - drag.x * .18f) : Mathf.Clamp(targetYaw - drag.x * .18f, 3f, 72f); + targetPitch = Mathf.Clamp(targetPitch + drag.y * .13f, 12f, deckIndex >= 0 ? 78f : 48f); } public void Zoom(float delta) { - targetZoom = Mathf.Clamp(targetZoom * Mathf.Exp(delta * .050f), .64f, 1.51f); + if (cameraMode != CameraMode.Orbit) + { + freeFov = Mathf.Clamp(freeFov * Mathf.Exp(delta * .035f), 25f, 78f); + return; + } + targetZoom = Mathf.Clamp(targetZoom * Mathf.Exp(delta * .050f), sailing ? .17f : .64f, 1.51f); } public void ResetView(bool immediate = false) { - targetYaw = DefaultYaw; - targetPitch = DefaultPitch; - targetZoom = 1f; + if (cameraMode == CameraMode.Bridge) + { + ViewBridge(); + return; + } + if (cameraMode == CameraMode.Service) + { + ExploreServiceArea(serviceArea); + return; + } + ResetOrbit(immediate); + } + + private void ResetOrbit(bool immediate) + { + cameraMode = CameraMode.Orbit; + viewCamera.orthographic = true; + targetYaw = deckIndex >= 0 ? 17f : DefaultYaw; + targetPitch = deckIndex >= 0 ? 55f : DefaultPitch; + targetZoom = deckIndex >= 0 ? .92f : 1f; if (!immediate) return; yaw = targetYaw; @@ -83,14 +119,152 @@ namespace Soundings ComposeCamera(); } + public void Look(Vector2 drag) + { + if (!sailing || drag.sqrMagnitude < .0001f) + return; + if (cameraMode == CameraMode.Orbit) + EnterFlight(); + freeYaw = Mathf.Repeat(freeYaw + drag.x * .22f, 360f); + freePitch = Mathf.Clamp(freePitch + drag.y * .19f, -80f, 84f); + } + + public void Fly(Vector3 input, float delta, bool boost) + { + if (!sailing || input.sqrMagnitude < .0001f || delta <= 0) + return; + if (cameraMode == CameraMode.Orbit) + EnterFlight(); + input = Vector3.ClampMagnitude(input, 1f); + bool interior = cameraMode is CameraMode.DeckWalk or CameraMode.Bridge or CameraMode.Service; + Quaternion heading = Quaternion.Euler(interior ? 0 : freePitch, freeYaw, 0); + Vector3 movement = heading * new Vector3(input.x, 0, input.z); + if (!interior) + movement += Vector3.up * input.y; + float speed = interior ? (boost ? 6.4f : 3.3f) : (boost ? 52f : 20f); + freePosition += movement * (speed * Mathf.Min(.10f, delta)); + if (cameraMode == CameraMode.DeckWalk) + { + freePosition.x = Mathf.Clamp(freePosition.x, -vesselLength * .38f, vesselLength * .31f); + freePosition.z = Mathf.Clamp(freePosition.z, -vesselBeam * .77f, vesselBeam * .77f); + freePosition.y = walkHeight; + } + else if (cameraMode == CameraMode.Bridge) + { + freePosition = decks.ClampBridgePosition(freePosition); + } + else if (cameraMode == CameraMode.Service) + { + freePosition.x = Mathf.Clamp(freePosition.x, -vesselLength * .358f, vesselLength * .358f); + freePosition.z = Mathf.Clamp(freePosition.z, -vesselBeam * .79f, vesselBeam * .79f); + freePosition.y = walkHeight; + } + else + { + Vector3 origin = vessel != null ? vessel.position : Vector3.zero; + freePosition.x = Mathf.Clamp(freePosition.x, origin.x - 235, origin.x + 235); + freePosition.y = Mathf.Clamp(freePosition.y, 1.4f, 150f); + freePosition.z = Mathf.Clamp(freePosition.z, origin.z - 180, origin.z + 180); + } + } + + private void EnterFlight() + { + cameraMode = CameraMode.Flight; + freeFov = 47f; + Vector3 angles = viewCamera.transform.eulerAngles; + freeYaw = angles.y; + freePitch = Mathf.DeltaAngle(0f, angles.x); + float distance = viewCamera.orthographicSize / Mathf.Tan(freeFov * .5f * Mathf.Deg2Rad); + freePosition = OrbitFocus() - viewCamera.transform.forward * distance; + freePosition.y = Mathf.Max(1.4f, freePosition.y); + viewCamera.orthographic = false; + } + + public void ShowDeck(int index) + { + if (displayedShip == null || index < -1 || index >= displayedShip.Decks.Count || (index == deckIndex && cameraMode == CameraMode.Orbit)) + return; + + deckIndex = index; + if (serviceDeck != null) + serviceDeck.Root.SetActive(false); + exteriorRoot.gameObject.SetActive(index < 0); + decks.Select(index); + ResetOrbit(true); + } + + public void ExploreDeck(int index) + { + if (!sailing || displayedShip == null || index < 0 || index >= displayedShip.Decks.Count) + return; + ShowDeck(index); + cameraMode = CameraMode.DeckWalk; + freeFov = 62f; + freePitch = 1.8f; + freeYaw = 90f; + freePosition = decks.WalkOrigin(index); + walkHeight = freePosition.y; + viewCamera.orthographic = false; + ComposeCamera(); + } + + public void ViewBridge() + { + if (!sailing || decks == null) + return; + if (serviceDeck != null) + serviceDeck.Root.SetActive(false); + deckIndex = -1; + cameraMode = CameraMode.Bridge; + exteriorRoot.gameObject.SetActive(false); + decks.SelectBridge(); + freeFov = 68f; + freePitch = 1.3f; + freeYaw = 90f; + freePosition = decks.BridgeOrigin(); + viewCamera.orthographic = false; + ComposeCamera(); + } + + public void ExploreServiceArea(int area) + { + if (!sailing || vessel == null || area < 0 || area > 5) + return; + if (serviceDeck == null) + serviceDeck = new ServiceDeckModel(vessel, vesselLength, vesselBeam, surface); + deckIndex = -1; + serviceArea = area; + cameraMode = CameraMode.Service; + exteriorRoot.gameObject.SetActive(false); + decks.HideRooms(); + serviceDeck.Root.SetActive(true); + freeFov = 66f; + freePitch = 2f; + freeYaw = serviceDeck.Heading(area); + freePosition = serviceDeck.Entry(area); + walkHeight = freePosition.y; + viewCamera.orthographic = false; + ComposeCamera(); + } + + public void UpdatePassengers(OnboardSession session, float delta) + { + if (sailing && decks != null && cameraMode != CameraMode.Service) + decks.Tick(session, delta); + } + public bool IsShipAt(Vector2 viewportPoint) { return vessel != null && hullBounds.IntersectRay(viewCamera.ViewportPointToRay(viewportPoint)); } - public void BeginPassage() + public void BeginPassage(WeatherCondition weather = WeatherCondition.Calm) { sailing = true; + water.SetFloat("_WeatherSeverity", (int)weather / 2f); + cameraMode = CameraMode.Orbit; + viewCamera.orthographic = true; targetYaw = 22f; targetPitch = 16f; targetZoom = 1.02f; @@ -119,6 +293,9 @@ namespace Soundings hull.z = 0; water.SetVector("_HullSpan", hull); water.SetFloat("_Underway", 0); + water.SetFloat("_WeatherSeverity", 0); + ShowDeck(-1); + decks?.HidePassengers(); ResetView(true); } @@ -126,6 +303,11 @@ namespace Soundings { if (!viewCamera.enabled) return; + if (cameraMode != CameraMode.Orbit) + { + ComposeCamera(); + return; + } float easing = 1 - Mathf.Exp(-Time.unscaledDeltaTime * 11f); if (!sailing && Mathf.Abs(yaw - targetYaw) < .005f && Mathf.Abs(pitch - targetPitch) < .005f && Mathf.Abs(zoom - targetZoom) < .0001f) @@ -136,13 +318,33 @@ namespace Soundings ComposeCamera(); } - private void ComposeCamera() + private Vector3 OrbitFocus() { - var center = new Vector3(2.1f, 4.25f, 0); + float level = deckIndex >= 0 && decks != null ? decks.FloorHeight(deckIndex) + .5f : 4.25f; + var center = new Vector3(deckIndex >= 0 ? -2f : 2.1f, level, 0); if (sailing) center.x += Mathf.Lerp(-2, 6.5f, passage); - Quaternion orbit = Quaternion.Euler(pitch, -yaw, 0); - viewCamera.transform.SetPositionAndRotation(center + orbit * (Vector3.back * 244f), orbit); + return center; + } + + private void ComposeCamera() + { + if (cameraMode == CameraMode.Orbit) + { + viewCamera.orthographic = true; + viewCamera.nearClipPlane = .25f; + Quaternion orbit = Quaternion.Euler(pitch, -yaw, 0); + viewCamera.transform.SetPositionAndRotation(OrbitFocus() + orbit * (Vector3.back * 244f), orbit); + } + else + { + viewCamera.orthographic = false; + viewCamera.nearClipPlane = .095f; + viewCamera.fieldOfView = freeFov; + Vector3 placement = cameraMode is CameraMode.Bridge or CameraMode.DeckWalk or CameraMode.Service + ? vessel.TransformPoint(freePosition) : freePosition; + viewCamera.transform.SetPositionAndRotation(placement, Quaternion.Euler(freePitch, freeYaw, 0)); + } FitViewport(); } @@ -190,8 +392,10 @@ namespace Soundings return; float cropX = Mathf.Min(1, aspect / backplateRatio) * .95f; float cropY = Mathf.Min(1, backplateRatio / aspect) * .95f; - float shiftX = Mathf.Clamp((yaw - DefaultYaw) * .00225f, -.47f * (1 - cropX), .47f * (1 - cropX)); - float shiftY = Mathf.Clamp((pitch - DefaultPitch) * .002f, -.47f * (1 - cropY), .47f * (1 - cropY)); + float panoramaYaw = cameraMode == CameraMode.Orbit ? Mathf.DeltaAngle(DefaultYaw, yaw) : Mathf.DeltaAngle(-DefaultYaw, freeYaw); + float shiftX = Mathf.Clamp(panoramaYaw * .00225f, -.47f * (1 - cropX), .47f * (1 - cropX)); + float panoramaPitch = cameraMode == CameraMode.Orbit ? pitch : freePitch; + float shiftY = Mathf.Clamp((panoramaPitch - DefaultPitch) * .002f, -.47f * (1 - cropY), .47f * (1 - cropY)); water.SetVector("_BackdropCrop", new Vector4(cropX, cropY, shiftX, shiftY)); } @@ -208,6 +412,7 @@ namespace Soundings return; } + displayedShip = ship; int hullIndex = ship.HullIndex; int deckCount = ship.Decks.Count; ulong layout = 0; @@ -222,12 +427,15 @@ namespace Soundings lastDecks = deckCount; lastLayout = layout; ReleaseShip(); + displayedShip = ship; var root = new GameObject("Cruise vessel"); vessel = root.transform; vessel.SetParent(transform, false); + exteriorRoot = new GameObject("Exterior").transform; + exteriorRoot.SetParent(vessel, false); vesselLength = 71 + hullIndex * 12; - float beam = 6.65f + hullIndex * .87f; + float beam = vesselBeam = 6.65f + hullIndex * .87f; water.SetVector("_HullSpan", new Vector4(vesselLength, beam, 0, 0)); hullBounds = new Bounds(new Vector3(0, 5.5f, 0), new Vector3(vesselLength, 12.3f + deckCount * 1.7f, beam * 2.1f)); FitViewport(); @@ -241,13 +449,24 @@ namespace Soundings Batch(mesh, finish); Batch(mesh, reflected); } + decks = new DeckPassengers(vessel, ship, vesselLength, beam, surface); + if (deckIndex >= 0 && deckIndex < ship.Decks.Count) + { + exteriorRoot.gameObject.SetActive(false); + decks.Select(deckIndex); + } + else + { + deckIndex = -1; + decks.Select(-1); + } } private void Batch(Mesh mesh, Material material) { var draw = new GameObject(material.name, typeof(MeshFilter), typeof(MeshRenderer)); draw.layer = 8; - draw.transform.SetParent(vessel, false); + draw.transform.SetParent(exteriorRoot, false); draw.GetComponent().sharedMesh = mesh; draw.GetComponent().sharedMaterial = material; } @@ -297,6 +516,11 @@ namespace Soundings private void ReleaseShip() { + decks?.Dispose(); + decks = null; + serviceDeck?.Release(); + serviceDeck = null; + displayedShip = null; if (vessel != null) { vessel.gameObject.SetActive(false); diff --git a/Assets/Soundings/Runtime/LedgerPage.cs b/Assets/Soundings/Runtime/LedgerPage.cs index 8abb541..33c2ec4 100644 --- a/Assets/Soundings/Runtime/LedgerPage.cs +++ b/Assets/Soundings/Runtime/LedgerPage.cs @@ -136,10 +136,17 @@ namespace Soundings AddDisplay(leaf, $"{origin} to {destinationName}", "log-sheet-title log-route-title"); AddText(leaf, $"{trip.ShipName} · {trip.Miles:N0} nm over {trip.Days} days", "log-secondary"); AddText(leaf, $"{trip.Guests:N0} passengers · {trip.FuelBurn:N0} t of fuel consumed", "log-secondary"); + if (trip.Onboard != null) + { + AddText(leaf, $"Guest survey {trip.Onboard.Happiness}/100 · Health {trip.Onboard.Health}/100 · {trip.Weather} seas", "log-note"); + AddText(leaf, $"{trip.Onboard.Provisions:N0} portions left · {trip.Onboard.WaterPercent}% freshwater · {trip.Onboard.SewagePercent}% treatment load", "log-secondary"); + } var statement = Add(leaf, "log-statement"); LogLine(statement, "Ticket revenue", Money(trip.TicketSales)); LogLine(statement, "Onboard revenue", Money(trip.OnboardSales)); + if (trip.Onboard?.Expenses > 0) + LogLine(statement, "Onboard operating costs", Money(-trip.Onboard.Expenses)); LogLine(statement, "Crew and catering", Money(-trip.Crew - trip.Catering)); LogLine(statement, "Port dues", Money(-trip.PortFees)); LogLine(statement, "Fuel expense", Money(-trip.FuelExpense)); diff --git a/Assets/Soundings/Runtime/Market.cs b/Assets/Soundings/Runtime/Market.cs index 2461144..a7d4514 100644 --- a/Assets/Soundings/Runtime/Market.cs +++ b/Assets/Soundings/Runtime/Market.cs @@ -3,7 +3,9 @@ using System.Collections.Generic; namespace Soundings { - public enum Facility { Empty, Cabin, Dining, Entertainment, Tank } + public enum WeatherCondition { Calm, Swell, Storm } + + public enum Facility { Empty, Cabin, Dining, Entertainment, Tank, Bar, Amenity, Galley, Stores, Water, Waste, Workshop } public sealed class FacilitySpec { @@ -103,7 +105,14 @@ namespace Soundings new FacilitySpec("Cabins", "CB", "32 guest berths", 8400, 32), new FacilitySpec("Dining hall", "DH", "48 seats · 3 services", 11800, 48), new FacilitySpec("Show lounge", "SL", "80 seats · improves demand", 15400, 80), - new FacilitySpec("Bunker tank", "BT", "+65 t of fuel capacity", 14200, 65) + new FacilitySpec("Bunker tank", "BT", "+65 t of fuel capacity", 14200, 65), + new FacilitySpec("Bar", "BR", "72 drink orders per service", 14800, 72), + new FacilitySpec("Pool terrace", "PT", "64 amenity admissions per service", 18600, 64), + new FacilitySpec("Galley", "GY", "+96 meals per service window", 22100, 96), + new FacilitySpec("Stores", "ST", "+900 meal portions of storage", 17600, 900), + new FacilitySpec("Water plant", "WP", "+14,000 L storage and +6,000 L/day output", 25400, 14000), + new FacilitySpec("Sewage", "SW", "+10,000 L buffer and +7,000 L/day treatment", 19800, 10000), + new FacilitySpec("Workshop", "WS", "Increases the benefit of onboard servicing", 18700, 2) }; public static readonly IReadOnlyList Hulls = new[] diff --git a/Assets/Soundings/Runtime/OnboardEconomy.cs b/Assets/Soundings/Runtime/OnboardEconomy.cs new file mode 100644 index 0000000..f14a387 --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardEconomy.cs @@ -0,0 +1,247 @@ +using System; + +namespace Soundings +{ + public enum OnboardService { Rooms, Meals, Drinks, Shows, Amenities } + + [Serializable] + public sealed class OnboardReport + { + public int Happiness, Health, Revenue, Expenses, Decisions, FuelBurn, Repair, Provisions, WaterPercent, SewagePercent; + public int[] ServiceSales; + } + + public readonly struct OnboardSample + { + public readonly int Requested, Served, Capacity, Revenue; + public OnboardSample(int requested, int served, int capacity, int revenue) + { + Requested = requested; + Served = served; + Capacity = capacity; + Revenue = revenue; + } + } + + public readonly struct VoyageEvent + { + public readonly string Title, Detail, Action, Alternative; + public readonly int Cost; + internal readonly int Service, Surge; + public VoyageEvent(string title, string detail, string action, string alternative, int cost, int service, int surge) + { + Title = title; + Detail = detail; + Action = action; + Alternative = alternative; + Cost = cost; + Service = service; + Surge = surge; + } + } + + public sealed partial class OnboardSession + { + private const int ServiceKinds = 5; + private const int PromotionTicks = 5; + private static readonly int[] Defaults = { 0, 12, 7, 18, 10 }; + private static readonly double[] BaseDemand = { 0, .71, .59, .43, .51 }; + private static readonly VoyageEvent[] Events = + { + new VoyageEvent("Dinner rush", "An early seating is filling up. Open overflow tables to expand meal capacity and lift the survey.", + "Open overflow service", "Keep the schedule", 650, 1, 40), + new VoyageEvent("Sunset crowd", "Guests want a sunset program. Run an extra set on deck to provide more show places.", + "Book an encore", "Use the regular program", 950, 3, 65) + }; + + private static readonly VoyageEvent[] StormEvents = + { + new VoyageEvent("Outdoor decks closed", "Passengers have moved indoors. Add an indoor set to open extra show places.", + "Book an indoor set", "Keep the schedule", 1050, 3, 84), + new VoyageEvent("Lounge queues", "The lounges are still busy. Set up a temporary drinks station to ease the queues.", + "Open another station", "Use the regular bars", 760, 2, 54) + }; + + public readonly Ship Ship; + public readonly Voyage Quote; + private readonly int ticks; + private readonly int[] revenue = new int[ServiceKinds]; + private readonly int[] saleUntil = new int[ServiceKinds]; + private readonly int[] capacity = new int[ServiceKinds]; + private readonly OnboardSample[] sample = new OnboardSample[ServiceKinds]; + private readonly int[] prices; + + private int tick, nextEvent, openedAt = -1, eventBenefitUntil, featuredService = -1, additionalCapacity, decisions; + private double satisfaction = 82; + public int Happiness => (int)Math.Round(satisfaction); + public int Revenue { get; private set; } + public int Expenses { get; private set; } + public float Progress => (float)tick / ticks; + public VoyageEvent? CurrentEvent => openedAt < 0 ? null : + (Quote.Weather == WeatherCondition.Storm ? StormEvents : Events)[nextEvent]; + public string EventResult { get; private set; } + public int RemainingEventTicks => openedAt < 0 ? 0 : Math.Max(0, openedAt + 6 - tick); + public bool CanAcceptEvent => CurrentEvent.HasValue && CanBuyEvent(CurrentEvent.Value); + private bool CanBuyEvent(VoyageEvent offer) => Expenses + offer.Cost <= Quote.TicketSales / 4; + + public OnboardSession(Ship ship, Voyage quote) + { + Ship = ship; + Quote = quote; + ticks = Math.Max(24, quote.Days * 8); + capacity[0] = ship.Beds; + capacity[1] = ship.Meals; + capacity[2] = ship.Count(Facility.Bar) * Market.Facilities[(int)Facility.Bar].Capacity; + capacity[3] = ship.Entertainment; + int outdoor = ship.Count(Facility.Amenity) * Market.Facilities[(int)Facility.Amenity].Capacity; + capacity[4] = quote.Weather switch { WeatherCondition.Storm => 0, WeatherCondition.Swell => outdoor * 2 / 3, _ => outdoor }; + + prices = (int[])(ship.ServicePrices?.Length == ServiceKinds ? ship.ServicePrices : Defaults).Clone(); + for (int i = 0; i < ServiceKinds; i++) + prices[i] = Market.Clamp(prices[i], 0, Defaults[i] * 4); + InitializeSystems(); + Measure(false); + } + + public static string ServiceLabel(OnboardService service) => service switch + { + OnboardService.Rooms => "Rooms", + OnboardService.Meals => "Meals", + OnboardService.Drinks => "Drinks", + OnboardService.Shows => "Entertainment", + _ => "Amenities" + }; + + public OnboardSample Get(OnboardService service) => sample[(int)service]; + + public int GetPrice(OnboardService service) => prices[(int)service]; + + internal void SavePrices() => Ship.ServicePrices = (int[])prices.Clone(); + + public int EffectivePrice(OnboardService service) + { + int price = GetPrice(service); + return price > 0 && DiscountTicks(service) > 0 ? Math.Max(1, price * 3 / 4) : price; + } + + public int DiscountTicks(OnboardService service) => Math.Max(0, saleUntil[(int)service] - tick); + + public void ChangePrice(OnboardService service, int amount) + { + int index = (int)service; + if (index == 0 || Progress >= 1) + return; + prices[index] = Market.Clamp(prices[index] + amount, 0, Defaults[index] * 4); + Measure(false); + } + + public bool StartSpecial(OnboardService service) + { + int index = (int)service; + if (index == 0 || GetPrice(service) <= 0 || capacity[index] <= 0 || DiscountTicks(service) > 0 || tick >= ticks) + return false; + saleUntil[index] = tick + PromotionTicks; + Measure(false); + return true; + } + + public void ResolveEvent(bool accept) + { + if (!CurrentEvent.HasValue || (accept && !CanAcceptEvent)) + return; + VoyageEvent offer = CurrentEvent.Value; + if (accept) + { + Expenses += offer.Cost; + featuredService = offer.Service; + additionalCapacity = offer.Surge; + eventBenefitUntil = tick + 8; + satisfaction = Math.Min(100, satisfaction + 5); + EventResult = offer.Action + " booked."; + } + else + { + satisfaction = Math.Max(0, satisfaction - 2); + EventResult = offer.Alternative + "."; + } + decisions++; + openedAt = -1; + nextEvent++; + Measure(false); + } + + public void AdvanceTo(float progress) + { + int goal = Market.Clamp((int)Math.Floor(progress * ticks + .0001), tick, ticks); + while (tick < goal) + { + tick++; + AdvanceSystems(); + if (openedAt >= 0 && tick >= openedAt + 6) + ResolveEvent(false); + if (openedAt < 0 && nextEvent < Events.Length && tick >= ticks * (nextEvent == 0 ? .23 : .59)) + openedAt = tick; + Measure(true); + } + if (tick >= ticks && openedAt >= 0) + ResolveEvent(false); + } + + public OnboardReport Report() => new OnboardReport + { + Happiness = Happiness, + Health = Health, + FuelBurn = ProjectedFuelBurn, + Repair = RepairCredit, + Provisions = ProvisionsRemaining, + WaterPercent = WaterPercent, + SewagePercent = SewagePercent, + Revenue = Revenue, + Expenses = Expenses, + Decisions = decisions, + ServiceSales = (int[])revenue.Clone() + }; + + private void Measure(bool collect) + { + sample[0] = new OnboardSample(Math.Max(Quote.Guests, Quote.RoomDemand), Quote.Guests, capacity[0], 0); + double fulfillment = 1; + double mealFulfillment = 1; + for (int i = 1; i < ServiceKinds; i++) + { + int price = EffectivePrice((OnboardService)i); + double wave = .76 + .48 * (.5 + .5 * Math.Sin((tick + i * 2.1) * .66)); + double appeal = Math.Max(.23, Math.Min(1.6, (Defaults[i] + 5.0) / (price + 5.0))); + bool featured = featuredService == i && tick <= eventBenefitUntil; + VoyageEvent? notice = CurrentEvent; + int rush = notice.HasValue && notice.Value.Service == i ? notice.Value.Surge : featured ? additionalCapacity / 2 : 0; + double indoorShift = Quote.Weather == WeatherCondition.Storm && (i == 2 || i == 3) ? 1.28 : 1; + int requested = Math.Min(Quote.Guests, rush + (int)Math.Round(Quote.Guests * BaseDemand[i] * appeal * wave * indoorShift)); + int possible = ServiceCapacity(i, capacity[i] + (featured ? additionalCapacity : 0)); + int served = Math.Min(requested, possible); + + if (collect) + { + int takings = (int)Math.Round(served * price * (i == 1 ? .17 : .13)); + revenue[i] += takings; + Revenue += takings; + } + if (i == (int)OnboardService.Meals) + { + mealFulfillment = requested == 0 ? 1 : (double)served / requested; + if (collect) + provisions = Math.Max(0, provisions - served * PortionPerMeal); + } + sample[i] = new OnboardSample(requested, served, possible, revenue[i]); + double affordability = price <= Defaults[i] ? 1 : .43 + .57 * Defaults[i] / price; + fulfillment += (requested == 0 ? 1 : (double)served / requested) * affordability; + } + if (collect) + { + UpdateHealth(mealFulfillment); + double target = 40 + 55 * fulfillment / ServiceKinds - (100 - health) * .28; + satisfaction = satisfaction * .77 + target * .23; + } + } + } +} diff --git a/Assets/Soundings/Runtime/OnboardEconomy.cs.meta b/Assets/Soundings/Runtime/OnboardEconomy.cs.meta new file mode 100644 index 0000000..337929f --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardEconomy.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9fa7b9054962f45139ed8cfe9a7d97d9 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/OnboardSystems.cs b/Assets/Soundings/Runtime/OnboardSystems.cs new file mode 100644 index 0000000..647cf15 --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardSystems.cs @@ -0,0 +1,143 @@ +using System; + +namespace Soundings +{ + public sealed partial class OnboardSession + { + private const double PortionPerMeal = .26; + private static readonly double[] FuelRates = { .78, 1, 1.22 }; + private static readonly float[] ShipSpeeds = { .82f, 1, 1.22f }; + private double provisions, water, waste, fuelIntegrated, health = 99, hydration = 1; + private int galleyUntil, pumpsUntil, treatmentUntil; + public bool Assisted { get; set; } = true; + public int EngineMode { get; private set; } = 1; + public float SpeedFactor => ShipSpeeds[EngineMode]; + public int Health => (int)Math.Round(health); + public int WaterPercent => (int)Math.Round(100 * water / Ship.WaterCapacity); + public int SewagePercent => (int)Math.Round(100 * waste / Ship.WasteCapacity); + public int ProvisionsRemaining => (int)Math.Floor(provisions); + public int RepairCredit { get; private set; } + public bool StoresOpened { get; private set; } + public int ProjectedFuelBurn => FuelForMode(EngineMode); + public bool GalleyBoost => galleyUntil > tick; + public bool PumpsBoost => pumpsUntil > tick; + public bool TreatmentBoost => treatmentUntil > tick; + public int GalleyCost => 420 + Quote.Guests * 2; + public int StoreCost => 180 + Quote.Guests * 3; + public int PumpCost => 410; + public int TreatmentCost => 360; + public int RepairCost => 780 + Ship.HullIndex * 490; + public bool CanOpenStores => !StoresOpened && provisions < Ship.FoodCapacity * .85 && CanSpend(StoreCost); + + public bool CanSpend(int cost) => tick < ticks && Expenses + cost <= Quote.TicketSales / 4; + + public bool CanSetEngineMode(int mode) => + mode >= 0 && mode < FuelRates.Length && (mode < 2 || FuelForMode(mode) + Quote.Reserve <= Ship.Fuel); + + public void SetEngineMode(int mode) + { + if (CanSetEngineMode(mode)) + EngineMode = mode; + } + + public void OpenStores() + { + if (!CanOpenStores) + return; + Expenses += StoreCost; + StoresOpened = true; + provisions = Math.Min(Ship.FoodCapacity, provisions + Math.Max(225, Quote.Guests * 1.6)); + Measure(false); + } + + public void ExtendGalley() + { + if (GalleyBoost || !CanSpend(GalleyCost)) + return; + Expenses += GalleyCost; + galleyUntil = tick + 7; + Measure(false); + } + + public void RunBoostPumps() + { + if (PumpsBoost || !CanSpend(PumpCost)) + return; + Expenses += PumpCost; + pumpsUntil = tick + 7; + } + + public void BoostTreatment() + { + if (TreatmentBoost || !CanSpend(TreatmentCost)) + return; + Expenses += TreatmentCost; + treatmentUntil = tick + 7; + } + + public void ServiceMachinery() + { + if (RepairCredit > 0 || Ship.Condition >= 100 || !CanSpend(RepairCost)) + return; + Expenses += RepairCost; + RepairCredit = Math.Min(6, 2 + Ship.Count(Facility.Workshop) * Market.Facilities[(int)Facility.Workshop].Capacity); + } + + private void InitializeSystems() + { + provisions = Math.Min(Ship.FoodCapacity, Quote.Guests * Quote.Days * 2.53); + water = Ship.WaterCapacity; + } + + private int FuelForMode(int mode) + { + double expected = Quote.FuelBurn * (fuelIntegrated + (ticks - tick) * FuelRates[mode]) / ticks; + return Math.Max(1, (int)Math.Round(expected, MidpointRounding.AwayFromZero)); + } + + private void AdvanceSystems() + { + if (Assisted && tick < ticks) + { + if (provisions < Math.Min(QuotaPerService() * 2, Ship.FoodCapacity * .28)) + OpenStores(); + if (WaterPercent < 24) + RunBoostPumps(); + if (SewagePercent > 76) + BoostTreatment(); + } + + fuelIntegrated += FuelRates[EngineMode]; + double portionOfDay = (double)Quote.Days / ticks; + water = Math.Min(Ship.WaterCapacity, water + Ship.WaterProduction * (PumpsBoost ? 1.9 : 1) * portionOfDay); + double requested = (Quote.Guests * 54 + Get(OnboardService.Amenities).Served * 28) * portionOfDay; + double delivered = Math.Min(water, requested); + water -= delivered; + hydration = requested <= 0 ? 1 : delivered / requested; + waste = Math.Min(Ship.WasteCapacity * 1.3, Math.Max(0, + waste + delivered * .74 - Ship.WasteTreatment * (TreatmentBoost ? 2.3 : 1) * portionOfDay)); + } + + private double QuotaPerService() => Math.Min(Ship.GalleyCapacity, Quote.Guests) * PortionPerMeal; + + private int ServiceCapacity(int service, int venueCapacity) + { + if (service == (int)OnboardService.Meals) + { + int galley = Ship.GalleyCapacity + (GalleyBoost ? 85 : 0); + int portions = (int)Math.Floor(provisions / PortionPerMeal); + return Math.Min(venueCapacity, Math.Min(galley, portions)); + } + if (service == (int)OnboardService.Amenities && WaterPercent < 22) + return venueCapacity / 3; + return venueCapacity; + } + + private void UpdateHealth(double mealFulfillment) + { + double sanitation = 1 - Math.Min(.67, Math.Max(0, waste / Ship.WasteCapacity - .68)); + double target = 53 + mealFulfillment * 32 + hydration * 9 + sanitation * 6; + health = health * .80 + target * .20; + } + } +} diff --git a/Assets/Soundings/Runtime/OnboardSystems.cs.meta b/Assets/Soundings/Runtime/OnboardSystems.cs.meta new file mode 100644 index 0000000..bddfc9b --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardSystems.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d4a3eb61885c9aa7882be33d913f9a08 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/OperationsPage.cs b/Assets/Soundings/Runtime/OperationsPage.cs index 9c96bb2..2deb1214 100644 --- a/Assets/Soundings/Runtime/OperationsPage.cs +++ b/Assets/Soundings/Runtime/OperationsPage.cs @@ -10,6 +10,7 @@ namespace Soundings { PortSpec origin = Market.Ports[quote.Origin]; AddText(folio, $"DEPARTURE FROM {origin.Name.ToUpperInvariant()}", "chart-paper-kicker chart-paper-section"); + DrawWeatherPicker(folio, quote); var passage = Add(folio, "chart-passage"); AddText(passage, $"{quote.Miles:N0} nm · {quote.Days} days", "chart-passage-distance"); AddText(passage, $"{quote.Guests} / {quote.Capacity} guests", "chart-passage-guests"); @@ -28,7 +29,10 @@ namespace Soundings if (!string.IsNullOrEmpty(blocker)) AddText(folio, blocker, "chart-paper-note chart-departure-blocker"); else - AddText(folio, "Cleared for departure", "chart-cleared"); + { + int seconds = Mathf.RoundToInt(PassageDuration(quote)); + AddText(folio, $"Cleared for departure · {seconds / 60}m {seconds % 60:00}s at 1×", "chart-cleared"); + } Button launch = Action("Cast off →", () => BeginVoyage(quote), "chart-ink-button chart-wide-button chart-cast-off", "dispatch"); launch.SetEnabled(blocker == null); folio.Add(launch); diff --git a/Assets/Soundings/Runtime/PassageInterface.cs b/Assets/Soundings/Runtime/PassageInterface.cs new file mode 100644 index 0000000..1a53226 --- /dev/null +++ b/Assets/Soundings/Runtime/PassageInterface.cs @@ -0,0 +1,292 @@ +using UnityEngine; +using UnityEngine.UIElements; + +namespace Soundings +{ + public sealed partial class SoundingsApp + { + private static readonly string[] PassageServices = { "rooms", "meals", "drinks", "shows", "amenities" }; + private readonly Label[] passageDemand = new Label[5]; + private readonly Label[] passagePrices = new Label[5]; + private readonly Button[] passageSpecials = new Button[5]; + private readonly Button[] passageMinus = new Button[5]; + private readonly Button[] passagePlus = new Button[5]; + private bool passageBusinessOpen = true; + private VisualElement passageProgress, passageEventHost; + private Label passageRemaining, passageHappiness, passageHealth, passageSupplies, passageSales, passageEventClock, passageEventResult; + private float renderedPassageProgress = -1, nextPassageReadout; + private Button passageEventAccept; + private string passageEventTitle; + + private void DrawUnderway(VisualElement workspace) + { + var overlay = Add(workspace, "voyage-overlay"); + overlay.pickingMode = PickingMode.Ignore; + var left = Add(overlay, "voyage-business"); + left.pickingMode = PickingMode.Ignore; + + var opener = Add(left, "voyage-business-opener"); + opener.pickingMode = PickingMode.Ignore; + opener.Add(Action(passageBusinessOpen ? "Onboard service −" : "Onboard service +", () => + { + passageBusinessOpen = !passageBusinessOpen; + Render(); + }, "voyage-drawer-toggle", "passage-business")); + if (passageBusinessOpen) + DrawPassageBusiness(left); + else + { + passageHappiness = null; + passageSales = null; + passageHealth = null; + passageSupplies = null; + for (int i = 0; i < PassageServices.Length; i++) + { + passageDemand[i] = null; + passagePrices[i] = null; + passageSpecials[i] = null; + passageMinus[i] = null; + passagePlus[i] = null; + } + } + + passageEventHost = Add(overlay, "voyage-event-host"); + passageEventHost.pickingMode = PickingMode.Ignore; + passageEventTitle = null; + passageEventClock = null; + passageEventAccept = null; + passageEventResult = null; + + var controls = Add(overlay, "voyage-deckbar"); + controls.pickingMode = PickingMode.Ignore; + AddText(controls, "SHIP VIEW", "voyage-caption voyage-deck-caption"); + AddPassageDeckButton(controls, -1, "Exterior", "passage-deck-all"); + for (int i = 0; i < Ship.Decks.Count; i++) + AddPassageDeckButton(controls, i, $"Deck {i + 1}", $"passage-deck-{i}"); + controls.Add(Action("Bridge", ViewPassageBridge, PassageViewClass(passageBridge), "passage-bridge")); + controls.Add(Action("Explore", ExplorePassageDeck, PassageViewClass(passageExploring && passageServiceArea < 0), "passage-explore")); + controls.Add(Action("Service deck", () => ExploreServiceArea(0), PassageViewClass(passageServiceArea >= 0), "passage-service")); + controls.Add(Action("Reset camera", () => + { + if (passageBridge) + ViewPassageBridge(); + else if (passageServiceArea >= 0) + ExploreServiceArea(passageServiceArea); + else if (passageExploring) + ExplorePassageDeck(); + else + harbor.ResetView(); + }, "voyage-view-button voyage-reset", "passage-camera-reset")); + + var rail = Add(overlay, "voyage-rail"); + var route = Add(rail, "voyage-route"); + string sea = underway.Weather switch + { + WeatherCondition.Storm => "Storm · Open decks closed", + WeatherCondition.Swell => "Swell · Limited outdoor service", + _ => "Calm seas" + }; + var routeContext = Add(route, "voyage-route-context"); + AddText(routeContext, $"UNDERWAY / {underway.ShipName.ToUpperInvariant()}", "voyage-caption"); + AddText(routeContext, sea, underway.Weather == WeatherCondition.Storm + ? "voyage-conditions voyage-conditions-warning" : "voyage-conditions"); + AddDisplay(route, $"{Market.Ports[underway.Origin].Name} → {Market.Ports[underway.Destination].Name}", "voyage-route-name"); + passageRemaining = AddText(route, "", "voyage-remaining"); + var progress = Add(route, "voyage-progress"); + passageProgress = Add(progress, "voyage-progress-fill"); + renderedPassageProgress = -1; + nextPassageReadout = 0; + + var speed = Add(rail, "voyage-speed"); + AddText(speed, "SIMULATION SPEED", "voyage-caption"); + var speeds = Add(speed, "voyage-speed-buttons"); + foreach (int multiplier in new[] { 1, 2, 4 }) + { + int requested = multiplier; + speeds.Add(Action($"{requested}×", () => SetPassageSpeed(requested), + requested == passageSpeed ? "voyage-view-button voyage-control-active" : "voyage-view-button", + $"passage-speed-{requested}")); + } + + var camera = Add(rail, "voyage-camera"); + AddText(camera, "CAMERA", "voyage-caption"); + AddText(camera, passageBridge || passageExploring || passageServiceArea >= 0 + ? "WASD to walk · Right-drag to look" + : "Wheel to zoom · Hold RMB + WASD / Q E to fly", "voyage-camera-help"); + rail.Add(Action("Skip to arrival", FinishVoyage, "voyage-view-button voyage-skip", "dock-now")); + UpdatePassageUi(Mathf.Clamp01(passageElapsed / PassageDuration(underway))); + } + + private void DrawPassageBusiness(VisualElement left) + { + var book = Add(left, "voyage-business-book"); + var metrics = Add(book, "voyage-business-metrics"); + var happiness = Add(metrics, "voyage-business-metric"); + AddText(happiness, "GUEST HAPPINESS", "voyage-caption"); + passageHappiness = AddDisplay(happiness, "", "voyage-business-value"); + var health = Add(metrics, "voyage-business-metric"); + AddText(health, "HEALTH", "voyage-caption"); + passageHealth = AddDisplay(health, "", "voyage-business-value"); + var sales = Add(metrics, "voyage-business-metric"); + AddText(sales, "TAKINGS", "voyage-caption"); + passageSales = AddDisplay(sales, "", "voyage-business-value"); + passageSupplies = AddText(book, "", "voyage-provisions"); + for (int i = 0; i < PassageServices.Length; i++) + { + OnboardService service = (OnboardService)i; + string slug = PassageServices[i]; + var entry = Add(book, "voyage-service"); + var line = Add(entry, "voyage-service-line"); + AddText(line, OnboardSession.ServiceLabel(service), "voyage-service-name"); + passageDemand[i] = AddText(line, "", "voyage-service-demand"); + if (service == OnboardService.Amenities && underway.Weather == WeatherCondition.Storm) + AddText(entry, "Outdoor venues closed", "voyage-service-included voyage-demand-short"); + if (service == OnboardService.Rooms) + { + AddText(entry, "Included in the booked fare", "voyage-service-included"); + continue; + } + + var prices = Add(entry, "voyage-price-row"); + passageMinus[i] = Action("−", () => AdjustPassagePrice(service, -1), "voyage-price-step", $"passage-price-{slug}-minus"); + passageMinus[i].tooltip = "Lower the onboard price by $1"; + prices.Add(passageMinus[i]); + passagePrices[i] = AddText(prices, "", "voyage-service-price"); + passagePlus[i] = Action("+", () => AdjustPassagePrice(service, 1), "voyage-price-step", $"passage-price-{slug}-plus"); + passagePlus[i].tooltip = "Raise the onboard price by $1"; + prices.Add(passagePlus[i]); + passageSpecials[i] = Action("Special −25%", () => + { + livePassage.StartSpecial(service); + RefreshPassageBusiness(); + }, "voyage-special", $"passage-special-{slug}"); + prices.Add(passageSpecials[i]); + } + AddText(book, "Guests served / requesting right now", "voyage-metric-help"); + } + + private void AddPassageDeckButton(VisualElement controls, int deck, string text, string id) + { + bool active = deck == passageDeck && !passageBridge && !passageExploring && passageServiceArea < 0; + controls.Add(Action(text, () => SelectPassageDeck(deck), PassageViewClass(active), id)); + } + + private static string PassageViewClass(bool active) => active + ? "voyage-view-button voyage-control-active" : "voyage-view-button"; + + private static void SetPassageText(Label label, string text) + { + if (label.text != text) + label.text = text; + } + + private void AdjustPassagePrice(OnboardService service, int delta) + { + livePassage.ChangePrice(service, delta); + RefreshPassageBusiness(); + } + + private void UpdatePassageUi(float progress) + { + if (underway == null || livePassage == null || passageProgress == null || passageRemaining == null) + return; + if (Mathf.Abs(progress - renderedPassageProgress) >= .002f) + { + passageProgress.style.width = Length.Percent(100 * progress); + renderedPassageProgress = progress; + } + int miles = Mathf.RoundToInt(underway.Miles * (1 - progress)); + int seconds = Mathf.CeilToInt((1 - progress) * PassageDuration(underway) / (passageSpeed * livePassage.SpeedFactor)); + string remaining = $"{miles:N0} nm remaining · {seconds / 60}:{seconds % 60:00} to arrival"; + if (passageRemaining.text != remaining) + passageRemaining.text = remaining; + if (Time.unscaledTime >= nextPassageReadout || livePassage.CurrentEvent?.Title != passageEventTitle) + { + nextPassageReadout = Time.unscaledTime + .12f; + RefreshPassageBusiness(); + RefreshPassageEvent(); + } + } + + private void RefreshPassageBusiness() + { + if (livePassage == null || passageHappiness == null) + return; + SetPassageText(passageHappiness, $"{livePassage.Happiness}/100"); + SetPassageText(passageHealth, $"{livePassage.Health}/100"); + SetPassageText(passageSupplies, $"Provisions remaining · {livePassage.ProvisionsRemaining:N0}"); + SetPassageText(passageSales, Money(livePassage.Revenue)); + for (int i = 0; i < PassageServices.Length; i++) + { + OnboardService service = (OnboardService)i; + OnboardSample demand = livePassage.Get(service); + SetPassageText(passageDemand[i], $"{demand.Served:N0} / {demand.Requested:N0} guests"); + passageDemand[i].EnableInClassList("voyage-demand-short", demand.Served < demand.Requested); + if (i == 0) + continue; + + int price = livePassage.GetPrice(service); + int ticks = livePassage.DiscountTicks(service); + SetPassageText(passagePrices[i], ticks > 0 ? Money(Mathf.Max(1, price * 3 / 4)) : Money(price)); + passageMinus[i].SetEnabled(price > 0 && demand.Capacity > 0); + passagePlus[i].SetEnabled(demand.Capacity > 0); + string offer = ticks > 0 ? $"Special · {ticks} left" : "Special −25%"; + if (passageSpecials[i].text != offer) + passageSpecials[i].text = offer; + passagePrices[i].tooltip = ticks > 0 ? $"Regular price: {Money(price)}" : ""; + passageSpecials[i].SetEnabled(price > 0 && demand.Capacity > 0 && ticks == 0); + } + } + + private void RefreshPassageEvent() + { + if (passageEventHost == null) + return; + VoyageEvent? current = livePassage.CurrentEvent; + string title = current?.Title; + if (title != passageEventTitle || title == null && passageEventResult == null && !string.IsNullOrEmpty(livePassage.EventResult)) + { + passageEventTitle = title; + passageEventHost.Clear(); + passageEventClock = null; + passageEventAccept = null; + passageEventResult = null; + if (current.HasValue) + { + VoyageEvent offer = current.Value; + var card = Add(passageEventHost, "voyage-event"); + AddText(card, "DECK OPERATIONS", "voyage-caption"); + AddDisplay(card, offer.Title, "voyage-event-title"); + AddText(card, offer.Detail, "voyage-event-copy"); + AddText(card, "Adds temporary service capacity and lifts guest happiness.", "voyage-event-impact"); + passageEventClock = AddText(card, "", "voyage-event-clock"); + passageEventAccept = Action($"{offer.Action} · {Money(offer.Cost)}", () => DecidePassageEvent(true), + "voyage-event-accept", "passage-event-0"); + card.Add(passageEventAccept); + card.Add(Action(offer.Alternative, () => DecidePassageEvent(false), "voyage-event-decline", "passage-event-1")); + } + else if (!string.IsNullOrEmpty(livePassage.EventResult)) + { + var result = Add(passageEventHost, "voyage-event voyage-event-result"); + passageEventResult = AddText(result, livePassage.EventResult, "voyage-event-copy"); + } + } + + if (passageEventClock != null) + { + int ticks = livePassage.RemainingEventTicks; + SetPassageText(passageEventClock, $"{ticks} service {(ticks == 1 ? "round" : "rounds")} remaining"); + passageEventAccept.SetEnabled(livePassage.CanAcceptEvent); + } + else if (passageEventResult != null) + SetPassageText(passageEventResult, livePassage.EventResult); + } + + private void DecidePassageEvent(bool accept) + { + livePassage.ResolveEvent(accept); + RefreshPassageBusiness(); + RefreshPassageEvent(); + } + } +} diff --git a/Assets/Soundings/Runtime/PassageInterface.cs.meta b/Assets/Soundings/Runtime/PassageInterface.cs.meta new file mode 100644 index 0000000..a0962ad --- /dev/null +++ b/Assets/Soundings/Runtime/PassageInterface.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 31dd2276af1d39352b5891573b187eab \ No newline at end of file diff --git a/Assets/Soundings/Runtime/PassageWeather.cs b/Assets/Soundings/Runtime/PassageWeather.cs new file mode 100644 index 0000000..014548c --- /dev/null +++ b/Assets/Soundings/Runtime/PassageWeather.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.UIElements; + +namespace Soundings +{ + public sealed partial class SoundingsApp + { + private sealed class PassageWeatherSelection + { + public WeatherCondition Condition; + public bool Loading; + public int Request; + public string Status; + } + + [Serializable] + private sealed class WeatherReply + { + public CurrentWeather current; + } + + [Serializable] + private sealed class CurrentWeather + { + public string time; + public float wind_speed_10m; + public float precipitation; + public int weather_code; + } + + private readonly Dictionary<(int, int), PassageWeatherSelection> passageWeather = new(); + + private static (int, int) WeatherRoute(int origin, int destination) + => origin < destination ? (origin, destination) : (destination, origin); + + private void ResetWeatherSelection() => passageWeather.Clear(); + + private WeatherCondition PassageWeatherFor(int origin, int destination) + => passageWeather.TryGetValue(WeatherRoute(origin, destination), out var selection) + ? selection.Condition + : WeatherCondition.Calm; + + private void DrawWeatherPicker(VisualElement parent, Voyage quote) + { + var route = WeatherRoute(quote.Origin, quote.Destination); + if (!passageWeather.TryGetValue(route, out var selection)) + { + selection = new PassageWeatherSelection(); + passageWeather.Add(route, selection); + } + quote.Weather = selection.Condition; + + var picker = Add(parent, "chart-money-row"); + picker.style.flexWrap = Wrap.Wrap; + var label = AddText(picker, "Sea state", "chart-money-label"); + label.style.marginRight = 5; + foreach (WeatherCondition condition in Enum.GetValues(typeof(WeatherCondition))) + { + var preset = condition; + string name = preset.ToString(); + bool selected = selection.Condition == preset; + Button choice = Action(name, () => + { + selection.Request++; + selection.Loading = false; + selection.Condition = preset; + selection.Status = null; + Render(); + }, "chart-step", "weather-" + name.ToLowerInvariant()); + choice.style.width = StyleKeyword.Auto; + choice.style.paddingLeft = 5; + choice.style.paddingRight = 5; + choice.style.marginRight = 2; + choice.style.minHeight = 25; + if (selected) + { + choice.style.backgroundColor = (Color)new Color32(39, 69, 70, 255); + choice.style.color = (Color)new Color32(248, 234, 200, 255); + } + picker.Add(choice); + } + + Button live = Action(selection.Loading ? "Checking…" : "Fetch live", () => + { + selection.Loading = true; + selection.Status = null; + StartCoroutine(FetchPassageWeather(route, selection, ++selection.Request)); + Render(); + }, "chart-step", "weather-live"); + live.tooltip = "Fetch current model weather at the midpoint of this route from Open-Meteo."; + live.SetEnabled(!selection.Loading); + live.style.width = StyleKeyword.Auto; + live.style.paddingLeft = 5; + live.style.paddingRight = 5; + live.style.minHeight = 25; + picker.Add(live); + + if (!string.IsNullOrEmpty(selection.Status)) + AddText(parent, selection.Status, "chart-paper-note"); + } + + private IEnumerator FetchPassageWeather((int Origin, int Destination) route, + PassageWeatherSelection selection, int request) + { + (double latitude, double longitude) = WeatherMidpoint(Market.Ports[route.Origin], Market.Ports[route.Destination]); + string address = FormattableString.Invariant( + $"https://api.open-meteo.com/v1/forecast?latitude={latitude:F3}&longitude={longitude:F3}¤t=wind_speed_10m,precipitation,weather_code&wind_speed_unit=kn&timezone=GMT"); + using var download = UnityWebRequest.Get(address); + download.timeout = 6; + yield return download.SendWebRequest(); + + if (selection.Request != request || !passageWeather.TryGetValue(route, out var active) || active != selection) + yield break; + + selection.Loading = false; + CurrentWeather reading = download.result == UnityWebRequest.Result.Success + ? ParseCurrentWeather(download.downloadHandler.text) + : null; + if (reading == null) + { + selection.Status = "Live weather unavailable. Preset kept."; + } + else + { + selection.Condition = ClassifyWeather(reading); + DateTime.TryParseExact(reading.time, "yyyy-MM-dd'T'HH:mm", CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var utc); + string stamp = utc == default ? reading.time : utc.ToString("MMM d HH:mm", CultureInfo.InvariantCulture); + selection.Status = $"Open-Meteo · {stamp} UTC · {reading.wind_speed_10m:0.#} kt"; + } + + if (!title && underway == null && page == 3 && Ship != null && WeatherRoute(Ship.Port, inspectedPort) == route) + Render(); + } + + private static CurrentWeather ParseCurrentWeather(string text) + { + if (string.IsNullOrWhiteSpace(text)) + return null; + try + { + CurrentWeather weather = JsonUtility.FromJson(text)?.current; + if (weather == null || string.IsNullOrWhiteSpace(weather.time) + || float.IsNaN(weather.wind_speed_10m) || float.IsInfinity(weather.wind_speed_10m) + || float.IsNaN(weather.precipitation) || float.IsInfinity(weather.precipitation) + || weather.wind_speed_10m < 0 || weather.precipitation < 0) + return null; + return weather; + } + catch (ArgumentException) + { + return null; + } + } + + private static WeatherCondition ClassifyWeather(CurrentWeather reading) + { + if (reading.weather_code >= 95 || reading.wind_speed_10m >= 32 || reading.precipitation >= 5) + return WeatherCondition.Storm; + if (reading.wind_speed_10m >= 16 || reading.precipitation >= 1 || reading.weather_code == 82) + return WeatherCondition.Swell; + return WeatherCondition.Calm; + } + + private static (double Latitude, double Longitude) WeatherMidpoint(PortSpec a, PortSpec b) + { + const double radians = Math.PI / 180; + double latA = a.Latitude * radians, latB = b.Latitude * radians; + double lonA = a.Longitude * radians, lonB = b.Longitude * radians; + double x = Math.Cos(latA) * Math.Cos(lonA) + Math.Cos(latB) * Math.Cos(lonB); + double y = Math.Cos(latA) * Math.Sin(lonA) + Math.Cos(latB) * Math.Sin(lonB); + double z = Math.Sin(latA) + Math.Sin(latB); + double horizontal = Math.Sqrt(x * x + y * y); + if (horizontal < 1e-8 && Math.Abs(z) < 1e-8) + { + float longitude = a.Longitude + Mathf.DeltaAngle(a.Longitude, b.Longitude) / 2; + return ((a.Latitude + b.Latitude) / 2, Mathf.Repeat(longitude + 180, 360) - 180); + } + return (Math.Atan2(z, horizontal) / radians, Math.Atan2(y, x) / radians); + } + } +} diff --git a/Assets/Soundings/Runtime/PassageWeather.cs.meta b/Assets/Soundings/Runtime/PassageWeather.cs.meta new file mode 100644 index 0000000..4d147ad --- /dev/null +++ b/Assets/Soundings/Runtime/PassageWeather.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9b91c5bc92d1d860f98340fb59cd8693 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/ServiceControls.cs b/Assets/Soundings/Runtime/ServiceControls.cs new file mode 100644 index 0000000..a03eba1 --- /dev/null +++ b/Assets/Soundings/Runtime/ServiceControls.cs @@ -0,0 +1,126 @@ +using UnityEngine.UIElements; + +namespace Soundings +{ + public sealed partial class SoundingsApp + { + private Label serviceReadout; + private Button serviceAction, serviceAssist; + private readonly Button[] engineControls = new Button[3]; + + private void DrawServiceNavigation(VisualElement workspace) + { + serviceReadout = null; + serviceAction = serviceAssist = null; + if (passageServiceArea < 0) + return; + + var stations = Add(workspace, "service-stations"); + for (int i = 0; i < ServiceDeckModel.Areas.Length; i++) + { + int area = i; + stations.Add(Action(ServiceDeckModel.Areas[area], () => ExploreServiceArea(area), + "service-station" + (area == passageServiceArea ? " service-selected" : ""), $"service-area-{area}")); + } + + var station = Add(workspace, "service-console"); + AddText(station, "SERVICE DECK", "eyebrow"); + AddDisplay(station, ServiceDeckModel.Areas[passageServiceArea], "service-title"); + serviceReadout = AddText(station, "", "service-metrics"); + if (passageServiceArea == 0) + { + var engines = Add(station, "service-engines"); + string[] modes = { "Economy", "Cruise", "Power" }; + for (int i = 0; i < modes.Length; i++) + { + int mode = i; + engineControls[i] = Action(modes[mode], () => + { + livePassage.SetEngineMode(mode); + UpdateServiceNavigation(); + }, "", $"service-engine-{mode}"); + engines.Add(engineControls[i]); + } + AddText(station, "Power runs faster when fuel covers the reserve.", "service-tip"); + } + else + { + serviceAction = Action("", OperateServiceArea, "primary service-operate", "service-operate"); + station.Add(serviceAction); + } + + serviceAssist = Action("", () => + { + livePassage.Assisted = !livePassage.Assisted; + UpdateServiceNavigation(); + }, "service-assist", "service-assist"); + station.Add(serviceAssist); + AddText(station, "Assisted mode opens reserves and boosts utilities when needed.", "service-tip"); + UpdateServiceNavigation(); + } + + private void UpdateServiceNavigation() + { + if (serviceReadout == null || livePassage == null) + return; + OnboardSession systems = livePassage; + + if (passageServiceArea == 0) + { + SetServiceText(serviceReadout, $"Projected burn {systems.ProjectedFuelBurn:N0} t / {Ship.Fuel:N0} t aboard\nReserve {underway.Reserve:N0} t"); + for (int i = 0; i < engineControls.Length; i++) + { + engineControls[i].EnableInClassList("service-selected", i == systems.EngineMode); + engineControls[i].SetEnabled(systems.CanSetEngineMode(i)); + } + } + else + { + var (reading, action, available) = passageServiceArea switch + { + 1 => ($"{systems.Get(OnboardService.Meals).Served:N0} served / {systems.Get(OnboardService.Meals).Requested:N0} meals requested\n{systems.ProvisionsRemaining:N0} portions in stores", + systems.GalleyBoost ? "Extra shift running" : $"Staff extra shift · {Money(systems.GalleyCost)}", + !systems.GalleyBoost && systems.CanSpend(systems.GalleyCost)), + 2 => ($"{systems.ProvisionsRemaining:N0} / {Ship.FoodCapacity:N0} portions\nGuest health {systems.Health}/100", + systems.StoresOpened ? "Reserve opened" : $"Release reserve · {Money(systems.StoreCost)}", systems.CanOpenStores), + 3 => ($"Hull condition {Ship.Condition}%\nService benefit +{systems.RepairCredit} on arrival", + systems.RepairCredit > 0 ? "Service complete" : $"Service machinery · {Money(systems.RepairCost)}", + systems.RepairCredit == 0 && Ship.Condition < 100 && systems.CanSpend(systems.RepairCost)), + 4 => ($"Freshwater tank {systems.WaterPercent}%\n{Ship.WaterProduction:N0} L/day normal output", + systems.PumpsBoost ? "Boost pumps running" : $"Run boost pumps · {Money(systems.PumpCost)}", + !systems.PumpsBoost && systems.CanSpend(systems.PumpCost)), + _ => ($"Treatment buffer {systems.SewagePercent}%\n{Ship.WasteTreatment:N0} L/day normal treatment", + systems.TreatmentBoost ? "Extra treatment running" : $"Boost treatment · {Money(systems.TreatmentCost)}", + !systems.TreatmentBoost && systems.CanSpend(systems.TreatmentCost)) + }; + SetServiceText(serviceReadout, reading); + if (serviceAction.text != action) + serviceAction.text = action; + serviceAction.SetEnabled(available); + } + + string mode = systems.Assisted ? "Operations: Assisted" : "Operations: Manual"; + if (serviceAssist.text != mode) + serviceAssist.text = mode; + } + + private void OperateServiceArea() + { + switch (passageServiceArea) + { + case 1: livePassage.ExtendGalley(); break; + case 2: livePassage.OpenStores(); break; + case 3: livePassage.ServiceMachinery(); break; + case 4: livePassage.RunBoostPumps(); break; + case 5: livePassage.BoostTreatment(); break; + } + UpdateServiceNavigation(); + } + + private static void SetServiceText(Label label, string value) + { + if (label.text != value) + label.text = value; + } + } +} diff --git a/Assets/Soundings/Runtime/ServiceControls.cs.meta b/Assets/Soundings/Runtime/ServiceControls.cs.meta new file mode 100644 index 0000000..65eb89b --- /dev/null +++ b/Assets/Soundings/Runtime/ServiceControls.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0db92d216f8a8dc72b5a482e3c1477d9 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/ServiceDeckModel.cs b/Assets/Soundings/Runtime/ServiceDeckModel.cs new file mode 100644 index 0000000..ed51da1 --- /dev/null +++ b/Assets/Soundings/Runtime/ServiceDeckModel.cs @@ -0,0 +1,207 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Soundings +{ + internal sealed class ServiceDeckModel + { + public static readonly string[] Areas = { "Engine room", "Galley", "Stores", "Maintenance", "Water plant", "Sewage treatment" }; + private readonly Dictionary batches = new Dictionary(); + private readonly List meshes = new List(); + private readonly List materials = new List(); + private readonly float span, width; + public GameObject Root { get; } + + public ServiceDeckModel(Transform parent, float length, float beam, Shader surface) + { + span = length * .68f; + width = beam * 1.75f; + Root = new GameObject("Service deck"); + Root.layer = 8; + Root.transform.SetParent(parent, false); + BuildEnvelope(); + for (int area = 0; area < Areas.Length; area++) + { + float x = AreaCenter(area); + int accent = area switch { 0 => 0xB88E58, 1 => 0xB77661, 2 => 0x9DA775, 3 => 0xCEAC61, 4 => 0x65B3C7, _ => 0x73AB82 }; + Box(accent, x, .022f, .82f, span / Areas.Length - .35f, .03f, .14f); + Box(0x263744, x, 2.72f, width * .5f - .15f, 4.7f, .64f, .16f); + Sign(Areas[area].ToUpperInvariant(), x, 2.72f, width * .5f - .26f, new Color32(235, 224, 193, 255)); + BuildArea(area, x, accent); + } + + foreach (var pair in batches) + { + var game = new GameObject("Service deck finish", typeof(MeshFilter), typeof(MeshRenderer)); + game.layer = 8; + game.transform.SetParent(Root.transform, false); + Mesh mesh = pair.Value.Bake(); + var material = new Material(surface) { color = ColorOf(pair.Key) }; + material.SetFloat("_Roughness", .56f); + material.SetFloat("_Emissive", pair.Key == 0xFFF1C8 ? 1 : .21f); + game.GetComponent().sharedMesh = mesh; + game.GetComponent().sharedMaterial = material; + meshes.Add(mesh); + materials.Add(material); + } + batches.Clear(); + Root.SetActive(false); + } + + public Vector3 Entry(int area) => new Vector3(AreaCenter(area), 1.65f, -.75f); + public float Heading(int area) => 0; + + private float AreaCenter(int area) => -span * .5f + span * (Mathf.Clamp(area, 0, Areas.Length - 1) + .5f) / Areas.Length; + + private void BuildEnvelope() + { + Box(0x596666, 0, -.13f, 0, span, .24f, width); + Box(0x626B6D, 0, 3.31f, 0, span, .22f, width); + for (int side = -1; side <= 1; side += 2) + { + Box(0x81918C, 0, 1.63f, side * width * .5f, span, 3.35f, .2f); + Box(0x37454D, 0, .32f, side * (width * .5f - .13f), span, .65f, .13f); + Box(0xB8AD82, 0, .018f, side * 1.12f, span - .20f, .024f, .06f); + Box(0x9F6E48, side * span * .5f, 1.62f, 0, .22f, 3.35f, width); + Pipe(0x638FAA, new Vector3(-span * .49f, 2.87f, side * (width * .5f - .43f)), + new Vector3(span * .49f, 2.87f, side * (width * .5f - .43f)), .12f); + } + + for (int i = 0; i <= 12; i++) + { + float x = span * (i / 12f - .5f); + Box(0x42545A, x, .002f, 0, .043f, .026f, width); + Box(0x52636B, x, 3.13f, 0, .24f, .14f, width); + Box(0xFFF1C8, x, 3.04f, -.20f, .57f, .038f, 1.05f); + } + for (int i = 1; i < Areas.Length; i++) + { + float x = span * (i / (float)Areas.Length - .5f); + Box(0x778580, x, 1.6f, width * .391f, .19f, 3.2f, width * .235f); + Box(0x263744, x, 1.6f, -width * .414f, .19f, 3.2f, width * .18f); + } + } + + private void BuildArea(int area, float x, int accent) + { + float wall = width * .5f; + float z = Mathf.Min(3.25f, wall - 1.35f); + switch (area) + { + case 0: + for (int side = -1; side <= 1; side += 2) + { + Box(0x3D484B, x, .16f, side * z, 5.4f, .33f, 1.75f); + Box(accent, x, .69f, side * z, 4.7f, .92f, 1.35f); + Pipe(0x526A74, new Vector3(x - 3.05f, .69f, side * z), new Vector3(x + 2.35f, .69f, side * z), .18f); + for (int i = -2; i <= 2; i++) + { + Box(0x7B8584, x + i * .86f, 1.27f, side * z, .51f, .30f, .80f); + Pipe(0xAA8170, new Vector3(x + i * .86f, 1.38f, side * z), new Vector3(x + i * .86f, 2.64f, side * z), .079f); + } + } + Panel(x + 2.94f, z, 0x62F0B4); + break; + case 1: + Box(0x92A19F, x, .49f, z, 5.40f, .92f, 1.54f); + Box(0xC7C8B9, x, 1.00f, z, 5.65f, .14f, 1.69f); + for (int i = 0; i < 3; i++) + { + float px = x - 1.65f + i * 1.66f; + Box(0x293943, px, 1.10f, z, 1.12f, .08f, 1.08f); + Pipe(accent, new Vector3(px, 1.12f, z), new Vector3(px, 1.38f, z), .26f); + } + Box(0x657478, x, 2.29f, z + .1f, 5.49f, .42f, 1.55f); + Box(0x839690, x, .61f, -z, 3.8f, 1.22f, 1.55f); + break; + case 2: + for (int shelf = 1; shelf <= 3; shelf++) + { + float level = shelf * .62f; + Box(0x655C48, x, level, z, 5.4f, .10f, 1.40f); + for (int i = -2; i <= 2; i++) + Box(i % 2 == 0 ? accent : 0xAF8F70, x + .91f * i, level + .21f, z, .70f, .36f, .76f); + } + for (int side = -1; side <= 1; side += 2) + Box(0x626B62, x + side * 2.45f, 1.13f, z, .12f, 2.26f, 1.59f); + break; + case 3: + Box(0x656B69, x, .48f, z, 5.30f, .93f, 1.35f); + Box(accent, x, .99f, z, 5.53f, .13f, 1.5f); + Box(0x4D6062, x, 1.83f, z + .65f, 5.30f, 1.01f, .14f); + for (int i = -3; i <= 3; i++) + { + float px = x + .61f * i; + Pipe(0xD2CAAF, new Vector3(px, 1.51f, z + .53f), new Vector3(px, 1.96f, z + .53f), .043f); + Box(i % 2 == 0 ? 0xAC784C : 0x748C84, px, 1.42f, z + .53f, .12f, .18f, .14f); + } + Box(0x705E56, x, .59f, -z, 3.14f, 1.18f, 1.25f); + break; + default: + for (int i = -1; i <= 1; i++) + { + float px = x + 1.49f * i; + Pipe(accent, new Vector3(px, .35f, z), new Vector3(px, 2.40f, z), .56f, 16); + Pipe(0xC3BFA7, new Vector3(px, 2.34f, z), new Vector3(px, 2.72f, z), .105f); + Box(0x3F5358, px, 1.40f, z - .49f, .24f, .48f, .26f); + } + Pipe(accent, new Vector3(x - 2.85f, 2.7f, z), new Vector3(x + 2.85f, 2.7f, z), .12f); + Panel(x + 2.94f, z, accent); + break; + } + } + + private void Panel(float x, float z, int signal) + { + Box(0x48595E, x, .66f, z, .96f, 1.32f, .83f); + Box(0x223240, x, 1.32f, z - .16f, 1.02f, .39f, .65f); + for (int i = -1; i <= 1; i++) + Box(signal, x + i * .21f, 1.38f, z - .493f, .08f, .08f, .022f); + } + + private void Sign(string words, float x, float y, float z, Color color) + { + var game = new GameObject(words, typeof(TextMesh)); + game.layer = 8; + game.transform.SetParent(Root.transform, false); + game.transform.localPosition = new Vector3(x, y, z); + var text = game.GetComponent(); + Font font = Resources.Load("Interface"); + text.font = font; + text.text = words; + text.fontStyle = FontStyle.Bold; + text.fontSize = 52; + text.characterSize = .10f; + text.anchor = TextAnchor.MiddleCenter; + text.color = color; + game.GetComponent().sharedMaterial = font.material; + } + + private HarborMesh Paint(int color) + { + if (!batches.TryGetValue(color, out HarborMesh mesh)) + { + mesh = new HarborMesh(); + batches.Add(color, mesh); + } + return mesh; + } + + private void Box(int color, float x, float y, float z, float w, float h, float d) => + Paint(color).Box(new Vector3(x, y, z), new Vector3(w, h, d)); + + private void Pipe(int color, Vector3 from, Vector3 to, float radius, int sides = 9) => Paint(color).Rod(from, to, radius, sides); + + private static Color32 ColorOf(int rgb) => new Color32((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb, 255); + + public void Release() + { + Root.SetActive(false); + UnityEngine.Object.Destroy(Root); + foreach (Mesh mesh in meshes) + UnityEngine.Object.Destroy(mesh); + foreach (Material material in materials) + UnityEngine.Object.Destroy(material); + } + } +} diff --git a/Assets/Soundings/Runtime/ServiceDeckModel.cs.meta b/Assets/Soundings/Runtime/ServiceDeckModel.cs.meta new file mode 100644 index 0000000..ed5d0ee --- /dev/null +++ b/Assets/Soundings/Runtime/ServiceDeckModel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6a54dfb1731cbd2abaf43b567036de24 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/SoundingsApp.cs b/Assets/Soundings/Runtime/SoundingsApp.cs index dec1a05..acc7a17 100644 --- a/Assets/Soundings/Runtime/SoundingsApp.cs +++ b/Assets/Soundings/Runtime/SoundingsApp.cs @@ -55,7 +55,7 @@ namespace Soundings root = document.rootVisualElement; root.style.flexGrow = 1; root.style.unityFontDefinition = interfaceFont; - foreach (string sheet in new[] { "Soundings", "Shipwork", "Ledger", "FirstVoyageGuide" }) + foreach (string sheet in new[] { "Soundings", "Shipwork", "Ledger", "FirstVoyageGuide", "Passage", "ServiceControls" }) { StyleSheet stylesheet = Resources.Load(sheet); if (stylesheet != null) @@ -105,7 +105,9 @@ namespace Soundings ledgerRecordOffset = 0; ledgerAccounts = false; worldChart = false; + ResetWeatherSelection(); tool = Facility.Cabin; + systemTools = false; shipName = "Peregrine"; pendingStart = null; harbor.ResetView(true); @@ -173,6 +175,7 @@ namespace Soundings private void Render() { string focus = (root.focusController?.focusedElement as VisualElement)?.name; + SetPassageFreeLook(false); root.Clear(); bool showingHarbor = !title && company != null && HarborOnScreen; harbor.SetVisible(showingHarbor); @@ -287,7 +290,10 @@ namespace Soundings scene.pickingMode = PickingMode.Ignore; scene.SetEnabled(!paused); if (underway != null) + { DrawUnderway(scene); + DrawServiceNavigation(scene); + } else { switch (page) @@ -325,10 +331,11 @@ namespace Soundings DrawHotbar(shell).SetEnabled(!paused); if (fleetOpen) DrawFleet(shell).SetEnabled(!paused); - if (!paused && !fleetOpen) - DrawGuide(shell); } + if (!paused && !fleetOpen) + DrawGuide(shell); + if (!string.IsNullOrEmpty(notice)) { var toast = Add(shell, "game-toast"); @@ -431,13 +438,9 @@ namespace Soundings GameIcon(menu, "anchor"); AddDisplay(menu, "Paused", "pause-title"); menu.Add(Action("Resume", () => { paused = false; Render(); }, "primary pause-command", "resume-game")); + menu.Add(Action("Restart first voyage guide", RestartGuide, "pause-command", "restart-guide")); if (underway == null) { - menu.Add(Action("Restart first voyage guide", () => - { - paused = false; - RestartGuide(); - }, "pause-command", "restart-guide")); menu.Add(Action("Title screen", () => { paused = fleetOpen = shipActionsOpen = false; @@ -453,6 +456,7 @@ namespace Soundings private void AttachCamera(VisualElement world) { int pointerId = -1; + bool freeLook = false; Vector2 start = Vector2.zero, last = Vector2.zero; bool dragging = false; world.RegisterCallback(evt => @@ -460,6 +464,8 @@ namespace Soundings if (paused || pointerId >= 0 || (evt.button != 0 && evt.button != 1)) return; pointerId = evt.pointerId; + freeLook = underway != null && evt.button == 1; + SetPassageFreeLook(freeLook); start = last = evt.localPosition; dragging = false; world.CapturePointer(pointerId); @@ -473,7 +479,10 @@ namespace Soundings if (dragging || (position - start).sqrMagnitude > 16) { dragging = true; - harbor.Orbit(position - last); + if (!freeLook) + harbor.Orbit(position - last); + else if (!passageCursorLocked) + harbor.Look(position - last); } last = position; }); @@ -482,6 +491,8 @@ namespace Soundings if (evt.pointerId != pointerId) return; pointerId = -1; + freeLook = false; + SetPassageFreeLook(false); world.ReleasePointer(evt.pointerId); if (!dragging && evt.button == 0 && underway == null && Ship != null && harbor.IsShipAt(new Vector2(evt.localPosition.x / world.resolvedStyle.width, @@ -491,7 +502,18 @@ namespace Soundings Render(); } }); - world.RegisterCallback(_ => pointerId = -1); + world.RegisterCallback(_ => + { + pointerId = -1; + freeLook = false; + if (!passageCursorLocked || !Input.GetMouseButton(1)) + SetPassageFreeLook(false); + }); + world.RegisterCallback(evt => + { + if (evt.pointerId == pointerId) + world.ReleasePointer(pointerId); + }); world.RegisterCallback(evt => { if (paused) @@ -577,6 +599,7 @@ namespace Soundings private void OnDestroy() { + SetPassageFreeLook(false); if (panel != null) Destroy(panel); } diff --git a/Assets/Soundings/Runtime/VisualSmoke.cs b/Assets/Soundings/Runtime/VisualSmoke.cs index 23fe792..d09ed0f 100644 --- a/Assets/Soundings/Runtime/VisualSmoke.cs +++ b/Assets/Soundings/Runtime/VisualSmoke.cs @@ -22,7 +22,8 @@ namespace Soundings Directory.CreateDirectory(directory); yield return CaptureSmoke(directory, "01-title"); - if (!SubmitSmoke("guide-toggle") || !CheckSmoke(!guidedCareer, "Guide can be turned off at title") + if (!CheckSmoke(guidedCareer, "The guide is on by default") + || !SubmitSmoke("guide-toggle") || !CheckSmoke(!guidedCareer, "Guide can be turned off at title") || !SubmitSmoke("guide-toggle") || !SubmitSmoke("start-used") || !CheckSmoke(Ship?.Name == "MV Meridian" && guideContext == GuideStep.SetCourse, "Guided used start")) yield break; @@ -33,10 +34,53 @@ namespace Soundings int fare = Ship.Fare; if (!SubmitSmoke("fare-plus") || !CheckSmoke(Ship.Fare == fare + 50 && guideContext == GuideStep.CastOff, "Fare control and departure guide")) yield break; - if (!SubmitSmoke("dispatch") || !CheckSmoke(underway != null && Ship.Port == 0 && company.Voyages == 0, "Cast off")) + if (!SubmitSmoke("weather-swell") || !CheckSmoke(PassageWeatherFor(0, 1) == WeatherCondition.Swell, "Select forecast conditions") + || !SubmitSmoke("weather-calm")) + yield break; + if (!SubmitSmoke("dispatch") || !CheckSmoke(underway != null && livePassage != null && Ship.Port == 0 + && company.Voyages == 0 && PassageDuration(underway) >= 120 && livePassage.Assisted && underway.Weather == WeatherCondition.Calm + && guideContext == GuideStep.AtSea && root.Q