Skip to content

Commit

Permalink
fix: timers
Browse files Browse the repository at this point in the history
closes #172
closes #170
closes #169
  • Loading branch information
DorielRivalet committed Aug 19, 2023
1 parent ab8099e commit 12921bb
Show file tree
Hide file tree
Showing 6 changed files with 257 additions and 201 deletions.
21 changes: 0 additions & 21 deletions MHFZ_Overlay/DataLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -415,27 +415,6 @@ public void CheckForIllegalModifications()
/// </value>
public AddressModel Model { get; } // TODO: fix null warning

/// <summary>
/// Gets the quest time elapsed. TODO: move somewhere else.
/// </summary>
/// <returns>The quest time elapsed.</returns>
public string GetQuestTimeElapsed()
{
decimal totalQuestDurationSeconds = (decimal)this.Model.TimeDefInt() / Numbers.FramesPerSecond; // Total duration of the quest in seconds
decimal timeRemainingInSeconds = (decimal)this.Model.TimeInt() / Numbers.FramesPerSecond; // Time left in the quest in seconds

// Calculate the elapsed time by subtracting the time left from the total duration
decimal elapsedTimeSeconds = totalQuestDurationSeconds - timeRemainingInSeconds;

// Create a TimeSpan object directly from elapsed time in seconds
TimeSpan elapsedTime = TimeSpan.FromSeconds((double)elapsedTimeSeconds);

// Format the TimeSpan object as a string
string formattedElapsedTime = elapsedTime.ToString(TimeFormats.MinutesSecondsMilliseconds, CultureInfo.InvariantCulture);

return formattedElapsedTime;
}

/// <summary>
/// Creates the code cave.
/// </summary>
Expand Down
91 changes: 60 additions & 31 deletions MHFZ_Overlay/Services/DatabaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,15 @@ public void InsertPersonalBest(DataLoader dataLoader, long currentPersonalBest,
var questID = dataLoader.Model.QuestID();
var actualOverlayMode = string.Empty;
dataLoader.Model.ShowSaveIcon = true;
var timeLeft = dataLoader.Model.TimeInt();

// TODO dure timedefint address
var timeDefIint = questID != Numbers.QuestIDFirstDistrictDuremudira && questID != Numbers.QuestIDSecondDistrictDuremudira ? dataLoader.Model.TimeDefInt() : Numbers.DuremudiraTimeLimitFrames;

var finalTimeValue = timeDefIint - timeLeft;

// Calculate the elapsed time of the quest
var finalTimeDisplay = TimeService.GetMinutesSecondsMillisecondsFromFrames((long)finalTimeValue);

var s = (Settings)System.Windows.Application.Current.TryFindResource("Settings");

Expand Down Expand Up @@ -587,21 +596,20 @@ public void InsertPersonalBest(DataLoader dataLoader, long currentPersonalBest,

using (var cmd = new SQLiteCommand(sql, conn))
{
var timeLeft = model.TimeInt(); // Example value of the TimeLeft variable
var finalTimeValue = model.TimeDefInt() - model.TimeInt();

// Calculate the elapsed time of the quest
var finalTimeDisplay = dataLoader.GetQuestTimeElapsed();

// Convert the elapsed time to a DateTime object
string objectiveImage;

// Gathering/etc
if ((dataLoader.Model.ObjectiveType() == 0x0 || dataLoader.Model.ObjectiveType() == 0x02 || dataLoader.Model.ObjectiveType() == 0x1002) && dataLoader.Model.QuestID() != 23527 && dataLoader.Model.QuestID() != 23628 && dataLoader.Model.QuestID() != 21731 && dataLoader.Model.QuestID() != 21749 && dataLoader.Model.QuestID() != 21746 && dataLoader.Model.QuestID() != 21750)
if ((dataLoader.Model.ObjectiveType() == 0x0 || dataLoader.Model.ObjectiveType() == 0x02 || dataLoader.Model.ObjectiveType() == 0x1002) && dataLoader.Model.QuestID() != 23527 && dataLoader.Model.QuestID() != 23628 && dataLoader.Model.QuestID() != 21749 && dataLoader.Model.QuestID() != 21750 && dataLoader.Model.QuestID() != Numbers.QuestIDFirstDistrictDuremudira && dataLoader.Model.QuestID() != Numbers.QuestIDSecondDistrictDuremudira)
{
objectiveImage = ViewModels.Windows.AddressModel.GetAreaIconFromID(dataLoader.Model.AreaID());
}

else if (dataLoader.Model.QuestID() == Numbers.QuestIDSecondDistrictDuremudira || dataLoader.Model.QuestID() == Numbers.QuestIDFirstDistrictDuremudira)
{
objectiveImage = dataLoader.Model.GetMonsterIcon(132);
}

// Tenrou Sky Corridor areas
else if (dataLoader.Model.AreaID() is 391 or 392 or 394 or 415 or 416)
{
Expand Down Expand Up @@ -856,7 +864,6 @@ FinalTimeValue ASC
@Attempts)";
using (var cmd = new SQLiteCommand(sql, conn))
{
var finalTimeValue = model.TimeDefInt() - model.TimeInt();
if (finalTimeValue < personalBest || personalBest == 0)
{
improvedPersonalBest = true;
Expand Down Expand Up @@ -5769,7 +5776,7 @@ FinalTimeValue ASC
time = reader.GetInt64(reader.GetOrdinal("TimeLeft"));
}

personalBest = ViewModels.Windows.AddressModel.GetMinutesSecondsMillisecondsFromFrames(time);
personalBest = TimeService.GetMinutesSecondsMillisecondsFromFrames(time);
}
else
{
Expand Down Expand Up @@ -5803,10 +5810,14 @@ public async Task<string> GetPersonalBestAsync(long questID, int weaponTypeID, s
await conn.OpenAsync();
using (var transaction = conn.BeginTransaction())
{
try
var numRetries = 0;
var success = false;
while (!success && numRetries < 3)
{
using (var cmd = new SQLiteCommand(
@"SELECT
try
{
using (var cmd = new SQLiteCommand(
@"SELECT
TimeLeft,
FinalTimeValue,
FinalTimeDisplay,
Expand All @@ -5824,37 +5835,51 @@ Quests q
ORDER BY
FinalTimeValue ASC
LIMIT 1", conn))
{
cmd.Parameters.AddWithValue("@questID", questID);
cmd.Parameters.AddWithValue("@weaponTypeID", weaponTypeID);
cmd.Parameters.AddWithValue("@category", category);

var reader = await cmd.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
long time = 0;
if (timerMode == "Elapsed")
cmd.Parameters.AddWithValue("@questID", questID);
cmd.Parameters.AddWithValue("@weaponTypeID", weaponTypeID);
cmd.Parameters.AddWithValue("@category", category);

var reader = await cmd.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
time = reader.GetInt64(reader.GetOrdinal("FinalTimeValue"));
long time = 0;
if (timerMode == "Elapsed")
{
time = reader.GetInt64(reader.GetOrdinal("FinalTimeValue"));
}
else
{
time = reader.GetInt64(reader.GetOrdinal("TimeLeft"));
}

personalBest = TimeService.GetMinutesSecondsMillisecondsFromFrames(time);
}
else
{
time = reader.GetInt64(reader.GetOrdinal("TimeLeft"));
personalBest = Messages.TimerNotLoaded;
}
}

personalBest = ViewModels.Windows.AddressModel.GetMinutesSecondsMillisecondsFromFrames(time);
transaction.Commit();
success = true;
}
catch (SQLiteException ex)
{
if (ex.ResultCode is SQLiteErrorCode.Locked or SQLiteErrorCode.Busy)
{
// Database is locked, retry after a short delay
numRetries++;
Logger.Warn(CultureInfo.InvariantCulture, ex);
Thread.Sleep(1_000);
}
else
{
personalBest = Messages.TimerNotLoaded;
// Some other error occurred, abort the transaction
HandleError(transaction, ex);
break;
}
}

transaction.Commit();
}
catch (Exception ex)
{
HandleError(transaction, ex);
}
}
}
Expand Down Expand Up @@ -6101,6 +6126,7 @@ DO UPDATE
{
// Database is locked, retry after a short delay
numRetries++;
Logger.Warn(CultureInfo.InvariantCulture, ex);
Thread.Sleep(1_000);
}
else
Expand Down Expand Up @@ -6168,6 +6194,7 @@ DO UPDATE
{
// Database is locked, retry after a short delay
numRetries++;
Logger.Warn(CultureInfo.InvariantCulture, ex);
Thread.Sleep(1_000);
}
else
Expand Down Expand Up @@ -6235,6 +6262,7 @@ DO UPDATE
{
// Database is locked, retry after a short delay
numRetries++;
Logger.Warn(CultureInfo.InvariantCulture, ex);
await Task.Delay(1_000);
}
else
Expand Down Expand Up @@ -6302,6 +6330,7 @@ DO UPDATE
{
// Database is locked, retry after a short delay
numRetries++;
Logger.Warn(CultureInfo.InvariantCulture, ex);
await Task.Delay(1_000);
}
else
Expand Down
59 changes: 49 additions & 10 deletions MHFZ_Overlay/Services/TimeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static TimeSpan GetTimeSpanFromFrames(decimal frames)

public static string GetTimeLeftPercent(decimal timeDefInt, decimal timeInt, bool isDure)
{
if (timeDefInt < timeInt)
if (timeDefInt < timeInt || timeDefInt <= 0)
{
return " (?)";
}
Expand Down Expand Up @@ -76,7 +76,7 @@ public static string TestTimerMethods(decimal timeDefInt)

for (decimal i = timeInt; i >= 0M; i--)
{
timer1Result = StringBuilderTimer(timeInt, timeDefInt, true, GetTimeLeftPercent(timeDefInt, timeInt, true), TimerMode.Elapsed);
timer1Result = StringBuilderTimer(timeInt, TimerFormat.MinutesSecondsMilliseconds, true, timeDefInt, true, GetTimeLeftPercent(timeDefInt, timeInt, true), TimerMode.Elapsed);
timer2Result = TimeSpanTimer(timeInt, timeDefInt, true, GetTimeLeftPercent(timeDefInt, timeInt, true), TimerMode.Elapsed);
timer3Result = SimpleTimer(timeInt, timeDefInt, true, GetTimeLeftPercent(timeDefInt, timeInt, true), TimerMode.Elapsed);

Expand All @@ -99,9 +99,10 @@ public static string TestTimerMethods(decimal timeDefInt)
Simple: {timer3Result}";
}

public static string SimpleTimer(decimal timeInt, decimal timeDefInt, bool timeLeftPercentShown = false, string timeLeftPercentNumber = "", TimerMode timerMode = TimerMode.Elapsed)
public static string SimpleTimer(decimal timeInt, decimal timeDefInt = 0, bool timeLeftPercentShown = false, string timeLeftPercentNumber = "", TimerMode timerMode = TimerMode.Elapsed)
{
decimal time = timerMode == TimerMode.Elapsed || timeInt >= timeDefInt ? time = timeDefInt - timeInt : time = timeInt;
// TODO wrong conditionals for timeint >= timedefint?
decimal time = timerMode == TimerMode.Elapsed && timeInt <= timeDefInt ? time = timeDefInt - timeInt : time = timeInt;
decimal milliseconds = time / 30 * 1000;
decimal totalMinutes = Math.Floor(milliseconds / 60000);
decimal minutes = totalMinutes >= 60 ? totalMinutes : Math.Floor(milliseconds / 60000);
Expand All @@ -112,10 +113,10 @@ public static string SimpleTimer(decimal timeInt, decimal timeDefInt, bool timeL
return $"{minutes:00}:{seconds:00}.{remainingMilliseconds:000}" + timeLeftPercent;
}

public static string StringBuilderTimer(decimal timeInt, decimal timeDefInt, bool timeLeftPercentShown = false, string timeLeftPercentNumber = "", TimerMode timerMode = TimerMode.Elapsed)
public static string StringBuilderTimer(decimal timeInt, TimerFormat timerFormat, bool isFrames = true, decimal timeDefInt = 0, bool timeLeftPercentShown = false, string timeLeftPercentNumber = "", TimerMode timerMode = TimerMode.Elapsed)
{
decimal time = timerMode == TimerMode.Elapsed || timeInt >= timeDefInt ? time = timeDefInt - timeInt : time = timeInt;
decimal framesPerSecond = Numbers.FramesPerSecond;
decimal time = timerMode == TimerMode.Elapsed && timeInt <= timeDefInt ? time = timeDefInt - timeInt : time = timeInt;
decimal framesPerSecond = isFrames ? Numbers.FramesPerSecond : 1;
decimal totalSeconds = time / framesPerSecond;
decimal totalMinutes = Math.Floor(totalSeconds / 60);
decimal minutes = totalMinutes >= 60 ? totalMinutes : Math.Floor(totalSeconds / 60);
Expand All @@ -124,15 +125,26 @@ public static string StringBuilderTimer(decimal timeInt, decimal timeDefInt, boo
var timeLeftPercent = timeLeftPercentShown ? timeLeftPercentNumber : string.Empty;

StringBuilder sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}.{2:000}", minutes, seconds, milliseconds);
switch (timerFormat)
{
default:
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}.{2:000}", minutes, seconds, milliseconds);
break;
case TimerFormat.MinutesSeconds:
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}", minutes, seconds);
break;
case TimerFormat.MinutesSecondsMilliseconds:
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}.{2:000}", minutes, seconds, milliseconds);
break;
}
sb.Append(timeLeftPercent);

return sb.ToString();
}

public static string TimeSpanTimer(decimal timeInt, decimal timeDefInt, bool timeLeftPercentShown = false, string timeLeftPercentNumber = "", TimerMode timerMode = TimerMode.Elapsed)
public static string TimeSpanTimer(decimal timeInt, decimal timeDefInt = 0, bool timeLeftPercentShown = false, string timeLeftPercentNumber = "", TimerMode timerMode = TimerMode.Elapsed)
{
decimal time = timerMode == TimerMode.Elapsed || timeInt >= timeDefInt ? time = timeDefInt - timeInt : time = timeInt;
decimal time = timerMode == TimerMode.Elapsed && timeInt <= timeDefInt ? time = timeDefInt - timeInt : time = timeInt;
decimal timeInSeconds = time / Numbers.FramesPerSecond;
TimeSpan timeInSecondsSpan = TimeSpan.FromSeconds((double)timeInSeconds);
int roundedMilliseconds = (int)(Math.Round(timeInSecondsSpan.TotalMilliseconds) % 1000);
Expand All @@ -144,4 +156,31 @@ public static string TimeSpanTimer(decimal timeInt, decimal timeDefInt, bool tim
return $"{minutes:00}:{timeInSecondsSpan.Seconds:00}.{roundedMilliseconds:000}" + timeLeftPercent;
}

/// <summary>
/// Gets the elapsed time in the desired format.
/// </summary>
/// <param name="frames"></param>
/// <returns></returns>
public static string GetMinutesSecondsFromSeconds(double seconds) => StringBuilderTimer((long)seconds, TimerFormat.MinutesSeconds, false);

/// <summary>
/// Gets the elapsed time in the desired format.
/// </summary>
/// <param name="frames"></param>
/// <returns></returns>
public static string GetMinutesSecondsFromFrames(double frames) => StringBuilderTimer((long)frames, TimerFormat.MinutesSeconds);

/// <summary>
/// Gets the elapsed time in the desired format.
/// </summary>
/// <param name="frames"></param>
/// <returns></returns>
public static string GetMinutesSecondsMillisecondsFromFrames(double frames) => StringBuilderTimer((long)frames, TimerFormat.MinutesSecondsMilliseconds);

/// <summary>
/// Gets the elapsed time in the desired format.
/// </summary>
/// <param name="frames"></param>
/// <returns></returns>
public static string GetMinutesSecondsMillisecondsFromFrames(long frames) => StringBuilderTimer(frames, TimerFormat.MinutesSecondsMilliseconds);
}
Loading

0 comments on commit 12921bb

Please sign in to comment.