diff --git a/Assets/Soundings/Editor/EconomyVerification.cs b/Assets/Soundings/Editor/EconomyVerification.cs index 489861a..11601c4 100644 --- a/Assets/Soundings/Editor/EconomyVerification.cs +++ b/Assets/Soundings/Editor/EconomyVerification.cs @@ -13,7 +13,8 @@ namespace Soundings.Editor VerifyFlagshipCampaign(); VerifyLiveCrossingSettlement(); VerifyStormAndShipSystems(); - Debug.Log("Soundings economy verification passed: both starts, pricing, fuel, accounting, saves, flagship progression, live settlement, weather and ship systems."); + VerifyPortOrders(); + Debug.Log("Soundings economy verification passed: both starts, pricing, fuel, accounting, saves, flagship progression, live settlement, weather, ship systems and port orders."); } private static void VerifyUsedStartAndProfit() @@ -223,6 +224,40 @@ namespace Soundings.Editor Require(company.Sail(ship, destination) == null, "complete campaign voyage"); } + private static void VerifyPortOrders() + { + Company company = Company.Start(false); + Ship ship = company.ActiveShip; + Voyage light = company.Forecast(ship, 1); + Voyage stocked = company.Forecast(ship, 1); + PortPlanning.Apply(ship, light, company.Day, 125, EntertainmentProgram.Shipboard); + PortPlanning.Apply(ship, stocked, company.Day, ship.FoodCapacity + 100, EntertainmentProgram.LiveMusic); + Require(light.Plan.FoodUnits == 125 && stocked.Plan.FoodUnits == ship.FoodCapacity + && stocked.Plan.FoodCost > light.Plan.FoodCost && stocked.Plan.ProgramCost > 0, "port food orders respect capacity and itemized costs"); + Require(PortPlanning.FoodPriceCents(0, company.Day) != PortPlanning.FoodPriceCents(1, company.Day), "ports have different food prices"); + + var understocked = new OnboardSession(ship, light) { Assisted = false }; + var provisioned = new OnboardSession(ship, stocked) { Assisted = false }; + understocked.AdvanceTo(.5f); + provisioned.AdvanceTo(.5f); + Require(provisioned.Get(OnboardService.Shows).Capacity > understocked.Get(OnboardService.Shows).Capacity, + "booked local act opens more show places in its scheduled service window"); + understocked.AdvanceTo(1); + provisioned.AdvanceTo(1); + Require(understocked.ProvisionsRemaining == 0 && provisioned.Health > understocked.Health + && provisioned.Happiness > understocked.Happiness, "underbuying food affects health and guest happiness"); + + int cash = company.Cash; + company.Cash = stocked.OperatingCash + stocked.LoanInterest + stocked.Principal - 1; + Require(company.DepartureBlock(ship, stocked) != null, "departure needs enough cash for dockside invoices"); + company.Cash = cash; + Require(company.Sail(ship, 1, provisioned) == null && company.Cash == cash + stocked.CashChange, + "port invoices settle in the voyage ledger"); + var loaded = JsonUtility.FromJson(JsonUtility.ToJson(company)); + Require(loaded.CanLoad() && loaded.History[0].Plan.FoodUnits == stocked.Plan.FoodUnits + && loaded.History[0].Plan.Program == EntertainmentProgram.LiveMusic, "dockside orders survive a saved arrival"); + } + private static void Require(bool condition, string description) { if (!condition) diff --git a/Assets/Soundings/Editor/SoundingsBuild.cs b/Assets/Soundings/Editor/SoundingsBuild.cs index f5c1c59..384b4c8 100644 --- a/Assets/Soundings/Editor/SoundingsBuild.cs +++ b/Assets/Soundings/Editor/SoundingsBuild.cs @@ -24,7 +24,7 @@ namespace Soundings.Editor EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(ScenePath, true) }; PlayerSettings.companyName = "Soundings"; PlayerSettings.productName = "Soundings"; - PlayerSettings.bundleVersion = "0.4.0"; + PlayerSettings.bundleVersion = "0.5.0"; PlayerSettings.defaultScreenWidth = 1920; PlayerSettings.defaultScreenHeight = 1080; PlayerSettings.fullScreenMode = FullScreenMode.FullScreenWindow; diff --git a/Assets/Soundings/Resources/Art/OceanDetail.png b/Assets/Soundings/Resources/Art/OceanDetail.png new file mode 100644 index 0000000..26ab02b Binary files /dev/null and b/Assets/Soundings/Resources/Art/OceanDetail.png differ diff --git a/Assets/Soundings/Resources/Art/OceanDetail.png.meta b/Assets/Soundings/Resources/Art/OceanDetail.png.meta new file mode 100644 index 0000000..5dae66d --- /dev/null +++ b/Assets/Soundings/Resources/Art/OceanDetail.png.meta @@ -0,0 +1,132 @@ +fileFormatVersion: 2 +guid: 908799eddb64409784df90744e666af8 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 13 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + flipGreenChannel: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMipmapLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 512 + textureSettings: + serializedVersion: 2 + filterMode: 2 + aniso: 4 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationMethod: 0 + spriteTessellationDetail: -1 + spriteGeometrySubdivision: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 512 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 512 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: WebGL + maxTextureSize: 512 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio.meta b/Assets/Soundings/Resources/Audio.meta new file mode 100644 index 0000000..b540bd2 --- /dev/null +++ b/Assets/Soundings/Resources/Audio.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 11dca20d70e42490c876759d5e3af804 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA.meta b/Assets/Soundings/Resources/Audio/PA.meta new file mode 100644 index 0000000..7e4a7d9 --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0acab46c810f26ddfb18d6fbc7d80c28 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/Attribution.txt b/Assets/Soundings/Resources/Audio/PA/Attribution.txt new file mode 100644 index 0000000..a10731f --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Attribution.txt @@ -0,0 +1,7 @@ +The Soundings shipboard announcements use original scripts synthesized offline with the af_heart voice from Kokoro-82M v1.0 by hexgrad. The Kokoro model is released under Apache 2.0. Only rendered announcement audio is included in Soundings. + +Model card and training-data credits +https://huggingface.co/hexgrad/Kokoro-82M + +The audio was generated with kokoro-onnx 0.6.0. +https://github.com/thewh1teagle/kokoro-onnx diff --git a/Assets/Soundings/Resources/Audio/PA/Attribution.txt.meta b/Assets/Soundings/Resources/Audio/PA/Attribution.txt.meta new file mode 100644 index 0000000..0e69ac5 --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Attribution.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 82f15791e2ecd53d38fcce00fc901c68 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/Bar.wav b/Assets/Soundings/Resources/Audio/PA/Bar.wav new file mode 100644 index 0000000..e6872b1 Binary files /dev/null and b/Assets/Soundings/Resources/Audio/PA/Bar.wav differ diff --git a/Assets/Soundings/Resources/Audio/PA/Bar.wav.meta b/Assets/Soundings/Resources/Audio/PA/Bar.wav.meta new file mode 100644 index 0000000..a9dc8ed --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Bar.wav.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: 06accf73f0e5dea068a191c6b79e812e +AudioImporter: + externalObjects: {} + serializedVersion: 8 + defaultSettings: + serializedVersion: 2 + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + preloadAudioData: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/Departure.wav b/Assets/Soundings/Resources/Audio/PA/Departure.wav new file mode 100644 index 0000000..82b0c19 Binary files /dev/null and b/Assets/Soundings/Resources/Audio/PA/Departure.wav differ diff --git a/Assets/Soundings/Resources/Audio/PA/Departure.wav.meta b/Assets/Soundings/Resources/Audio/PA/Departure.wav.meta new file mode 100644 index 0000000..f2ab88a --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Departure.wav.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: 290966337ddab1358964477fc7a3202d +AudioImporter: + externalObjects: {} + serializedVersion: 8 + defaultSettings: + serializedVersion: 2 + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + preloadAudioData: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/Dining.wav b/Assets/Soundings/Resources/Audio/PA/Dining.wav new file mode 100644 index 0000000..727ee7d Binary files /dev/null and b/Assets/Soundings/Resources/Audio/PA/Dining.wav differ diff --git a/Assets/Soundings/Resources/Audio/PA/Dining.wav.meta b/Assets/Soundings/Resources/Audio/PA/Dining.wav.meta new file mode 100644 index 0000000..e3dbdc3 --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Dining.wav.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: ea2c7e5d0d8bc1b5da77b0e0a8d791dc +AudioImporter: + externalObjects: {} + serializedVersion: 8 + defaultSettings: + serializedVersion: 2 + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + preloadAudioData: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/DiningSpecial.wav b/Assets/Soundings/Resources/Audio/PA/DiningSpecial.wav new file mode 100644 index 0000000..d3004d0 Binary files /dev/null and b/Assets/Soundings/Resources/Audio/PA/DiningSpecial.wav differ diff --git a/Assets/Soundings/Resources/Audio/PA/DiningSpecial.wav.meta b/Assets/Soundings/Resources/Audio/PA/DiningSpecial.wav.meta new file mode 100644 index 0000000..ed34b5d --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/DiningSpecial.wav.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: 53420062d12c46893aa758dc4fbb67bc +AudioImporter: + externalObjects: {} + serializedVersion: 8 + defaultSettings: + serializedVersion: 2 + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + preloadAudioData: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/Show.wav b/Assets/Soundings/Resources/Audio/PA/Show.wav new file mode 100644 index 0000000..bd4b038 Binary files /dev/null and b/Assets/Soundings/Resources/Audio/PA/Show.wav differ diff --git a/Assets/Soundings/Resources/Audio/PA/Show.wav.meta b/Assets/Soundings/Resources/Audio/PA/Show.wav.meta new file mode 100644 index 0000000..e5d29d7 --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Show.wav.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: 32f007cea9c4ab25c867e04b222d9dac +AudioImporter: + externalObjects: {} + serializedVersion: 8 + defaultSettings: + serializedVersion: 2 + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + preloadAudioData: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Audio/PA/Terrace.wav b/Assets/Soundings/Resources/Audio/PA/Terrace.wav new file mode 100644 index 0000000..c12a4d0 Binary files /dev/null and b/Assets/Soundings/Resources/Audio/PA/Terrace.wav differ diff --git a/Assets/Soundings/Resources/Audio/PA/Terrace.wav.meta b/Assets/Soundings/Resources/Audio/PA/Terrace.wav.meta new file mode 100644 index 0000000..c091e30 --- /dev/null +++ b/Assets/Soundings/Resources/Audio/PA/Terrace.wav.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: d45dcb6ac9382e62a9d2991e9cbb5d5e +AudioImporter: + externalObjects: {} + serializedVersion: 8 + defaultSettings: + serializedVersion: 2 + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + preloadAudioData: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Chart.uss b/Assets/Soundings/Resources/Chart.uss index 2deb121e..7860546 100644 --- a/Assets/Soundings/Resources/Chart.uss +++ b/Assets/Soundings/Resources/Chart.uss @@ -423,3 +423,160 @@ color: #35654d; -unity-font-style: bold; } + +.port-orders-link { + flex-direction: row; + align-items: center; + justify-content: space-between; + margin-top: 7px; + padding: 6px 7px; + background-color: rgba(115, 95, 57, .09); + border-left-width: 2px; + border-left-color: #ac8b59; +} + +.port-orders-link-copy, +.port-orders-header-copy { + flex-grow: 1; + flex-shrink: 1; + min-width: 0; +} + +.port-orders-summary { + color: #344845; + font-size: 11px; + white-space: normal; +} + +.navigation-chart .port-orders-edit { + min-height: 23px; + margin-left: 5px; + font-size: 11px; +} + +.port-orders-stage { + position: absolute; + left: 34px; + right: 382px; + top: 153px; + bottom: 88px; + background-color: #e8dcc0; + border-color: #c2a474; + border-width: 1px; + border-radius: 3px; +} + +.port-orders-paper { + padding: 18px 24px 15px; +} + +.port-orders-header, +.port-orders-total { + flex-direction: row; + align-items: center; + justify-content: space-between; +} + +.port-orders-title { + color: #284a4c; + font-size: 36px; + margin-top: 2px; +} + +.port-orders-section { + color: #344845; + font-size: 22px; + margin-top: 12px; + margin-bottom: 2px; +} + +.port-orders-note { + color: #655844; + font-size: 12px; + white-space: normal; +} + +.port-orders-shortage { + color: #8a4331; + -unity-font-style: bold; +} + +.port-orders-food { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + margin-top: 6px; + margin-bottom: 5px; +} + +.port-orders-food .chart-ink-button { + margin-right: 5px; + min-height: 28px; + font-size: 12px; +} + +.port-orders-input { + width: 78px; + margin: 0 5px 0 0; + color: #243e3a; +} + +.port-orders-input .unity-base-field__input, +.port-orders-input .unity-base-text-field__input, +.port-orders-input .unity-integer-field__input { + min-height: 28px; + background-color: #f6e9c9; + border-color: #b89f73; + border-radius: 2px; + color: #243e3a; + font-size: 14px; + -unity-font-style: bold; + -unity-text-align: middle-center; +} + +.port-orders-input .unity-text-element { color: #243e3a; } + +.navigation-chart .port-program-choice { + min-height: 45px; + flex-direction: row; + align-items: center; + background-color: #efe1c4; + border-color: #bda883; + border-radius: 2px; + padding: 6px 10px; + margin-top: 4px; +} + +.navigation-chart .port-program-choice:hover, +.navigation-chart .port-program-choice:focus, +.navigation-chart .port-program-booked { + background-color: #dfdfc4; + border-color: #668078; +} + +.port-program-choice .port-orders-link-copy { align-items: flex-start; } +.port-program-choice .port-orders-link-copy Label { -unity-text-align: middle-left; } + +.port-program-title, +.port-orders-price { + color: #294745; + font-size: 13px; + -unity-font-style: bold; +} + +.port-orders-price { + margin-left: 7px; +} + +.port-orders-total { + margin-top: 12px; + padding-top: 8px; + border-top-width: 1px; + border-top-color: #bda883; +} + +.port-orders-total-value { + color: #294745; + font-size: 24px; + margin-left: 10px; +} diff --git a/Assets/Soundings/Resources/HarborReflection.shader b/Assets/Soundings/Resources/HarborReflection.shader index 6c81a00..5a9f1bb 100644 --- a/Assets/Soundings/Resources/HarborReflection.shader +++ b/Assets/Soundings/Resources/HarborReflection.shader @@ -13,20 +13,26 @@ Shader "Soundings/Harbor Reflection" ZWrite Off Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM + #pragma target 3.0 #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" + #include "OceanWaves.cginc" fixed4 _Color; + float _SoundingsSeaSailing, _SoundingsSeaWeather, _SoundingsSeaTime; struct Output { float4 clip : SV_POSITION; float3 world : TEXCOORD0; }; Output vert(appdata_base input) { Output output; float4 worldPosition = mul(unity_ObjectToWorld, input.vertex); + float time = lerp(_Time.y, _SoundingsSeaTime, _SoundingsSeaSailing); + float3 wave = OceanWave(worldPosition.xz, time, _SoundingsSeaWeather) * _SoundingsSeaSailing; worldPosition.y = -worldPosition.y * .59; - worldPosition.z += sin(worldPosition.x * .53 + worldPosition.y * 2.14 + _Time.y * 1.55) * .27; - worldPosition.x += sin(worldPosition.y * .88 - _Time.y) * .29; + worldPosition.y += wave.x * 1.5; + worldPosition.z += sin(worldPosition.x * .53 + worldPosition.y * 2.14 + time * 1.55) * .27 + wave.z * 4; + worldPosition.x += sin(worldPosition.y * .88 - time) * .29 + wave.y * 4; output.clip = UnityWorldToClipPos(worldPosition.xyz); output.world = worldPosition.xyz; return output; @@ -35,8 +41,9 @@ Shader "Soundings/Harbor Reflection" fixed4 frag(Output input) : SV_Target { clip(-input.world.y); - float breakup = .48 + .38 * sin(input.world.y * 14 + input.world.x * .62 - _Time.y * 1.02); - float alpha = saturate(1 + input.world.y / 7.5) * breakup * .34; + float time = lerp(_Time.y, _SoundingsSeaTime, _SoundingsSeaSailing); + float breakup = .48 + .38 * sin(input.world.y * 14 + input.world.x * .62 - time * 1.02); + float alpha = saturate(1 + input.world.y / 7.5) * breakup * lerp(.34, .24 - .11 * _SoundingsSeaWeather, _SoundingsSeaSailing); return fixed4(_Color.rgb * float3(.51,.60,.64), alpha); } ENDCG diff --git a/Assets/Soundings/Resources/HarborWater.shader b/Assets/Soundings/Resources/HarborWater.shader index 5bf0ffe..52da4e5 100644 --- a/Assets/Soundings/Resources/HarborWater.shader +++ b/Assets/Soundings/Resources/HarborWater.shader @@ -3,10 +3,11 @@ Shader "Soundings/Harbor Water" Properties { _Backdrop ("Harbor photograph", 2D) = "black" {} + _OceanDetail ("Ocean surface detail", 2D) = "gray" {} _BackdropCrop ("Harbor crop", Vector) = (1,1,0,0) _HullSpan ("Hull length and beam", Vector) = (71,7,0,0) _HullCourse ("Hull heading and wake strength", Vector) = (1,0,0,0) - _Underway ("Open water blend", Range(0,1)) = 0 + _Underway ("Open water", Float) = 0 _WeatherSeverity ("Sea conditions", Range(0,1)) = 0 } SubShader @@ -17,14 +18,17 @@ Shader "Soundings/Harbor Water" Cull Off ZWrite Off CGPROGRAM + #pragma target 3.0 #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" + #include "OceanWaves.cginc" - sampler2D _Backdrop; + sampler2D _Backdrop, _OceanDetail; float4 _BackdropCrop, _HullSpan, _HullCourse, _ViewSize; float3 _ViewOrigin, _ViewForward, _ViewRight, _ViewUp; float _Underway, _WeatherSeverity, _SeaTime; + static const float3 Sun = float3(-.761,.441,-.474); struct Output { float4 clip : SV_POSITION; float2 screen : TEXCOORD0; }; Output vert(appdata_base input) @@ -36,6 +40,117 @@ Shader "Soundings/Harbor Water" return output; } + float3 SkyGradient(float3 ray) + { + float warmth = pow(saturate(.55 + dot(ray.xz, Sun.xz) * .55), 2.3); + float3 horizon = lerp(float3(.50,.63,.68), float3(.91,.66,.46), warmth * .88); + float elevation = pow(saturate(ray.y), .52); + float3 sky = lerp(horizon, float3(.084,.218,.347), elevation); + float3 squall = lerp(float3(.39,.48,.53), float3(.102,.156,.202), elevation); + return lerp(sky, squall, _WeatherSeverity); + } + + float3 Sky(float3 ray, float time) + { + float2 wind = float2(.0014,-.0010) * time; + float2 layers = ray.xz * (.76 / (max(0, ray.y) + .21)) + wind; + float cloud = tex2Dlod(_OceanDetail, float4(layers * .19, 0, 2)).b * .68 + + tex2Dlod(_OceanDetail, float4(layers * .40 + .38, 0, 2)).b * .32; + float coverage = smoothstep(.57 - .15 * _WeatherSeverity, .82, cloud); + coverage *= smoothstep(-.015,.16,ray.y) * (1 - smoothstep(.66, 1, ray.y)); + float facing = pow(saturate(dot(ray, Sun)), 5); + float3 color = SkyGradient(ray); + float3 vapor = lerp(color * 1.14 + float3(.124,.106,.087) * facing, + color * .65 + float3(.038,.048,.056), _WeatherSeverity); + return lerp(color, vapor, coverage * (.65 + .3 * _WeatherSeverity)); + } + + float2 HullPoint(float2 world) + { + float2 relative = world - _HullSpan.zw; + return float2(dot(relative, float2(_HullCourse.x, -_HullCourse.y)), dot(relative, _HullCourse.yx)); + } + + float HullShade(float2 hullPoint) + { + float halfLength = _HullSpan.x * .5; + float along = abs(hullPoint.x / max(1, halfLength)); + float beam = _HullSpan.y * lerp(.24, 1, saturate(1 - pow(along, 3.2))); + return (1 - smoothstep(.1, 5.8, abs(hullPoint.y) - beam)) * (1 - smoothstep(.91, 1.105, along)); + } + + float BowWhitewater(float2 hull, float breakup) + { + float beam = _HullSpan.y; + float fromStem = _HullSpan.x * .49 - hull.x; + float steer = sqrt(_HullCourse.z); + float bandWidth = 1.55 + max(0, fromStem) * .022; + float glass = abs(hull.y) - (1 + max(0, fromStem) * .37); + float wedge = 1 - smoothstep(.2, bandWidth, abs(glass)); + float stem = 1 - smoothstep(.4, 2.9 + steer * 2.8, length(float2(fromStem + .9, hull.y * .68))); + float flare = smoothstep(-1.9, 7, fromStem) * (1 - smoothstep(_HullSpan.x * .56, _HullSpan.x * 1.16, fromStem)); + float rip = .75 + .25 * sin(fromStem * 1.45 + hull.y + _SeaTime * 7); + float nearBeam = beam * lerp(.22, 1, smoothstep(0, _HullSpan.x * .33, fromStem)); + float hullWash = 1 - smoothstep(.18, 2.05, abs(abs(hull.y) - nearBeam)); + hullWash *= smoothstep(0, 8, fromStem) * (1 - smoothstep(_HullSpan.x * .88, _HullSpan.x, fromStem)); + return saturate((wedge * flare * .81 + stem * .89 + hullWash * .57) * rip * breakup) * (steer * .93); + } + + float3 OpenSea(float3 origin, float3 ray, float2 screen) + { + float skyLine = smoothstep(-.0033, .0010, ray.y); + float down = max(.00042, -ray.y); + float distance = min(5800, origin.y / down); + float2 position = origin.xz + ray.xz * distance; + float3 waves = OceanWave(position, _SeaTime, _WeatherSeverity); + float intersectionBlend = 1 - smoothstep(180, 600, distance); + position -= ray.xz * clamp(waves.x / down, -9, 9) * intersectionBlend; + waves = OceanWave(position, _SeaTime, _WeatherSeverity); + + float2 rotated = float2(position.x * .82 - position.y * .57, position.x * .57 + position.y * .82); + float mip = clamp(log2(max(1, distance) / 76), 0, 7); + float3 chop = tex2Dlod(_OceanDetail, float4(position * .041 + float2(-.022,.013) * _SeaTime, 0, mip)).rgb; + float3 ripples = tex2Dlod(_OceanDetail, float4(rotated * .107 + float2(.032,.020) * _SeaTime, 0, mip + .65)).rgb; + float detail = 1 - smoothstep(85, 670, distance); + float swellDetail = 1 - smoothstep(180, 690, distance); + float roughness = lerp(.43, .96, _WeatherSeverity); + float2 slope = waves.yz * swellDetail + + ((chop.rg - .5) * .47 + (ripples.rg - .5) * .25) * detail * roughness; + float3 normal = normalize(float3(-slope.x, 1, -slope.y)); + float rough = ((chop.b - .5) * .045 + (ripples.b - .5) * .015) * detail; + float light = saturate(dot(normal, Sun)); + float3 fromBelow = lerp(float3(.031,.159,.220), float3(.064,.205,.274), .23 + .53 * light + rough * 7); + fromBelow = lerp(fromBelow, fromBelow * .60 + float3(.019,.028,.030), _WeatherSeverity * .82); + float reflection = .19 + .64 * pow(1 - saturate(dot(-ray, normal)), 4); + float3 reflected = reflect(ray, normal); + float3 color = lerp(fromBelow, SkyGradient(reflected) * .75, reflection); + float glint = pow(saturate(dot(reflected, Sun)), lerp(78, 29, _WeatherSeverity)); + color += glint * float3(.48,.38,.24) * (1 - .86 * _WeatherSeverity); + float nightFoam = smoothstep(.74,.96, chop.b * .67 + ripples.b * .33 + slope.x * .39); + color = lerp(color, float3(.53,.67,.69), nightFoam * detail * (.22 + _WeatherSeverity * .57)); + + if (_HullSpan.x > 1) + { + float2 hull = HullPoint(position); + color *= 1 - HullShade(hull) * .35; + float breakup = .63 + smoothstep(.28,.73, chop.b + ripples.b * .33) * .55; + float foam = BowWhitewater(hull, breakup); + color = lerp(color, float3(.79,.89,.89), foam); + } + + float mist = 1 - exp(-distance * (.00040 + .00077 * _WeatherSeverity)); + color = lerp(color, SkyGradient(float3(ray.x, 0, ray.z)) * .90, mist * .80); + if (skyLine > 0) + color = lerp(color, Sky(ray, _SeaTime), skyLine); + if (_WeatherSeverity > .75) + { + float2 grid = float2(screen.x * 165 + screen.y * 42, screen.y * 23 + _SeaTime * 17); + float rain = step(.978, frac(grid.x + floor(grid.y) * .381)) * smoothstep(.56, .68, frac(grid.y)); + color += rain * float3(.095,.133,.15); + } + return color; + } + fixed4 frag(Output input) : SV_Target { float2 screen = input.screen; @@ -43,67 +158,22 @@ Shader "Soundings/Harbor Water" float3 viewOffset = offsetOnFilm.x * _ViewRight + offsetOnFilm.y * _ViewUp; float3 origin = _ViewOrigin + viewOffset * _ViewSize.z; float3 ray = normalize(_ViewForward + viewOffset * (1 - _ViewSize.z)); - float distanceToWater = min(2600, max(0, -origin.y / min(ray.y, -.0001))); - float2 world = origin.xz + ray.xz * distanceToWater; + if (_Underway > .5) + { + if (ray.y >= .0010) + return fixed4(Sky(ray, _SeaTime), 1); + return fixed4(OpenSea(origin, ray, screen), 1); + } + float2 uv = (screen - .5) * _BackdropCrop.xy + .5 + _BackdropCrop.zw; - float waterMask = 1 - smoothstep(.55,.69,uv.y); - float2 relative = world - _HullSpan.zw; - float2 p = float2(dot(relative, float2(_HullCourse.x, -_HullCourse.y)), - dot(relative, _HullCourse.yx)); - float t = lerp(_Time.y, _SeaTime, _Underway); - float textureWave = sin(world.y * 1.94 + world.x * .30 + sin(world.x * .44 - t * (.30 + 1.2 * _WeatherSeverity))) - * (.0015 + .003 * _WeatherSeverity); + float waterMask = 1 - smoothstep(.55, .69, uv.y); + float distance = min(2600, max(0, -origin.y / min(ray.y, -.0001))); + float2 world = origin.xz + ray.xz * distance; + float textureWave = sin(world.y * 1.94 + world.x * .30 + sin(world.x * .44 - _Time.y * .30)) * .0015; uv += waterMask * float2(textureWave, textureWave * .14); float3 color = tex2D(_Backdrop, uv).rgb; - if (_Underway > 0) - { - float seaHeight = clamp(uv.y * .59 + .056, .055, .49); - float drift = sin(p.y * .166 + t * .19) * .017; - float3 openWater = tex2D(_Backdrop, float2(saturate(uv.x + drift), seaHeight)).rgb; - float skyBand = lerp(smoothstep(-.006, .004, ray.y), smoothstep(.67, .70, screen.y), _ViewSize.z); - float twilight = lerp(saturate(ray.y * 2.8), saturate((screen.y - .70) * 3.8), _ViewSize.z); - 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(world.y * .83 + world.x * .45 - t * 2.4) * sin(world.x * .48 + world.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); - } - - if (_HullSpan.x < 1) - return fixed4(color, 1); - - float halfLength = _HullSpan.x * .5; - float along = abs((p.x + halfLength * .022) / halfLength); - float shaft = saturate(1 - pow(max(0,along), 3.2)); - float waterline = _HullSpan.y * lerp(.28, 1, shaft); - float offset = abs(p.y + .5) - waterline; - float shadow = (1 - smoothstep(-.8, 5.1, offset)) * (1 - smoothstep(.90,1.12,along)); - color *= 1 - .39 * shadow * waterMask; - float edgeWave = sin(p.x * 1.46 + p.y * 1.88 + t * .65) + .36 * sin(p.x * 3.3 + p.y * 2.42 - t * .50); - float foam = saturate(edgeWave - .55) * (1 - smoothstep(.12, 1.3, abs(offset - .25))) * (1 - smoothstep(.81,1.06,along)); - color += float3(.19,.23,.24) * foam * waterMask; - if (_Underway > 0) - { - float trail = max(0, -p.x - halfLength * .88); - float v = abs(p.y) - (2.2 + trail * .19); - float turbulence = .5 + .28 * sin(p.x * 1.5 + p.y * 5.6 + t * 4) - + .22 * sin(p.y * 13.7 - p.x * .37 - t * 2.2); - float wake = smoothstep(.05, 2, trail) * (1 - smoothstep(1, 5 + trail * .062, abs(v))) - * (1 - smoothstep(12, 89, trail)) * turbulence; - color = lerp(color, float3(.72,.84,.84), wake * waterMask * .43 * _Underway * _HullCourse.z); - } + if (_HullSpan.x > 1) + color *= 1 - HullShade(HullPoint(world)) * .33 * waterMask; return fixed4(color, 1); } ENDCG diff --git a/Assets/Soundings/Resources/OceanWaves.cginc b/Assets/Soundings/Resources/OceanWaves.cginc new file mode 100644 index 0000000..e799848 --- /dev/null +++ b/Assets/Soundings/Resources/OceanWaves.cginc @@ -0,0 +1,18 @@ +#ifndef SOUNDINGS_OCEAN_WAVES +#define SOUNDINGS_OCEAN_WAVES + +float3 OceanWave(float2 position, float time, float storm) +{ + float amplitude = lerp(.35, 1.46, storm * storm); + float2 windWave = float2(.052, .115); + float2 swellWave = float2(-.073, .170); + float2 crossWave = float2(.217, -.136); + float s1, c1, s2, c2, s3, c3; + sincos(dot(position, windWave) - time * .93, s1, c1); + sincos(dot(position, swellWave) - time * 1.22 + 1.3, s2, c2); + sincos(dot(position, crossWave) - time * 1.64 + 2.9, s3, c3); + float2 gradient = .65 * windWave * c1 + .25 * swellWave * c2 + .10 * crossWave * c3; + return amplitude * float3(.65 * s1 + .25 * s2 + .10 * s3, gradient); +} + +#endif diff --git a/Assets/Soundings/Resources/OceanWaves.cginc.meta b/Assets/Soundings/Resources/OceanWaves.cginc.meta new file mode 100644 index 0000000..3113415 --- /dev/null +++ b/Assets/Soundings/Resources/OceanWaves.cginc.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5ffe9ba48d1c4ac3beef4f1623b1c331 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Resources/Passage.uss b/Assets/Soundings/Resources/Passage.uss index 2d61cdc..0b6e859 100644 --- a/Assets/Soundings/Resources/Passage.uss +++ b/Assets/Soundings/Resources/Passage.uss @@ -82,11 +82,14 @@ .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 { +.voyage-footer { position: absolute; - bottom: 100px; - left: 7%; - right: 7%; + bottom: 18px; + left: 5%; + right: 5%; +} +.voyage-deckbar { + margin: 0 2% 7px; flex-direction: row; flex-wrap: wrap; justify-content: center; @@ -107,10 +110,6 @@ .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; @@ -151,3 +150,51 @@ .action.helm-order { flex-grow: 1; min-height: 25px; padding: 2px 4px; margin-right: 2px; font-size: 11px; } .helm-help { color: #b7c8c4; font-size: 11px; margin: 2px 0 6px; } .action.helm-toggle { min-height: 32px; font-size: 12px; } + +.station-reticle { + position: absolute; + left: 50%; + top: 50%; + width: 6px; + height: 6px; + margin-left: -3px; + margin-top: -3px; + border-width: 1px; + border-color: #f0e7c5; + border-radius: 3px; + background-color: rgba(10, 23, 30, .46); +} +.station-prompt, .station-feedback { + position: absolute; + left: 36%; + right: 36%; + align-items: center; + padding: 7px 12px; + border-width: 1px; + background-color: rgba(7, 23, 29, .94); + border-color: #768e86; +} +.station-prompt { top: 54%; } +.station-requested { border-color: #d0af71; } +.station-title { font-size: 11px; color: #d8b77f; -unity-font-style: bold; } +.station-command { font-size: 14px; color: #f0ecda; margin-top: 2px; white-space: normal; -unity-text-align: middle-center; } +.station-feedback { bottom: 149px; color: #f4dbad; font-size: 13px; white-space: normal; -unity-text-align: middle-center; } +.crew-call-readout { color: #e7c78b; font-size: 11px; margin-top: 3px; } +.crew-call-urgent { color: #ffc290; } + +.passage-announcement { + position: absolute; + left: 28%; + right: 28%; + bottom: 184px; + padding: 6px 12px 7px; + background-color: rgba(9, 20, 28, .91); + border-top-width: 1px; + border-top-color: #b99966; +} +.passage-announcement-caption { + color: #efe9d8; + font-size: 13px; + white-space: normal; + margin-top: 2px; +} diff --git a/Assets/Soundings/Resources/PassageWake.shader b/Assets/Soundings/Resources/PassageWake.shader new file mode 100644 index 0000000..43faac2 --- /dev/null +++ b/Assets/Soundings/Resources/PassageWake.shader @@ -0,0 +1,58 @@ +Shader "Soundings/Passage Wake" +{ + Properties { _OceanDetail ("Wake detail", 2D) = "gray" {} } + SubShader + { + Tags { "Queue"="Background+2" "RenderType"="Transparent" } + Pass + { + Cull Off + ZWrite Off + Blend SrcAlpha OneMinusSrcAlpha + CGPROGRAM + #pragma target 3.0 + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + #include "OceanWaves.cginc" + + sampler2D _OceanDetail; + float _SeaTime, _WeatherSeverity; + struct Input { float4 vertex : POSITION; float4 trace : TEXCOORD0; }; + struct Output { float4 clip : SV_POSITION; float4 trace : TEXCOORD0; float2 water : TEXCOORD1; }; + + Output vert(Input input) + { + Output output; + float3 vertex = input.vertex.xyz; + vertex.y += OceanWave(vertex.xz, _SeaTime, _WeatherSeverity).x; + output.clip = UnityObjectToClipPos(float4(vertex, 1)); + output.trace = input.trace; + output.water = vertex.xz; + return output; + } + + fixed4 frag(Output input) : SV_Target + { + float across = abs(input.trace.x); + float age = input.trace.y; + float thrust = input.trace.z; + float distance = input.trace.w; + float2 water = input.water; + float eddies = tex2D(_OceanDetail, water * .118 + float2(-.016,.016) * _SeaTime).b; + float flecks = tex2D(_OceanDetail, water * .285 + float2(.008,-.011) * _SeaTime).b; + float disturbed = 1 - smoothstep(.28,.47, across + .065 * (eddies - .5)); + float stripes = sin(across * 22 + eddies * 5 + distance * .055); + float churn = smoothstep(.36,.78, eddies * .57 + flecks * .43 + stripes * .14); + float kelvin = 1 - smoothstep(.044,.155, abs(across - .76 + .08 * (eddies - .5))); + float ripples = .41 + .59 * sin(distance * .47 + across * 16 - _SeaTime * 2.8); + float whitewater = disturbed * (.54 + .45 * churn) + kelvin * saturate(ripples) * (.33 + .42 * eddies); + float lifetime = (1 - smoothstep(4, 34, age)); + float alpha = whitewater * thrust * lifetime * (.89 - _WeatherSeverity * .13); + float3 foam = lerp(float3(.47,.68,.71), float3(.87,.94,.93), churn * .84 + .15); + return fixed4(foam, saturate(alpha)); + } + ENDCG + } + } +} diff --git a/Assets/Soundings/Resources/PassageWake.shader.meta b/Assets/Soundings/Resources/PassageWake.shader.meta new file mode 100644 index 0000000..a27eb8a --- /dev/null +++ b/Assets/Soundings/Resources/PassageWake.shader.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: a457616e3bfc4633be04e46ee0f39e33 +ShaderImporter: + defaultTextures: [] + nonModifiableTextures: [] diff --git a/Assets/Soundings/Resources/PassengerSurface.shader b/Assets/Soundings/Resources/PassengerSurface.shader new file mode 100644 index 0000000..a06a3fa --- /dev/null +++ b/Assets/Soundings/Resources/PassengerSurface.shader @@ -0,0 +1,40 @@ +Shader "Soundings/Passenger Surface" +{ + SubShader + { + Tags { "RenderType"="Opaque" "Queue"="Geometry" } + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + + struct Input { float4 vertex : POSITION; float3 normal : NORMAL; fixed4 tint : COLOR; }; + struct Output { float4 clip : SV_POSITION; float3 normal : TEXCOORD0; fixed4 tint : COLOR; }; + + Output vert(Input input) + { + Output output; + output.clip = UnityObjectToClipPos(input.vertex); + output.normal = UnityObjectToWorldNormal(input.normal); + output.tint = input.tint; + return output; + } + + fixed4 frag(Output input) : SV_Target + { + // A gradual coverage ramp keeps changing service occupancy from cutting people in and out abruptly. + float noise = frac(dot(floor(input.clip.xy), float2(.754877, .56984))); + clip(input.tint.a - noise - .001); + float3 normal = normalize(input.normal); + float sun = saturate(dot(normal, normalize(float3(-.69,.40,-.43)))); + float overhead = saturate(normal.y * .5 + .5); + float3 light = lerp(float3(.55,.63,.71), float3(.83,.88,.94), overhead) + + sun * float3(.38,.29,.176); + return fixed4(saturate(input.tint.rgb * light), 1); + } + ENDCG + } + } +} diff --git a/Assets/Soundings/Resources/PassengerSurface.shader.meta b/Assets/Soundings/Resources/PassengerSurface.shader.meta new file mode 100644 index 0000000..47aef13 --- /dev/null +++ b/Assets/Soundings/Resources/PassengerSurface.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 6b1e9755ea9d51f529eea0041be47cad +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Soundings/Runtime/Company.cs b/Assets/Soundings/Runtime/Company.cs index 9c28306..23ecbd9 100644 --- a/Assets/Soundings/Runtime/Company.cs +++ b/Assets/Soundings/Runtime/Company.cs @@ -54,8 +54,10 @@ namespace Soundings TicketSales, OnboardSales, Crew, Catering, PortFees, FuelExpense, LoanInterest, Principal, ReputationChange; public string ShipName; public OnboardReport Onboard; + public DeparturePlan Plan; public WeatherCondition Weather; - public int OperatingCash => Crew + Catering + PortFees + (Onboard?.Expenses ?? 0); + public int OperatingCash => Crew + Catering + PortFees + (Plan == null ? 0 : Plan.FoodCost + Plan.ProgramCost) + + (Onboard?.Expenses ?? 0); public int NetIncome => TicketSales + OnboardSales - OperatingCash - FuelExpense - LoanInterest; public int CashChange => TicketSales + OnboardSales - OperatingCash - LoanInterest - Principal; public int RequiredFuel => FuelBurn + Reserve; @@ -384,7 +386,8 @@ namespace Soundings if (quote.Guests <= 0) return "Raise demand or lower the fare to attract passengers."; if (Cash < quote.OperatingCash + quote.LoanInterest + quote.Principal) - return "Cash must cover the voyage expenses and loan payment."; + return quote.Plan == null ? "Cash must cover the voyage expenses and loan payment." + : "Cash must cover port orders, voyage expenses and the loan payment."; return null; } diff --git a/Assets/Soundings/Runtime/CompanyPages.cs b/Assets/Soundings/Runtime/CompanyPages.cs index 51d9be4..2867034 100644 --- a/Assets/Soundings/Runtime/CompanyPages.cs +++ b/Assets/Soundings/Runtime/CompanyPages.cs @@ -118,7 +118,7 @@ namespace Soundings var contents = Add(folio, "chart-folio-content"); AddText(contents, "LOOK UP PORT", "chart-paper-kicker"); AddChartDirectory(contents); - DrawPortFolio(contents); + DrawPortFolio(board, contents); } private static void ChartKey(VisualElement legend, string name, string color) @@ -145,7 +145,7 @@ namespace Soundings parent.Add(selector); } - private void DrawPortFolio(VisualElement parent) + private void DrawPortFolio(VisualElement board, VisualElement parent) { Ship ship = Ship; int selected = inspectedPort; @@ -160,7 +160,7 @@ namespace Soundings if (quote != null && permitted && eligible) { - DrawVoyageFolio(parent, ship, quote); + DrawVoyageFolio(board, parent, ship, quote); return; } @@ -173,6 +173,7 @@ namespace Soundings ChartLine(parent, $"From {Market.Ports[ship.Port].Name}", $"{quote.Miles:N0} nm"); if (berth) { + ChartLine(parent, "Provisions at this berth", $"{FoodUnitPrice(selected)} / portion"); DrawChartBunkering(parent, ship); return; } diff --git a/Assets/Soundings/Runtime/DeckPassengers.cs b/Assets/Soundings/Runtime/DeckPassengers.cs index b94aead..6fc4cc1 100644 --- a/Assets/Soundings/Runtime/DeckPassengers.cs +++ b/Assets/Soundings/Runtime/DeckPassengers.cs @@ -27,6 +27,7 @@ namespace Soundings private readonly Ship ship; private readonly float length, beam; private readonly Shader shader; + private readonly int programDeck = -1, programRoom = -1; private readonly Dictionary paint = new(); private readonly List meshes = new(); private readonly Layout[] decks; @@ -34,7 +35,7 @@ namespace Soundings private Layout bridge; private Transform helmWheel; private float rudderDegrees; - private Mesh clothes, head; + private readonly PassengerCrowd passengerCrowd = new(); private int activeIndex = -1; private bool bridgeView; private float animationTime; @@ -43,7 +44,9 @@ namespace Soundings { public readonly GameObject Room, Crowd, Interior, Cutaway; public readonly ShipWalkSpace WalkSpace; - public readonly List People = new(); + public readonly List People = new(); + public readonly List Stations = new(); + public Mesh CrowdMesh; public Layout(string name, Transform parent, ShipWalkSpace walkSpace = null) { @@ -58,15 +61,6 @@ namespace Soundings } } - 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; @@ -75,7 +69,16 @@ namespace Soundings this.beam = beam; shader = surface; decks = new Layout[ship.Decks.Count]; - BuildPeopleMeshes(); + Facility programVenue = ship.Entertainment > 0 ? Facility.Entertainment : Facility.Dining; + for (int index = 0; index < ship.Decks.Count; index++) + { + int room = Array.IndexOf(ship.Decks[index].Cells, programVenue); + if (room < 0) + continue; + programDeck = index; + programRoom = room; + break; + } promenade = BuildPromenade(); promenade.Crowd.SetActive(false); } @@ -107,6 +110,8 @@ namespace Soundings public Vector3 BridgeOrigin() => new(BridgeCenter - 1.74f, BridgeHeight + EyeHeight, 0); internal ShipWalkSpace BridgeWalkSpace => bridge.WalkSpace; internal ShipWalkSpace WalkSpace(int index) => decks[index].WalkSpace; + internal IReadOnlyList ActiveStations => bridgeView ? bridge.Stations + : activeIndex < 0 ? Array.Empty() : decks[activeIndex].Stations; internal void SetRudder(float degrees) { @@ -177,55 +182,50 @@ namespace Soundings public void Tick(OnboardSession session, float delta) { - if (bridgeView || session == null) + if (session == null) return; animationTime += Mathf.Max(0, delta); + if (bridgeView) + return; 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; - } + layout.CrowdMesh ??= passengerCrowd.CreateMesh(layout.Crowd, length, beam); + passengerCrowd.Draw(layout.CrowdMesh, layout.People, session, activeIndex < 0, animationTime, delta); } 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++) + int deck = ship.Decks.Count - 1; + float y = BridgeHeight + .015f; + float deckLength = VesselExterior.DeckLength(length, deck); + float width = VesselExterior.DeckHalfBeam(beam, deck); + float offset = VesselExterior.DeckOffset(length, deck); + float aft = offset - deckLength * .305f; + float fore = Mathf.Min(BridgeCenter - 6.0f, offset + deckLength * .17f); + int walkers = 7 + ship.HullIndex * 3; + for (int side = -1; side <= 1; side += 2) { - 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); + for (int i = 0; i < walkers; i++) + { + float occupancy = Mathf.Lerp(.15f, .95f, i / (float)(walkers - 1)); + var route = new Vector3(aft, y, side * width * .865f); + layout.People.Add(new DeckGuest(route, fore, width * .075f, (i + (side > 0 ? .43f : 0)) / walkers, + 15 + i * 13 + (side > 0 ? 131 : 0), occupancy)); + } + + float rail = width - .56f; + float heading = side < 0 ? 180 : 0; + AddGuest(layout, GuestActivity.Rail, new Vector3(fore + .92f, y, side * rail), 78 + side, heading, -1, .28f); + AddGuest(layout, GuestActivity.Photograph, new Vector3(aft - .98f, y, side * (rail - .16f)), 32 + side, heading, -1, .57f); } - 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); + + float pool = offset + deckLength * .01f; + AddGuest(layout, GuestActivity.Talk, new Vector3(pool - 3.40f, y, -1.14f), 37, 0, (int)OnboardService.Amenities, .20f); + AddGuest(layout, GuestActivity.Talk, new Vector3(pool - 3.62f, y, -.20f), 214, 167, (int)OnboardService.Amenities, .44f); + AddGuest(layout, GuestActivity.Rest, new Vector3(pool + 1.77f, y, width * .67f + .07f), 35, 180, (int)OnboardService.Amenities, .23f, .26f); + AddGuest(layout, GuestActivity.Photograph, new Vector3(pool + .9f, y, -2.32f), 62, 180, (int)OnboardService.Amenities, .64f); return layout; } @@ -330,14 +330,23 @@ namespace Soundings if (row < rows - 1) RoomEntrance(layout, interior, cutaway, x, y, center.z + halfRow, cellWidth, door, 1, index, slot, facility); Room(structure, layout, facility, center, cellWidth - .19f, rowDepth - .18f, index * 70 + slot, - row == 0 ? -1 : 1); + row == 0 ? -1 : 1, index == programDeck && slot == programRoom); if (row == 0 || row == rows - 1) RoomWindow(interior, cutaway, x, y, halfWidth * (row == 0 ? -1 : 1), cellWidth, row == 0 ? -1 : 1, facility is Facility.Cabin or Facility.Dining or Facility.Bar or Facility.Amenity); } } - AddPerson(layout, new Vector3(aft + usableLength * .23f, y + .055f, AisleCenter(0)), -1, 0, index * 6, 1.6f, false); - AddPerson(layout, new Vector3(aft + usableLength * .72f, y + .055f, AisleCenter(rows - 2)), -1, 1, index * 6 + 1, 1.5f, false); + for (int aisle = 0; aisle < rows - 1; aisle++) + { + int walkers = columns / 2; + for (int walker = 0; walker < walkers; walker++) + { + float start = (walker + .29f * aisle) / walkers; + var route = new Vector3(aft + 1.35f, y + .055f, AisleCenter(aisle)); + layout.People.Add(new DeckGuest(route, fore - 1.2f, .37f, start, + index * 53 + aisle * 17 + walker * 11, .19f + walker * .14f)); + } + } structure.Finish(); interior.Finish(); cutaway.Finish(); @@ -425,7 +434,8 @@ namespace Soundings letters.color = new Color32(222, 224, 212, 255); } - private void Room(Geometry shape, Layout layout, Facility facility, Vector3 pos, float width, float depth, int seed, int facing) + private void Room(Geometry shape, Layout layout, Facility facility, Vector3 pos, float width, float depth, + int seed, int facing, bool programVenue) { int floor = facility switch { @@ -439,18 +449,41 @@ namespace Soundings Box(color, x, y, z, w, h, d); layout.WalkSpace.Block(pos + new Vector3(x, y, z * facing), new Vector3(w, h, d)); } - void Seat(float x, float z, int color) + void Seat(float x, float z, int color, int direction = 1) { Vector3 center = pos + new Vector3(x, 0, z * facing); - Chair(shape, center, color, facing); + Chair(shape, center, color, facing * direction); layout.WalkSpace.Block(center, new Vector3(.50f, .91f, .54f)); } + void Guest(GuestActivity activity, float x, float z, int variant, OnboardService service, + float occupancy, float seatHeight = 0, int direction = 1, float lift = 0, EntertainmentProgram? program = null) + { + float heading = facing * direction > 0 ? 0 : 180; + AddGuest(layout, activity, pos + new Vector3(x, lift, z * facing), + seed * 11 + variant, heading, (int)service, occupancy, seatHeight, program); + } Box(floor, 0, -.018f, 0, width, .045f, depth); if (facility == Facility.Empty) return; - int service = -1; + StationKind? station = facility switch + { + Facility.Cabin => StationKind.Cabins, + Facility.Dining => StationKind.Dining, + Facility.Bar => StationKind.Bar, + Facility.Entertainment => StationKind.Stage, + Facility.Amenity => StationKind.Pool, + Facility.Galley => StationKind.Galley, + Facility.Stores => StationKind.Stores, + Facility.Water => StationKind.Water, + Facility.Waste => StationKind.Waste, + Facility.Workshop => StationKind.Maintenance, + _ => null + }; + if (station.HasValue) + layout.Stations.Add(new ShipStation(station.Value, pos + new Vector3(0, 1.45f, -.33f * depth * facing))); + switch (facility) { case Facility.Cabin: @@ -471,7 +504,8 @@ namespace Soundings Box(Alloy, width * .35f, .765f, -depth * .31f, .38f, .034f, .054f); Solid(Joinery, -width * .39f, .95f, -depth * .24f, .67f, 1.90f, .88f); Box(Alloy, -width * .337f, 1.00f, -depth * .24f, .033f, .15f, .035f); - service = (int)OnboardService.Rooms; + Guest(seed % 3 == 0 ? GuestActivity.Read : GuestActivity.Rail, .05f, -depth * .05f, 1, + OnboardService.Rooms, Mathf.Lerp(.31f, .98f, seed % 9 / 8f)); break; case Facility.Dining: for (int side = -1; side <= 1; side += 2) @@ -488,9 +522,13 @@ namespace Soundings Box(LightStrip, x + .22f, .85f, place + .05f, .065f, .080f, .065f); } Seat(x, -.58f, Upholstery); - Seat(x, .81f, Upholstery); + Seat(x, .81f, Upholstery, -1); + Guest(GuestActivity.Dine, x, -.61f, side + 1, OnboardService.Meals, side < 0 ? .21f : .56f, .54f); + Guest(GuestActivity.Dine, x, .84f, side + 4, OnboardService.Meals, side < 0 ? .75f : .93f, .54f, -1); } - service = (int)OnboardService.Meals; + if (programVenue) + Guest(GuestActivity.Guitar, 0, .32f, 32, OnboardService.Shows, .22f, direction: -1, + program: EntertainmentProgram.LiveMusic); break; case Facility.Bar: Solid(Joinery, 0, .48f, depth * .18f, width * .77f, .94f, .81f); @@ -503,9 +541,16 @@ namespace Soundings Box(i % 2 == 0 ? SafetyGreen : 13, x + .12f, 1.117f, depth * .19f, .07f, .18f, .071f); Box(Alloy, x + .12f, 1.224f, depth * .19f, .055f, .06f, .044f); if (i != 0) - Seat(x, depth * .18f - .91f, 6); + { + float stool = depth * .18f - .97f; + Box(Alloy, x, .057f, stool, .39f, .11f, .39f); + Box(Alloy, x, .35f, stool, .077f, .69f, .077f); + Box(Upholstery, x, .69f, stool, .38f, .10f, .39f); + Box(Alloy, x, .26f, stool, .30f, .035f, .23f); + layout.WalkSpace.Block(pos + new Vector3(x, 0, stool * facing), new Vector3(.39f, .76f, .40f)); + Guest(GuestActivity.Drink, x, stool, i + 4, OnboardService.Drinks, i is 1 or -1 ? .35f : .73f, .80f); + } } - service = (int)OnboardService.Drinks; break; case Facility.Entertainment: Solid(Gasket, 0, .19f, depth * .307f, width * .82f, .38f, .99f); @@ -516,9 +561,23 @@ namespace Soundings for (int row = -1; row <= 0; row++) for (int i = -2; i <= 2; i++) if (i != 0) - Seat(i * width * .139f, -.37f + row * .62f, 10); - AddPerson(layout, pos + new Vector3(0, .425f, depth * .31f * facing), (int)OnboardService.Shows, 0, seed + 41, 0, false, 180); - service = (int)OnboardService.Shows; + { + float x = i * width * .139f; + float z = -.37f + row * .62f; + Seat(x, z, 10); + Guest(GuestActivity.Watch, x, z, 46 + i + row * 5, OnboardService.Shows, + row == 0 ? .29f + Mathf.Abs(i) * .13f : .59f + Mathf.Abs(i) * .13f, .54f); + } + Guest(GuestActivity.Perform, 0, depth * .31f, 30, OnboardService.Shows, .06f, direction: -1, lift: .42f); + if (programVenue) + { + Guest(GuestActivity.Guitar, 0, depth * .31f, 38, OnboardService.Shows, .22f, direction: -1, lift: .42f, + program: EntertainmentProgram.LiveMusic); + Guest(GuestActivity.Revue, -width * .145f, depth * .31f, 35, OnboardService.Shows, .22f, + direction: -1, lift: .42f, program: EntertainmentProgram.Headline); + Guest(GuestActivity.Revue, width * .145f, depth * .31f, 22, OnboardService.Shows, .22f, + direction: -1, lift: .42f, program: EntertainmentProgram.Headline); + } break; case Facility.Amenity: Solid(Ivory, 0, .18f, depth * .18f, width * .65f, .33f, depth * .44f); @@ -529,8 +588,9 @@ namespace Soundings { Solid(Joinery, side * width * .308f, .25f, -depth * .25f, 1.41f, .34f, .53f); Box(Ivory, side * width * .308f, .451f, -depth * .25f, 1.35f, .105f, .49f); + Guest(side > 0 ? GuestActivity.Read : GuestActivity.Rest, side * width * .308f, -depth * .25f, + side + 3, OnboardService.Amenities, side < 0 ? .30f : .75f, .60f); } - service = (int)OnboardService.Amenities; break; case Facility.Tank: var start = pos + new Vector3(-width * .32f, .61f, 0); @@ -578,15 +638,6 @@ namespace Soundings 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 * facing), service, i, seed + i, 0, seats); - } } private Layout BuildBridge() @@ -671,6 +722,7 @@ namespace Soundings float stationOffset = extent * .66f; BridgeConsole(geometry, walk, new Vector3(x + 1.39f, y, 0), 2.27f, 0); + layout.Stations.Add(new ShipStation(StationKind.Helm, new Vector3(x + .38f, y + 1.40f, 0))); BridgeConsole(geometry, walk, new Vector3(x + 1.83f, y, -stationOffset), 1.72f, 1); BridgeConsole(geometry, walk, new Vector3(x + 1.83f, y, stationOffset), 1.72f, 2); BuildHelmWheel(geometry, layout.Room.transform, new Vector3(x + .85f, y + 1.116f, 0)); @@ -846,31 +898,9 @@ namespace Soundings private float BridgeCenter => VesselExterior.BridgeCenter(length, ship.Decks.Count); - 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 AddGuest(Layout layout, GuestActivity activity, Vector3 station, int seed, float heading, + int service, float occupancy, float seatHeight = 0, EntertainmentProgram? program = null) => + layout.People.Add(new DeckGuest(activity, station, seed, heading, service, occupancy, seatHeight, program)); private static void Chair(Geometry shape, Vector3 at, int color, int side) { @@ -947,6 +977,7 @@ namespace Soundings public void Dispose() { + passengerCrowd.Dispose(); foreach (Mesh mesh in meshes) UnityEngine.Object.Destroy(mesh); foreach (Material material in paint.Values) diff --git a/Assets/Soundings/Runtime/FirstVoyageGuide.cs b/Assets/Soundings/Runtime/FirstVoyageGuide.cs index 2242b59..adf7652 100644 --- a/Assets/Soundings/Runtime/FirstVoyageGuide.cs +++ b/Assets/Soundings/Runtime/FirstVoyageGuide.cs @@ -157,11 +157,11 @@ namespace Soundings 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"); + return ("Work the service deck", "Walk up to the equipment and press F when the station prompt appears. You can switch operating modes here.", "service-assist"); if (passageBridge) - return ("Navigate from the bridge", "Choose Take the helm to steer. Return to autopilot to walk around again.", "helm-toggle"); + return ("Navigate from the bridge", "Face the wheel and press F to take the helm. Return to autopilot to walk around again.", "helm-toggle"); if (passageExploring) - return ("Walk the ship", "Move with WASD. Hold the right mouse button to look, or turn with Q and E.", null); + return ("Make your rounds", "Walk with WASD. Face a counter, room, or station and press F to help the crew.", 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: diff --git a/Assets/Soundings/Runtime/Harbor.cs b/Assets/Soundings/Runtime/Harbor.cs index a740bd9..1776820 100644 --- a/Assets/Soundings/Runtime/Harbor.cs +++ b/Assets/Soundings/Runtime/Harbor.cs @@ -3,7 +3,7 @@ using UnityEngine; namespace Soundings { - public sealed class Harbor : MonoBehaviour + public sealed partial class Harbor : MonoBehaviour { private readonly Dictionary materials = new Dictionary(); private readonly Dictionary reflections = new Dictionary(); @@ -11,8 +11,10 @@ namespace Soundings private readonly List shipMeshes = new List(); private Camera viewCamera; private Transform vessel; + private Transform waterSurface; private Material water; private Mesh waterMesh; + private PassageWake wake; private Shader surface, reflection; private float backplateRatio, vesselLength = 72, vesselTop = 16.4f; private int lastHull = -2, lastDecks; @@ -21,7 +23,8 @@ namespace Soundings private const float DefaultYaw = 37f, DefaultPitch = 17.5f; private float yaw = DefaultYaw, pitch = DefaultPitch, zoom = 1f; private float targetYaw = DefaultYaw, targetPitch = DefaultPitch, targetZoom = 1f; - private float seaTime, seaSeverity; + private float seaTime, seaSeverity, passageDistance; + private Vector2 seaCenter; private Vector3 hullMotion, hullMotionVelocity; private bool sailing; private Bounds hullBounds; @@ -39,6 +42,8 @@ namespace Soundings private enum CameraMode { Orbit, DeckWalk, Bridge, Service } public RenderTexture Frame { get; private set; } + internal Vector3 PassageWorldPosition => vessel != null ? vessel.position : Vector3.zero; + internal bool PassageUsesPerspective => sailing && cameraMode == CameraMode.Orbit && !viewCamera.orthographic; internal Vector3 FirstPersonPosition => freePosition; internal bool FirstPersonPositionIsClear => walkSpace != null && walkSpace.CanStand(freePosition); @@ -47,6 +52,8 @@ namespace Soundings surface = Resources.Load("HarborSurface"); reflection = Resources.Load("HarborReflection"); water = new Material(Resources.Load("HarborWater")); + var oceanDetail = Resources.Load("Art/OceanDetail"); + water.SetTexture("_OceanDetail", oceanDetail); var cameraObject = new GameObject("Harbor camera", typeof(Camera)); cameraObject.transform.SetParent(transform, false); @@ -55,7 +62,7 @@ namespace Soundings viewCamera.clearFlags = CameraClearFlags.SolidColor; viewCamera.backgroundColor = new Color(.09f, .17f, .23f); viewCamera.nearClipPlane = .25f; - viewCamera.farClipPlane = 1050; + viewCamera.farClipPlane = 1300; viewCamera.cullingMask = 1 << 8; viewCamera.enabled = false; @@ -64,6 +71,7 @@ namespace Soundings var waterObject = new GameObject("Harbor backdrop and water", typeof(MeshFilter), typeof(MeshRenderer)); waterObject.layer = 8; waterObject.transform.SetParent(transform, false); + waterSurface = waterObject.transform; var ocean = new HarborMesh(); ocean.Quad(new Vector3(-2000, 0, -2000), new Vector3(-2000, 0, 2000), new Vector3(2000, 0, 2000), new Vector3(2000, 0, -2000)); @@ -71,6 +79,7 @@ namespace Soundings waterMesh.bounds = new Bounds(Vector3.zero, Vector3.one * 4000); waterObject.GetComponent().sharedMesh = waterMesh; waterObject.GetComponent().sharedMaterial = water; + wake = new PassageWake(transform, oceanDetail); } public void SetVisible(bool visible) => viewCamera.enabled = visible; @@ -79,8 +88,12 @@ namespace Soundings { 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); + targetYaw -= drag.x * .18f; + if (sailing) + targetYaw = Mathf.Repeat(targetYaw + 180f, 360f) - 180f; + else + targetYaw = Mathf.Clamp(targetYaw, 3f, 72f); + targetPitch = Mathf.Clamp(targetPitch + drag.y * .13f, sailing ? 4f : 12f, deckIndex >= 0 ? 79f : 69f); } public void RotateView(float degrees) @@ -100,7 +113,7 @@ namespace Soundings freeFov = Mathf.Clamp(freeFov * Mathf.Exp(delta * .035f), 25f, 78f); return; } - targetZoom = Mathf.Clamp(targetZoom * Mathf.Exp(delta * .050f), sailing ? .17f : .64f, 1.51f); + targetZoom = Mathf.Clamp(targetZoom * Mathf.Exp(delta * .050f), sailing ? .62f : .64f, sailing ? 1.82f : 1.51f); } public void ResetView(bool immediate = false) @@ -127,9 +140,8 @@ namespace Soundings { cameraMode = CameraMode.Orbit; walkSpace = null; - viewCamera.orthographic = true; - targetYaw = deckIndex >= 0 ? 17f : DefaultYaw; - targetPitch = deckIndex >= 0 ? 55f : DefaultPitch; + targetYaw = deckIndex >= 0 ? 17f : sailing ? 24f : DefaultYaw; + targetPitch = deckIndex >= 0 ? 57f : sailing ? 13f : DefaultPitch; targetZoom = deckIndex >= 0 ? .92f : 1f; if (!immediate) return; @@ -236,28 +248,31 @@ namespace Soundings return vessel != null && hullBounds.IntersectRay(viewCamera.ViewportPointToRay(viewportPoint)); } - public void BeginPassage(WeatherCondition weather = WeatherCondition.Calm) + public void BeginPassage(WeatherCondition weather = WeatherCondition.Calm, float duration = 180f) { sailing = true; seaSeverity = (int)weather / 2f; seaTime = 0; + float nominalKnots = 17f + 2f * (displayedShip?.HullIndex ?? 0); + float weatherSlowdown = weather == WeatherCondition.Storm ? 1.32f : weather == WeatherCondition.Swell ? 1.14f : 1f; + passageDistance = nominalKnots * .514444f * duration / weatherSlowdown; hullMotion = hullMotionVelocity = Vector3.zero; water.SetFloat("_WeatherSeverity", seaSeverity); - cameraMode = CameraMode.Orbit; - viewCamera.orthographic = true; - targetYaw = 22f; - targetPitch = 16f; - targetZoom = 1.02f; + Shader.SetGlobalFloat("_SoundingsSeaWeather", seaSeverity); + Shader.SetGlobalFloat("_SoundingsSeaSailing", 1); + wake.Reset(); SetPassage(Vector2.zero, 0, 0, 0); + ResetOrbit(true); } public void SetPassage(Vector2 routePosition, float heading, float speed, float delta) { - seaTime += delta * (1 + speed * .033f); + seaTime += delta; float headingRadians = heading * Mathf.Deg2Rad; float sine = Mathf.Sin(headingRadians); float cosine = Mathf.Cos(headingRadians); - var center = new Vector2(routePosition.x * 13f - 3.6f, -routePosition.y * 13f); + var center = new Vector2(routePosition.x, -routePosition.y) * passageDistance; + seaCenter = center; if (vessel != null && delta > 0) { // Use wave heights along the waterline to drive a damped heave, pitch and roll. @@ -281,18 +296,26 @@ namespace Soundings water.SetVector("_HullCourse", new Vector4(cosine, sine, Mathf.Clamp01(speed / 19f), 0)); water.SetFloat("_SeaTime", seaTime); water.SetFloat("_Underway", 1); + waterSurface.localPosition = new Vector3(center.x, 0, center.y); + Shader.SetGlobalFloat("_SoundingsSeaTime", seaTime); + wake.Update(center, new Vector2(cosine, -sine), speed, vesselLength, vesselBeam, seaTime, seaSeverity); } private float WaveHeight(Vector2 point) { - float amplitude = Mathf.Lerp(.12f, 1.45f, seaSeverity * seaSeverity); - return amplitude * (.72f * Mathf.Sin(.052f * point.x + .115f * point.y - .93f * seaTime) - + .28f * Mathf.Sin(-.073f * point.x + .17f * point.y - 1.22f * seaTime + 1.30f)); + float amplitude = Mathf.Lerp(.35f, 1.46f, seaSeverity * seaSeverity); + return amplitude * (.65f * Mathf.Sin(.052f * point.x + .115f * point.y - .93f * seaTime) + + .25f * Mathf.Sin(-.073f * point.x + .17f * point.y - 1.22f * seaTime + 1.30f) + + .10f * Mathf.Sin(.217f * point.x - .136f * point.y - 1.64f * seaTime + 2.9f)); } public void EndPassage() { sailing = false; + seaCenter = Vector2.zero; + waterSurface.localPosition = Vector3.zero; + wake.Reset(); + Shader.SetGlobalFloat("_SoundingsSeaSailing", 0); if (vessel != null) vessel.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity); Vector4 hull = water.GetVector("_HullSpan"); @@ -315,11 +338,11 @@ namespace Soundings ComposeCamera(); return; } - float easing = 1 - Mathf.Exp(-Time.unscaledDeltaTime * 11f); + float easing = 1 - Mathf.Exp(-Time.unscaledDeltaTime * (sailing ? 12f : 11f)); if (!sailing && Mathf.Abs(yaw - targetYaw) < .005f && Mathf.Abs(pitch - targetPitch) < .005f && Mathf.Abs(zoom - targetZoom) < .0001f) return; - yaw = Mathf.Lerp(yaw, targetYaw, easing); + yaw = Mathf.Repeat(yaw + Mathf.DeltaAngle(yaw, targetYaw) * easing + 180f, 360f) - 180f; pitch = Mathf.Lerp(pitch, targetPitch, easing); zoom = Mathf.Lerp(zoom, targetZoom, easing); ComposeCamera(); @@ -329,8 +352,11 @@ namespace Soundings { float level = deckIndex >= 0 && decks != null ? decks.FloorHeight(deckIndex) + .5f : vesselTop * .39f; var center = new Vector3(deckIndex >= 0 ? -2f : 2.1f, level, 0); - if (sailing && vessel != null) - center = vessel.TransformPoint(center); + if (sailing) + { + center.x += seaCenter.x; + center.z = seaCenter.y; + } return center; } @@ -338,10 +364,13 @@ namespace Soundings { if (cameraMode == CameraMode.Orbit) { - viewCamera.orthographic = true; + viewCamera.orthographic = !sailing; viewCamera.nearClipPlane = .25f; + viewCamera.fieldOfView = deckIndex >= 0 ? 45f : 38f; + float aspect = Frame == null ? 16f / 9f : (float)Frame.width / Frame.height; + float distance = sailing ? vesselLength * Mathf.Max(1.29f, 2.16f / aspect) * zoom : 244f; Quaternion orbit = Quaternion.Euler(pitch, -yaw, 0); - viewCamera.transform.SetPositionAndRotation(OrbitFocus() + orbit * (Vector3.back * 244f), orbit); + viewCamera.transform.SetPositionAndRotation(OrbitFocus() + orbit * (Vector3.back * distance), orbit); } else { @@ -393,6 +422,7 @@ namespace Soundings if (Frame == null) return; float aspect = (float)Frame.width / Frame.height; + viewCamera.aspect = aspect; viewCamera.orthographicSize = Mathf.Max(17.6f, vesselLength * .71f / aspect) * zoom; Transform view = viewCamera.transform; float viewHeight = viewCamera.orthographic ? viewCamera.orthographicSize : Mathf.Tan(viewCamera.fieldOfView * Mathf.Deg2Rad * .5f); @@ -401,7 +431,7 @@ namespace Soundings water.SetVector("_ViewRight", view.right); water.SetVector("_ViewUp", view.up); water.SetVector("_ViewSize", new Vector4(viewHeight * aspect, viewHeight, viewCamera.orthographic ? 1 : 0, 0)); - if (backplateRatio <= 0) + if (backplateRatio <= 0 || sailing) return; float cropX = Mathf.Min(1, aspect / backplateRatio) * .95f; float cropY = Mathf.Min(1, backplateRatio / aspect) * .95f; @@ -549,6 +579,7 @@ namespace Soundings { ReleaseFrame(); ReleaseShip(); + wake?.Dispose(); foreach (Material material in materials.Values) Destroy(material); foreach (Material material in reflections.Values) diff --git a/Assets/Soundings/Runtime/HarborStations.cs b/Assets/Soundings/Runtime/HarborStations.cs new file mode 100644 index 0000000..99c0d01 --- /dev/null +++ b/Assets/Soundings/Runtime/HarborStations.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Soundings +{ + internal enum StationKind { Helm, Engine, Galley, Stores, Maintenance, Water, Waste, Cabins, Dining, Bar, Stage, Pool } + + internal readonly struct ShipStation + { + public readonly StationKind Kind; + public readonly Vector3 Position; + + public ShipStation(StationKind kind, Vector3 position) + { + Kind = kind; + Position = position; + } + } + + public sealed partial class Harbor + { + internal bool TryGetFacingStation(out StationKind kind) + { + kind = default; + IReadOnlyList targets = cameraMode switch + { + CameraMode.Bridge or CameraMode.DeckWalk => decks?.ActiveStations, + CameraMode.Service => serviceDeck?.Stations, + _ => null + }; + if (targets == null || walkSpace == null) + return false; + + Vector3 facing = Quaternion.Euler(freePitch, freeYaw, 0) * Vector3.forward; + float best = float.PositiveInfinity; + for (int i = 0; i < targets.Count; i++) + { + ShipStation station = targets[i]; + Vector3 offset = station.Position - freePosition; + float distance = offset.magnitude; + if (distance < .05f || distance > 3.2f) + continue; + float alignment = Vector3.Dot(facing, offset) / distance; + if (alignment < .955f) + continue; + float score = distance + (1 - alignment) * 9; + if (score >= best || !walkSpace.HasSightLine(freePosition, station.Position)) + continue; + best = score; + kind = station.Kind; + } + return !float.IsPositiveInfinity(best); + } + } +} diff --git a/Assets/Soundings/Runtime/HarborStations.cs.meta b/Assets/Soundings/Runtime/HarborStations.cs.meta new file mode 100644 index 0000000..0ba41ff --- /dev/null +++ b/Assets/Soundings/Runtime/HarborStations.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e0079204c090001b08b1d66aafb7f364 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/LedgerPage.cs b/Assets/Soundings/Runtime/LedgerPage.cs index 33c2ec4..98de233 100644 --- a/Assets/Soundings/Runtime/LedgerPage.cs +++ b/Assets/Soundings/Runtime/LedgerPage.cs @@ -140,6 +140,8 @@ namespace Soundings { 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"); + if (trip.Onboard.CrewCalls > 0) + AddText(leaf, $"Crew calls answered · {trip.Onboard.CrewCalls}", "log-secondary"); } var statement = Add(leaf, "log-statement"); @@ -148,6 +150,12 @@ namespace Soundings if (trip.Onboard?.Expenses > 0) LogLine(statement, "Onboard operating costs", Money(-trip.Onboard.Expenses)); LogLine(statement, "Crew and catering", Money(-trip.Crew - trip.Catering)); + if (trip.Plan != null) + { + LogLine(statement, $"Provisions · {trip.Plan.FoodUnits:N0} portions", Money(-trip.Plan.FoodCost)); + if (trip.Plan.ProgramCost > 0) + LogLine(statement, PortPlanning.ProgramLabel(trip.Plan.Program), Money(-trip.Plan.ProgramCost)); + } LogLine(statement, "Port dues", Money(-trip.PortFees)); LogLine(statement, "Fuel expense", Money(-trip.FuelExpense)); LogLine(statement, "Loan interest", Money(-trip.LoanInterest)); diff --git a/Assets/Soundings/Runtime/OnboardEconomy.cs b/Assets/Soundings/Runtime/OnboardEconomy.cs index f14a387..10ccd7c 100644 --- a/Assets/Soundings/Runtime/OnboardEconomy.cs +++ b/Assets/Soundings/Runtime/OnboardEconomy.cs @@ -7,7 +7,7 @@ namespace Soundings [Serializable] public sealed class OnboardReport { - public int Happiness, Health, Revenue, Expenses, Decisions, FuelBurn, Repair, Provisions, WaterPercent, SewagePercent; + public int Happiness, Health, Revenue, Expenses, Decisions, FuelBurn, Repair, Provisions, WaterPercent, SewagePercent, CrewCalls; public int[] ServiceSales; } @@ -177,11 +177,13 @@ namespace Soundings { tick++; AdvanceSystems(); + AdvancePerformance(); if (openedAt >= 0 && tick >= openedAt + 6) ResolveEvent(false); if (openedAt < 0 && nextEvent < Events.Length && tick >= ticks * (nextEvent == 0 ? .23 : .59)) openedAt = tick; Measure(true); + AdvanceCrewRequest(); } if (tick >= ticks && openedAt >= 0) ResolveEvent(false); @@ -191,6 +193,7 @@ namespace Soundings { Happiness = Happiness, Health = Health, + CrewCalls = CrewRequestsCompleted, FuelBurn = ProjectedFuelBurn, Repair = RepairCredit, Provisions = ProvisionsRemaining, @@ -215,9 +218,13 @@ namespace Soundings bool featured = featuredService == i && tick <= eventBenefitUntil; VoyageEvent? notice = CurrentEvent; int rush = notice.HasValue && notice.Value.Service == i ? notice.Value.Surge : featured ? additionalCapacity / 2 : 0; + bool performance = i == (int)OnboardService.Shows && PerformanceActive; + if (performance) + rush += PortPlanning.ShowDemand(BookedProgram); 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 extraSeats = performance ? PortPlanning.ShowSeats(BookedProgram) : 0; + int possible = ServiceCapacity(i, capacity[i] + extraSeats + (featured ? additionalCapacity : 0) + CrewServiceBoost(i)); int served = Math.Min(requested, possible); if (collect) @@ -239,7 +246,7 @@ namespace Soundings if (collect) { UpdateHealth(mealFulfillment); - double target = 40 + 55 * fulfillment / ServiceKinds - (100 - health) * .28; + double target = Math.Min(100, 40 + 55 * fulfillment / ServiceKinds - (100 - health) * .28 + CrewSurveyBonus); satisfaction = satisfaction * .77 + target * .23; } } diff --git a/Assets/Soundings/Runtime/OnboardPerformances.cs b/Assets/Soundings/Runtime/OnboardPerformances.cs new file mode 100644 index 0000000..83c54ff --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardPerformances.cs @@ -0,0 +1,42 @@ +using System; + +namespace Soundings +{ + public sealed partial class OnboardSession + { + private int performanceStarted = -1; + private EntertainmentProgram BookedProgram => Quote.Plan?.Program ?? EntertainmentProgram.Shipboard; + private int PerformanceRounds => PortPlanning.ShowRounds(BookedProgram); + public bool PerformanceActive => performanceStarted >= 0 && tick < performanceStarted + PerformanceRounds; + internal bool CanAdvancePerformance => BookedProgram != EntertainmentProgram.Shipboard && performanceStarted < 0 + && tick + PerformanceRounds < ticks; + internal string PerformanceLabel + { + get + { + if (BookedProgram == EntertainmentProgram.Shipboard) + return "Shipboard sets"; + string title = PortPlanning.ProgramLabel(BookedProgram); + if (PerformanceActive) + return $"{title} · now playing ({performanceStarted + PerformanceRounds - tick} rounds)"; + return $"{title} · {(performanceStarted < 0 ? "up next" : "finished")}"; + } + } + + internal bool TryAdvancePerformance() + { + if (!CanAdvancePerformance) + return false; + performanceStarted = tick; + Measure(false); + return true; + } + + private void AdvancePerformance() + { + if (BookedProgram != EntertainmentProgram.Shipboard && performanceStarted < 0 + && tick >= Math.Min(ticks - PerformanceRounds, ticks * PortPlanning.ShowTime(BookedProgram))) + performanceStarted = tick; + } + } +} diff --git a/Assets/Soundings/Runtime/OnboardPerformances.cs.meta b/Assets/Soundings/Runtime/OnboardPerformances.cs.meta new file mode 100644 index 0000000..ed6faa1 --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardPerformances.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 33add9d45e2f46cf2b14d12302c004f8 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/OnboardRounds.cs b/Assets/Soundings/Runtime/OnboardRounds.cs new file mode 100644 index 0000000..80e316f --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardRounds.cs @@ -0,0 +1,168 @@ +using System; + +namespace Soundings +{ + public sealed partial class OnboardSession + { + private static readonly float[] CrewCallSchedule = { .12f, .43f, .71f }; + private readonly int[] stationReadyAt = new int[(int)StationKind.Pool + 1]; + private readonly int[] stationBoostUntil = new int[ServiceKinds]; + private int nextCrewCall, crewCallDeadline; + + internal StationKind? CrewCall { get; private set; } + internal int CrewRequestsCompleted { get; private set; } + internal int CrewRoundsLeft => CrewCall == null ? 0 : crewCallDeadline - tick; + private double CrewSurveyBonus => CrewRequestsCompleted * 1.6; + + internal static string StationName(StationKind station) => station switch + { + StationKind.Helm => "Bridge helm", + StationKind.Engine => "Engine control", + StationKind.Galley => "Galley pass", + StationKind.Stores => "Provision stores", + StationKind.Maintenance => "Maintenance bench", + StationKind.Water => "Freshwater pumps", + StationKind.Waste => "Treatment plant", + StationKind.Cabins => "Cabin service", + StationKind.Dining => "Dining host", + StationKind.Bar => "Bar counter", + StationKind.Stage => "Show lounge", + _ => "Pool terrace" + }; + + internal string StationAction(StationKind station) => station switch + { + StationKind.Engine => $"Set {EngineOrderName(NextEngineOrder())} power", + StationKind.Galley => $"Staff an extra shift · ${GalleyCost:N0}", + StationKind.Stores => $"Release the reserve · ${StoreCost:N0}", + StationKind.Maintenance => $"Service machinery · ${RepairCost:N0}", + StationKind.Water => $"Boost pumps · ${PumpCost:N0}", + StationKind.Waste => $"Start extra treatment · ${TreatmentCost:N0}", + StationKind.Cabins => "Check in with guests", + StationKind.Dining => $"Call an extra seating · ${GalleyCost:N0}", + StationKind.Bar => "Start happy hour · 25% off", + StationKind.Stage => CanAdvancePerformance ? "Call the booked act" : "Open overflow seating", + StationKind.Pool => "Host a poolside game", + _ => "Take the helm" + }; + + internal string StationBlock(StationKind station) + { + if (tick >= ticks) + return "Service has ended for this crossing"; + if (stationReadyAt[(int)station] > tick) + return "The crew is handling this station"; + return station switch + { + StationKind.Galley or StationKind.Dining when GalleyBoost => "The extra shift is already running", + StationKind.Galley or StationKind.Dining when !CanSpend(GalleyCost) => "No room in the operating budget", + StationKind.Dining when ProvisionsRemaining < 12 => "Too little food in stores for another seating", + StationKind.Stores when StoresOpened => "The reserve has already been released", + StationKind.Stores when !CanOpenStores => "Reserve stock is unavailable at this level or budget", + StationKind.Maintenance when Ship.Condition == 100 || RepairCredit > 0 => "Machinery is already serviced", + StationKind.Maintenance when !CanSpend(RepairCost) => "No room in the operating budget", + StationKind.Water when PumpsBoost => "The boost pumps are running", + StationKind.Water when !CanSpend(PumpCost) => "No room in the operating budget", + StationKind.Waste when TreatmentBoost => "Extra treatment is already running", + StationKind.Waste when !CanSpend(TreatmentCost) => "No room in the operating budget", + StationKind.Bar when DiscountTicks(OnboardService.Drinks) > 0 => "Happy hour is already underway", + StationKind.Bar when GetPrice(OnboardService.Drinks) == 0 || capacity[(int)OnboardService.Drinks] == 0 => "There is no paid bar service to promote", + StationKind.Stage when capacity[(int)OnboardService.Shows] == 0 => "No show lounge is fitted", + StationKind.Pool when Quote.Weather == WeatherCondition.Storm => "The terrace is closed in this weather", + StationKind.Pool when WaterPercent < 22 => "Freshwater is too low for pool operation", + _ => null + }; + } + + internal bool TryWorkStation(StationKind station, out string result) + { + result = StationBlock(station); + if (result != null || station == StationKind.Helm) + return false; + + switch (station) + { + case StationKind.Engine: SetEngineMode(NextEngineOrder()); break; + case StationKind.Galley: + case StationKind.Dining: ExtendGalley(); break; + case StationKind.Stores: OpenStores(); break; + case StationKind.Maintenance: ServiceMachinery(); break; + case StationKind.Water: RunBoostPumps(); break; + case StationKind.Waste: BoostTreatment(); break; + case StationKind.Bar: StartSpecial(OnboardService.Drinks); break; + case StationKind.Stage: + if (!TryAdvancePerformance()) + stationBoostUntil[(int)OnboardService.Shows] = tick + 6; + break; + case StationKind.Pool: stationBoostUntil[(int)OnboardService.Amenities] = tick + 6; break; + } + stationReadyAt[(int)station] = tick + (station == StationKind.Engine ? 1 : 8); + + bool answered = station == CrewCall; + if (answered) + { + CrewRequestsCompleted++; + CrewCall = null; + } + if (answered || station is StationKind.Cabins or StationKind.Pool or StationKind.Stage) + satisfaction = Math.Min(100, satisfaction + (answered ? 4 : 2)); + Measure(false); + result = answered ? "Crew call answered · Guest survey improved" : StationResult(station); + return true; + } + + private string StationResult(StationKind station) => station switch + { + StationKind.Engine => $"Engine order acknowledged · {EngineOrderName(EngineMode)}", + StationKind.Galley or StationKind.Dining => "Extra service is running", + StationKind.Stores => $"Reserve delivered · {ProvisionsRemaining:N0} portions aboard", + StationKind.Maintenance => "Service logged · Less wear on arrival", + StationKind.Water => "Freshwater boost is running", + StationKind.Waste => "Treatment boost is running", + StationKind.Cabins => "Guest services checked in · Survey improved", + StationKind.Bar => "Happy hour started · Drinks are 25% off", + StationKind.Stage => "Show lounge ready for guests", + _ => "Poolside game started · More terrace capacity" + }; + + private int NextEngineOrder() => EngineMode == 2 || !CanSetEngineMode(EngineMode + 1) ? 0 : EngineMode + 1; + private static string EngineOrderName(int mode) => mode == 0 ? "Economy" : mode == 1 ? "Cruise" : "Power"; + + private int CrewServiceBoost(int service) => stationBoostUntil[service] <= tick ? 0 + : service == (int)OnboardService.Shows ? 42 : 24; + + private void AdvanceCrewRequest() + { + if (CrewCall != null && tick >= crewCallDeadline) + CrewCall = null; + if (CrewCall != null || nextCrewCall >= CrewCallSchedule.Length || tick < ticks * CrewCallSchedule[nextCrewCall]) + return; + + StationKind station; + switch (nextCrewCall++) + { + case 0: + station = ProvisionsRemaining < Quote.Guests && StationBlock(StationKind.Stores) == null + ? StationKind.Stores : StationKind.Galley; + break; + case 1: + station = capacity[(int)OnboardService.Shows] > 0 ? StationKind.Stage : StationKind.Cabins; + break; + default: + if (WaterPercent < 33) + station = StationKind.Water; + else if (SewagePercent > 68) + station = StationKind.Waste; + else + station = capacity[(int)OnboardService.Drinks] > 0 ? StationKind.Bar : StationKind.Maintenance; + break; + } + if (StationBlock(station) != null) + station = StationKind.Cabins; + if (StationBlock(station) != null) + return; + CrewCall = station; + crewCallDeadline = Math.Min(ticks, tick + Math.Max(6, ticks / 6)); + } + } +} diff --git a/Assets/Soundings/Runtime/OnboardRounds.cs.meta b/Assets/Soundings/Runtime/OnboardRounds.cs.meta new file mode 100644 index 0000000..552702a --- /dev/null +++ b/Assets/Soundings/Runtime/OnboardRounds.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9b31fac231f3787f084eb4f25ccc5e0a \ No newline at end of file diff --git a/Assets/Soundings/Runtime/OnboardSystems.cs b/Assets/Soundings/Runtime/OnboardSystems.cs index 647cf15..444540e 100644 --- a/Assets/Soundings/Runtime/OnboardSystems.cs +++ b/Assets/Soundings/Runtime/OnboardSystems.cs @@ -85,7 +85,7 @@ namespace Soundings private void InitializeSystems() { - provisions = Math.Min(Ship.FoodCapacity, Quote.Guests * Quote.Days * 2.53); + provisions = Math.Min(Ship.FoodCapacity, Quote.Plan == null ? Quote.Guests * Quote.Days * 2.53 : Quote.Plan.FoodUnits); water = Ship.WaterCapacity; } diff --git a/Assets/Soundings/Runtime/OperationsPage.cs b/Assets/Soundings/Runtime/OperationsPage.cs index 2deb1214..547b650 100644 --- a/Assets/Soundings/Runtime/OperationsPage.cs +++ b/Assets/Soundings/Runtime/OperationsPage.cs @@ -6,9 +6,10 @@ namespace Soundings { public sealed partial class SoundingsApp { - private void DrawVoyageFolio(VisualElement folio, Ship ship, Voyage quote) + private void DrawVoyageFolio(VisualElement chart, VisualElement folio, Ship ship, Voyage quote) { PortSpec origin = Market.Ports[quote.Origin]; + PreparePortOrders(ship, quote); AddText(folio, $"DEPARTURE FROM {origin.Name.ToUpperInvariant()}", "chart-paper-kicker chart-paper-section"); DrawWeatherPicker(folio, quote); var passage = Add(folio, "chart-passage"); @@ -24,6 +25,7 @@ namespace Soundings ChartStepper(fares, Money(ship.Fare), "fare", () => ChangeFare(ship, -50), () => ChangeFare(ship, 50), ship.Fare > Market.MinFare, ship.Fare < Market.MaxFare); + DrawPortOrdersLink(folio, quote.Plan); DrawChartBunkering(folio, ship, quote); string blocker = company.DepartureBlock(ship, quote); if (!string.IsNullOrEmpty(blocker)) @@ -36,6 +38,8 @@ namespace Soundings Button launch = Action("Cast off →", () => BeginVoyage(quote), "chart-ink-button chart-wide-button chart-cast-off", "dispatch"); launch.SetEnabled(blocker == null); folio.Add(launch); + if (portOrdersOpen) + DrawPortOrders(chart, ship, quote); } private void DrawChartBunkering(VisualElement folio, Ship ship, Voyage quote = null) diff --git a/Assets/Soundings/Runtime/PassageAnnouncements.cs b/Assets/Soundings/Runtime/PassageAnnouncements.cs new file mode 100644 index 0000000..a18d134 --- /dev/null +++ b/Assets/Soundings/Runtime/PassageAnnouncements.cs @@ -0,0 +1,53 @@ +using UnityEngine.UIElements; + +namespace Soundings +{ + public sealed partial class SoundingsApp + { + private VisualElement announcementBanner; + private Label announcementCaption; + + private void DrawAnnouncement(VisualElement overlay) + { + announcementBanner = Add(overlay, "passage-announcement"); + announcementBanner.pickingMode = PickingMode.Ignore; + AddText(announcementBanner, "SHIP PA", "voyage-caption"); + announcementCaption = AddText(announcementBanner, "", "passage-announcement-caption"); + UpdateAnnouncement(); + } + + private void UpdateAnnouncement() + { + if (announcementBanner == null) + return; + string text = passageAudio.Caption; + announcementBanner.style.display = text == null ? DisplayStyle.None : DisplayStyle.Flex; + if (text != null) + SetPassageText(announcementCaption, text); + } + + private void StartPassageSpecial(OnboardService service) + { + if (livePassage.StartSpecial(service)) + { + if (service == OnboardService.Meals) + passageAudio.Announce(PassageAnnouncement.DiningSpecial); + else if (service == OnboardService.Drinks) + passageAudio.Announce(PassageAnnouncement.Bar); + } + RefreshPassageBusiness(); + } + + private void AnnounceStation(StationKind station) + { + switch (station) + { + case StationKind.Galley: + case StationKind.Dining: passageAudio.Announce(PassageAnnouncement.Dining); break; + case StationKind.Bar: passageAudio.Announce(PassageAnnouncement.Bar); break; + case StationKind.Stage: passageAudio.Announce(PassageAnnouncement.Show); break; + case StationKind.Pool: passageAudio.Announce(PassageAnnouncement.Terrace); break; + } + } + } +} diff --git a/Assets/Soundings/Runtime/PassageAnnouncements.cs.meta b/Assets/Soundings/Runtime/PassageAnnouncements.cs.meta new file mode 100644 index 0000000..5e4b183 --- /dev/null +++ b/Assets/Soundings/Runtime/PassageAnnouncements.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 38c0385acc58f47928b969fba0475d7f \ No newline at end of file diff --git a/Assets/Soundings/Runtime/PassageAudio.cs b/Assets/Soundings/Runtime/PassageAudio.cs new file mode 100644 index 0000000..6b2e225 --- /dev/null +++ b/Assets/Soundings/Runtime/PassageAudio.cs @@ -0,0 +1,247 @@ +using System; +using UnityEngine; + +namespace Soundings +{ + internal enum PassageAnnouncement { Departure, Dining, DiningSpecial, Bar, Show, Terrace } + + internal sealed class PassageAudio : MonoBehaviour + { + private const int SampleRate = 22050; + private static readonly string[] Announcements = + { + "Welcome aboard. We have cleared the berth and are now under way. On behalf of the captain and crew, enjoy your voyage.", + "May I have your attention, please. We have opened an additional seating in the main dining room.", + "For a limited time, specialty dining is available at a reduced price. Please ask your dining team for details.", + "Ladies and gentlemen, happy hour has started at the bar. We look forward to seeing you there.", + "Our next performance is starting shortly. Please join us for live entertainment.", + "Join us on the pool terrace. Our crew is ready to get the next deck activity under way." + }; + + private AudioSource wind, engine, effects, voice; + private AudioClip step, hardStep, confirmation; + private readonly AudioClip[] spoken = new AudioClip[Announcements.Length]; + private readonly float[] repeatAfter = new float[Announcements.Length]; + private float distanceSinceStep; + private float announcementTime, announcementGap, announcementClock; + private bool leftFoot, crossing, voicePaused; + private PassageAnnouncement? currentAnnouncement, pendingAnnouncement; + + internal PassageAnnouncement? CurrentAnnouncement => currentAnnouncement; + internal string Caption => currentAnnouncement.HasValue ? Announcements[(int)currentAnnouncement.Value] : null; + + internal void Initialize() + { + if (FindAnyObjectByType() == null) + gameObject.AddComponent(); + wind = Source(MakeBed("Sea wash", false)); + engine = Source(MakeBed("Propulsion and ventilation", true)); + effects = Source(null); + effects.volume = .72f; + step = MakeStep(false); + hardStep = MakeStep(true); + confirmation = MakeClip("Crew acknowledgement", .22f, t => + { + float first = Pulse(t, 0, .09f) * Mathf.Sin(t * 716 * Mathf.PI * 2); + float second = Pulse(t, .074f, .14f) * Mathf.Sin(t * 958 * Mathf.PI * 2); + return (first + second * .75f) * .12f; + }); + + var address = new GameObject("Ship public address"); + address.transform.SetParent(transform, false); + voice = address.AddComponent(); + voice.playOnAwake = false; + voice.spatialBlend = 0; + voice.volume = .95f; + address.AddComponent().cutoffFrequency = 165; + address.AddComponent().cutoffFrequency = 4300; + for (int i = 0; i < spoken.Length; i++) + spoken[i] = Resources.Load($"Audio/PA/{(PassageAnnouncement)i}"); + } + + internal void Begin() + { + crossing = true; + distanceSinceStep = 0; + announcementClock = announcementGap = 0; + Array.Clear(repeatAfter, 0, repeatAfter.Length); + wind.Play(); + engine.Play(); + Announce(PassageAnnouncement.Departure); + } + + internal void End() + { + crossing = false; + voice.Stop(); + voicePaused = false; + currentAnnouncement = pendingAnnouncement = null; + } + + internal void Announce(PassageAnnouncement line) + { + int index = (int)line; + if (!crossing || spoken[index] == null || currentAnnouncement == line || pendingAnnouncement == line + || repeatAfter[index] > announcementClock) + return; + + if (currentAnnouncement.HasValue || announcementGap > 0 || voicePaused) + pendingAnnouncement = line; + else + PlayAnnouncement(line); + } + + internal void Mix(float delta, bool active, float knots, WeatherCondition weather, bool indoors, bool engineering) + { + UpdateAnnouncements(delta, active); + float pace = Mathf.Clamp01(knots / 21); + float storm = (int)weather / 2f; + float sea = active ? (.12f + pace * .17f + storm * .14f) * (indoors ? .19f : 1) : 0; + float motor = active ? (.035f + pace * .15f) * (engineering ? 1.65f : indoors ? .60f : .72f) : 0; + if (currentAnnouncement.HasValue) + { + sea *= .54f; + motor *= .60f; + } + wind.volume = Mathf.MoveTowards(wind.volume, sea, delta * .58f); + engine.volume = Mathf.MoveTowards(engine.volume, motor, delta * .58f); + engine.pitch = .84f + pace * .32f; + if (!crossing && wind.volume == 0 && engine.volume == 0) + { + if (wind.isPlaying) + wind.Stop(); + if (engine.isPlaying) + engine.Stop(); + } + } + + private void PlayAnnouncement(PassageAnnouncement line) + { + int index = (int)line; + currentAnnouncement = line; + voice.clip = spoken[index]; + announcementTime = voice.clip.length; + repeatAfter[index] = announcementClock + 20f; + voice.Play(); + } + + private void UpdateAnnouncements(float delta, bool active) + { + if (!crossing) + return; + if (!active) + { + if (!voicePaused) + voice.Pause(); + voicePaused = true; + return; + } + if (voicePaused) + { + voice.UnPause(); + voicePaused = false; + } + + announcementClock += delta; + if (currentAnnouncement.HasValue) + { + announcementTime -= delta; + if (announcementTime <= 0) + { + currentAnnouncement = null; + announcementGap = .44f; + } + return; + } + + announcementGap = Mathf.Max(0, announcementGap - delta); + if (announcementGap == 0 && pendingAnnouncement is PassageAnnouncement next) + { + pendingAnnouncement = null; + PlayAnnouncement(next); + } + } + + internal void Step(float distance, bool metal) + { + distanceSinceStep += distance; + if (distanceSinceStep < .65f) + return; + distanceSinceStep -= .65f; + leftFoot = !leftFoot; + effects.pitch = leftFoot ? .96f : 1.04f; + effects.PlayOneShot(metal ? hardStep : step, metal ? .46f : .36f); + } + + internal void Confirm() + { + effects.pitch = 1; + effects.PlayOneShot(confirmation, .66f); + } + + private AudioSource Source(AudioClip clip) + { + var source = gameObject.AddComponent(); + source.playOnAwake = false; + source.loop = clip != null; + source.clip = clip; + source.volume = 0; + source.spatialBlend = 0; + return source; + } + + private static AudioClip MakeBed(string name, bool motor) + { + uint state = motor ? 5193u : 1996u; + float filtered = 0; + const float seconds = 6; + return MakeClip(name, seconds, t => + { + filtered += (Noise(ref state) - filtered) * (motor ? .014f : .075f); + float seam = Mathf.Clamp01(Mathf.Min(t, seconds - t) * 16); + float wave = .68f + .18f * Mathf.Cos(t * Mathf.PI * 2 / seconds) + .11f * Mathf.Sin(t * Mathf.PI * 4 / seconds); + if (!motor) + return filtered * .74f * wave * seam; + float propeller = .16f * Mathf.Sin(t * 46 * Mathf.PI * 2) + .073f * Mathf.Sin(t * 92 * Mathf.PI * 2) + + .041f * Mathf.Sin(t * 131 * Mathf.PI * 2); + return propeller * wave + filtered * .36f * seam; + }); + } + + private static AudioClip MakeStep(bool metal) + { + uint state = metal ? 572u : 728u; + float filtered = 0; + return MakeClip(metal ? "Steel deck footfall" : "Carpet footfall", .14f, t => + { + float grit = Noise(ref state); + filtered += (grit - filtered) * .14f; + float impact = Mathf.Sin(t * (metal ? 123 : 94) * Mathf.PI * 2) * Pulse(t, 0, .078f) * .36f; + float scuff = (metal ? grit * .22f : filtered * .53f) * Pulse(t, .015f, .12f); + return impact + scuff; + }); + } + + private static AudioClip MakeClip(string name, float seconds, Func waveform) + { + var data = new float[Mathf.CeilToInt(seconds * SampleRate)]; + for (int i = 0; i < data.Length; i++) + data[i] = waveform((float)i / SampleRate); + AudioClip clip = AudioClip.Create(name, data.Length, 1, SampleRate, false); + clip.SetData(data, 0); + return clip; + } + + private static float Pulse(float time, float start, float length) + { + float progress = Mathf.Clamp01((time - start) / length); + return Mathf.Min(1, progress * 20) * (1 - progress) * (1 - progress); + } + + private static float Noise(ref uint state) + { + state = unchecked(state * 1664525u + 1013904223u); + return (state >> 8) * (2f / 16777215) - 1; + } + } +} diff --git a/Assets/Soundings/Runtime/PassageAudio.cs.meta b/Assets/Soundings/Runtime/PassageAudio.cs.meta new file mode 100644 index 0000000..1e41cd9 --- /dev/null +++ b/Assets/Soundings/Runtime/PassageAudio.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bb13384ff97f23a3dbf792a49511424c \ No newline at end of file diff --git a/Assets/Soundings/Runtime/PassageInterface.cs b/Assets/Soundings/Runtime/PassageInterface.cs index cbf7dac..0a5ca21 100644 --- a/Assets/Soundings/Runtime/PassageInterface.cs +++ b/Assets/Soundings/Runtime/PassageInterface.cs @@ -13,7 +13,7 @@ namespace Soundings 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 Label passageRemaining, passageHappiness, passageHealth, passageSupplies, passageSales, passageEventClock, passageEventResult, passagePerformance; private float renderedPassageProgress = -1, nextPassageReadout; private Button passageEventAccept; private string passageEventTitle; @@ -40,6 +40,7 @@ namespace Soundings passageSales = null; passageHealth = null; passageSupplies = null; + passagePerformance = null; for (int i = 0; i < PassageServices.Length; i++) { passageDemand[i] = null; @@ -57,7 +58,9 @@ namespace Soundings passageEventAccept = null; passageEventResult = null; - var controls = Add(overlay, "voyage-deckbar"); + var footer = Add(overlay, "voyage-footer"); + footer.pickingMode = PickingMode.Ignore; + var controls = Add(footer, "voyage-deckbar"); controls.pickingMode = PickingMode.Ignore; AddText(controls, "SHIP VIEW", "voyage-caption voyage-deck-caption"); AddPassageDeckButton(controls, -1, "Exterior", "passage-deck-all"); @@ -78,7 +81,7 @@ namespace Soundings harbor.ResetView(); }, "voyage-view-button voyage-reset", "passage-camera-reset")); - var rail = Add(overlay, "voyage-rail"); + var rail = Add(footer, "voyage-rail"); var route = Add(rail, "voyage-route"); string sea = underway.Weather switch { @@ -92,6 +95,7 @@ namespace Soundings ? "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"); + crewCallReadout = AddText(route, "", "crew-call-readout"); var progress = Add(route, "voyage-progress"); passageProgress = Add(progress, "voyage-progress-fill"); renderedPassageProgress = -1; @@ -116,6 +120,8 @@ namespace Soundings AddText(camera, cameraHelp, "voyage-camera-help"); rail.Add(Action("Skip to arrival", FinishVoyage, "voyage-view-button voyage-skip", "dock-now")); DrawHelmControls(overlay); + DrawAnnouncement(overlay); + DrawStationInteractions(overlay); UpdatePassageUi(passageHelm.Progress); } @@ -141,6 +147,8 @@ namespace Soundings 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.Shows && underway.Plan?.Program is EntertainmentProgram.LiveMusic or EntertainmentProgram.Headline) + passagePerformance = AddText(entry, "", "voyage-service-included"); if (service == OnboardService.Amenities && underway.Weather == WeatherCondition.Storm) AddText(entry, "Outdoor venues closed", "voyage-service-included voyage-demand-short"); if (service == OnboardService.Rooms) @@ -157,11 +165,7 @@ namespace Soundings 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}"); + passageSpecials[i] = Action("Special −25%", () => StartPassageSpecial(service), "voyage-special", $"passage-special-{slug}"); prices.Add(passageSpecials[i]); } AddText(book, "Guests served / requesting right now", "voyage-metric-help"); @@ -208,6 +212,7 @@ namespace Soundings nextPassageReadout = Time.unscaledTime + .12f; RefreshPassageBusiness(); RefreshPassageEvent(); + UpdateCrewCall(); } } @@ -219,6 +224,8 @@ namespace Soundings SetPassageText(passageHealth, $"{livePassage.Health}/100"); SetPassageText(passageSupplies, $"Provisions remaining · {livePassage.ProvisionsRemaining:N0}"); SetPassageText(passageSales, Money(livePassage.Revenue)); + if (passagePerformance != null) + SetPassageText(passagePerformance, livePassage.PerformanceLabel); for (int i = 0; i < PassageServices.Length; i++) { OnboardService service = (OnboardService)i; @@ -287,7 +294,12 @@ namespace Soundings private void DecidePassageEvent(bool accept) { + VoyageEvent? chosen = accept && livePassage.CanAcceptEvent ? livePassage.CurrentEvent : null; livePassage.ResolveEvent(accept); + if (chosen?.Service == (int)OnboardService.Meals) + passageAudio.Announce(PassageAnnouncement.Dining); + else if (chosen?.Service == (int)OnboardService.Shows) + passageAudio.Announce(PassageAnnouncement.Show); RefreshPassageBusiness(); RefreshPassageEvent(); } diff --git a/Assets/Soundings/Runtime/PassageWake.cs b/Assets/Soundings/Runtime/PassageWake.cs new file mode 100644 index 0000000..a483c8e --- /dev/null +++ b/Assets/Soundings/Runtime/PassageWake.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Soundings +{ + internal sealed class PassageWake : IDisposable + { + private const int Rows = 58, Columns = 7; + private const float TrackAge = 34f; + private readonly List trail = new(Rows - 1); + private readonly Vector3[] positions = new Vector3[Rows * Columns]; + private readonly List profiles = new(Rows * Columns); + private readonly int[] triangles = new int[(Rows - 1) * (Columns - 1) * 6]; + private readonly GameObject root; + private readonly Mesh mesh; + private readonly Material finish; + + private readonly struct Station + { + internal readonly Vector2 Center, Forward; + internal readonly float Time, Thrust; + + internal Station(Vector2 center, Vector2 forward, float time, float thrust) + { + Center = center; + Forward = forward; + Time = time; + Thrust = thrust; + } + } + + internal PassageWake(Transform parent, Texture2D detail) + { + root = new GameObject("Propeller wash", typeof(MeshFilter), typeof(MeshRenderer)); + root.layer = 8; + root.transform.SetParent(parent, false); + mesh = new Mesh { name = "World-space wake ribbon" }; + mesh.MarkDynamic(); + finish = new Material(Resources.Load("PassageWake")); + finish.SetTexture("_OceanDetail", detail); + root.GetComponent().sharedMesh = mesh; + root.GetComponent().sharedMaterial = finish; + for (int i = 0; i < positions.Length; i++) + profiles.Add(Vector4.zero); + int face = 0; + for (int row = 0; row < Rows - 1; row++) + for (int col = 0; col < Columns - 1; col++) + { + int near = row * Columns + col; + int far = near + Columns; + triangles[face++] = near; + triangles[face++] = far; + triangles[face++] = far + 1; + triangles[face++] = near; + triangles[face++] = far + 1; + triangles[face++] = near + 1; + } + Reset(); + } + + internal void Reset() + { + trail.Clear(); + root.SetActive(false); + } + + internal void Update(Vector2 center, Vector2 bow, float speed, float length, float beam, float time, float storm) + { + Vector2 propellers = center - bow * (length * .476f); + float thrust = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(.9f, 14, speed)); + var newest = new Station(propellers, bow, time, thrust); + while (trail.Count > 0 && time - trail[0].Time > TrackAge) + trail.RemoveAt(0); + + if (trail.Count == 0) + { + if (root.activeSelf) + root.SetActive(false); + if (thrust > 0) + trail.Add(newest); + return; + } + + float gap = Vector2.Distance(propellers, trail[^1].Center); + if (gap > Mathf.Max(62, length * .45f)) + { + // Snapshots can jump directly to a different part of a passage. + Reset(); + if (thrust > 0) + trail.Add(newest); + return; + } + + int row = 0; + float distance = 0; + Vector2 prior = propellers; + WriteRow(row++, newest, time, 0, beam); + for (int i = trail.Count - 1; i >= 0; i--) + { + Station sample = trail[i]; + float section = Vector2.Distance(prior, sample.Center); + if (section < .19f) + continue; + distance += section; + WriteRow(row++, sample, time, distance, beam); + prior = sample.Center; + } + if (distance < 1) + { + if (root.activeSelf) + root.SetActive(false); + return; + } + + mesh.SetVertices(positions, 0, row * Columns); + mesh.SetUVs(0, profiles, 0, row * Columns); + mesh.SetIndices(triangles, 0, (row - 1) * (Columns - 1) * 6, MeshTopology.Triangles, 0, true); + Bounds bounds = mesh.bounds; + bounds.Expand(new Vector3(0, 4, 0)); + mesh.bounds = bounds; + finish.SetFloat("_SeaTime", time); + finish.SetFloat("_WeatherSeverity", storm); + if (!root.activeSelf) + root.SetActive(true); + + if (gap >= 3f && thrust > 0) + { + if (trail.Count >= Rows - 1) + trail.RemoveAt(0); + trail.Add(newest); + } + } + + private void WriteRow(int row, Station station, float time, float distance, float beam) + { + float age = time - station.Time; + float width = beam * .62f + distance * .34f; + Vector2 right = new Vector2(-station.Forward.y, station.Forward.x); + for (int col = 0; col < Columns; col++) + { + float across = 2f * col / (Columns - 1) - 1f; + Vector2 point = station.Center + right * (across * width); + int vertex = row * Columns + col; + positions[vertex] = new Vector3(point.x, .055f, point.y); + profiles[vertex] = new Vector4(across, age, station.Thrust, distance); + } + } + + public void Dispose() + { + UnityEngine.Object.Destroy(root); + UnityEngine.Object.Destroy(mesh); + UnityEngine.Object.Destroy(finish); + } + } +} diff --git a/Assets/Soundings/Runtime/PassageWake.cs.meta b/Assets/Soundings/Runtime/PassageWake.cs.meta new file mode 100644 index 0000000..82efda1 --- /dev/null +++ b/Assets/Soundings/Runtime/PassageWake.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 14a09ab625f143dda7bb95599c29e029 diff --git a/Assets/Soundings/Runtime/PassengerCrowd.cs b/Assets/Soundings/Runtime/PassengerCrowd.cs new file mode 100644 index 0000000..1d5b662 --- /dev/null +++ b/Assets/Soundings/Runtime/PassengerCrowd.cs @@ -0,0 +1,418 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; + +namespace Soundings +{ + internal enum GuestActivity { Walk, Rail, Talk, Photograph, Read, Dine, Drink, Watch, Perform, Rest, Guitar, Revue } + + internal sealed class DeckGuest + { + internal readonly GuestActivity Activity; + internal readonly Vector3 Station; + internal readonly int Service, Seed; + internal readonly float Heading, RequiredOccupancy, SeatHeight, RouteEnd, LaneRadius, RouteStart; + internal readonly EntertainmentProgram? Program; + internal float Presence; + internal bool Initialized; + + internal DeckGuest(GuestActivity activity, Vector3 station, int seed, float heading, int service, float occupancy, + float seatHeight, EntertainmentProgram? program = null) + { + Activity = activity; + Station = station; + Seed = seed; + Heading = heading; + Service = service; + RequiredOccupancy = occupancy; + SeatHeight = seatHeight; + Program = program; + } + + internal DeckGuest(Vector3 start, float end, float laneRadius, float phase, int seed, float occupancy) + : this(GuestActivity.Walk, start, seed, 0, -1, occupancy, 0) + { + RouteEnd = end; + LaneRadius = laneRadius; + RouteStart = phase; + } + } + + internal sealed class PassengerCrowd : System.IDisposable + { + private static readonly Color32[] Shirts = + { + new(222, 213, 191, 255), new(61, 115, 125, 255), new(172, 94, 75, 255), + new(55, 73, 96, 255), new(195, 161, 101, 255), new(129, 147, 122, 255), + new(103, 86, 110, 255), new(125, 167, 179, 255), new(200, 124, 129, 255) + }; + private static readonly Color32[] Trousers = + { + new(52, 66, 76, 255), new(66, 78, 92, 255), new(169, 154, 128, 255), new(104, 105, 100, 255) + }; + private static readonly Color32[] Skin = + { + new(222, 175, 145, 255), new(178, 123, 91, 255), new(199, 150, 116, 255), + new(111, 73, 55, 255), new(236, 190, 160, 255) + }; + private static readonly Color32[] Hair = + { + new(53, 43, 39, 255), new(97, 69, 48, 255), new(170, 130, 78, 255), new(140, 139, 130, 255) + }; + private static readonly Color32 Shoes = new(54, 47, 42, 255); + private static readonly Color32 Paper = new(219, 202, 161, 255); + private static readonly Color32 Dark = new(46, 57, 61, 255); + private static readonly Color32 Glass = new(188, 160, 110, 255); + private static readonly Primitive Globe = new(8, 4); + private static readonly Primitive Joint = new(6, 3); + private readonly List vertices = new(22000); + private readonly List normals = new(22000); + private readonly List colors = new(22000); + private readonly List indices = new(76000); + private readonly List meshes = new(); + private readonly Material material; + + private Matrix4x4 guestMatrix; + private Quaternion guestRotation; + private byte coverage; + + internal PassengerCrowd() + { + material = new Material(Resources.Load("PassengerSurface")) { name = "Passenger clothing and skin" }; + } + + internal Mesh CreateMesh(GameObject root, float length, float beam) + { + var mesh = new Mesh { name = "Articulated deck passengers", indexFormat = IndexFormat.UInt32 }; + mesh.MarkDynamic(); + root.AddComponent().sharedMesh = mesh; + root.AddComponent().sharedMaterial = material; + mesh.bounds = new Bounds(Vector3.up * 16, new Vector3(length, 40, beam * 2)); + meshes.Add(mesh); + return mesh; + } + + internal void Draw(Mesh mesh, List people, OnboardSession session, bool outside, float clock, float delta) + { + vertices.Clear(); + normals.Clear(); + colors.Clear(); + indices.Clear(); + float voyageOccupancy = Mathf.Clamp01(session.Quote.Guests / (float)Mathf.Max(1, session.Ship.Beds)); + EntertainmentProgram? playing = session.PerformanceActive ? session.Quote.Plan?.Program : null; + float promenadeAvailability = session.Quote.Weather switch + { + WeatherCondition.Storm => 0, + WeatherCondition.Swell => .66f, + _ => 1 + }; + foreach (DeckGuest guest in people) + { + float occupancy = voyageOccupancy; + if (guest.Service >= 0) + { + OnboardSample service = session.Get((OnboardService)guest.Service); + occupancy = service.Served / (float)Mathf.Max(1, service.Capacity); + } + if (guest.Program.HasValue) + occupancy = guest.Program == playing ? 1 : 0; + else if (guest.Activity == GuestActivity.Perform && playing.HasValue) + occupancy = 0; + if (outside) + occupancy *= promenadeAvailability; + float goal = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(guest.RequiredOccupancy - .13f, + guest.RequiredOccupancy + .13f, occupancy)); + if (session.Quote.Guests == 0 || occupancy <= 0) + goal = 0; + if (!guest.Initialized) + { + guest.Presence = goal; + guest.Initialized = true; + } + else + guest.Presence = Mathf.MoveTowards(guest.Presence, goal, delta * .47f); + if (guest.Presence > .012f) + RenderGuest(guest, clock); + } + + Bounds bounds = mesh.bounds; + mesh.Clear(); + mesh.SetVertices(vertices); + mesh.SetNormals(normals); + mesh.SetColors(colors); + mesh.SetTriangles(indices, 0, false); + mesh.bounds = bounds; + } + + private void RenderGuest(DeckGuest guest, float clock) + { + int seed = guest.Seed; + float variation = Hash(seed); + float stature = Mathf.Lerp(.91f, 1.075f, variation); + float time = clock + Hash(seed + 15) * 80; + bool walking = guest.Activity == GuestActivity.Walk; + float gait = 0; + float heading = guest.Heading; + Vector3 station = guest.Station; + if (walking) + { + float speed = guest.Station.z < 0 ? .91f : .97f; + float distance = clock * speed; + station = WalkRoute(guest, distance, out heading); + gait = (distance + guest.RouteStart * 5) / (.90f * stature); + } + guestRotation = Quaternion.Euler(0, heading, 0); + guestMatrix = Matrix4x4.TRS(station, guestRotation, Vector3.one * stature); + coverage = (byte)Mathf.RoundToInt(guest.Presence * 255f); + + Color32 shirt = Shirts[seed % Shirts.Length]; + Color32 pants = Trousers[(seed / 4 + seed) % Trousers.Length]; + Color32 skin = Skin[(seed / 2 + seed) % Skin.Length]; + Color32 hair = Hair[(seed / 3 + seed) % Hair.Length]; + bool seated = guest.SeatHeight > 0; + float breathe = Mathf.Sin(time * 2.2f) * .013f; + float step = walking ? Mathf.Sin(gait * Mathf.PI * 2) : 0; + float armSwing = walking ? Mathf.Cos(gait * Mathf.PI * 2) : 0; + float sway = walking ? .031f * step : .02f * Mathf.Sin(time * 1.25f); + float hipY = seated ? guest.SeatHeight / stature : .862f + (walking ? .018f * Mathf.Cos(gait * Mathf.PI * 4) : breathe * .2f); + Vector3 pelvis = new(sway, hipY, 0); + Vector3 chest = pelvis + new Vector3(-sway * .54f, .382f + breathe, seated ? .083f : .022f + Mathf.Abs(step) * .021f); + Vector3 neck = chest + new Vector3(0, .195f, .016f); + float glance = Mathf.Sin(time * .66f) * (walking ? .16f : .39f); + Quaternion headTurn = Quaternion.Euler(Mathf.Sin(time * 1.02f) * 5, glance * Mathf.Rad2Deg, 0); + Vector3 face = neck + new Vector3(.02f * Mathf.Sin(time), .115f, .018f); + + Ellipsoid(Globe, pelvis + Vector3.up * .11f, new Vector3(.176f, .178f, .12f), Quaternion.identity, pants); + Ellipsoid(Globe, Vector3.Lerp(pelvis, chest, .66f) + Vector3.up * .058f, + new Vector3(.205f + variation * .021f, .284f, .127f), Quaternion.Euler(seated ? 12 : 3, step * 8, -step * 3), shirt); + Ellipsoid(Joint, neck - Vector3.up * .017f, new Vector3(.057f, .103f, .060f), Quaternion.identity, skin); + Ellipsoid(Globe, face, new Vector3(.102f, .136f, .103f), headTurn, skin); + Ellipsoid(Globe, face + headTurn * new Vector3(0, .067f, -.022f), + new Vector3(.104f, seed % 3 == 0 ? .104f : .079f, .104f), headTurn, hair); + Ellipsoid(Joint, face + headTurn * new Vector3(0, -.011f, .099f), new Vector3(.024f, .029f, .026f), headTurn, skin); + if (seed % 4 == 2 || guest.Activity == GuestActivity.Rail) + { + for (int side = -1; side <= 1; side += 2) + Ellipsoid(Joint, face + headTurn * new Vector3(side * .044f, .026f, .086f), + new Vector3(.042f, .025f, .018f), headTurn, Dark); + } + if (guest.Activity == GuestActivity.Guitar) + { + Quaternion guitar = Quaternion.Euler(-13, 0, 22); + Ellipsoid(Globe, pelvis + new Vector3(.10f, .285f, .225f), new Vector3(.194f, .206f, .055f), guitar, Paper); + Ellipsoid(Joint, pelvis + new Vector3(.062f, .31f, .279f), new Vector3(.051f, .053f, .013f), guitar, Dark); + Limb(pelvis + new Vector3(.002f, .329f, .229f), pelvis + new Vector3(-.337f, .563f, .252f), .037f, Shoes); + } + + for (int side = -1; side <= 1; side += 2) + { + Vector3 hip = pelvis + new Vector3(side * .102f, 0, 0); + Vector3 foot = Foot(side, walking, seated, gait, hipY); + Vector3 knee = seated ? new Vector3(side * .130f, hipY - .08f, .37f) : Bend(hip, foot, .43f, Vector3.forward); + Limb(hip, knee, .086f, pants); + Limb(knee, foot, .065f, pants); + Ellipsoid(Joint, foot + new Vector3(0, -.034f, .061f), new Vector3(.079f, .070f, .159f), Quaternion.identity, Shoes); + + Vector3 shoulder = chest + new Vector3(side * .18f, .088f, 0); + Vector3 hand = ArmGesture(guest.Activity, side, hipY, time, armSwing, face); + Vector3 elbow = Bend(shoulder, hand, .30f, new Vector3(.55f * side, -.58f, -.60f)); + Limb(shoulder, elbow, .067f, shirt); + Limb(elbow, hand, .043f, skin); + Ellipsoid(Joint, hand, new Vector3(.046f, .061f, .047f), Quaternion.identity, skin); + if (side > 0) + RenderProp(guest.Activity, hand); + } + } + + private static Vector3 WalkRoute(DeckGuest guest, float distance, out float heading) + { + float length = guest.RouteEnd - guest.Station.x; + float radius = guest.LaneRadius; + float turn = Mathf.PI * radius; + float lap = (length + turn) * 2; + float point = Mathf.Repeat(distance + guest.RouteStart * lap, lap); + Vector3 anchor = guest.Station; + if (point < length) + { + heading = 90; + return anchor + new Vector3(point, 0, -radius); + } + point -= length; + if (point < turn) + { + float arc = point / radius; + heading = 90 - arc * Mathf.Rad2Deg; + return anchor + new Vector3(length + radius * Mathf.Sin(arc), 0, -radius * Mathf.Cos(arc)); + } + point -= turn; + if (point < length) + { + heading = -90; + return anchor + new Vector3(length - point, 0, radius); + } + float lastArc = (point - length) / radius; + heading = -90 - lastArc * Mathf.Rad2Deg; + return anchor + new Vector3(-radius * Mathf.Sin(lastArc), 0, radius * Mathf.Cos(lastArc)); + } + + private static Vector3 Foot(int side, bool walking, bool seated, float gait, float hipY) + { + if (seated) + return new Vector3(side * .135f, Mathf.Max(.095f, hipY - .49f), .42f); + if (!walking) + return new Vector3(side * .124f, .104f, side * .057f); + + const float stance = .59f; + float phase = Mathf.Repeat(gait + (side > 0 ? .5f : 0), 1); + float z = .266f - phase * .90f; + float height = 0; + if (phase >= stance) + { + float swing = (phase - stance) / (1 - stance); + z = Mathf.SmoothStep(-.265f, .266f, swing); + height = .128f * Mathf.Sin(Mathf.PI * swing); + } + return new Vector3(side * .107f, .104f + height, z); + } + + private static Vector3 Bend(Vector3 root, Vector3 tip, float length, Vector3 direction) + { + Vector3 axis = tip - root; + float half = axis.magnitude * .5f; + if (half < .001f) + return root; + axis /= half * 2; + Vector3 plane = (direction - axis * Vector3.Dot(axis, direction)).normalized; + return (root + tip) * .5f + plane * Mathf.Sqrt(Mathf.Max(0, length * length - half * half)); + } + + private static Vector3 ArmGesture(GuestActivity activity, int side, float hipY, float time, float stride, Vector3 face) + { + float beat = Mathf.Repeat(time * .167f + (side < 0 ? .47f : 0), 1); + float action = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(.61f, .85f, beat)) + * (1 - Mathf.SmoothStep(0, 1, Mathf.InverseLerp(.89f, 1, beat))); + switch (activity) + { + case GuestActivity.Walk: + return new Vector3(side * .25f, .914f + Mathf.Abs(stride) * .037f, side * stride * .245f); + case GuestActivity.Rail: + return new Vector3(side * .19f, hipY + .25f, .37f); + case GuestActivity.Read: + return new Vector3(side * .12f, hipY + .33f, .37f); + case GuestActivity.Dine: + case GuestActivity.Drink: + Vector3 table = new(side * .16f, hipY + .27f, activity == GuestActivity.Dine ? .43f : .35f); + return side > 0 ? Vector3.Lerp(table, face + new Vector3(.056f, -.047f, .134f), action) : table; + case GuestActivity.Watch: + float applause = action * (.63f + .37f * Mathf.Sin(time * 19f)); + return new Vector3(side * Mathf.Lerp(.19f, .047f, applause), hipY + .15f + action * .32f, .28f + action * .10f); + case GuestActivity.Photograph: + return Vector3.Lerp(new Vector3(side * .125f, hipY + .28f, .29f), + face + new Vector3(side * .098f, -.045f, .24f), action); + case GuestActivity.Talk: + return new Vector3(side * (.248f + action * .18f), hipY + .12f + action * .34f, .13f + action * .14f); + case GuestActivity.Perform: + return side > 0 ? face + new Vector3(.065f, -.067f, .17f) + : new Vector3(-.28f - action * .26f, hipY + .21f + action * .41f, .13f + action * .17f); + case GuestActivity.Guitar: + return side > 0 ? new Vector3(.108f, hipY + .30f + Mathf.Sin(time * 12.7f) * .080f, .302f) + : new Vector3(-.25f + Mathf.Sin(time * 2.8f) * .045f, hipY + .52f, .268f); + case GuestActivity.Revue: + float arc = time * 3.2f + side * 1.1f; + return new Vector3(side * (.32f + Mathf.Cos(arc) * .16f), hipY + .52f + Mathf.Sin(arc) * .35f, .24f); + default: + return new Vector3(side * .21f, hipY + .15f, .23f); + } + } + + private void RenderProp(GuestActivity activity, Vector3 hand) + { + if (activity is GuestActivity.Drink or GuestActivity.Photograph or GuestActivity.Read or GuestActivity.Perform) + { + Vector3 size = activity switch + { + GuestActivity.Drink => new Vector3(.052f, .091f, .052f), + GuestActivity.Read => new Vector3(.136f, .081f, .023f), + GuestActivity.Photograph => new Vector3(.063f, .105f, .019f), + _ => new Vector3(.037f, .103f, .037f) + }; + Color32 color = activity == GuestActivity.Drink ? Glass : activity == GuestActivity.Read ? Paper : Dark; + Ellipsoid(Joint, hand + new Vector3(-size.x * .5f, size.y * .54f, size.z + .025f), size, + activity == GuestActivity.Read ? Quaternion.Euler(-37, 0, 0) : Quaternion.identity, color); + } + } + + private void Limb(Vector3 from, Vector3 to, float radius, Color32 color) + { + Vector3 direction = to - from; + float distance = direction.magnitude; + if (distance > .001f) + Ellipsoid(Joint, (from + to) * .5f, new Vector3(radius, distance * .55f + radius * .33f, radius), + Quaternion.FromToRotation(Vector3.up, direction / distance), color); + } + + private void Ellipsoid(Primitive primitive, Vector3 center, Vector3 size, Quaternion rotation, Color32 color) + { + int offset = vertices.Count; + Matrix4x4 position = guestMatrix * Matrix4x4.TRS(center, rotation, size); + Quaternion orient = guestRotation * rotation; + Vector3 inverseSize = new(1f / size.x, 1f / size.y, 1f / size.z); + color.a = coverage; + foreach (Vector3 point in primitive.Points) + { + vertices.Add(position.MultiplyPoint3x4(point)); + normals.Add(orient * Vector3.Scale(point, inverseSize).normalized); + colors.Add(color); + } + foreach (int index in primitive.Indices) + indices.Add(offset + index); + } + + private static float Hash(int seed) + { + uint value = unchecked((uint)seed + 105789u); + value = (value ^ (value >> 16)) * 0x7feb352d; + value = (value ^ (value >> 15)) * 0x846ca68b; + return ((value ^ (value >> 16)) & 0xffff) / 65535f; + } + + public void Dispose() + { + foreach (Mesh mesh in meshes) + Object.Destroy(mesh); + Object.Destroy(material); + } + + private sealed class Primitive + { + internal readonly Vector3[] Points; + internal readonly int[] Indices; + + internal Primitive(int sides, int bands) + { + Points = new Vector3[sides * (bands + 1)]; + Indices = new int[sides * bands * 6]; + for (int band = 0; band <= bands; band++) + { + float vertical = (band / (float)bands - .5f) * Mathf.PI; + for (int side = 0; side < sides; side++) + { + float azimuth = side * Mathf.PI * 2 / sides; + Points[band * sides + side] = new Vector3(Mathf.Cos(azimuth) * Mathf.Cos(vertical), Mathf.Sin(vertical), + Mathf.Sin(azimuth) * Mathf.Cos(vertical)); + if (band == bands) + continue; + int a = band * sides + side, b = band * sides + (side + 1) % sides; + int offset = a * 6; + Indices[offset] = a; + Indices[offset + 1] = a + sides; + Indices[offset + 2] = b + sides; + Indices[offset + 3] = a; + Indices[offset + 4] = b + sides; + Indices[offset + 5] = b; + } + } + } + } + } +} diff --git a/Assets/Soundings/Runtime/PassengerCrowd.cs.meta b/Assets/Soundings/Runtime/PassengerCrowd.cs.meta new file mode 100644 index 0000000..26d5bf6 --- /dev/null +++ b/Assets/Soundings/Runtime/PassengerCrowd.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f8ee7c9272a64e4819d3535873a5f716 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/PortPlanning.cs b/Assets/Soundings/Runtime/PortPlanning.cs new file mode 100644 index 0000000..83c52d8 --- /dev/null +++ b/Assets/Soundings/Runtime/PortPlanning.cs @@ -0,0 +1,105 @@ +using System; + +namespace Soundings +{ + public enum EntertainmentProgram { Shipboard, LiveMusic, Headline } + + [Serializable] + public sealed class DeparturePlan + { + public int FoodUnits, FoodCost, ProgramCost; + public EntertainmentProgram Program; + } + + public static class PortPlanning + { + private static readonly int[] FoodMarket = + { + 462, 590, 477, 338, 423, 635, 514, 397, 452, 302, 350, 311, 475, 326, 539, 535, 658, 610, 496, 318, 372, 332 + }; + + public static int FoodPriceCents(int port, int day) + { + int market = port < FoodMarket.Length ? FoodMarket[port] : 460; + return market + ((day / 7 * 17 + port * 23) % 37) - 18; + } + + public static int RecommendedFood(Ship ship, Voyage quote) => + Math.Min(ship.FoodCapacity, (int)Math.Ceiling(quote.Guests * quote.Days * 2.53)); + + public static int EstimatedFoodUse(Ship ship, Voyage quote) => + (int)Math.Ceiling(Math.Min(Math.Min(ship.Meals, ship.GalleyCapacity), quote.Guests * .71) * Math.Max(24, quote.Days * 8) * .26); + + public static string ProgramLabel(EntertainmentProgram program) => program switch + { + EntertainmentProgram.LiveMusic => "Local musicians", + EntertainmentProgram.Headline => "Headline revue", + _ => "Shipboard sets" + }; + + public static bool CanBook(Ship ship, EntertainmentProgram program) => program switch + { + EntertainmentProgram.Shipboard => true, + EntertainmentProgram.LiveMusic => ship.Meals > 0 || ship.Entertainment > 0, + EntertainmentProgram.Headline => ship.Entertainment > 0, + _ => false + }; + + public static int ProgramPrice(EntertainmentProgram program, Voyage quote, int day) + { + int market = FoodPriceCents(quote.Origin, day); + return program switch + { + EntertainmentProgram.LiveMusic => 800 + market + 120 * quote.Days, + EntertainmentProgram.Headline => 2000 + market * 2 + 250 * quote.Days, + _ => 0 + }; + } + + internal static int ShowSeats(EntertainmentProgram program) => program switch + { + EntertainmentProgram.LiveMusic => 48, + EntertainmentProgram.Headline => 86, + _ => 0 + }; + + internal static int ShowDemand(EntertainmentProgram program) => program switch + { + EntertainmentProgram.LiveMusic => 29, + EntertainmentProgram.Headline => 57, + _ => 0 + }; + + internal static int ShowRounds(EntertainmentProgram program) => program switch + { + EntertainmentProgram.LiveMusic => 7, + EntertainmentProgram.Headline => 10, + _ => 0 + }; + + internal static double ShowTime(EntertainmentProgram program) => program == EntertainmentProgram.LiveMusic ? .42 : .63; + + public static void Apply(Ship ship, Voyage quote, int day, int? foodUnits, EntertainmentProgram program) + { + int ordered = Market.Clamp(foodUnits ?? RecommendedFood(ship, quote), 0, ship.FoodCapacity); + if (!CanBook(ship, program)) + program = EntertainmentProgram.Shipboard; + + quote.Plan = new DeparturePlan + { + FoodUnits = ordered, + FoodCost = (ordered * FoodPriceCents(quote.Origin, day) + 50) / 100, + Program = program, + ProgramCost = ProgramPrice(program, quote, day) + }; + + // The port invoice replaces the food share of baseline catering. Labor and other supplies still matter. + quote.Catering = quote.Guests * quote.Days * 15; + double shows = Math.Min(1, (double)ship.Entertainment / Math.Max(1, ship.Capacity)); + double provisionCoverage = Math.Min(1, (double)ordered / Math.Max(1, EstimatedFoodUse(ship, quote))); + double baselineSales = quote.Guests * quote.Days * (6 + 7 * provisionCoverage + shows * 18); + double bookedSales = Math.Min(quote.Guests, ShowSeats(program)) * ShowRounds(program) * 1.4; + quote.OnboardSales = (int)Math.Round(baselineSales + bookedSales); + } + } +} diff --git a/Assets/Soundings/Runtime/PortPlanning.cs.meta b/Assets/Soundings/Runtime/PortPlanning.cs.meta new file mode 100644 index 0000000..8bbf448 --- /dev/null +++ b/Assets/Soundings/Runtime/PortPlanning.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1037ad77f8a98c0d2b8e93cf06bbc076 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/PortPlanningPage.cs b/Assets/Soundings/Runtime/PortPlanningPage.cs new file mode 100644 index 0000000..f77b7d0 --- /dev/null +++ b/Assets/Soundings/Runtime/PortPlanningPage.cs @@ -0,0 +1,142 @@ +using System; +using UnityEngine.UIElements; + +namespace Soundings +{ + public sealed partial class SoundingsApp + { + private bool portOrdersOpen; + private Ship portOrdersShip; + private int portOrdersOrigin = -1, portOrdersDestination = -1, portOrdersDay = -1; + private int? portFoodOrder; + private EntertainmentProgram portProgram; + + private void PreparePortOrders(Ship ship, Voyage quote) + { + if (portOrdersShip != ship || portOrdersOrigin != quote.Origin || portOrdersDestination != quote.Destination + || portOrdersDay != company.Day) + { + portOrdersShip = ship; + portOrdersOrigin = quote.Origin; + portOrdersDestination = quote.Destination; + portOrdersDay = company.Day; + portOrdersOpen = false; + portFoodOrder = null; + portProgram = EntertainmentProgram.Shipboard; + } + PortPlanning.Apply(ship, quote, company.Day, portFoodOrder, portProgram); + } + + private string FoodUnitPrice(int port) => (PortPlanning.FoodPriceCents(port, company.Day) / 100m).ToString("C2"); + + private void DrawPortOrdersLink(VisualElement folio, DeparturePlan plan) + { + var row = Add(folio, "port-orders-link"); + var copy = Add(row, "port-orders-link-copy"); + AddText(copy, "PORT ORDERS", "chart-paper-kicker"); + AddText(copy, $"{plan.FoodUnits:N0} portions · {PortPlanning.ProgramLabel(plan.Program)}", "port-orders-summary"); + row.Add(Action(portOrdersOpen ? "Close" : "Edit", TogglePortOrders, "chart-ink-button port-orders-edit", "port-plan-open")); + } + + private void TogglePortOrders() + { + portOrdersOpen = !portOrdersOpen; + Render(); + } + + private void DrawPortOrders(VisualElement chart, Ship ship, Voyage quote) + { + var orderSheet = new ScrollView(ScrollViewMode.Vertical) { horizontalScrollerVisibility = ScrollerVisibility.Hidden }; + orderSheet.AddToClassList("port-orders-stage"); + chart.Add(orderSheet); + var paper = Add(orderSheet, "port-orders-paper"); + + var heading = Add(paper, "port-orders-header"); + var headingCopy = Add(heading, "port-orders-header-copy"); + string origin = Market.Ports[quote.Origin].Name; + AddText(headingCopy, $"{origin.ToUpperInvariant()} · DAY {company.Day}", "chart-paper-kicker"); + AddDisplay(headingCopy, "Dockside orders", "port-orders-title"); + heading.Add(Action("Back to chart", TogglePortOrders, "chart-ink-button", "port-plan-close")); + + DrawFoodOrder(paper, ship, quote); + DrawEntertainmentOrder(paper, ship, quote); + + var total = Add(paper, "port-orders-total"); + var invoice = Add(total, "port-orders-link-copy"); + AddText(invoice, "PORT INVOICE", "chart-paper-kicker"); + AddText(invoice, "Confirmed at cast off and charged on arrival.", "port-orders-note"); + AddDisplay(total, Money(quote.Plan.FoodCost + quote.Plan.ProgramCost), "port-orders-total-value"); + } + + private void DrawFoodOrder(VisualElement paper, Ship ship, Voyage quote) + { + int ordered = quote.Plan.FoodUnits; + int expected = PortPlanning.EstimatedFoodUse(ship, quote); + AddDisplay(paper, "Provisions", "port-orders-section"); + AddText(paper, $"{FoodUnitPrice(quote.Origin)} a portion · {quote.Guests:N0} guests · {ship.FoodCapacity:N0} portions of storage", + "port-orders-note"); + var order = Add(paper, "port-orders-food"); + Button fewer = Action("−100", () => SetPortFood(ordered - 100, ship), "chart-ink-button", "port-food-less"); + fewer.SetEnabled(ordered > 0); + order.Add(fewer); + + var units = new IntegerField { name = "port-food-units", value = ordered, isDelayed = true, tooltip = "Enter the exact number of portions and press Enter" }; + units.AddToClassList("port-orders-input"); + units.RegisterValueChangedCallback(evt => SetPortFood(evt.newValue, ship)); + order.Add(units); + + Button more = Action("+100", () => SetPortFood(ordered + 100, ship), "chart-ink-button", "port-food-more"); + more.SetEnabled(ordered < ship.FoodCapacity); + order.Add(more); + Button recommended = Action(portFoodOrder.HasValue ? "Use recommended" : "Recommended selected", () => + { + portFoodOrder = null; + Render(); + }, "chart-ink-button", "port-food-recommended"); + recommended.SetEnabled(portFoodOrder.HasValue); + order.Add(recommended); + AddText(order, Money(quote.Plan.FoodCost), "port-orders-price"); + + string indicator = ordered < expected ? "port-orders-note port-orders-shortage" : "port-orders-note"; + AddText(paper, ordered < expected ? $"Short by {expected - ordered:N0} portions at standard meal service." + : $"Estimated meal service uses {expected:N0} portions. Extra stock covers demand spikes.", indicator); + } + + private void SetPortFood(int portions, Ship ship) + { + portFoodOrder = Market.Clamp(portions, 0, ship.FoodCapacity); + Render(); + } + + private void DrawEntertainmentOrder(VisualElement paper, Ship ship, Voyage quote) + { + AddDisplay(paper, "Entertainment", "port-orders-section"); + foreach (EntertainmentProgram program in Enum.GetValues(typeof(EntertainmentProgram))) + { + bool booked = quote.Plan.Program == program; + bool available = PortPlanning.CanBook(ship, program); + Button choice = Action("", () => + { + portProgram = program; + Render(); + }, booked ? "port-program-choice port-program-booked" : "port-program-choice", $"port-program-{(int)program}"); + choice.SetEnabled(available); + var copy = Add(choice, "port-orders-link-copy"); + copy.pickingMode = PickingMode.Ignore; + AddText(copy, PortPlanning.ProgramLabel(program) + (booked ? " · Selected" : ""), "port-program-title"); + string description = program switch + { + EntertainmentProgram.LiveMusic => "A mid-voyage set with 48 additional places for 7 service rounds.", + EntertainmentProgram.Headline when !available => "Requires a fitted show lounge.", + EntertainmentProgram.Headline => "A late-voyage revue with 86 additional places for 10 service rounds.", + _ => "Run the ship’s regular entertainment with the venues already fitted." + }; + AddText(copy, description, "port-orders-note"); + int price = PortPlanning.ProgramPrice(program, quote, company.Day); + AddText(choice, price == 0 ? "Included" : Money(price), "port-orders-price"); + choice.tooltip = $"{PortPlanning.ProgramLabel(program)} · {(price == 0 ? "Included" : Money(price))}"; + paper.Add(choice); + } + } + } +} diff --git a/Assets/Soundings/Runtime/PortPlanningPage.cs.meta b/Assets/Soundings/Runtime/PortPlanningPage.cs.meta new file mode 100644 index 0000000..6bda6a1 --- /dev/null +++ b/Assets/Soundings/Runtime/PortPlanningPage.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bfe8ae3cbe862675d82692463120cf66 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/ServiceControls.cs b/Assets/Soundings/Runtime/ServiceControls.cs index a03eba1..329b77b 100644 --- a/Assets/Soundings/Runtime/ServiceControls.cs +++ b/Assets/Soundings/Runtime/ServiceControls.cs @@ -108,7 +108,12 @@ namespace Soundings { switch (passageServiceArea) { - case 1: livePassage.ExtendGalley(); break; + case 1: + bool extraShift = livePassage.GalleyBoost; + livePassage.ExtendGalley(); + if (!extraShift && livePassage.GalleyBoost) + passageAudio.Announce(PassageAnnouncement.Dining); + break; case 2: livePassage.OpenStores(); break; case 3: livePassage.ServiceMachinery(); break; case 4: livePassage.RunBoostPumps(); break; diff --git a/Assets/Soundings/Runtime/ServiceDeckModel.cs b/Assets/Soundings/Runtime/ServiceDeckModel.cs index ef4e777..a5a9a84 100644 --- a/Assets/Soundings/Runtime/ServiceDeckModel.cs +++ b/Assets/Soundings/Runtime/ServiceDeckModel.cs @@ -17,10 +17,12 @@ namespace Soundings private readonly Dictionary batches = new Dictionary(); private readonly List meshes = new List(); private readonly List materials = new List(); + private readonly List stations = new(); private readonly float span, halfWidth, bayLength, doorway; private readonly Font font; public GameObject Root { get; } internal ShipWalkSpace WalkSpace { get; } + internal IReadOnlyList Stations => stations; public ServiceDeckModel(Transform parent, float length, float beam, Shader fallbackSurface) { @@ -128,6 +130,8 @@ namespace Soundings float z = halfWidth - 1.13f; float workSpan = Mathf.Min(bayLength - .90f, 7f); + stations.Add(new ShipStation((StationKind)((int)StationKind.Engine + area), + new Vector3(x, 1.51f, Mathf.Min(2.64f, z - .95f)))); switch (area) { case 0: Machinery(x, z, workSpan); break; diff --git a/Assets/Soundings/Runtime/ShipWalkSpace.cs b/Assets/Soundings/Runtime/ShipWalkSpace.cs index 90901e7..a812f0f 100644 --- a/Assets/Soundings/Runtime/ShipWalkSpace.cs +++ b/Assets/Soundings/Runtime/ShipWalkSpace.cs @@ -27,6 +27,21 @@ namespace Soundings public bool CanStand(Vector3 position) => CanStand(Plan(position)); + internal bool HasSightLine(Vector3 from, Vector3 to) + { + Vector2 origin = Plan(from); + Vector2 line = Plan(to) - origin; + float limit = 1 - .12f / Mathf.Max(.12f, line.magnitude); + foreach (Rect obstacle in solids) + { + Rect surface = Rect.MinMaxRect(obstacle.xMin + BodyRadius, obstacle.yMin + BodyRadius, + obstacle.xMax - BodyRadius, obstacle.yMax - BodyRadius); + if (Sweep(origin, line, surface, out float hit, out _) && hit < limit) + return false; + } + return true; + } + public Vector3 Entry(Vector3 requested) { Vector2 origin = Confine(Plan(requested)); diff --git a/Assets/Soundings/Runtime/SoundingsApp.cs b/Assets/Soundings/Runtime/SoundingsApp.cs index 3f006df..5a022b1 100644 --- a/Assets/Soundings/Runtime/SoundingsApp.cs +++ b/Assets/Soundings/Runtime/SoundingsApp.cs @@ -12,6 +12,7 @@ namespace Soundings private static FontDefinition interfaceFont; private Company company; private Harbor harbor; + private PassageAudio passageAudio; private PanelSettings panel; private VisualElement root; private Font displayFont; @@ -41,6 +42,8 @@ namespace Soundings Application.targetFrameRate = 60; harbor = gameObject.AddComponent(); harbor.Initialize(); + passageAudio = gameObject.AddComponent(); + passageAudio.Initialize(); displayFont = Resources.Load("Display"); interfaceFont = FontDefinition.FromFont(Resources.Load("Interface")); titleArt = Resources.Load("Art/FlagshipTitle"); diff --git a/Assets/Soundings/Runtime/StationInteractions.cs b/Assets/Soundings/Runtime/StationInteractions.cs new file mode 100644 index 0000000..c22c984 --- /dev/null +++ b/Assets/Soundings/Runtime/StationInteractions.cs @@ -0,0 +1,129 @@ +using UnityEngine; +using UnityEngine.UIElements; + +namespace Soundings +{ + public sealed partial class SoundingsApp + { + private VisualElement stationPrompt; + private Label stationTitle, stationCommand, stationFeedback, crewCallReadout; + private float stationFeedbackUntil; + private string stationFeedbackText; + + private void DrawStationInteractions(VisualElement overlay) + { + stationPrompt = null; + if (!passageBridge && !passageExploring) + return; + + var reticle = Add(overlay, "station-reticle"); + reticle.pickingMode = PickingMode.Ignore; + stationPrompt = Add(overlay, "station-prompt"); + stationPrompt.pickingMode = PickingMode.Ignore; + stationTitle = AddText(stationPrompt, "", "station-title"); + stationCommand = AddText(stationPrompt, "", "station-command"); + stationFeedback = AddText(overlay, "", "station-feedback"); + stationFeedback.pickingMode = PickingMode.Ignore; + UpdateStationInteractions(); + } + + private void UpdateStationInteractions() + { + if (stationPrompt == null || livePassage == null) + return; + + bool visible = harbor.TryGetFacingStation(out StationKind station); + stationPrompt.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None; + if (visible) + { + bool requested = livePassage.CrewCall == station; + string action = station == StationKind.Helm && passageHelm.Manual + ? "Return to autopilot" : livePassage.StationAction(station); + string blocker = station == StationKind.Helm ? null : livePassage.StationBlock(station); + SetPassageText(stationTitle, requested ? $"{OnboardSession.StationName(station)} · Crew call" : OnboardSession.StationName(station)); + SetPassageText(stationCommand, blocker ?? $"[F] {action}"); + stationPrompt.EnableInClassList("station-requested", requested); + } + + bool showResult = !string.IsNullOrEmpty(stationFeedbackText) && Time.unscaledTime < stationFeedbackUntil; + stationFeedback.style.display = showResult ? DisplayStyle.Flex : DisplayStyle.None; + if (showResult) + SetPassageText(stationFeedback, stationFeedbackText); + } + + private bool UseFacingStation() + { + if (livePassage == null || !harbor.TryGetFacingStation(out StationKind station)) + return false; + + if (station == StationKind.Helm) + { + ToggleHelm(); + ShowStationResult(passageHelm.Manual ? "Manual helm engaged" : "Autopilot engaged", true); + return true; + } + + bool worked = livePassage.TryWorkStation(station, out string result); + if (worked) + AnnounceStation(station); + if (worked && station >= StationKind.Engine && station <= StationKind.Waste) + { + int area = (int)station - (int)StationKind.Engine; + if (area != passageServiceArea) + { + passageServiceArea = area; + Render(); + } + } + ShowStationResult(result, worked); + RefreshPassageBusiness(); + return worked; + } + + private void ShowStationResult(string result, bool worked) + { + stationFeedbackText = result; + stationFeedbackUntil = Time.unscaledTime + 3.4f; + if (worked) + passageAudio.Confirm(); + UpdateStationInteractions(); + } + + private void UpdateCrewCall() + { + if (crewCallReadout == null) + return; + + string text; + if (livePassage.CrewCall is StationKind station) + text = $"Crew call · {OnboardSession.StationName(station)} · {StationDeck(station)} · {livePassage.CrewRoundsLeft} rounds"; + else if (livePassage.CrewRequestsCompleted > 0) + text = $"Crew calls answered · {livePassage.CrewRequestsCompleted}"; + else + text = ""; + + SetPassageText(crewCallReadout, text); + crewCallReadout.style.display = text.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex; + crewCallReadout.EnableInClassList("crew-call-urgent", livePassage.CrewRoundsLeft is > 0 and <= 2); + } + + private string StationDeck(StationKind station) + { + if (station <= StationKind.Waste) + return "Service deck"; + + Facility room = station switch + { + StationKind.Cabins => Facility.Cabin, + StationKind.Dining => Facility.Dining, + StationKind.Bar => Facility.Bar, + StationKind.Stage => Facility.Entertainment, + _ => Facility.Amenity + }; + for (int i = 0; i < Ship.Decks.Count; i++) + if (System.Array.IndexOf(Ship.Decks[i].Cells, room) >= 0) + return $"Deck {i + 1}"; + return "Guest decks"; + } + } +} diff --git a/Assets/Soundings/Runtime/StationInteractions.cs.meta b/Assets/Soundings/Runtime/StationInteractions.cs.meta new file mode 100644 index 0000000..d506a0d --- /dev/null +++ b/Assets/Soundings/Runtime/StationInteractions.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 165c6f1f48ec795b1b9e38a98ac89ec1 \ No newline at end of file diff --git a/Assets/Soundings/Runtime/VisualSmoke.cs b/Assets/Soundings/Runtime/VisualSmoke.cs index be8b45c..3bce107 100644 --- a/Assets/Soundings/Runtime/VisualSmoke.cs +++ b/Assets/Soundings/Runtime/VisualSmoke.cs @@ -34,25 +34,70 @@ 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("port-plan-open")) + yield break; + IntegerField provisioning = root.Q("port-food-units"); + if (!CheckSmoke(provisioning != null && provisioning.value > 0, "Dockside orders show recommended provisions")) + yield break; + provisioning.value = 1120; + if (!SubmitSmoke("port-program-1") || !CheckSmoke(portFoodOrder == 1120 && portProgram == EntertainmentProgram.LiveMusic, + "Order an exact food quantity and book local musicians")) + yield break; + yield return CaptureSmoke(directory, "03a-dockside-orders"); + if (!SubmitSmoke("port-plan-close")) + yield break; 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