Skip to content

オートモードの加減速処理を修正 - #5298

Merged
TinyKitten merged 4 commits into
devfrom
fix/simulation-mode-routes
Feb 16, 2026
Merged

TinyKitten merged 4 commits into
devfrom
fix/simulation-mode-routes

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Feb 16, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

リリースノート

  • バグ修正

    • 駅セグメント選択を改め判定精度を向上(groupIdではなくidに基づく判定)
    • セグメント終端で確実に停車する挙動を修正(停車状態の維持と遷移を改善)
  • その他の改善

    • 位置更新を線形補間に切替え、移動精度とタイミングを改善
    • 速度プロファイル生成に入力検証と安全処理を追加し出力安定性を向上(惰行/巡航/減速判定を最適化)
  • テスト

    • 上記挙動を検証するテストを追加・更新しタイミングや境界条件を強化

@TinyKitten TinyKitten self-assigned this Feb 16, 2026
@github-actions github-actions Bot added the react label Feb 16, 2026
@coderabbitai

coderabbitai Bot commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉


📝 Walkthrough

Walkthrough

駅の選択をgroupIdからidへ切替し、セグメント内移動を線形補間で計算。セグメント終端で速度0のdwellを導入し、速度プロファイル生成は入力検証とcoast判定を再構築。テスト群をそれぞれ更新・追加。

Changes

Cohort / File(s) Summary
シミュレーションモード核心ロジック
src/hooks/useSimulationMode.ts
segment選択をgroupId→idへ変更。dwellPendingRef追加、セグメント進行量算出・線形補間によるlat/lon計算に変更。速度切れでdwell(speed=0)を設定し次セグメントへ進行、セグメント開始時に進行状態リセット。
シミュレーションテスト
src/hooks/useSimulationMode.test.tsx
INBOUND期待値へ修正、タイマー進行量調整、セグメントidベース選択とdwell挙動(終端で0km/h)を検証する新テスト追加。
速度プロファイル生成ロジック
src/utils/trainSpeed.ts
入力バリデーション(非正値で[0]返却)、safeInterval導入、coast可否判定とcoast/cruise/減速の再計算。出力空時のフォールバックを追加。不要変数除去。
速度プロファイルテスト
src/utils/trainSpeed.test.ts
テスト群を大幅更新:非負性、coastあり/なしの挙動、maxSpeed上限、境界ケース(distance=0)などを追加・修正。モックとクリアを明示。

Sequence Diagram(s)

sequenceDiagram
  participant Timer
  participant SimHook as useSimulationMode
  participant SpeedGen as generateTrainSpeedProfile
  participant Movement as MovementEmitter

  Timer->>SimHook: tick()
  SimHook->>SimHook: resolve current segment (match by id)
  SimHook->>SpeedGen: request speed profile for segment
  SpeedGen-->>SimHook: speed profile array
  SimHook->>SimHook: compute segmentDistance / nextProgressDistance / moveDistance
  SimHook->>SimHook: interpolate lat/lon between prevWaypoint & nextWaypoint
  alt speeds exhausted (end of segment)
    SimHook->>SimHook: set dwellPendingRef (speed = 0)
    SimHook->>Movement: emit location (speed=0, heading cleared)
    SimHook->>SimHook: advance to next non-empty segment, reset progress
  else moving within segment
    SimHook->>Movement: emit interpolated location (speed = moveDistance)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Poem

🐰 兎が跳ねるはIDの径、
線で結んで座標すべる、
速度は波、時にゼロへ止まり、
次の区間へぽょんと進むよ、
小さな耳でシミュを祝うよ。

🚥 Pre-merge checks | ✅ 2 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Merge Conflict Detection ⚠️ Warning ❌ Merge conflicts detected (8 files):

⚔️ src/hooks/useSimulationMode.test.tsx (content)
⚔️ src/hooks/useSimulationMode.ts (content)
⚔️ src/hooks/useTelemetryEnabled.test.ts (content)
⚔️ src/hooks/useTelemetryEnabled.ts (content)
⚔️ src/hooks/useTelemetrySender.enabled.test.tsx (content)
⚔️ src/hooks/useTelemetrySender.ts (content)
⚔️ src/utils/trainSpeed.test.ts (content)
⚔️ src/utils/trainSpeed.ts (content)

These conflicts must be resolved before merging into dev.
Resolve conflicts locally and push changes to this branch.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed プルリクエストのタイトルは「オートモードの加減速処理を修正」で、実装内容の中心である加減速ロジック(trainSpeed関連)と駅選択ロジック、セグメント終端の停車処理の修正を適切に要約しており、主要な変更を明確に表現している。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/simulation-mode-routes
⚔️ Resolve merge conflicts (beta)
  • Auto-commit resolved conflicts to branch fix/simulation-mode-routes
  • Create stacked PR with resolved conflicts
  • Post resolved changes as copyable diffs in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/hooks/useSimulationMode.ts (1)

418-455: ⚠️ Potential issue | 🟡 Minor

終端ループ時に始点へ戻す処理を追加したい
nextSegmentIndex が -1 のとき座標が終端のまま index が 0 に戻るため、次ティックで始点区間へワープします。ループ時は始点座標へリセットしてから次区間へ進む方が安全です。

修正案
-      if (dwellPendingRef.current) {
-        const prev = store.get(locationAtom);
-        if (prev) {
-          setLocation({
-            timestamp: Date.now(),
-            coords: {
-              ...prev.coords,
-              speed: 0,
-              heading: null,
-            },
-          });
-        }
-        const nextSegmentIndex = speedProfilesRef.current.findIndex(
-          (seg, idx) => seg.length > 0 && idx > segmentIndexRef.current
-        );
-        segmentIndexRef.current =
-          nextSegmentIndex === -1 ? 0 : nextSegmentIndex;
+      if (dwellPendingRef.current) {
+        const nextSegmentIndex = speedProfilesRef.current.findIndex(
+          (seg, idx) => seg.length > 0 && idx > segmentIndexRef.current
+        );
+        const nextIndex = nextSegmentIndex === -1 ? 0 : nextSegmentIndex;
+        const prev = store.get(locationAtom);
+        const firstStation = maybeRevsersedStations[0];
+        if (prev) {
+          const resetToFirst =
+            nextSegmentIndex === -1 &&
+            firstStation?.latitude != null &&
+            firstStation?.longitude != null;
+          setLocation({
+            timestamp: Date.now(),
+            coords: {
+              ...prev.coords,
+              ...(resetToFirst
+                ? {
+                    latitude: firstStation.latitude,
+                    longitude: firstStation.longitude,
+                  }
+                : {}),
+              speed: 0,
+              heading: null,
+            },
+          });
+        }
+        segmentIndexRef.current = nextIndex;
         childIndexRef.current = 0;
         segmentProgressDistanceRef.current = 0;
         dwellPendingRef.current = false;
         return;
       }
@@
-  }, [enabled, selectedDirection, step]);
+  }, [enabled, selectedDirection, step, maybeRevsersedStations]);
🤖 Fix all issues with AI agents
In `@src/utils/trainSpeed.test.ts`:
- Around line 5-7: Replace the afterEach hook's call to jest.restoreAllMocks()
with jest.clearAllMocks() in the test file: locate the afterEach block
(afterEach(() => { jest.restoreAllMocks(); });) and change the mock-reset
function to jest.clearAllMocks() so the test follows the repository's guideline
and aligns with other test files.

Comment thread src/utils/trainSpeed.test.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/utils/trainSpeed.test.ts`:
- Around line 44-60: The test for generateTrainSpeedProfile can produce false
positives because start may be -1 (making slice empty) and equal-values
(25,25,25...) satisfy the current non-increasing check; update the test to
assert start !== -1 (fail if no maxSpeed found), then verify the coast segment
is strictly decreasing (each next value < previous) rather than non-increasing,
and finally restore the Math.random spy by calling mockRestore() (or use the spy
reference returned by jest.spyOn) at the end of the test to avoid leaking the
mock; target the generateTrainSpeedProfile usage and the Math.random spy in your
changes.
🧹 Nitpick comments (1)
src/utils/trainSpeed.test.ts (1)

92-102: approxDistanceの意図をテスト側で固定すると将来壊れにくいです
現状は「デフォルトinterval=1前提の近似」なので、明示的にinterval: 1を渡す/speed * intervalで積算する形にすると読み手に優しいです。

Comment thread src/utils/trainSpeed.test.ts Resolved
@TinyKitten
TinyKitten merged commit 9b8ee66 into dev Feb 16, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the fix/simulation-mode-routes branch February 16, 2026 11:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant