diff --git a/UXAssist/CHANGELOG.md b/UXAssist/CHANGELOG.md index c3899a1..8c69d50 100644 --- a/UXAssist/CHANGELOG.md +++ b/UXAssist/CHANGELOG.md @@ -4,6 +4,7 @@ ## Changlog * 1.6.3 - Unreleased + * `Sunlight at night`: Base lighting on the camera and the viewed surface instead of Icarus's facing direction, including planet view. Keep building, terrain, solar-panel, and belt lighting directions synchronized, recover when the active light or planet changes, and restore native lighting when sailing, disabling the feature, or using white rendering mode. * `Quick build Mining Machines`: Add a Factory-tab button that searches dense layouts at the nearest solid vein group using native collision shapes, including interleaving feet, joint placement of nearby miners, and a final pass to fill remaining compatible positions. `Allow restoring/burying veins` is off by default: uses only visible nodes and skips all restoration and burial calculations. When enabled, restores available buried nodes and may bury unused nodes to improve coverage. Optimizes summed vein coverage, requires at least 3 covered nodes per miner after any burial, and places the full ordinary miner layout regardless of stock, leaving ghosts awaiting missing materials. Accelerates layout searches with up to 4 background workers, capped at half the available logical processors. Writes replayable JSON snapshots during feature tuning and keeps the completion tip visible for about 8 seconds. * 1.6.2 * `Increase maximum power usage in Logistic Stations and Advanced Mining Machines`: Fix zero or corrupted mining speeds when adjusting an Advanced Mining Machine's speed slider with the option enabled. @@ -437,6 +438,7 @@ ## 更新日志 * 1.6.3 - Unreleased + * `夜间日光灯`:按镜头和当前观察位置的地表方向计算光照,不再跟随机甲朝向,行星视图也适用。统一建筑、地表、太阳能板和传送带的光照方向,在光源或行星切换后恢复功能,并在航行、关闭功能或白模渲染时恢复原版光照。 * `快速铺设采矿机`:在「工厂」页增加按钮,按游戏实际碰撞体在最近的固体矿脉搜索密集布局,支持脚部交错、邻近矿机联动调整及结束前补入剩余可用位置。「允许恢复/掩埋矿物」默认关闭:仅使用可见矿点,跳过所有恢复和掩埋计算;开启后,恢复可恢复的掩埋矿点,并允许掩埋未被使用的矿点来提高覆盖数。以各台矿机覆盖矿点数之和为目标,要求每台在掩埋后仍覆盖至少 3 个矿点,不受库存限制地生成完整布局,缺少采矿机的位置保留待建造虚影。使用最多 4 个后台线程加速布局搜索,线程数不超过可用逻辑线程数的一半。功能调试期间输出可离线重放的 JSON 数据,完成提示保留约 8 秒。 * 1.6.2 * `提升物流塔和大型采矿机的最大功耗`:修复启用后调整大型采矿机开采速度时出现 0% 或异常速度的问题。 diff --git a/UXAssist/Patches/Factory/FactoryPatch.cs b/UXAssist/Patches/Factory/FactoryPatch.cs index 63380c6..314483e 100644 --- a/UXAssist/Patches/Factory/FactoryPatch.cs +++ b/UXAssist/Patches/Factory/FactoryPatch.cs @@ -108,8 +108,6 @@ public static class FactoryPatch UnlimitInteractiveEnabled.SettingChanged += (_, _) => ArchitectModePatch.UnlimitInteractive.Enable(UnlimitInteractiveEnabled.Value); RemoveSomeConditionEnabled.SettingChanged += (_, _) => ArchitectModePatch.RemoveSomeConditionBuild.Enable(RemoveSomeConditionEnabled.Value); NightLightEnabled.SettingChanged += (_, _) => RenderingPatch.NightLight.Enable(NightLightEnabled.Value); - NightLightAngleX.SettingChanged += (_, _) => RenderingPatch.NightLight.UpdateSunlightAngle(); - NightLightAngleY.SettingChanged += (_, _) => RenderingPatch.NightLight.UpdateSunlightAngle(); RemoveBuildRangeLimitEnabled.SettingChanged += (_, _) => ArchitectModePatch.RemoveBuildRangeLimit.Enable(RemoveBuildRangeLimitEnabled.Value); LargerAreaForUpgradeAndDismantleEnabled.SettingChanged += (_, _) => ArchitectModePatch.LargerAreaForUpgradeAndDismantle.Enable(LargerAreaForUpgradeAndDismantleEnabled.Value); LargerAreaForTerraformEnabled.SettingChanged += (_, _) => ArchitectModePatch.LargerAreaForTerraform.Enable(LargerAreaForTerraformEnabled.Value); diff --git a/UXAssist/Patches/Factory/RenderingPatch.cs b/UXAssist/Patches/Factory/RenderingPatch.cs index 6b619ef..b75ab47 100644 --- a/UXAssist/Patches/Factory/RenderingPatch.cs +++ b/UXAssist/Patches/Factory/RenderingPatch.cs @@ -12,12 +12,6 @@ namespace UXAssist.Patches.Factory; internal static class RenderingPatch { - public static void Enable(bool enable) - { - DoNotRenderEntities.Enable(enable); - NightLight.Enable(enable); - } - internal class DoNotRenderEntities : PatchImpl { public static bool HideSorters; @@ -92,140 +86,173 @@ internal static class RenderingPatch internal class NightLight : PatchImpl { - private static bool _nightlightInitialized; - private static bool _mechaOnEarth; - private static AnimationState _sail; private static Light _sunlight; + private static Quaternion _sunlightLocalRotation; + private static PlanetSimulator _planetSimulator; + private static int _sunDirectionId; + private static int _globalSunDirectionId; protected override void OnEnable() { - GameLogicProc.OnGameEnd += OnGameEnd; + _sunDirectionId = Shader.PropertyToID("_SunDir"); + _globalSunDirectionId = Shader.PropertyToID("_Global_SunDir"); + GameLogicProc.OnGameEnd += RestoreSunlight; } protected override void OnDisable() { - GameLogicProc.OnGameEnd -= OnGameEnd; - if (_sunlight) - { - _sunlight.transform.localEulerAngles = new Vector3(0f, 180f); - _sunlight = null; - } - _sail = null; - _mechaOnEarth = false; - _nightlightInitialized = false; + GameLogicProc.OnGameEnd -= RestoreSunlight; + RestoreSunlight(); } - private static void OnGameEnd() + private static void RestoreSunlight() { - if (_sunlight) + var sunlight = _sunlight; + if (sunlight) + sunlight.transform.localRotation = _sunlightLocalRotation; + var planetSimulator = _planetSimulator; + _sunlight = null; + _planetSimulator = null; + + if ((!sunlight && !planetSimulator) || !GameMain.instance || !GameMain.instance._running || GameMain.instance.isMenuDemo || FactoryModel.whiteMode0) return; + var starSimulator = GameMain.universeSimulator?.LocalStarSimulator(); + if (starSimulator) + Shader.SetGlobalVector(_globalSunDirectionId, starSimulator.transform.forward); + if (planetSimulator && planetSimulator.isActiveAndEnabled && planetSimulator.planetData != null) { - _sunlight.transform.localEulerAngles = new Vector3(0f, 180f); - _sunlight = null; + var rotation = GameMain.localPlanet?.runtimeRotation ?? Quaternion.identity; + var planet = planetSimulator.planetData; + Vector3 direction = Quaternion.Inverse(rotation) * (planet.star.uPosition - planet.uPosition).normalized; + ApplyPlanetSunlightDirection(planetSimulator, direction); } - _sail = null; - _mechaOnEarth = false; - _nightlightInitialized = false; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void UpdateSunlightAngle() + internal static Vector3 CalculateSunlightDirection(Vector3 surfaceUp, Vector3 cameraForward, Vector3 cameraUp, float angleX, float angleY) { - if (!_sunlight) return; - _sunlight.transform.rotation = - Quaternion.LookRotation(-GameMain.mainPlayer.transform.up + GameMain.mainPlayer.transform.forward * FactoryPatch.NightLightAngleX.Value / 10f + - GameMain.mainPlayer.transform.right * FactoryPatch.NightLightAngleY.Value / 10f); + surfaceUp.Normalize(); + // Screen-right stays stable when the native globe camera's offset crosses its viewing axis. + var right = Vector3.ProjectOnPlane(Vector3.Cross(cameraUp, cameraForward), surfaceUp); + if (right.sqrMagnitude < 0.000001f) + right = Vector3.Cross(-cameraForward, surfaceUp); + right.Normalize(); + var towardCamera = Vector3.Cross(surfaceUp, right); + return (surfaceUp - towardCamera * (angleX / 10f) - right * (angleY / 10f)).normalized; } [HarmonyPostfix] - [HarmonyPatch(typeof(GameMain), nameof(GameMain.LateUpdate))] - public static void GameMain_LateUpdate_Postfix(GameMain __instance) + [HarmonyPatch(typeof(GameCamera), nameof(GameCamera.FrameLogic))] + private static void UpdateLighting() { - if (__instance.isMenuDemo || !__instance._running) return; - - if (!_nightlightInitialized) + var camera = GameCamera.main; + if (!camera) return; + var game = GameMain.instance; + var player = GameMain.mainPlayer; + var planet = GameMain.localPlanet; + if (!game || !game._running || game.isMenuDemo || player == null || planet == null || + player.movementState == EMovementState.Sail || FactoryModel.whiteMode0) { - if (!GameMain.mainPlayer.controller.model.gameObject.activeInHierarchy) return; - if (_sail == null) _sail = GameMain.mainPlayer.animator.sails[GameMain.mainPlayer.animator.sailAnimIndex]; - _nightlightInitialized = true; - } - - var sailing = _sail && _sail.enabled; - if (_mechaOnEarth) - { - if (!sailing) - { - UpdateSunlightAngle(); - return; - } - _mechaOnEarth = false; - if (!_sunlight) return; - _sunlight.transform.localEulerAngles = new Vector3(0f, 180f); - _sunlight = null; + RestoreSunlight(); return; } - if (sailing) return; - _mechaOnEarth = true; - if (_sunlight == null) + var universe = GameMain.universeSimulator; + var sunlight = universe?.LocalStarSimulator()?.sunLight; + var planetSimulator = universe?.FindPlanetSimulator(planet); + if (!sunlight || !planetSimulator) { - _sunlight = GameMain.universeSimulator?.LocalStarSimulator()?.sunLight; + RestoreSunlight(); + return; } + + var cameraTransform = camera.transform; + var target = GameCamera.generalTarget; + var surfaceUp = GameCamera.instance && GameCamera.instance.isPlanetMode + ? cameraTransform.position + : target ? target.position : player.position; + if (surfaceUp.sqrMagnitude < 0.000001f) + { + RestoreSunlight(); + return; + } + + if (_sunlight != sunlight || _planetSimulator != planetSimulator) + { + RestoreSunlight(); + _sunlight = sunlight; + _sunlightLocalRotation = sunlight.transform.localRotation; + _planetSimulator = planetSimulator; + } + + var direction = CalculateSunlightDirection(surfaceUp, cameraTransform.forward, cameraTransform.up, + FactoryPatch.NightLightAngleX.Value, FactoryPatch.NightLightAngleY.Value); + // Native camera updates run after the star and planet callbacks. + sunlight.transform.rotation = Quaternion.FromToRotation(Vector3.forward, -direction); + Shader.SetGlobalVector(_globalSunDirectionId, direction); + ApplyPlanetSunlightDirection(planetSimulator, direction); } - // Harmony transpiler: StarSimulator_LateUpdate_Transpiler - // Target: StarSimulator.LateUpdate - // Fallback: None — patch will fail loudly if the target method body changes. + + private static void ApplyPlanetSunlightDirection(PlanetSimulator planetSimulator, Vector3 direction) + { + if (planetSimulator.surfaceRenderer != null && planetSimulator.surfaceRenderer.Length > 0 && planetSimulator.surfaceRenderer[0]) + SetSunlightDirection(planetSimulator.surfaceRenderer[0].sharedMaterial, direction); + SetSunlightDirection(planetSimulator.reformMat0, direction); + SetSunlightDirection(planetSimulator.reformMat1, direction); + SetSunlightDirection(planetSimulator.atmoMat, direction); + SetSunlightDirection(planetSimulator.atmoMatLate, direction); + } + + private static void SetSunlightDirection(Material material, Vector3 direction) + { + if (material) material.SetVector(_sunDirectionId, direction); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void SetNativeGlobalSunDirection(string _, Vector4 direction, StarSimulator simulator) + { + if (_sunlight && simulator.sunLight == _sunlight && !FactoryModel.whiteMode0) return; + Shader.SetGlobalVector(_globalSunDirectionId, direction); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void SetNativePlanetSunDirection(Material material, string _, Vector4 direction, PlanetSimulator simulator) + { + if (simulator == _planetSimulator && simulator.planetData == GameMain.localPlanet && !FactoryModel.whiteMode0 && _sunlight) return; + material.SetVector(_sunDirectionId, direction); + } + + // Harmony transpiler: DeferNativeSunDirectionWrites + // Targets: StarSimulator.LateUpdate and PlanetSimulator.LateRefresh sun-direction setters. + // Fallback: TranspilerGuard returns original instructions when a sun-direction setter is not found. [HarmonyTranspiler] [HarmonyPatch(typeof(StarSimulator), nameof(StarSimulator.LateUpdate))] - private static IEnumerable StarSimulator_LateUpdate_Transpiler(IEnumerable instructions, ILGenerator generator) - { - var matcher = new CodeMatcher(instructions, generator); - var label1 = generator.DefineLabel(); - var label2 = generator.DefineLabel(); - matcher.MatchForward(false, - new CodeMatch(OpCodes.Ldarg_0), - new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(Component), nameof(Component.transform))) - ).InsertAndAdvance( - new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(NightLight), nameof(_mechaOnEarth))), - new CodeInstruction(OpCodes.Brfalse_S, label1), - new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(GameMain), nameof(GameMain.mainPlayer))), - new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.transform))), - new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Transform), nameof(Transform.up))), - new CodeInstruction(OpCodes.Stloc_0), - new CodeInstruction(OpCodes.Br_S, label2) - ); - matcher.Labels.Add(label1); - matcher.MatchForward(false, - new CodeMatch(OpCodes.Stloc_0) - ).Advance(1).Labels.Add(label2); - return matcher.InstructionEnumeration(); - } - // Harmony transpiler: PlanetSimulator_LateRefresh_Transpiler - // Target: PlanetSimulator.LateRefresh - // Fallback: None — patch will fail loudly if the target method body changes. - [HarmonyTranspiler] [HarmonyPatch(typeof(PlanetSimulator), nameof(PlanetSimulator.LateRefresh))] - private static IEnumerable PlanetSimulator_LateRefresh_Transpiler(IEnumerable instructions, ILGenerator generator) + private static IEnumerable DeferNativeSunDirectionWrites(IEnumerable instructions, MethodBase original) { - // var vec = (NightlightEnabled ? GameMain.mainPlayer.transform.up : (Quaternion.Inverse(localPlanet.runtimeRotation) * (__instance.planetData.star.uPosition - __instance.planetData.uPosition).normalized)); - var matcher = new CodeMatcher(instructions, generator); - var label1 = generator.DefineLabel(); - var label2 = generator.DefineLabel(); - matcher.MatchForward(false, - new CodeMatch(OpCodes.Stloc_1) - ).Advance(1).InsertAndAdvance( - new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(NightLight), nameof(_mechaOnEarth))), - new CodeInstruction(OpCodes.Brfalse_S, label1), - new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(GameMain), nameof(GameMain.mainPlayer))), - new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.transform))), - new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Transform), nameof(Transform.up))), - new CodeInstruction(OpCodes.Stloc_2), - new CodeInstruction(OpCodes.Br_S, label2) - ); - matcher.Labels.Add(label1); - matcher.MatchForward(false, - new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(FactoryModel), nameof(FactoryModel.whiteMode0))) - ).Labels.Add(label2); - return matcher.InstructionEnumeration(); + var isPlanet = original.DeclaringType == typeof(PlanetSimulator); + var property = isPlanet ? "_SunDir" : "_Global_SunDir"; + var setter = isPlanet + ? AccessTools.Method(typeof(Material), nameof(Material.SetVector), [typeof(string), typeof(Vector4)]) + : AccessTools.Method(typeof(Shader), nameof(Shader.SetGlobalVector), [typeof(string), typeof(Vector4)]); + var replacement = AccessTools.Method(typeof(NightLight), isPlanet ? nameof(SetNativePlanetSunDirection) : nameof(SetNativeGlobalSunDirection)); + var matcher = new CodeMatcher(instructions); + var matched = false; + while (true) + { + matcher.MatchForward(false, new CodeMatch(OpCodes.Ldstr, property)); + if (matcher.IsInvalid) break; + matcher.Advance(1).MatchForward(false, new CodeMatch(instruction => instruction.Calls(setter) || instruction.opcode == OpCodes.Ldstr)); + if (matcher.IsInvalid) + return matcher.Finish(instructions, UXAssist.Logger, nameof(DeferNativeSunDirectionWrites)); + if (!matcher.Instruction.Calls(setter)) + { + UXAssist.Logger?.LogWarning($"Transpiler '{nameof(DeferNativeSunDirectionWrites)}' found an unexpected sun-direction write; returning original instructions."); + return instructions; + } + matcher.InsertAndAdvance(new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(matcher.Instruction)); + matcher.Set(OpCodes.Call, replacement).Advance(1); + matched = true; + } + return matched ? matcher.InstructionEnumeration() : matcher.Finish(instructions, UXAssist.Logger, nameof(DeferNativeSunDirectionWrites)); } } } diff --git a/UXAssist/README.md b/UXAssist/README.md index 44691da..2a809be 100644 --- a/UXAssist/README.md +++ b/UXAssist/README.md @@ -44,6 +44,8 @@ * Increase capacity of player order queue to 128 (from 16) * Factory * Sunlight at night + * Lighting follows the camera instead of Icarus's facing direction, including planet view. Negative X tilts the light toward the camera; negative Y shifts it to the right of the screen. Positive values reverse these directions. Existing angle values are retained. + * Lighting directions stay synchronized across buildings and terrain. Native lighting is restored when sailing, disabling the feature, or using the game's white rendering mode. * Remove some build conditions * Remove build count and range limit * Larger area for upgrade and dismantle (up to 31x31) @@ -244,6 +246,8 @@ * 将玩家指令队列的容量增加到128(原来为16) * 工厂 * 夜间日光灯 + * 光照随镜头变化,不再跟随机甲朝向,行星视图也适用。X 的负值使光线朝镜头倾斜,Y 的负值使光源向画面右侧偏移;正值反向。保留现有角度设置。 + * 建筑与地表的光照方向保持一致。航行、关闭功能或进入游戏白模渲染时恢复原版光照。 * 移除部分不影响游戏逻辑的建造条件 * 移除建造数量和范围限制 * 扩大范围升级和拆除区域(最大 31×31)