From ca3e5ce5e131c6f820d8fa069bf1b1566c60c844 Mon Sep 17 00:00:00 2001
From: skidau <skidau@gmail.com>
Date: Mon, 17 Nov 2014 16:05:16 +1100
Subject: [PATCH] Added an exception check when the game is close to
 overflowing.  Fixes the fifo overflow that occurs in Battalion Wars 2.
 Changed the CPEnd loop check to an exact match.

---
 Source/Core/VideoCommon/CommandProcessor.cpp | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/Source/Core/VideoCommon/CommandProcessor.cpp b/Source/Core/VideoCommon/CommandProcessor.cpp
index 899438b9e4..a47cfa18b1 100644
--- a/Source/Core/VideoCommon/CommandProcessor.cpp
+++ b/Source/Core/VideoCommon/CommandProcessor.cpp
@@ -330,7 +330,7 @@ void GatherPipeBursted()
 	}
 
 	// update the fifo pointer
-	if (fifo.CPWritePointer >= fifo.CPEnd)
+	if (fifo.CPWritePointer == fifo.CPEnd)
 		fifo.CPWritePointer = fifo.CPBase;
 	else
 		fifo.CPWritePointer += GATHER_PIPE_SIZE;
@@ -342,6 +342,10 @@ void GatherPipeBursted()
 		ProcessorInterface::Fifo_CPUEnd = fifo.CPEnd;
 	}
 
+	// If the game is running close to overflowing, make the exception checking more frequent.
+	if (fifo.bFF_HiWatermark)
+		CoreTiming::ForceExceptionCheck(0);
+
 	Common::AtomicAdd(fifo.CPReadWriteDistance, GATHER_PIPE_SIZE);
 
 	RunGpu();
@@ -470,8 +474,7 @@ void ProcessFifoAllDistance()
 {
 	if (IsOnThread())
 	{
-		while (!interruptWaiting && fifo.bFF_GPReadEnable &&
-			fifo.CPReadWriteDistance && !AtBreakpoint())
+		while (!interruptWaiting && fifo.bFF_GPReadEnable && fifo.CPReadWriteDistance && !AtBreakpoint())
 			Common::YieldCPU();
 	}
 }