Compare commits

..

33 Commits

Author SHA1 Message Date
Maxluli 315e61dc89 Cleaned the doc repo 2023-06-09 11:57:31 +02:00
Maxluli 40c7e3df81 Added a new table of figures script 2023-06-09 11:51:55 +02:00
Maxluli 1a8a73a143 Fixed images 2023-06-09 09:33:05 +02:00
Maxluli a7c6ad610c Updated the code to show on the documentation 2023-06-08 14:30:18 +02:00
Maxluli ac5641125a Edited syntax 2023-06-08 14:24:18 +02:00
Maxluli 5e8bd09c5e Added (hopfully) the last things to the doc 2023-06-08 12:20:28 +02:00
Maxluli 1774cfaf49 Added a lot to the Conclusion 2023-06-08 09:22:05 +02:00
Maxluli db162a3829 Too much writing for today 2023-06-07 14:41:49 +02:00
Maxluli 73a5bcf116 Added to the performance tab of the doc 2023-06-07 12:51:59 +02:00
Maxluli 6653eee01c Added technical difficulties to the doc 2023-06-06 15:43:42 +02:00
Maxluli 8a69b42d9b Updated 'différences avec le cahier des charges original' 2023-06-06 14:12:10 +02:00
Maxluli 81a7b12500 Updated some doc 2023-06-06 11:26:18 +02:00
Maxluli a1406091e8 Fixed typos 2023-06-05 16:41:17 +02:00
Maxluli 90c8963369 Added a User Manual 2023-06-05 16:17:17 +02:00
Maxluli 8cb387af33 Eating commit 2023-06-05 11:29:55 +02:00
Maxluli 0cbe2e1346 Started to write the User Manual 2023-06-05 11:08:32 +02:00
Maxluli 718ec17e59 Added photos for the user manual 2023-06-02 14:31:10 +02:00
Maxluli a368e02453 Added a lot to the doc and modified the pdf generation 2023-06-02 13:41:12 +02:00
Maxluli bef8b9d635 fixed all the last big bugs before going to PWA 2023-06-01 14:30:30 +02:00
Maxluli 3f4b82301d Added a lot to the doc and I need to sleep 2023-05-31 14:41:59 +02:00
Maxluli ad618574c4 Added a lot to the main doc 2023-05-31 13:01:59 +02:00
Maxluli 68d2f951e8 End of the day push 2023-05-30 15:57:32 +02:00
Maxluli ddd3e32fe1 Added modifications to the OCR documentation 2023-05-30 13:52:07 +02:00
Maxluli 77c8d71b03 Pushed some modifications I made in the weekend 2023-05-30 08:12:31 +02:00
Maxluli 1524a8aa8f End of the day push 2023-05-25 14:40:10 +02:00
Maxluli cee58a56de End of the day commit 2023-05-24 16:43:36 +02:00
Maxluli 734ffe4f4b End of the day push 2023-05-23 18:04:58 +02:00
Maxluli 431f2ae3d5 Added to the dpc 2023-05-22 16:04:07 +02:00
Maxluli b256921ba4 End of the day push 2023-05-17 16:56:47 +02:00
Maxluli c067db9395 Added to the doc 2023-05-17 15:21:53 +02:00
Maxluli 382b584087 Added to jdb 2023-05-16 13:15:09 +02:00
Maxluli 0ebaeafa98 Pushing yersteday's work 2023-05-16 08:08:07 +02:00
Maxluli c94ceabc6b Added to doc 2023-05-15 11:15:12 +02:00
302 changed files with 87172 additions and 28313 deletions
+1 -1
View File
@@ -30,7 +30,7 @@ Voici les liens Git vers les autres sous projets
[Clean Selenium](https://gitea.parano.ch/Maxluli/Selenium_Clean) [Clean Selenium](https://gitea.parano.ch/Maxluli/Selenium_Clean)
[Test merge](https://gitea.parano.ch/Maxluli/Test_Merge) [Projet Full](https://gitea.parano.ch/Maxluli/TrackTrends)
Faites attention, il faut absolument verifier pour chaque projet leur Readme.md car chaque projet a des prérequis pour être utilisés correctement. Faites attention, il faut absolument verifier pour chaque projet leur Readme.md car chaque projet a des prérequis pour être utilisés correctement.
+96 -28
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 30/05/2023
/// File : ConfigurationTool.cs /// File : ConfigurationTool.cs
/// Brief : Class that contains all the methods needed to create a config file for the OCR /// Brief : Class that contains all the methods used to create config files for the main programm
/// Version : 0.1 /// Version : Alpha 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -12,8 +12,10 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Tesseract; using Tesseract;
using System.IO; using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Test_Merge namespace TrackTrends
{ {
public class ConfigurationTool public class ConfigurationTool
{ {
@@ -21,43 +23,100 @@ namespace Test_Merge
public const int NUMBER_OF_DRIVERS = 20; public const int NUMBER_OF_DRIVERS = 20;
public const int NUMBER_OF_ZONES = 9; public const int NUMBER_OF_ZONES = 9;
public const string CONFIGS_FOLDER_NAME = "./Presets/"; public const string CONFIGS_FOLDER_NAME = "./Presets/";
/// <summary>
/// Creates the configuration tool. It can only be created if you already have the dimensions of the main zone
/// </summary>
/// <param name="fullImage">The full image coming from the F1TV Data Channel</param>
/// <param name="mainZoneDimensions">The dimensions of the zone where all the drivers data are situated</param>
public ConfigurationTool(Bitmap fullImage, Rectangle mainZoneDimensions) public ConfigurationTool(Bitmap fullImage, Rectangle mainZoneDimensions)
{ {
MainZone = new Zone(fullImage, mainZoneDimensions,"Main"); MainZone = new Zone(fullImage, mainZoneDimensions,"Main");
AutoCalibrate(); AutoCalibrate();
} }
/// <summary>
/// Resets the main zone
/// </summary>
public void ResetMainZone() public void ResetMainZone()
{ {
MainZone.ResetZones(); MainZone.ResetZones();
} }
/// <summary>
/// Reset the windows
/// </summary>
public void ResetWindows() public void ResetWindows()
{ {
MainZone.ResetWindows(); MainZone.ResetWindows();
} }
/// <summary>
/// Save the current config in a JSON file stored in /Presets/
/// </summary>
/// <param name="drivers">A list of all the drivers in the GP. IMPORTANT, they need to ALL be mentionned or the program wont be able to detect the missing ones and will F up everything</param>
/// <param name="configName">The name the config should have</param>
public void SaveToJson(List<string> drivers, string configName) public void SaveToJson(List<string> drivers, string configName)
{ {
string JSON = ""; string JSON = "";
JSON += "{" + Environment.NewLine; JsonObject jsonFileObject = new JsonObject();
JSON += MainZone.ToJSON() + "," + Environment.NewLine;
JSON += "\"Drivers\":[" + Environment.NewLine;
for (int i = 0; i < drivers.Count; i++) //Creates the mainZone object
JsonObject mainZoneObject = new JsonObject();
mainZoneObject.Add("x",MainZone.Bounds.X);
mainZoneObject.Add("y",MainZone.Bounds.Y);
mainZoneObject.Add("width",MainZone.Bounds.Width);
mainZoneObject.Add("height",MainZone.Bounds.Height);
JsonArray driverZonesArray = new JsonArray();
//Creates all the subzones that contain driver infos
int DriverID = 0;
foreach (Zone driverZone in MainZone.Zones)
{ {
JSON += "\"" + drivers[i] + "\""; DriverID++;
if (i < drivers.Count - 1) JsonObject driverZoneObject = new JsonObject();
JSON += ","; driverZoneObject.Add("name","Driver"+DriverID);
JSON += Environment.NewLine; driverZoneObject.Add("x", driverZone.Bounds.X);
driverZoneObject.Add("y", driverZone.Bounds.Y);
driverZoneObject.Add("width", driverZone.Bounds.Width);
driverZoneObject.Add("height", driverZone.Bounds.Height);
JsonArray windowsArray = new JsonArray();
JsonObject windowObject = new JsonObject();
//Creates all the windows of the current driver zone
//Note : We store ALL the windows and zones in the JSON because they are not spaced exactly the same on the main zone
foreach (Window window in driverZone.Windows)
{
windowObject.Add(window.Name, new JsonObject {
{ "x", window.Bounds.X },
{ "y", window.Bounds.Y },
{ "width", window.Bounds.Width },
{ "height", window.Bounds.Height }
});
}
windowsArray.Add(windowObject);
driverZoneObject.Add("Windows",windowsArray);
driverZonesArray.Add(driverZoneObject);
} }
JSON += "]" + Environment.NewLine; mainZoneObject.Add("DriverZones",driverZonesArray);
JSON += "}"; JsonArray driversArray = new JsonArray();
if (!Directory.Exists(CONFIGS_FOLDER_NAME)) foreach (string driver in drivers)
Directory.CreateDirectory(CONFIGS_FOLDER_NAME); {
driversArray.Add(driver);
}
mainZoneObject.Add("Drivers",driversArray);
jsonFileObject.Add("Main",mainZoneObject);
JSON = jsonFileObject.ToString();
//Saving the file
string path = CONFIGS_FOLDER_NAME + configName; string path = CONFIGS_FOLDER_NAME + configName;
if (File.Exists(path + ".json")) if (File.Exists(path + ".json"))
@@ -77,6 +136,11 @@ namespace Test_Merge
File.WriteAllText(path, JSON); File.WriteAllText(path, JSON);
} }
/// <summary>
/// Adds a window in the windows list
/// Be carefull of the order. It cant be random or it will crash. The programm expect the first to be position, second Gap to leader etc...
/// </summary>
/// <param name="rectangles">The bounds of the window</param>
public void AddWindows(List<Rectangle> rectangles) public void AddWindows(List<Rectangle> rectangles)
{ {
foreach (Zone driverZone in MainZone.Zones) foreach (Zone driverZone in MainZone.Zones)
@@ -92,41 +156,45 @@ namespace Test_Merge
driverZone.AddWindow(new DriverPositionWindow(driverZone.ZoneImage, rectangles[i - 1], false)); driverZone.AddWindow(new DriverPositionWindow(driverZone.ZoneImage, rectangles[i - 1], false));
break; break;
case 2: case 2:
//First zone should be the Gap to leader //Second zone should be the Gap to leader
driverZone.AddWindow(new DriverGapToLeaderWindow(driverZone.ZoneImage, rectangles[i - 1], false)); driverZone.AddWindow(new DriverGapToLeaderWindow(driverZone.ZoneImage, rectangles[i - 1], false));
break; break;
case 3: case 3:
//First zone should be the driver's Lap Time //Third zone should be the driver's Lap Time
driverZone.AddWindow(new DriverLapTimeWindow(driverZone.ZoneImage, rectangles[i - 1], false)); driverZone.AddWindow(new DriverLapTimeWindow(driverZone.ZoneImage, rectangles[i - 1], false));
break; break;
case 4: case 4:
//First zone should be the driver's DRS status //Fourth zone should be the driver's DRS status
driverZone.AddWindow(new DriverDrsWindow(driverZone.ZoneImage, rectangles[i - 1], false)); driverZone.AddWindow(new DriverDrsWindow(driverZone.ZoneImage, rectangles[i - 1], false));
break; break;
case 5: case 5:
//First zone should be the driver's Tyre's informations //Fifth zone should be the driver's Tyre's informations
driverZone.AddWindow(new DriverTyresWindow(driverZone.ZoneImage, rectangles[i - 1], false)); driverZone.AddWindow(new DriverTyresWindow(driverZone.ZoneImage, rectangles[i - 1], false));
break; break;
case 6: case 6:
//First zone should be the driver's Name //Sixth zone should be the driver's Name
driverZone.AddWindow(new DriverNameWindow(driverZone.ZoneImage, rectangles[i - 1], false)); driverZone.AddWindow(new DriverNameWindow(driverZone.ZoneImage, rectangles[i - 1], false));
break; break;
case 7: case 7:
//First zone should be the driver's First Sector //Seventh zone should be the driver's First Sector
driverZone.AddWindow(new DriverSectorWindow(driverZone.ZoneImage, rectangles[i - 1], 1, false)); driverZone.AddWindow(new DriverSectorWindow(driverZone.ZoneImage, rectangles[i - 1], 1, false));
break; break;
case 8: case 8:
//First zone should be the driver's Second Sector //Zone number eight should be the driver's Second Sector
driverZone.AddWindow(new DriverSectorWindow(driverZone.ZoneImage, rectangles[i - 1], 2, false)); driverZone.AddWindow(new DriverSectorWindow(driverZone.ZoneImage, rectangles[i - 1], 2, false));
break; break;
case 9: case 9:
//First zone should be the driver's Position Sector //Zone number nine should be the driver's Position Sector
driverZone.AddWindow(new DriverSectorWindow(driverZone.ZoneImage, rectangles[i - 1], 3, false)); driverZone.AddWindow(new DriverSectorWindow(driverZone.ZoneImage, rectangles[i - 1], 3, false));
break; break;
} }
} }
} }
} }
/// <summary>
/// This will automatically create all the driver zones at the correct places if the main zone has been weel positionned
/// You cant just divide the image by the number of pilots or it will be messy and inconsistent at the end (Garbage in Garbage Out)
/// </summary>
public void AutoCalibrate() public void AutoCalibrate()
{ {
List<Rectangle> detectedText = new List<Rectangle>(); List<Rectangle> detectedText = new List<Rectangle>();
@@ -137,6 +205,8 @@ namespace Test_Merge
var tessImage = Pix.LoadFromMemory(Window.ImageToByte(image)); var tessImage = Pix.LoadFromMemory(Window.ImageToByte(image));
Page page = engine.Process(tessImage); Page page = engine.Process(tessImage);
//Runs a quick OCR detection. Not to detect any content but just to detect where is all the text positionned.
//For each row it decides the best Zone location and adds it to the Driver zone list
using (var iter = page.GetIterator()) using (var iter = page.GetIterator())
{ {
iter.Begin(); iter.Begin();
@@ -145,7 +215,6 @@ namespace Test_Merge
Rect boundingBox; Rect boundingBox;
if (iter.TryGetBoundingBox(PageIteratorLevel.Word, out boundingBox)) if (iter.TryGetBoundingBox(PageIteratorLevel.Word, out boundingBox))
{ {
//var text = iter.GetText(PageIteratorLevel.Word).ToUpper();
//We remove all the rectangles that are definitely too big //We remove all the rectangles that are definitely too big
if (boundingBox.Height < image.Height / NUMBER_OF_DRIVERS) if (boundingBox.Height < image.Height / NUMBER_OF_DRIVERS)
{ {
@@ -184,8 +253,7 @@ namespace Test_Merge
//We add the driver zones //We add the driver zones
Zone driverZone = new Zone(MainZone.ZoneImage, windowRectangle, "DriverZone"); Zone driverZone = new Zone(MainZone.ZoneImage, windowRectangle, "DriverZone");
MainZone.AddZone(driverZone); MainZone.AddZone(driverZone);
//driverZone.ZoneImage.Save("Driver" + i+".png");
driverZone.ZoneImage.Save("Driver" + i+".png");
i++; i++;
} }
} }
+379
View File
@@ -0,0 +1,379 @@
/// Author : Maxime Rohmer
/// Date : 09/06/2023
/// File : DataWrapper.cs
/// Brief : Class that is used to interface between the main Form (vue) and the Storage (wich is a class that wraps the sqlite database, so the model) its almost MVC :D
/// Version : Beta 1.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace TrackTrends
{
internal class DataWrapper
{
private Reader Reader;
private SqliteStorage Storage;
List<List<DriverData>> LiveDriverDataLogs = new List<List<DriverData>>();
//Note : It could be usefull to get the mainForm at the start of the programm and not have to take it in half of the methods.
/// <summary>
/// Constructs a new DataWrapper. It needs the config file so it can create a Reader, It also needs a first screenshot for the same reason
/// </summary>
/// <param name="configFile">The JSON config file that is created by the configuration tool</param>
/// <param name="screenshot">A screenshot of the </param>
public DataWrapper(string configFile, Bitmap screenshot)
{
Reader = new Reader(configFile, screenshot, true);
//The Storage is here and on the Reader. It seems bad but it is ok as we dont use it at all to insert data and are only using it here to read some. The reader takes care of the inserts (Note: We could technically do both here but I did not find it usefull to transfer everything here)
Storage = Reader.Storage;
}
/// <summary>
/// Refreshes the controller so it has the latest driver datas (Be sure to call it everytime you need to use any other method and expects the data to be up to date)
/// </summary>
/// <returns>Error code, 0 is success, 1 is not (Note: Maybe it could be interesting in the future to add some more error handling here)</returns>
public int Refresh()
{
LiveDriverDataLogs.Add(Reader.Decode(Reader.MainZones, Reader.Drivers));
if (LiveDriverDataLogs.Count > 0)
return 0;
return 1;
}
/// <summary>
/// Changes the image to the newest screenshot in all of the zones and windows
/// </summary>
/// <param name="image">The new screenshot to put everywhere (Do not mix resolutions)</param>
public void ChangeImage(Bitmap image)
{
Reader.ChangeImage(image);
}
/// <summary>
/// Gets all the data from one driver and also displays into the given panel the last five laps (or less if its the sart of the race) Note: Its responsive :D
/// </summary>
/// <param name="driverName">The name of the driver (should not be case sensitive but it MUST already exist in the first list that has been inserted into the DB)</param>
/// <param name="lastFiveLapsPanel">The pannel where you want the five last laps to be displayed</param>
/// <param name="form1">The Main form.</param>
/// <returns></returns>
public DriverData GetFullDriverData(string driverName, Panel lastFiveLapsPanel, Main form1)
{
//Note : I know that its a bad idea to ask the Form in this method and some others because it means that it wont work with any main form. And to that Ill say that... your right !
DriverData result = new DriverData();
if (LiveDriverDataLogs.Count > 0)
{
//Searches the most recent live data from the given driverName
foreach (DriverData data in LiveDriverDataLogs[LiveDriverDataLogs.Count - 1])
{
if (data.Name == driverName)
result = data;
}
if (result.Name != "")
{
//Recovers and displays the last five laps from the driver
lastFiveLapsPanel.Controls.Clear();
Size labelDimensions = new Size(lastFiveLapsPanel.Width, lastFiveLapsPanel.Height / 5);
List<(int LapTime, int Lap)> lapsInfos = Storage.GetDriverLaptimes(driverName, 5);
int id = 0;
foreach ((int LapTime, int Lap) lapData in lapsInfos)
{
//Hardcodes the new button.
//Note : It could be smart to have like a default button for all the methods to use without needing to rewrite everything.
Button newButton = new Button();
lastFiveLapsPanel.Controls.Add(newButton);
newButton.Name = driverName + "_" + lapData.Lap;
newButton.Text = Reader.ConvertMsToTime(lapData.LapTime);
newButton.Size = labelDimensions;
newButton.FlatStyle = FlatStyle.Popup;
newButton.Click += form1.btnLapTime_Click;
newButton.Location = new Point(0, id * newButton.Height);
id++;
}
}
}
return result;
}
/// <summary>
/// Runs trough every drivers live data to recover the drivers that are close to each others
/// </summary>
/// <param name="pnlBattles">The control that will host the displayed battles</param>
/// <param name="form1">The main form. It needs to have a method called 'btnDriver_Click' so it can reads the buttons clicks</param>
public void DisplayBattles(Panel pnlBattles,Main form1)
{
DriverData oldDriver = null;
List<(DriverData d1, DriverData d2, int gap)> battles = new List<(DriverData d1, DriverData d2, int gap)>();
//Search trough all the drivers and finds the one battling
foreach (DriverData driver in LiveDriverDataLogs[LiveDriverDataLogs.Count - 1])
{
if (oldDriver != null && driver.Position != -1 && oldDriver.Position != -1)
{
if (driver.GapToLeader < oldDriver.GapToLeader)
{
//There is a problem with the drivers gaps
}
else
{
int gap = driver.GapToLeader - oldDriver.GapToLeader;
//3000ms is 3s. If drivers are that close then they are definitely in battle. If they are farther then maybe not
if (gap <= 3000)
{
battles.Add((oldDriver, driver, gap));
}
}
oldDriver = driver;
}
else
{
oldDriver = driver;
}
}
//We will only display 4 battles max
int maxBattles = 4;
if (battles.Count > 0)
{
pnlBattles.Controls.Clear();
int maxUiHeight = Math.Max(pnlBattles.Height / maxBattles, pnlBattles.Height / battles.Count);
int id = 0;
foreach ((DriverData d1, DriverData d2, int gap) battle in battles)
{
if(id < maxBattles)
{
//*hardcoding* the different controls that needs to be added to the panel.
//Note : this stuff could totally be handled by the Form with method returning a list of the drivers. It was just easier for me at the time to code it this way but its not the prettiest
Button btnFirstDriver = new Button();
Button btnSecondDriver = new Button();
Label lblGap = new Label();
pnlBattles.Controls.Add(btnFirstDriver);
pnlBattles.Controls.Add(lblGap);
pnlBattles.Controls.Add(btnSecondDriver);
btnFirstDriver.Anchor = AnchorStyles.Left | AnchorStyles.Top;
btnSecondDriver.Anchor = AnchorStyles.Right | AnchorStyles.Top;
lblGap.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
lblGap.TextAlign = ContentAlignment.MiddleCenter;
lblGap.Font = new Font(lblGap.Font.FontFamily, 15);
btnFirstDriver.Click += form1.btnDriver_Click;
btnSecondDriver.Click += form1.btnDriver_Click;
btnFirstDriver.FlatStyle = FlatStyle.Popup;
btnSecondDriver.FlatStyle = FlatStyle.Popup;
lblGap.FlatStyle = FlatStyle.Popup;
btnFirstDriver.Size = new Size(pnlBattles.Width / 3, maxUiHeight);
btnSecondDriver.Size = new Size(pnlBattles.Width / 3, maxUiHeight);
lblGap.Size = new Size(pnlBattles.Width / 3, maxUiHeight);
btnFirstDriver.Location = new Point(pnlBattles.Width / 3 * 0, id * maxUiHeight);
lblGap.Location = new Point(pnlBattles.Width / 3 * 1, id * maxUiHeight);
btnSecondDriver.Location = new Point(pnlBattles.Width / 3 * 2, id * maxUiHeight);
btnFirstDriver.Text = battle.d1.Name;
lblGap.Text = "+ " + Reader.ConvertMsToTime(battle.gap);
if (battle.gap <= 2000)
lblGap.ForeColor = Color.Yellow;
if (battle.gap <= 1000)
lblGap.ForeColor = Color.Green;
btnSecondDriver.Text = battle.d2.Name;
btnFirstDriver.Name = battle.d1.Name + "_" + id;
lblGap.Name = "lbl_Gap_" + id;
btnSecondDriver.Name = battle.d2.Name + "_" + id;
}
else
{
break;
}
id++;
}
}
}
/// <summary>
/// Searches the fastest and slowests drivers and displays them in the given panels
/// </summary>
/// <param name="pnlFastest">Panel that will contain the constructed controls</param>
/// <param name="pnlSlowest">Panel that will contain the constructed controls</param>
/// <param name="form1">The main form that needs to implement the method btnDriver_Click to allow it to recover custom buttons click</param>
public void DisplayTimesDeltas(Panel pnlFastest,Panel pnlSlowest, Main form1)
{
List<(int avg, string driverName)> averages = new List<(int avg, string driverName)>();
foreach (DriverData driver in LiveDriverDataLogs[LiveDriverDataLogs.Count - 1])
{
//We want to recover the last 5 lap times
List<(int lapTime,int lap)> laps = Storage.GetDriverLaptimes(driver.Name,5);
if(laps.Count > 0)
{
int avg = 0;
foreach ((int lapTime, int lap) lap in laps)
{
avg += lap.lapTime;
}
avg = avg / laps.Count;
averages.Add((avg, driver.Name));
}
}
int numberOfDriversToShow = 5;
if (averages.Count > 0 && averages.Count > numberOfDriversToShow)
{
averages = averages.OrderBy(item => item.avg).ToList();
pnlFastest.Controls.Clear();
pnlSlowest.Controls.Clear();
int maxUiSize = pnlFastest.Height / numberOfDriversToShow;
//Displays the fastest drivers
for (int i = 0; i < numberOfDriversToShow; i++)
{
Button newButton = new Button();
(int avg, string driver) data = averages[i];
pnlFastest.Controls.Add(newButton);
newButton.Size = new Size(pnlFastest.Width, maxUiSize);
newButton.Location = new Point(0, i * maxUiSize);
newButton.Text = data.driver;
newButton.FlatStyle = FlatStyle.Popup;
newButton.Name = data.driver + "_fastest_" + i;
newButton.Click += form1.btnDriver_Click;
//We take the average time lost per lap
if (i != 0)
newButton.Text += " + " + Reader.ConvertMsToTime(Convert.ToInt32(((float)data.avg - (float)averages[0].avg) / 5.0f));
}
//Displays the slowests drivers
int badId = 0;
for (int i = averages.Count -1; i >= averages.Count - numberOfDriversToShow; i--)
{
Button newButton = new Button();
(int avg, string driver) data = averages[i];
pnlSlowest.Controls.Add(newButton);
newButton.Size = new Size(pnlFastest.Width, maxUiSize);
newButton.Location = new Point(0, badId * maxUiSize);
newButton.Text = data.driver;
newButton.FlatStyle = FlatStyle.Popup;
newButton.Name = data.driver + "_slowest_" + i;
newButton.Click += form1.btnDriver_Click;
//We take the average time lost per lap
newButton.Text += " + " + Reader.ConvertMsToTime(Convert.ToInt32(((float)data.avg - (float)averages[0].avg) / 5.0f));
badId++;
}
}
}
/// <summary>
/// Will add to the list of overtakes the different changes of position
/// </summary>
/// <param name="lsbResult">The listbox containing all the infos</param>
public void DisplayOvertakes(ListBox lsbResult)
{
//Note : This method SHOULD REALLY not do this but just return a string or a list of string with the new overtakes so the form can handle it as it wishes
if (LiveDriverDataLogs.Count > 1)
{
List<DriverData> oldList = LiveDriverDataLogs[LiveDriverDataLogs.Count - 2];
List<DriverData> newList = LiveDriverDataLogs[LiveDriverDataLogs.Count - 1];
for (int i = 0; i < LiveDriverDataLogs[LiveDriverDataLogs.Count - 1].Count;i++)
{
if (oldList[i].Name != newList[i].Name) {
//There has been a change in the standings
for(int y = 0; y < oldList.Count;y++)
{
if (newList[y].Name == oldList[i].Name)
{
//We found its new location
if (y > i)
{
//The driver overtook someone
lsbResult.Items.Add(newList[y].Name + " climbed to " + y);
}
else
{
//The driver got overtook by someone
lsbResult.Items.Add(newList[y].Name + " fell to " + y);
}
}
}
}
}
}
}
/// <summary>
/// Displays a messageBox containing the infos about a lap time
/// </summary>
/// <param name="driverName">The name of the driver that has done the lapTime</param>
/// <param name="Lap">The number of the lap on wich the lapTime has been set (CAUTION ITS NOT THE RACING LAP ITS FROM THE DB)</param>
/// <param name="LapTime">The time (in ms) of the lap</param>
public void DisplayLapTimeInfos(string driverName, int Lap, string LapTime)
{
List<int> sectors = Storage.GetSectorsFromLapTime(driverName, Lap);
string message = "Lap time infos" + Environment.NewLine;
message += LapTime + Environment.NewLine;
if (sectors.Count > 0)
message += "Sector 1 : " + Reader.ConvertMsToTime(sectors[0]) + Environment.NewLine;
if (sectors.Count > 1)
message += "Sector 2 : " + Reader.ConvertMsToTime(sectors[1]) + Environment.NewLine;
if (sectors.Count > 2)
message += "Sector 3 : " + Reader.ConvertMsToTime(sectors[2]) + Environment.NewLine;
MessageBox.Show(message);
}
/// <summary>
/// Displays the live ranking with the names of the drivers and their gap to the leader in the right order
/// </summary>
/// <param name="pnl">The control that will host all the new controls</param>
/// <param name="form1">The main form</param>
public void DisplayLiveRanking(Panel pnl, Main form1)
{
if (LiveDriverDataLogs.Count > 0)
{
pnl.Controls.Clear();
//Gets the last item that should be the most recent data
List<DriverData> liveData = LiveDriverDataLogs[LiveDriverDataLogs.Count - 1];
Button[] buttons = new Button[liveData.Count];
Size buttonDimensions = new Size(pnl.Width, pnl.Height / liveData.Count);
for (int driverCount = 0; driverCount < liveData.Count; driverCount++)
{
Button newButton = new Button();
newButton.Size = buttonDimensions;
newButton.Location = new Point(0, driverCount * buttonDimensions.Height);
newButton.FlatStyle = FlatStyle.Popup;
DriverData driver = liveData[driverCount];
if (driver.Position == -1)
{
//Its a DNF
newButton.Enabled = false;
}
if (driver.Position > 1)
{
newButton.Text = driver.Name + " +" + Reader.ConvertMsToTime(driver.GapToLeader);
}
else
{
newButton.Text = driver.Name;
}
newButton.Name = liveData[driverCount].Name;
newButton.TextAlign = ContentAlignment.MiddleLeft;
newButton.FlatStyle = FlatStyle.Popup;
newButton.Click += form1.btnDriver_Click;
buttons[driverCount] = newButton;
}
//Note : It could be better to have this directly in the same loop
foreach (Button button in buttons)
{
pnl.Controls.Add(button);
}
}
}
}
}
+7 -4
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverData.cs /// File : DriverData.cs
/// Brief : Class used to store Driver informations /// Brief : File containing classes that behave just like structures to store data about drivers
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -10,7 +10,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Test_Merge namespace TrackTrends
{ {
public class DriverData public class DriverData
{ {
@@ -36,6 +36,9 @@ namespace Test_Merge
Sector3 = sector3; Sector3 = sector3;
CurrentTyre = tyre; CurrentTyre = tyre;
} }
/// <summary>
/// Creates a default driver data with empty values
/// </summary>
public DriverData() public DriverData()
{ {
DRS = false; DRS = false;
+21 -5
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverDrsWindow.cs /// File : DriverDrsWindow.cs
/// Brief : Window containing DRS related method and infos /// Brief : Window containing DRS related method and infos
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -13,9 +13,9 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Tesseract; using Tesseract;
namespace Test_Merge namespace TrackTrends
{ {
internal class DriverDrsWindow:Window public class DriverDrsWindow:Window
{ {
private static int EmptyDrsGreenValue = -1; private static int EmptyDrsGreenValue = -1;
private static Random rnd = new Random(); private static Random rnd = new Random();
@@ -23,9 +23,17 @@ namespace Test_Merge
{ {
Name = "DRS"; Name = "DRS";
} }
public override async Task<object> DecodePng() /// <summary>
/// Method that will decode the content of the window
/// </summary>
/// <returns>returns a boolean (true = DRS OPEN, false = DRS CLOSED)</returns>
public override object DecodePng()
{ {
bool result = false; bool result = false;
//DEBUG
//WindowImage.Save("./DRS/"+rnd.Next(0,99999)+".png");
int greenValue = GetGreenPixels(); int greenValue = GetGreenPixels();
if (EmptyDrsGreenValue == -1) if (EmptyDrsGreenValue == -1)
EmptyDrsGreenValue = greenValue; EmptyDrsGreenValue = greenValue;
@@ -35,6 +43,10 @@ namespace Test_Merge
return result; return result;
} }
/// <summary>
/// Method that will get the green pixel proportion in the image, this can be used to determin if the DRS has been actuated
/// </summary>
/// <returns>The number of clearely green pixels</returns>
private unsafe int GetGreenPixels() private unsafe int GetGreenPixels()
{ {
int tot = 0; int tot = 0;
@@ -69,6 +81,10 @@ namespace Test_Merge
return tot; return tot;
} }
/// <summary>
/// This method is used to lock on where exactly the DRS window is
/// </summary>
/// <returns>Returns a rectangle containing the DRS</returns>
public Rectangle GetBox() public Rectangle GetBox()
{ {
var tessImage = Pix.LoadFromMemory(ImageToByte(WindowImage)); var tessImage = Pix.LoadFromMemory(ImageToByte(WindowImage));
+7 -7
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 30/05/2023
/// File : DriverGapToLeaderWindow.cs /// File : DriverGapToLeaderWindow.cs
/// Brief : Window containing infos about the gap to the leader of a driver /// Brief : Window containing infos about the gap to the leader of a driver
/// Version : 0.1 /// Version : Alpha 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,9 +11,9 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Test_Merge namespace TrackTrends
{ {
internal class DriverGapToLeaderWindow:Window public class DriverGapToLeaderWindow:Window
{ {
public DriverGapToLeaderWindow(Bitmap image, Rectangle bounds, bool generateEngine = true) : base(image, bounds,generateEngine) public DriverGapToLeaderWindow(Bitmap image, Rectangle bounds, bool generateEngine = true) : base(image, bounds,generateEngine)
{ {
@@ -22,10 +22,10 @@ namespace Test_Merge
/// <summary> /// <summary>
/// Decodes the gap to leader using Tesseract OCR /// Decodes the gap to leader using Tesseract OCR
/// </summary> /// </summary>
/// <returns></returns> /// <returns>Returns the gap to the leader in miliseconds (int)</returns>
public override async Task<object> DecodePng() public override object DecodePng()
{ {
int result = await GetTimeFromPng(WindowImage, OcrImage.WindowType.Gap, Engine); int result = GetTimeFromPng(WindowImage, OcrImage.WindowType.Gap, Engine);
return result; return result;
} }
} }
+6 -6
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverLapTimeWindow /// File : DriverLapTimeWindow
/// Brief : Window containing infos about the lap time of a driver /// Brief : Window containing infos about the lap time of a driver
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,9 +11,9 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Drawing; using System.Drawing;
namespace Test_Merge namespace TrackTrends
{ {
internal class DriverLapTimeWindow:Window public class DriverLapTimeWindow:Window
{ {
public DriverLapTimeWindow(Bitmap image, Rectangle bounds, bool generateEngine = true) : base(image, bounds,generateEngine) public DriverLapTimeWindow(Bitmap image, Rectangle bounds, bool generateEngine = true) : base(image, bounds,generateEngine)
{ {
@@ -23,9 +23,9 @@ namespace Test_Merge
/// Decodes the lap time contained in the image using OCR Tesseract /// Decodes the lap time contained in the image using OCR Tesseract
/// </summary> /// </summary>
/// <returns>The laptime in int (ms)</returns> /// <returns>The laptime in int (ms)</returns>
public override async Task<object> DecodePng() public override object DecodePng()
{ {
int result = await GetTimeFromPng(WindowImage, OcrImage.WindowType.LapTime, Engine); int result = GetTimeFromPng(WindowImage, OcrImage.WindowType.LapTime, Engine);
return result; return result;
} }
} }
+9 -10
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverNameWindow /// File : DriverNameWindow
/// Brief : Window containing infos about the name of the driver /// Brief : Window containing infos about the name of the driver
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,11 +11,10 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Drawing; using System.Drawing;
namespace Test_Merge namespace TrackTrends
{ {
public class DriverNameWindow : Window public class DriverNameWindow : Window
{ {
public static Random rnd = new Random();
public DriverNameWindow(Bitmap image, Rectangle bounds, bool generateEngine = true) : base(image, bounds,generateEngine) public DriverNameWindow(Bitmap image, Rectangle bounds, bool generateEngine = true) : base(image, bounds,generateEngine)
{ {
Name = "Name"; Name = "Name";
@@ -23,12 +22,12 @@ namespace Test_Merge
/// <summary> /// <summary>
/// Decodes using OCR wich driver name is in the image /// Decodes using OCR wich driver name is in the image
/// </summary> /// </summary>
/// <param name="DriverList"></param> /// <param name="DriverList">A list of all the names that can be on the image</param>
/// <returns>The driver name in string</returns> /// <returns>a string representing the found driver name. It will be one of the ones given in the list</returns>
public override async Task<object> DecodePng(List<string> DriverList) public override object DecodePng(List<string> DriverList)
{ {
string result = ""; string result = "";
result = await GetStringFromPng(WindowImage, Engine); result = GetStringFromPng(WindowImage, Engine);
if (!IsADriver(DriverList, result)) if (!IsADriver(DriverList, result))
{ {
@@ -40,8 +39,8 @@ namespace Test_Merge
/// <summary> /// <summary>
/// Verifies that the name found in the OCR is a valid name /// Verifies that the name found in the OCR is a valid name
/// </summary> /// </summary>
/// <param name="driverList"></param> /// <param name="driverList">The list of all the drivers name that can be found in the image</param>
/// <param name="potentialDriver"></param> /// <param name="potentialDriver">The driver you want to be sure if it exists or not</param>
/// <returns>If ye or no the driver exists</returns> /// <returns>If ye or no the driver exists</returns>
private static bool IsADriver(List<string> driverList, string potentialDriver) private static bool IsADriver(List<string> driverList, string potentialDriver)
{ {
+7 -7
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverPosition.cs /// File : DriverPositionWindow.cs
/// Brief : Window containing infos about the position of a driver. /// Brief : Window containing infos about the position of a driver.
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,7 +11,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Drawing; using System.Drawing;
namespace Test_Merge namespace TrackTrends
{ {
public class DriverPositionWindow:Window public class DriverPositionWindow:Window
{ {
@@ -22,10 +22,10 @@ namespace Test_Merge
/// <summary> /// <summary>
/// Decodes the position number using Tesseract OCR /// Decodes the position number using Tesseract OCR
/// </summary> /// </summary>
/// <returns>The position of the pilot in int</returns> /// <returns>An int representing the position of the driver (should be between 1 and 20 included)</returns>
public override async Task<object> DecodePng() public override object DecodePng()
{ {
string ocrResult = await GetStringFromPng(WindowImage, Engine, "0123456789"); string ocrResult = GetStringFromPng(WindowImage, Engine, "0123456789");
int position; int position;
try try
+6 -6
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverSectorWindow.cs /// File : DriverSectorWindow.cs
/// Brief : Window containing infos about a driver sector time. Can be the first second or third, does not matter. /// Brief : Window containing infos about a driver sector time. Can be the first second or third, does not matter.
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,9 +11,9 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Drawing; using System.Drawing;
namespace Test_Merge namespace TrackTrends
{ {
internal class DriverSectorWindow:Window public class DriverSectorWindow:Window
{ {
public DriverSectorWindow(Bitmap image, Rectangle bounds, int sectorId, bool generateEngine = true) : base(image, bounds,generateEngine) public DriverSectorWindow(Bitmap image, Rectangle bounds, int sectorId, bool generateEngine = true) : base(image, bounds,generateEngine)
{ {
@@ -23,9 +23,9 @@ namespace Test_Merge
/// Decodes the sector /// Decodes the sector
/// </summary> /// </summary>
/// <returns>the sector time in int (ms)</returns> /// <returns>the sector time in int (ms)</returns>
public override async Task<object> DecodePng() public override object DecodePng()
{ {
int ocrResult = await GetTimeFromPng(WindowImage, OcrImage.WindowType.Sector, Engine); int ocrResult = GetTimeFromPng(WindowImage, OcrImage.WindowType.Sector, Engine);
return ocrResult; return ocrResult;
} }
} }
+16 -11
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : DriverTyresWindow.cs /// File : DriverTyresWindow.cs
/// Brief : Window containing infos about a driver's tyre /// Brief : Window containing infos about a driver's tyre
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,13 +11,11 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Drawing; using System.Drawing;
namespace Test_Merge namespace TrackTrends
{ {
public class DriverTyresWindow:Window public class DriverTyresWindow:Window
{ {
private static Random rnd = new Random(); private static Random rnd = new Random();
int seed = rnd.Next(0, 10000);
//Those are the colors I found but you can change them if they change in the future like in 2019 //Those are the colors I found but you can change them if they change in the future like in 2019
public static Color SOFT_TYRE_COLOR = Color.FromArgb(0xff, 0x00, 0x00); public static Color SOFT_TYRE_COLOR = Color.FromArgb(0xff, 0x00, 0x00);
public static Color MEDIUM_TYRE_COLOR = Color.FromArgb(0xf5, 0xbf, 0x00); public static Color MEDIUM_TYRE_COLOR = Color.FromArgb(0xf5, 0xbf, 0x00);
@@ -34,22 +32,25 @@ namespace Test_Merge
/// This will decode the content of the image /// This will decode the content of the image
/// </summary> /// </summary>
/// <returns>And object containing what was on the image</returns> /// <returns>And object containing what was on the image</returns>
public override async Task<object> DecodePng() public override object DecodePng()
{ {
return await GetTyreInfos(); return GetTyreInfos();
} }
/// <summary> /// <summary>
/// Method that will decode whats on the image and return the tyre infos it could manage to recover /// Method that will decode whats on the image and return the tyre infos it could manage to recover
/// </summary> /// </summary>
/// <returns>A tyre object containing tyre infos</returns> /// <returns>A tyre object containing tyre infos</returns>
private async Task<Tyre> GetTyreInfos() private Tyre GetTyreInfos()
{ {
//DEBUG
//WindowImage.Save("./Tyre/raw_"+rnd.Next(0,99999)+".png");
Bitmap tyreZone = GetSmallBitmapFromBigOne(WindowImage, FindTyreZone()); Bitmap tyreZone = GetSmallBitmapFromBigOne(WindowImage, FindTyreZone());
Tyre.Type type = Tyre.Type.Undefined; Tyre.Type type = Tyre.Type.Undefined;
type = GetTyreTypeFromColor(OcrImage.GetAvgColorFromBitmap(tyreZone)); type = GetTyreTypeFromColor(OcrImage.GetAvgColorFromBitmap(tyreZone));
int laps = -1; int laps = -1;
string number = await GetStringFromPng(tyreZone, Engine, "0123456789", OcrImage.WindowType.Tyre); string number = GetStringFromPng(tyreZone, Engine, "0123456789", OcrImage.WindowType.Tyre);
try try
{ {
laps = Convert.ToInt32(number); laps = Convert.ToInt32(number);
@@ -59,7 +60,11 @@ namespace Test_Merge
//We could not convert the number so its a letter so its 0 laps old //We could not convert the number so its a letter so its 0 laps old
laps = 0; laps = 0;
} }
//tyreZone.Save(Reader.DEBUG_DUMP_FOLDER + "Tyre" + type + "Laps" + laps + '#' + rnd.Next(0, 1000) + ".png");
//71 is the most laps an f1 race is ever going to have (mexico) so any more would be considered as bad (and remember you cant go trough a full race without making at least one pitstop)
if (laps > 75)
laps = 0;
return new Tyre(type, laps); return new Tyre(type, laps);
} }
/// <summary> /// <summary>
@@ -73,7 +78,7 @@ namespace Test_Merge
int height = bmp.Height / 2; int height = bmp.Height / 2;
Color limitColor = Color.FromArgb(0x50, 0x50, 0x50); Color limitColor = Color.FromArgb(0x50, 0x50, 0x50);
Color currentColor = Color.FromArgb(0, 0, 0); Color currentColor = Color.FromArgb(0, 0, 0);
//25F
Size newWindowSize = new Size(bmp.Height - Convert.ToInt32((float)bmp.Height / 100f * 25f), bmp.Height - Convert.ToInt32((float)bmp.Height / 100f * 35f)); Size newWindowSize = new Size(bmp.Height - Convert.ToInt32((float)bmp.Height / 100f * 25f), bmp.Height - Convert.ToInt32((float)bmp.Height / 100f * 35f));
while (currentColor.R <= limitColor.R && currentColor.G <= limitColor.G && currentColor.B <= limitColor.B && currentPosition > 0) while (currentColor.R <= limitColor.R && currentColor.G <= limitColor.G && currentColor.B <= limitColor.B && currentPosition > 0)
+96 -43
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : F1TVEmulator.cs /// File : F1TVEmulator.cs
/// Brief : Class that contains methods to emulate a browser and navigate the F1TV website /// Brief : Class that contains methods to emulate a browser and navigate the F1TV website
/// Version : 0.1 /// Version : Beta 1.0
using OpenQA.Selenium; using OpenQA.Selenium;
using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Firefox;
@@ -18,7 +18,7 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Test_Merge namespace TrackTrends
{ {
internal class F1TVEmulator internal class F1TVEmulator
{ {
@@ -39,6 +39,9 @@ namespace Test_Merge
GrandPrixUrl = grandPrixUrl; GrandPrixUrl = grandPrixUrl;
Ready = false; Ready = false;
} }
/// <summary>
/// Will start the python programm that runs the Cookie Recovering
/// </summary>
private void StartCookieRecovering() private void StartCookieRecovering()
{ {
string scriptPath = PYTHON_COOKIE_RETRIEVAL_FILENAME; string scriptPath = PYTHON_COOKIE_RETRIEVAL_FILENAME;
@@ -51,43 +54,56 @@ namespace Test_Merge
string output = process.StandardOutput.ReadToEnd(); string output = process.StandardOutput.ReadToEnd();
process.WaitForExit(); process.WaitForExit();
} }
/// <summary>
/// Method that will recover the needed cookies in the DB
/// </summary>
/// <param name="host"> The host of the wanted cookie ex: ./formula1.com</param>
/// <param name="name">The name of the wanted cookie ex: login</param>
/// <returns>returns the value of the cookie if it has been found</returns>
/// <exception cref="InvalidOperationException"></exception>
public string GetCookie(string host, string name) public string GetCookie(string host, string name)
{ {
StartCookieRecovering(); StartCookieRecovering();
string value = ""; string value = "";
List<Cookie> cookies = new List<Cookie>(); List<Cookie> cookies = new List<Cookie>();
using (var reader = new StreamReader(COOKIES_CSV_FILENAME)) if (File.Exists(COOKIES_CSV_FILENAME))
{ {
// Read the header row and validate column order using (var reader = new StreamReader(COOKIES_CSV_FILENAME))
string header = reader.ReadLine();
string[] expectedColumns = { "host_key", "name", "value", "path", "expires_utc", "is_secure", "is_httponly" };
string[] actualColumns = header.Split(',');
for (int i = 0; i < expectedColumns.Length; i++)
{ {
if (expectedColumns[i] != actualColumns[i]) // Read the header row and validate column order
string header = reader.ReadLine();
string[] expectedColumns = { "host_key", "name", "value", "path", "expires_utc", "is_secure", "is_httponly" };
string[] actualColumns = header.Split(',');
for (int i = 0; i < expectedColumns.Length; i++)
{ {
throw new InvalidOperationException($"Expected column '{expectedColumns[i]}' at index {i} but found '{actualColumns[i]}'"); if (expectedColumns[i] != actualColumns[i])
{
throw new InvalidOperationException($"Expected column '{expectedColumns[i]}' at index {i} but found '{actualColumns[i]}'");
}
} }
}
// Read each data row and parse values into a Cookie object // Read each data row and parse values into a Cookie object
while (!reader.EndOfStream) while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] fields = line.Split(',');
string hostname = fields[0];
string cookieName = fields[1];
if (hostname == host && cookieName == name)
{ {
value = fields[2]; string line = reader.ReadLine();
string[] fields = line.Split(',');
string hostname = fields[0];
string cookieName = fields[1];
if (hostname == host && cookieName == name)
{
value = fields[2];
}
} }
} }
} }
return value; return value;
} }
/// <summary>
/// Starts the headless browser
/// </summary>
/// <returns>Error code 1xx</returns>
public async Task<int> Start() public async Task<int> Start()
{ {
Ready = false; Ready = false;
@@ -97,8 +113,9 @@ namespace Test_Merge
string loginCookieValue = GetCookie(COOKIE_HOST, loginCookieName); string loginCookieValue = GetCookie(COOKIE_HOST, loginCookieName);
string loginSessionValue = GetCookie(COOKIE_HOST, loginSessionCookieName); string loginSessionValue = GetCookie(COOKIE_HOST, loginSessionCookieName);
int windowWidth = 1920; //Cookie retreival has gone wrong (usually its because of python not being installed properly)
int windowHeight = 768; if (loginCookieValue == "" || loginSessionValue == "")
return 100;
var service = FirefoxDriverService.CreateDefaultService(GECKODRIVER_FILENAME); var service = FirefoxDriverService.CreateDefaultService(GECKODRIVER_FILENAME);
service.Host = "127.0.0.1"; service.Host = "127.0.0.1";
@@ -170,6 +187,18 @@ namespace Test_Merge
return 104; return 104;
} }
try
{
IWebElement LiveButton = Driver.FindElement(By.ClassName("btn-manage-account"));
//By.ClassName("btn btn-controls btn-main btn-manage-account no-redirect")
LiveButton.Click();
}
catch
{
Console.Write("Going for a rediff");
}
//Again waits for the page to fully load (when you accept cookies it takes a little time for the page to load) //Again waits for the page to fully load (when you accept cookies it takes a little time for the page to load)
//Cannot use The timeout because the feed loading is not really loading so there is not event or anything //Cannot use The timeout because the feed loading is not really loading so there is not event or anything
Thread.Sleep(5000); Thread.Sleep(5000);
@@ -194,9 +223,9 @@ namespace Test_Merge
actions.SendKeys(OpenQA.Selenium.Keys.Space).Perform(); actions.SendKeys(OpenQA.Selenium.Keys.Space).Perform();
//Clicks on the settings Icon //Clicks on the settings Icon
int tries = 0; int settingsClickTries = 0;
bool success = false; bool settingsClickSuccess = false;
while (tries < 100 && !success) while (settingsClickTries < 100 && !settingsClickSuccess)
{ {
Thread.Sleep(100); Thread.Sleep(100);
try try
@@ -207,17 +236,17 @@ namespace Test_Merge
SelectElement select = new SelectElement(selectElement); SelectElement select = new SelectElement(selectElement);
IWebElement selectOption = selectElement.FindElement(By.CssSelector("option[value^='1080_']")); IWebElement selectOption = selectElement.FindElement(By.CssSelector("option[value^='1080_']"));
selectOption.Click(); selectOption.Click();
success = true; settingsClickSuccess = true;
} }
catch catch
{ {
//Sometimes it can crash because it could not get the options to show up in time. When it happens just retry //Sometimes it can crash because it could not get the options to show up in time. When it happens just retry
success = false; settingsClickSuccess = false;
tries++; settingsClickTries++;
} }
} }
if (!success) if (!settingsClickSuccess)
{ {
Screenshot("ERROR105"); Screenshot("ERROR105");
Driver.Dispose(); Driver.Dispose();
@@ -227,15 +256,27 @@ namespace Test_Merge
Screenshot("BEFOREFULLSCREEN"); Screenshot("BEFOREFULLSCREEN");
//Makes the feed fullscreen //Makes the feed fullscreen
//Driver.Manage().Window.Size = new System.Drawing.Size(windowWidth, windowHeight); int fullScreenClickTries = 0;
bool fullScreenClickSuccess = false;
Driver.Manage().Window.Maximize(); Driver.Manage().Window.Maximize();
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); //WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
try while (fullScreenClickTries < 100 && !fullScreenClickSuccess)
{ {
IWebElement fullScreenButton = Driver.FindElement(By.ClassName("bmpui-ui-fullscreentogglebutton")); Thread.Sleep(150);
fullScreenButton.Click(); try
{
IWebElement fullScreenButton = Driver.FindElement(By.ClassName("bmpui-ui-fullscreentogglebutton"));
fullScreenButton.Click();
fullScreenClickSuccess = true;
}
catch
{
fullScreenClickSuccess = false;
fullScreenClickTries++;
}
} }
catch
if (!fullScreenClickSuccess)
{ {
Screenshot("ERROR106"); Screenshot("ERROR106");
Driver.Dispose(); Driver.Dispose();
@@ -248,18 +289,22 @@ namespace Test_Merge
Ready = true; Ready = true;
return 0; return 0;
} }
/// <summary>
/// Takes a screenshot of what the headless browser is displaying
/// </summary>
/// <param name="name">Optional ! The name of the picture so it can be saved</param>
/// <returns>Returns the screenshot in the bitmap format</returns>
public Bitmap Screenshot(string name = "TEST") public Bitmap Screenshot(string name = "TEST")
{ {
Bitmap result = new Bitmap(4242, 6969); Bitmap result = new Bitmap(4242, 6969);
try try
{ {
//Screenshot scrsht = ((ITakesScreenshot)Driver).GetScreenshot(); //Screenshot scrsht = ((ITakesScreenshot)Driver).GetScreenshot();
//profileriver.SetPreference("layout.css.devPixelsPerPx", "1.0"); //profileriver.SetPreferencC:\Users\Moi\source\repos\Test_Merge\README.mde("layout.css.devPixelsPerPx", "1.0");
//Screenshot scrsht = Driver.GetFullPageScreenshot(); //Screenshot scrsht = Driver.GetFullPageScreenshot();
Screenshot scrsht = Driver.GetScreenshot(); Screenshot scrsht = Driver.GetScreenshot();
byte[] screenshotBytes = Convert.FromBase64String(scrsht.AsBase64EncodedString); byte[] screenshotBytes = Convert.FromBase64String(scrsht.AsBase64EncodedString);
MemoryStream stream = new MemoryStream(screenshotBytes); MemoryStream stream = new MemoryStream(screenshotBytes);
@@ -273,15 +318,23 @@ namespace Test_Merge
} }
return result; return result;
} }
/// <summary>
/// Stops the Emulation. Note: if you plan to start it again please use ResetDriver() instead
/// </summary>
public void Stop() public void Stop()
{ {
Ready = false; Ready = false;
Driver.Dispose(); if (Driver != null)
Driver.Dispose();
} }
/// <summary>
/// Resets the emulation
/// </summary>
public void ResetDriver() public void ResetDriver()
{ {
Ready = false; Ready = false;
Driver.Dispose(); if (Driver != null)
Driver.Dispose();
Driver = null; Driver = null;
} }
} }
+483 -6
View File
@@ -1,27 +1,504 @@
using System; /// Author : Maxime Rohmer
/// Date : 09/06/2023
/// File : Form1.cs
/// Brief : Class that controls the main view of the app
/// Version : Beta 1.0
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.IO;
namespace Test_Merge namespace TrackTrends
{ {
public partial class Form1 : Form public partial class Main : Form
{ {
public Form1() private F1TVEmulator Emulator = null;
private DataWrapper Wrapper = null;
private bool cancelRequested = false;
private SemaphoreSlim semaphore = new SemaphoreSlim(1);
string ConfigFile = "";
string GpUrl = "";
//For the responsive content
Size oldSize = new Size();
Size oldRankingSize = new Size();
Size oldLapTimesSize = new Size();
Size oldBattles = new Size();
Size oldPnlBattles = new Size();
Size oldPnlRankings = new Size();
Size oldPnlFastest = new Size();
Size oldPnlSlowest = new Size();
Point oldRankingPosition = new Point();
Point oldBattlePosition = new Point();
Point oldDriverInfoPosition = new Point();
Point olPnlFastestPosition = new Point();
Point oldPnlSlowestPosition = new Point();
public Main()
{ {
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// Will update everything that is not data related
/// </summary>
public void RefreshUI()
{
if (Directory.Exists(ConfigurationTool.CONFIGS_FOLDER_NAME))
{
lsbPresets.DataSource = null;
lsbPresets.DataSource = Directory.GetFiles(ConfigurationTool.CONFIGS_FOLDER_NAME);
}
}
/// <summary>
/// Opens the settings page. Also disposes of the browser if there is one opened and all thos things
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSettings_Click(object sender, EventArgs e) private void btnSettings_Click(object sender, EventArgs e)
{ {
if (Emulator != null)
Emulator.ResetDriver();
btnStartDecoding.Enabled = false;
btnStopUpdating.Enabled = false;
btnResetEmulator.Text = "Launch";
Emulator = null;
Wrapper = null;
GC.Collect();
Settings settingsForm = new Settings(); Settings settingsForm = new Settings();
settingsForm.ShowDialog(); settingsForm.ShowDialog();
MessageBox.Show(settingsForm.GrandPrixUrl + Environment.NewLine + settingsForm.GrandPrixName + Environment.NewLine + settingsForm.GrandPrixYear); RefreshUI();
//MessageBox.Show(settingsForm.GrandPrixUrl + Environment.NewLine + settingsForm.GrandPrixName + Environment.NewLine + settingsForm.GrandPrixYear);
if (settingsForm.GrandPrixUrl != "" && settingsForm.SelectedConfigFile != "")
{
GpUrl = settingsForm.GrandPrixUrl;
tbxGpUrl.Text = GpUrl;
if (File.Exists(settingsForm.SelectedConfigFile))
{
ConfigFile = settingsForm.SelectedConfigFile;
for(int i = 0; i < lsbPresets.Items.Count; i++)
{
if (lsbPresets.Items[i].ToString() == ConfigFile)
lsbPresets.SelectedIndex = i;
}
}
else
{
//Should technically never show up but we never know
MessageBox.Show("The config file has not been found please return to the config and change it");
}
}
else
{
//WE dont care anymore, the user will choose its Grand Prix himself in the main program
//MessageBox.Show("There is no URL for the Grand Prix you want to decode. Please return to the config and add a valid one");
}
}
/// <summary>
/// Will do everything that needs to be done at the first start of the app
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void Form1_Load(object sender, EventArgs e)
{
//Those are the default values but they will need to be changed later when the configuration has been done
ConfigFile = "./Presets/Clean_4K_2023.json";
GpUrl = "https://f1tv.formula1.com/detail/1000006688/2023-azerbaijan-grand-prix?action=play";
tbxGpUrl.Text = GpUrl;
this.DoubleBuffered = true;
oldSize = this.Size;
oldRankingSize = gpbxRanking.Size;
oldLapTimesSize = gpbxLapTimes.Size;
oldBattles = gpbxBattles.Size;
oldPnlRankings = pnlLiveRanking.Size;
oldPnlBattles = pnlBattles.Size;
oldPnlFastest = pnlFastest.Size;
oldPnlSlowest = pnlSlowest.Size;
oldRankingPosition = gpbxRanking.Location;
oldBattlePosition = gpbxBattles.Location;
oldDriverInfoPosition = gpbxDriverInfos.Location;
olPnlFastestPosition = pnlFastest.Location;
oldPnlSlowestPosition = pnlSlowest.Location;
tip1.SetToolTip(btnResetEmulator, "Starts or restarts the emulator. You need to start this to use the app");
tip1.SetToolTip(btnSettings, "Opens the configuration menu");
tip1.SetToolTip(tbxGpUrl, "Insert the URL of the Grand Prix you want to track. Dont forget the \"?action=play\" at the end");
tip1.SetToolTip(lsbPresets, "Select a configuration preset to use with the decoding");
tip1.SetToolTip(pbxResult,"A preview of what the program sees. You should see the DATA page of the F1TV here");
tip1.SetToolTip(lsbOvertakes,"A list of all the activity. You can scroll to see the most recent overtakes");
tip1.SetToolTip(gpbxBattles,"The four first battles in the field. A battle is two drivers less than 3 seconds apart");
tip1.SetToolTip(gpbxLapTimes,"The fastest and slowest drivers on track at the moment. It takes the average lapTime of the last 5 laps to choose who is the fastes or the slowest");
RefreshUI();
}
/// <summary>
/// Will start or stop the process of decoding
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btnUpdate_Click(object sender, EventArgs e)
{
cancelRequested = false;
if (Emulator != null && Wrapper != null)
{
// Disable UI controls to prevent re-entrancy
btnResetEmulator.Enabled = false;
btnStartDecoding.Enabled = false;
btnStopUpdating.Enabled = true;
btnSettings.Enabled = false;
while (!cancelRequested)
{
await semaphore.WaitAsync();
try
{
// Start the time-consuming task on a separate thread
await Task.Run(async () =>
{
Stopwatch sw = new Stopwatch();
sw.Start();
Bitmap screen = Emulator.Screenshot();
screen.Save("HopefullyDataScreenshot.png");
Invoke((MethodInvoker)delegate
{
pbxResult.Image = (Bitmap)screen.Clone();
});
Wrapper.ChangeImage(screen);
int errorCode = Wrapper.Refresh();
sw.Stop();
// Task completed
Invoke((MethodInvoker)delegate
{
DisplayResults(errorCode, sw, screen);
DisplayBattles();
DisplayDeltas();
DisplayOvertakes();
});
});
}
finally
{
semaphore.Release();
}
}
// Re-enable UI controls
btnStopUpdating.Text = "Stop";
btnStartDecoding.Enabled = true;
btnStopUpdating.Enabled = false;
btnResetEmulator.Enabled = true;
btnSettings.Enabled = true;
}
}
/// <summary>
/// Will display the overtakes in the overtakes list box
/// </summary>
private void DisplayOvertakes()
{
Wrapper.DisplayOvertakes(lsbOvertakes);
}
/// <summary>
/// Will display the battles in the battles pannel
/// </summary>
private void DisplayBattles()
{
Wrapper.DisplayBattles(pnlBattles, this);
}
/// <summary>
/// Will display the time differences in the faster and slowest pannels
/// </summary>
private void DisplayDeltas()
{
Wrapper.DisplayTimesDeltas(pnlFastest, pnlSlowest, this);
}
/// <summary>
/// Will try to stop the emulator (usually does not work please do not count on it)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (Emulator != null)
{
Emulator.Stop();
}
}
/// <summary>
/// Will display the live ranking on the live ranking pannel. Its called like this because historically it was the method that just recovered the bare results from the OCR
/// </summary>
/// <param name="errorCode"></param>
/// <param name="sw"></param>
/// <param name="screen"></param>
private void DisplayResults(int errorCode, Stopwatch sw, Bitmap screen)
{
if (errorCode != 0)
{
cancelRequested = true;
MessageBox.Show("An error has occured while trying to recover data from live feed. This can happen sometimes. I would advise you to restart a few times. If the problem persists check your configuration.");
}
else
{
Wrapper.DisplayLiveRanking(pnlLiveRanking, this);
}
}
/// <summary>
/// Will stop the data recovering operation and resets some buttons and text
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStopUpdating_Click(object sender, EventArgs e)
{
// Set the cancellation flag
cancelRequested = true;
btnStopUpdating.Enabled = false;
btnResetEmulator.Enabled = false;
btnStopUpdating.Text = "Stopping";
}
/// <summary>
/// Will start the F1TVEmulator, again this name is historical because back at the start of this project this button did not have a name
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void button1_Click(object sender, EventArgs e)
{
lsbOvertakes.Items.Clear();
btnResetEmulator.Text = "Launching";
btnResetEmulator.Enabled = false;
btnSettings.Enabled = true;
btnStartDecoding.Enabled = false;
btnStopUpdating.Enabled = false;
btnSettings.Enabled = false;
int errorCode = -1;
await Task.Run(async () =>
{
if (Emulator != null)
Emulator.ResetDriver();
Emulator = null;
Wrapper = null;
GC.Collect();
Emulator = new F1TVEmulator(GpUrl);
errorCode = await Emulator.Start();
});
if (errorCode != 0)
{
string message = "";
switch (errorCode)
{
case 100:
message = "Error " + errorCode + " Could not recover cookies. It could be because of an improper installation of python or bad cookies in the chrome database. Please try to log on to the F1TV using chrome again";
break;
case 101:
message = "Error " + errorCode + " Could not start the driver. It could be because an other instance is runnin make sure you closed them all before trying again";
break;
case 102:
message = "Error " + errorCode + " Could not navigate on the F1TV site. Make sure the correct URL has been given and that you logged from chrome. It can take a few minutes to update";
break;
case 103:
message = "Error " + errorCode + " The url is not a valid url";
break;
case 104:
message = "Error " + errorCode + " The url is not a valid url";
break;
case 105:
message = "Error " + errorCode + " There has been an error trying to emulate button presses. Please try again";
break;
case 106:
message = "Error " + errorCode + " There has been an error trying to emulate button presses. Please try again";
break;
default:
message = "Could not start the emulator Error " + errorCode;
break;
}
MessageBox.Show(message);
btnResetEmulator.Enabled = true;
btnSettings.Enabled = true;
btnResetEmulator.Text = "Retry";
}
else
{
Wrapper = new DataWrapper(ConfigFile, Emulator.Screenshot());
btnResetEmulator.Text = "Re launch";
btnResetEmulator.Enabled = true;
btnSettings.Enabled = true;
btnStartDecoding.Enabled = true;
}
}
/// <summary>
/// Silly way to remove borders from groupbox and make them look like pannels with titles
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void removeBorders(object sender, PaintEventArgs e)
{
GroupBox gpbx = (GroupBox)sender;
using (Pen pen = new Pen(gpbx.BackColor, 50))
{
e.Graphics.DrawRectangle(pen, 0, 0, gpbx.Width - 1, gpbx.Height - 1);
e.Graphics.DrawRectangle(pen, 0, 0, gpbx.Width - 1, gpbx.Height - 1);
}
using (var brush = new SolidBrush(gpbx.ForeColor))
{
var textPosition = new Point(5, 0); // Adjust the X and Y values as needed
e.Graphics.DrawString(gpbx.Text, gpbx.Font, brush, textPosition);
}
}
/// <summary>
/// Will change the preset to use when starting the emulator
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lsbPresets_SelectedIndexChanged(object sender, EventArgs e)
{
if (lsbPresets.SelectedIndex >= 0)
ConfigFile = lsbPresets.Items[lsbPresets.SelectedIndex].ToString();
}
/// <summary>
/// Will change the URL the emulator will use, historical name again
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (tbxGpUrl.Text != "")
GpUrl = tbxGpUrl.Text;
}
/// <summary>
/// This is called by the automatically generated buttons. Its here to fill in the driver info tab whenever the user clicks on a button that contains the name of a driver
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void btnDriver_Click(object sender, EventArgs e)
{
//Removes the cover
if (pnlCover.Visible = true)
pnlCover.Visible = false;
//Happens when a driver button has been clicked
//MessageBox.Show((sender as Button).Name + " has been selected");
Button btn = (sender as Button);
string[] parts = btn.Name.Split('_');
DriverData driver = Wrapper.GetFullDriverData(parts[0], pnlCurrentDriverLapsHistory, this);
lblCurrentDriverName.Text = driver.Name;
lblCurrentDriverPosition.Text = driver.Position.ToString();
lblCurrentDriverGapToLeader.Text = Reader.ConvertMsToTime(driver.GapToLeader);
lblCurrentDriverLapTime.Text = Reader.ConvertMsToTime(driver.LapTime);
lblCurrentDriverTyreAge.Text = driver.CurrentTyre.NumberOfLaps.ToString();
if (driver.DRS)
{
lblCurrentDriverDRS.Text = "Open";
lblCurrentDriverDRS.ForeColor = Color.FromArgb(0, 164, 46);
}
else
{
lblCurrentDriverDRS.Text = "Closed";
lblCurrentDriverDRS.ForeColor = Color.Black;
}
switch (driver.CurrentTyre.Coumpound)
{
case Tyre.Type.Undefined:
lblCurrentDriverTyreType.Text = "uuuuh...";
lblCurrentDriverTyreType.ForeColor = Color.Violet;
break;
case Tyre.Type.Hard:
lblCurrentDriverTyreType.Text = "Hard";
lblCurrentDriverTyreType.ForeColor = Color.FromArgb(164, 165, 168);
break;
case Tyre.Type.Medium:
lblCurrentDriverTyreType.Text = "Medium";
lblCurrentDriverTyreType.ForeColor = Color.FromArgb(245, 191, 0);
break;
case Tyre.Type.Soft:
lblCurrentDriverTyreType.Text = "Soft";
lblCurrentDriverTyreType.ForeColor = Color.FromArgb(255, 0, 0);
break;
case Tyre.Type.Inter:
lblCurrentDriverTyreType.Text = "Intermediate";
lblCurrentDriverTyreType.ForeColor = Color.FromArgb(0, 164, 46);
break;
case Tyre.Type.Wet:
lblCurrentDriverTyreType.Text = "Wet";
lblCurrentDriverTyreType.ForeColor = Color.FromArgb(39, 96, 166);
break;
}
}
/// <summary>
/// This is supposed to be called by an automatically generated button. It should be any button with a laptime info on it
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void btnLapTime_Click(object sender, EventArgs e)
{
//Happens when a lapTime has been clicked
Button btn = sender as Button;
string[] parts = btn.Name.Split('_');
Wrapper.DisplayLapTimeInfos(parts[0], Convert.ToInt32(parts[1]), btn.Text);
}
/// <summary>
/// Will trigger responsive calculation everytime the form changes size
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Main_Resize(object sender, EventArgs e)
{
int xDiff = this.Width - oldSize.Width;
int yDiff = this.Height - oldSize.Height;
int padding = 10;
//This will take half the newly created space
gpbxRanking.Size = new Size(oldRankingSize.Width + xDiff / 2, oldRankingSize.Height + yDiff);
gpbxRanking.Location = new Point(oldRankingPosition.X + xDiff / 2, gpbxRanking.Location.Y);
//Will take half the new height and half the new height
gpbxLapTimes.Size = new Size(oldLapTimesSize.Width + xDiff / 2, oldLapTimesSize.Height + yDiff / 2);
//Will take half the new height and half the new width
gpbxBattles.Size = new Size(oldBattles.Width + xDiff / 2, oldBattles.Height + yDiff / 2);
gpbxBattles.Location = new Point(gpbxBattles.Location.X, oldBattlePosition.Y + yDiff / 2);
//The infos wont change width but will need to be centerd
Point startOfZone = new Point(gpbxOvertakes.Width + gpbxOvertakes.Location.X, gpbxOvertakes.Location.Y);
Point endOfZone = new Point(gpbxRanking.Location.X, gpbxOvertakes.Location.Y);
int totalWidth = endOfZone.X - startOfZone.X;
gpbxDriverInfos.Location = new Point(startOfZone.X + (totalWidth / 2 - gpbxDriverInfos.Width / 2), oldDriverInfoPosition.Y + yDiff);
//Now resizing internals
pnlFastest.Size = new Size(oldPnlFastest.Width + xDiff / 4,oldPnlFastest.Height + yDiff / 4);
pnlFastest.Location = new Point(olPnlFastestPosition.X,olPnlFastestPosition.Y + yDiff / 4);
pnlSlowest.Size = new Size(oldPnlSlowest.Width + xDiff / 4, oldPnlSlowest.Height + yDiff / 4);
pnlSlowest.Location = new Point(oldPnlSlowestPosition.X + xDiff / 4, oldPnlSlowestPosition.Y + yDiff / 4);
pnlBattles.Size = new Size(oldPnlBattles.Width + xDiff / 2,oldPnlBattles.Height + yDiff / 2);
pnlLiveRanking.Size = new Size(oldPnlRankings.Width + xDiff / 2,oldPnlRankings.Height + yDiff);
} }
} }
} }
+174 -26
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : OcrImage.cs /// File : OcrImage.cs
/// Brief : Class containing all the methods used to enhance images for OCR /// Brief : Class containing all the methods used to enhance images for OCR
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,7 +11,7 @@ using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Imaging; using System.Drawing.Imaging;
namespace Test_Merge namespace TrackTrends
{ {
public class OcrImage public class OcrImage
{ {
@@ -19,6 +19,8 @@ namespace Test_Merge
//Any color that has any of its R,G or B channel higher than the treshold will be considered as being usefull information //Any color that has any of its R,G or B channel higher than the treshold will be considered as being usefull information
public static Color F1TV_BACKGROUND_TRESHOLD = Color.FromArgb(0x50, 0x50, 0x50); public static Color F1TV_BACKGROUND_TRESHOLD = Color.FromArgb(0x50, 0x50, 0x50);
Bitmap InputBitmap; Bitmap InputBitmap;
Random rnd = new Random();
public enum WindowType public enum WindowType
{ {
LapTime, LapTime,
@@ -44,28 +46,57 @@ namespace Test_Merge
public Bitmap Enhance(WindowType type = WindowType.Text) public Bitmap Enhance(WindowType type = WindowType.Text)
{ {
Bitmap outputBitmap = (Bitmap)InputBitmap.Clone(); Bitmap outputBitmap = (Bitmap)InputBitmap.Clone();
//Note : If you plan to activate all the comments that I used to debug the OCR I would advise to make sure that the debug folder exists
switch (type) switch (type)
{ {
case WindowType.LapTime: case WindowType.Gap:
outputBitmap = Tresholding(outputBitmap, 185); //outputBitmap.Save(Window.GAPTOLEADER_DEBUG_FOLDER + @"\raw_" + id + ".png");
outputBitmap = Tresholding(outputBitmap, 165);
//outputBitmap.Save(Window.GAPTOLEADER_DEBUG_FOLDER + @"\treshold_" + id + ".png");
outputBitmap = Resize(outputBitmap, 2); outputBitmap = Resize(outputBitmap, 2);
//outputBitmap.Save(Window.GAPTOLEADER_DEBUG_FOLDER + @"\resize_" + id + ".png");
outputBitmap = Dilatation(outputBitmap, 1); outputBitmap = Dilatation(outputBitmap, 1);
outputBitmap = Erode(outputBitmap, 1); //outputBitmap.Save(Window.GAPTOLEADER_DEBUG_FOLDER + @"\Final_dilatation_" + id + ".png");
break;
case WindowType.Sector:
//outputBitmap.Save(Window.SECTOR1_DEBUG_FOLDER + @"\raw_" + id + ".png");
outputBitmap = VanishOxyAction(outputBitmap);
//outputBitmap.Save(Window.SECTOR1_DEBUG_FOLDER + @"\vanish_" + id + ".png");
outputBitmap = Tresholding(outputBitmap, 150);
//outputBitmap.Save(Window.SECTOR1_DEBUG_FOLDER + @"\Final_treshold_" + id + ".png");
break;
case WindowType.LapTime:
//outputBitmap.Save(Window.LAPTIME_DEBUG_FOLDER + @"\raw_" + id + ".png");
outputBitmap = Tresholding(outputBitmap, 185);
//outputBitmap.Save(Window.LAPTIME_DEBUG_FOLDER + @"\Treshold_" + id + ".png");
outputBitmap = SobelEdgeDetection(outputBitmap);
//outputBitmap.Save(Window.LAPTIME_DEBUG_FOLDER + @"\SobelDetection_" + id + ".png");
break; break;
case WindowType.Text: case WindowType.Text:
outputBitmap = InvertColors(outputBitmap); //outputBitmap.Save(Window.STRING_DEBUG_FOLDER + @"\raw_" + id + ".png");
outputBitmap = Tresholding(outputBitmap, 165); outputBitmap = Tresholding(outputBitmap, 165);
outputBitmap = Resize(outputBitmap, 2); //outputBitmap.Save(Window.STRING_DEBUG_FOLDER + @"\Final_treshold_" + id + ".png");
outputBitmap = Dilatation(outputBitmap, 1);
break; break;
case WindowType.Tyre: case WindowType.Tyre:
//outputBitmap.Save(Window.TYRE_DEBUG_FOLDER + @"\raw_" + id + ".png");
outputBitmap = RemoveUseless(outputBitmap); outputBitmap = RemoveUseless(outputBitmap);
outputBitmap = Resize(outputBitmap, 4); //outputBitmap.Save(Window.TYRE_DEBUG_FOLDER + @"\uselessRemoved_" + id + ".png");
outputBitmap = Dilatation(outputBitmap, 1); outputBitmap = Dilatation(outputBitmap, 1);
//outputBitmap.Save(Window.TYRE_DEBUG_FOLDER + @"\Final_dilatation_" + id + ".png");
break; break;
default: default:
outputBitmap = Tresholding(outputBitmap, 165); outputBitmap = Tresholding(outputBitmap, 165);
outputBitmap = Resize(outputBitmap, 4); outputBitmap = Resize(outputBitmap, 2);
outputBitmap = Erode(outputBitmap, 1); outputBitmap = Erode(outputBitmap, 1);
break; break;
} }
@@ -79,32 +110,147 @@ namespace Test_Merge
public static Bitmap Grayscale(Bitmap inputBitmap) public static Bitmap Grayscale(Bitmap inputBitmap)
{ {
Rectangle rect = new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height); Rectangle rect = new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height);
BitmapData bmpData = inputBitmap.LockBits(rect, ImageLockMode.ReadWrite, inputBitmap.PixelFormat); BitmapData bmpData = inputBitmap.LockBits(rect, ImageLockMode.ReadOnly, inputBitmap.PixelFormat);
int bytesPerPixel = Bitmap.GetPixelFormatSize(inputBitmap.PixelFormat) / 8; int bytesPerPixel = Bitmap.GetPixelFormatSize(inputBitmap.PixelFormat) / 8;
Bitmap resultBitmap = new Bitmap(inputBitmap.Width, inputBitmap.Height);
unsafe unsafe
{ {
byte* ptr = (byte*)bmpData.Scan0.ToPointer(); byte* inputPtr = (byte*)bmpData.Scan0.ToPointer();
for (int y = 0; y < inputBitmap.Height; y++) byte* resultPtr = (byte*)resultBitmap.LockBits(rect, ImageLockMode.WriteOnly, resultBitmap.PixelFormat).Scan0.ToPointer();
Parallel.For(0, inputBitmap.Height, y =>
{ {
byte* currentLine = ptr + (y * bmpData.Stride); byte* currentLine = inputPtr + (y * bmpData.Stride);
byte* resultLine = resultPtr + (y * resultBitmap.Width * bytesPerPixel);
for (int x = 0; x < inputBitmap.Width; x++) for (int x = 0; x < inputBitmap.Width; x++)
{ {
byte* pixel = currentLine + (x * bytesPerPixel); byte* inputPixel = currentLine + (x * bytesPerPixel);
byte* resultPixel = resultLine + (x * bytesPerPixel);
byte blue = pixel[0]; byte blue = inputPixel[0];
byte green = pixel[1]; byte green = inputPixel[1];
byte red = pixel[2]; byte red = inputPixel[2];
//Those a specific values to correct the weights so its more pleasing to the human eye //Those a specific values to correct the weights so its more pleasing to the human eye
int gray = (int)(red * 0.3 + green * 0.59 + blue * 0.11); int gray = (int)(red * 0.3 + green * 0.59 + blue * 0.11);
pixel[0] = pixel[1] = pixel[2] = (byte)gray; //This is not a proper treshold method but it is helping the sobel edge detection
if (gray <= F1TV_BACKGROUND_TRESHOLD.R)
{
resultPixel[0] = resultPixel[1] = resultPixel[2] = 0;
}
else
{
resultPixel[0] = resultPixel[1] = resultPixel[2] = (byte)gray;
}
} }
} });
resultBitmap.UnlockBits(resultBitmap.LockBits(rect, ImageLockMode.WriteOnly, resultBitmap.PixelFormat));
} }
inputBitmap.UnlockBits(bmpData); inputBitmap.UnlockBits(bmpData);
return resultBitmap;
}
/// <summary>
/// Method that uses the Sobel Edge detection to outline the edges of the characters to help with the OCR
/// </summary>
/// <param name="grayscaleImage">The image with the sobel edge detection used</param>
/// <returns></returns>
private Bitmap SobelEdgeDetection(Bitmap grayscaleImage)
{
// Create a new bitmap for the edges
Bitmap edgesImage = new Bitmap(grayscaleImage.Width, grayscaleImage.Height);
// Define the Sobel operators
// Its just a matrix that we will use on the all image
int[,] sobelX = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
int[,] sobelY = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
// Apply the Sobel operators and normalize the gradients
// NOTE: I dont know how easy or hard it would be to make this paralel but it could be a good idea to do so if possible.
//Parallel.For(1, grayscaleImage.Height - 1, y =>
for (int y = 1; y < grayscaleImage.Height - 1; y++)
{
for (int x = 1; x < grayscaleImage.Width - 1; x++)
{
int gradientX = CalculateGradient(grayscaleImage, sobelX, x, y);
int gradientY = CalculateGradient(grayscaleImage, sobelY, x, y);
int gradient = (int)Math.Sqrt(gradientX * gradientX + gradientY * gradientY);
// Normalize the gradient value
// In some rare cases the value can exceed 255 so we limit it with the Math.Min method
gradient = Math.Min(255, Math.Max(0, gradient));
edgesImage.SetPixel(x, y, Color.FromArgb(gradient, gradient, gradient));
}
}//);
return edgesImage;
}
/// <summary>
/// Method that's here to be used by the sobel edge detection method (Chat GPT has been used for parts of this method)
/// </summary>
/// <param name="grayscaleImage">The input image with the grayscale processing already done</param>
/// <param name="sobelOperator">The matrix to apply</param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>Returns the processed gradient</returns>
private int CalculateGradient(Bitmap grayscaleImage, int[,] sobelOperator, int x, int y)
{
int gradient = 0;
for (int j = -1; j <= 1; j++)
{
for (int i = -1; i <= 1; i++)
{
int pixelX = grayscaleImage.GetPixel(x + i, y + j).R;
gradient += sobelOperator[j + 1, i + 1] * pixelX;
}
}
return gradient;
}
/// <summary>
/// Method that is used to whiten an image. Ignore the funny name. Its used to prevent colored text to trouble the OCR when it uses grayscaling
/// </summary>
/// <param name="inputBitmap">The bitmap to vanish</param>
/// <returns></returns>
public Bitmap VanishOxyAction(Bitmap inputBitmap)
{
unsafe
{
BitmapData bitmapData = inputBitmap.LockBits(new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height), ImageLockMode.ReadWrite, inputBitmap.PixelFormat);
int bytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(inputBitmap.PixelFormat) / 8;
int heightInPixels = bitmapData.Height;
int widthInBytes = bitmapData.Width * bytesPerPixel;
byte* PtrFirstPixel = (byte*)bitmapData.Scan0;
Parallel.For(0, heightInPixels, y =>
{
byte* currentLine = PtrFirstPixel + (y * bitmapData.Stride);
for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
{
int blue = currentLine[x];
int green = currentLine[x + 1];
int red = currentLine[x + 2];
int max = Math.Max(Math.Max(blue, green), red);
if (max > 255 / 3)
max = 255;
currentLine[x] = currentLine[x + 1] = currentLine[x + 2] = (byte)max;
}
});
inputBitmap.UnlockBits(bitmapData);
}
return inputBitmap; return inputBitmap;
} }
/// <summary> /// <summary>
@@ -160,10 +306,12 @@ namespace Test_Merge
unsafe unsafe
{ {
byte* ptr = (byte*)bmpData.Scan0.ToPointer(); byte* ptr = (byte*)bmpData.Scan0.ToPointer();
for (int y = 0; y < inputBitmap.Height; y++) int bmpHeight = inputBitmap.Height;
int bmpWidth = inputBitmap.Width;
Parallel.For(0, bmpHeight, y =>
{ {
byte* currentLine = ptr + (y * bmpData.Stride); byte* currentLine = ptr + (y * bmpData.Stride);
for (int x = 0; x < inputBitmap.Width; x++) for (int x = 0; x < bmpWidth; x++)
{ {
byte* pixel = currentLine + (x * bytesPerPixel); byte* pixel = currentLine + (x * bytesPerPixel);
@@ -174,7 +322,7 @@ namespace Test_Merge
if (R <= F1TV_BACKGROUND_TRESHOLD.R && G <= F1TV_BACKGROUND_TRESHOLD.G && B <= F1TV_BACKGROUND_TRESHOLD.B) if (R <= F1TV_BACKGROUND_TRESHOLD.R && G <= F1TV_BACKGROUND_TRESHOLD.G && B <= F1TV_BACKGROUND_TRESHOLD.B)
pixel[0] = pixel[1] = pixel[2] = 0; pixel[0] = pixel[1] = pixel[2] = 0;
} }
} });
} }
inputBitmap.UnlockBits(bmpData); inputBitmap.UnlockBits(bmpData);
@@ -267,7 +415,7 @@ namespace Test_Merge
int G = pixel[1]; int G = pixel[1];
int R = pixel[2]; int R = pixel[2];
if (R >= F1TV_BACKGROUND_TRESHOLD.R + 15 || G >= F1TV_BACKGROUND_TRESHOLD.G + 15 || B >= F1TV_BACKGROUND_TRESHOLD.B + 15) if (R >= F1TV_BACKGROUND_TRESHOLD.R + 25 || G >= F1TV_BACKGROUND_TRESHOLD.G + 25 || B >= F1TV_BACKGROUND_TRESHOLD.B + 25)
{ {
pixel[0] = 0xFF; pixel[0] = 0xFF;
pixel[1] = 0xFF; pixel[1] = 0xFF;
@@ -324,7 +472,7 @@ namespace Test_Merge
} }
inputBitmap.UnlockBits(bmpData); inputBitmap.UnlockBits(bmpData);
return Color.FromArgb(255, Convert.ToInt32((float)totR / (float)totPixels), Convert.ToInt32((float)totG / (float)totPixels), Convert.ToInt32((float)totB / (float)totPixels)); return Color.FromArgb(255, Math.Min(Convert.ToInt32((float)totR / (float)totPixels), 255), Math.Min(Convert.ToInt32((float)totG / (float)totPixels), 255), Math.Min(Convert.ToInt32((float)totB / (float)totPixels), 255));
} }
/// <summary> /// <summary>
/// This method simply inverts all the colors in a Bitmap /// This method simply inverts all the colors in a Bitmap
-22
View File
@@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_Merge
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
+223 -115
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : Reader.cs /// File : Reader.cs
/// Brief : Class used to Read the config file for the OCR /// Brief : Class used to Read the config file for the OCR
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -14,7 +14,7 @@ using System.Windows.Forms;
using System.IO; using System.IO;
using System.Text.Json; using System.Text.Json;
namespace Test_Merge namespace TrackTrends
{ {
public class Reader public class Reader
{ {
@@ -22,123 +22,188 @@ namespace Test_Merge
public List<string> Drivers; public List<string> Drivers;
public List<Zone> MainZones; public List<Zone> MainZones;
public Reader(string configFile, Bitmap image,bool loadOCR = true) private SqliteStorage _storage;
private List<DriverData>[] DriverDataLogs = new List<DriverData>[NUMBER_OF_DRIVERS];
private int[] DriverLaps = new int[NUMBER_OF_DRIVERS];
public SqliteStorage Storage { get => _storage; private set => _storage = value; }
public Reader(string configFile, Bitmap image, bool loadOCR = true)
{ {
MainZones = Load(image,configFile,ref Drivers,loadOCR); Storage = new SqliteStorage();
MainZones = Load(image, configFile, ref Drivers, loadOCR);
} }
/// <summary> /// <summary>
/// Method that reads the JSON config file and create all the Zones and Windows /// Method that reads the JSON config file and create all the Zones and Windows
/// </summary> /// </summary>
/// <param name="imageNumber">The image #id on wich you want to create the zones on</param> /// <param name="imageNumber">The image #id on wich you want to create the zones on</param>
public static List<Zone> Load(Bitmap image,string configFilePath,ref List<string> driverListToFill,bool LoadOCR) public List<Zone> Load(Bitmap image, string configFilePath, ref List<string> driverListToFill, bool LoadOCR)
{ {
// Note : You may wonder why in the H... I have all the zones and windows stored in a JSON file and not just for example the first and the last
// Its because they are not perfectly aligned to each others and every zone has his own alignement to the main image
List<Zone> mainZones = new List<Zone>(); List<Zone> mainZones = new List<Zone>();
Bitmap fullImage = image; Bitmap fullImage = image;
List<string> drivers;
Zone mainZone; Zone mainZone;
for (int i = 0; i < NUMBER_OF_DRIVERS; i++)
{
DriverDataLogs[i] = new List<DriverData>();
DriverLaps[i] = 0;
}
try try
{ {
using (var streamReader = new StreamReader(configFilePath)) string jsonString = File.ReadAllText(configFilePath);
JsonDocument document = JsonDocument.Parse(jsonString);
JsonElement root = document.RootElement;
mainZones = new List<Zone>();
driverListToFill = new List<string>();
JsonElement main = root.GetProperty("Main");
int x = main.GetProperty("x").GetInt32();
int y = main.GetProperty("y").GetInt32();
int width = main.GetProperty("width").GetInt32();
int height = main.GetProperty("height").GetInt32();
mainZone = new Zone(fullImage, new Rectangle(x, y, width, height), "Main");
mainZone.ResetWindows();
mainZone.ResetZones();
JsonElement driverZones = main.GetProperty("DriverZones");
foreach (JsonElement driverZoneElement in driverZones.EnumerateArray())
{ {
var jsonText = streamReader.ReadToEnd(); string name = driverZoneElement.GetProperty("name").GetString();
var jsonDocument = JsonDocument.Parse(jsonText); int driverX = driverZoneElement.GetProperty("x").GetInt32() + mainZone.Bounds.X;
int driverY = driverZoneElement.GetProperty("y").GetInt32() + mainZone.Bounds.Y;
int driverWidth = driverZoneElement.GetProperty("width").GetInt32();
int driverHeight = driverZoneElement.GetProperty("height").GetInt32();
var driversNames = jsonDocument.RootElement.GetProperty("Drivers"); Zone driverZone = new Zone(fullImage, new Rectangle(driverX, driverY, driverWidth, driverHeight), "Driver");
driverListToFill = new List<string>();
foreach (var nameElement in driversNames.EnumerateArray()) JsonElement windowsElement = driverZoneElement.GetProperty("Windows");
//string[] windowNames = new string[] { "Position","GapToLeader","LapTime","DRS","Tyres","Name","Sector1","Sector2","Sector3" };
foreach (JsonElement windowElement in windowsElement.EnumerateArray())
{ {
driverListToFill.Add(nameElement.GetString()); //Position
JsonElement posEl = windowElement.GetProperty("Position");
DriverPositionWindow positionWindow = new DriverPositionWindow(driverZone.ZoneImage,
new Rectangle(
posEl.GetProperty("x").GetInt32(),
posEl.GetProperty("y").GetInt32(),
posEl.GetProperty("width").GetInt32(),
posEl.GetProperty("height").GetInt32()),
LoadOCR);
//GapToLeader
JsonElement gapEl = windowElement.GetProperty("GapToLeader");
DriverGapToLeaderWindow gapWindow = new DriverGapToLeaderWindow(driverZone.ZoneImage,
new Rectangle(
gapEl.GetProperty("x").GetInt32(),
gapEl.GetProperty("y").GetInt32(),
gapEl.GetProperty("width").GetInt32(),
gapEl.GetProperty("height").GetInt32()),
LoadOCR);
//LapTime
JsonElement lapEl = windowElement.GetProperty("LapTime");
DriverLapTimeWindow lapWindow = new DriverLapTimeWindow(driverZone.ZoneImage,
new Rectangle(
lapEl.GetProperty("x").GetInt32(),
lapEl.GetProperty("y").GetInt32(),
lapEl.GetProperty("width").GetInt32(),
lapEl.GetProperty("height").GetInt32()),
LoadOCR);
//DRS
JsonElement drsEl = windowElement.GetProperty("DRS");
DriverDrsWindow drsWindow = new DriverDrsWindow(driverZone.ZoneImage,
new Rectangle(
drsEl.GetProperty("x").GetInt32(),
drsEl.GetProperty("y").GetInt32(),
drsEl.GetProperty("width").GetInt32(),
drsEl.GetProperty("height").GetInt32()),
LoadOCR);
//Tyre
JsonElement tyresEl = windowElement.GetProperty("Tyres");
DriverTyresWindow tyreWindow = new DriverTyresWindow(driverZone.ZoneImage,
new Rectangle(
tyresEl.GetProperty("x").GetInt32(),
tyresEl.GetProperty("y").GetInt32(),
tyresEl.GetProperty("width").GetInt32(),
tyresEl.GetProperty("height").GetInt32()),
LoadOCR);
//Name
JsonElement nameEl = windowElement.GetProperty("Name");
DriverNameWindow nameWindow = new DriverNameWindow(driverZone.ZoneImage,
new Rectangle(
nameEl.GetProperty("x").GetInt32(),
nameEl.GetProperty("y").GetInt32(),
nameEl.GetProperty("width").GetInt32(),
nameEl.GetProperty("height").GetInt32()),
LoadOCR);
//Sector1
JsonElement sec1El = windowElement.GetProperty("Sector1");
DriverSectorWindow sec1Window = new DriverSectorWindow(driverZone.ZoneImage,
new Rectangle(
sec1El.GetProperty("x").GetInt32(),
sec1El.GetProperty("y").GetInt32(),
sec1El.GetProperty("width").GetInt32(),
sec1El.GetProperty("height").GetInt32()),
1, LoadOCR);
//Sector2
JsonElement sec2El = windowElement.GetProperty("Sector2");
DriverSectorWindow sec2Window = new DriverSectorWindow(driverZone.ZoneImage,
new Rectangle(
sec2El.GetProperty("x").GetInt32(),
sec2El.GetProperty("y").GetInt32(),
sec2El.GetProperty("width").GetInt32(),
sec2El.GetProperty("height").GetInt32()),
2, LoadOCR);
//Sector3
JsonElement sec3El = windowElement.GetProperty("Sector3");
DriverSectorWindow sec3Window = new DriverSectorWindow(driverZone.ZoneImage,
new Rectangle(
sec3El.GetProperty("x").GetInt32(),
sec3El.GetProperty("y").GetInt32(),
sec3El.GetProperty("width").GetInt32(),
sec3El.GetProperty("height").GetInt32()),
3, LoadOCR);
driverZone.AddWindow(positionWindow);
driverZone.AddWindow(gapWindow);
driverZone.AddWindow(lapWindow);
driverZone.AddWindow(drsWindow);
driverZone.AddWindow(tyreWindow);
driverZone.AddWindow(nameWindow);
driverZone.AddWindow(sec1Window);
driverZone.AddWindow(sec2Window);
driverZone.AddWindow(sec3Window);
} }
mainZone.AddZone(driverZone);
var mainProperty = jsonDocument.RootElement.GetProperty("Main");
Point MainPosition = new Point(mainProperty.GetProperty("x").GetInt32(), mainProperty.GetProperty("y").GetInt32());
Size MainSize = new Size(mainProperty.GetProperty("width").GetInt32(), mainProperty.GetProperty("height").GetInt32());
Rectangle MainRectangle = new Rectangle(MainPosition, MainSize);
mainZone = new Zone(image, MainRectangle,"Main");
var zones = mainProperty.GetProperty("Zones");
var driverZone = zones[0].GetProperty("DriverZone");
Point FirstZonePosition = new Point(driverZone.GetProperty("x").GetInt32(), driverZone.GetProperty("y").GetInt32());
Size FirstZoneSize = new Size(driverZone.GetProperty("width").GetInt32(), driverZone.GetProperty("height").GetInt32());
var windows = driverZone.GetProperty("Windows");
var driverPosition = windows[0].GetProperty("Position");
Size driverPositionArea = new Size(driverPosition.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverPositionPosition = new Point(driverPosition.GetProperty("x").GetInt32(), driverPosition.GetProperty("y").GetInt32());
var driverGapToLeader = windows[0].GetProperty("GapToLeader");
Size driverGapToLeaderArea = new Size(driverGapToLeader.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverGapToLeaderPosition = new Point(driverGapToLeader.GetProperty("x").GetInt32(), driverGapToLeader.GetProperty("y").GetInt32());
var driverLapTime = windows[0].GetProperty("LapTime");
Size driverLapTimeArea = new Size(driverLapTime.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverLapTimePosition = new Point(driverLapTime.GetProperty("x").GetInt32(), driverLapTime.GetProperty("y").GetInt32());
var driverDrs = windows[0].GetProperty("DRS");
Size driverDrsArea = new Size(driverDrs.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverDrsPosition = new Point(driverDrs.GetProperty("x").GetInt32(), driverDrs.GetProperty("y").GetInt32());
var driverTyres = windows[0].GetProperty("Tyres");
Size driverTyresArea = new Size(driverTyres.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverTyresPosition = new Point(driverTyres.GetProperty("x").GetInt32(), driverTyres.GetProperty("y").GetInt32());
var driverName = windows[0].GetProperty("Name");
Size driverNameArea = new Size(driverName.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverNamePosition = new Point(driverName.GetProperty("x").GetInt32(), driverName.GetProperty("y").GetInt32());
var driverSector1 = windows[0].GetProperty("Sector1");
Size driverSector1Area = new Size(driverSector1.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverSector1Position = new Point(driverSector1.GetProperty("x").GetInt32(), driverSector1.GetProperty("y").GetInt32());
var driverSector2 = windows[0].GetProperty("Sector2");
Size driverSector2Area = new Size(driverSector2.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverSector2Position = new Point(driverSector2.GetProperty("x").GetInt32(), driverSector2.GetProperty("y").GetInt32());
var driverSector3 = windows[0].GetProperty("Sector3");
Size driverSector3Area = new Size(driverSector3.GetProperty("width").GetInt32(), FirstZoneSize.Height);
Point driverSector3Position = new Point(driverSector3.GetProperty("x").GetInt32(), driverSector3.GetProperty("y").GetInt32());
float offset = (((float)mainZone.ZoneImage.Height - (float)(driverListToFill.Count * FirstZoneSize.Height)) / (float)driverListToFill.Count);
Bitmap MainZoneImage = mainZone.ZoneImage;
List<Zone> zonesToAdd = new List<Zone>();
List<Bitmap> zonesImages = new List<Bitmap>();
for (int i = 0; i < NUMBER_OF_DRIVERS; i++)
{
Point tmpPos = new Point(0, FirstZonePosition.Y + i * FirstZoneSize.Height - Convert.ToInt32(i * offset));
Zone newDriverZone = new Zone(MainZoneImage, new Rectangle(tmpPos, FirstZoneSize), "DriverZone");
zonesToAdd.Add(newDriverZone);
zonesImages.Add(newDriverZone.ZoneImage);
newDriverZone.ZoneImage.Save("Driver"+i+".png");
}
//Parallel.For(0, NUMBER_OF_DRIVERS, i =>
for (int i = 0; i < NUMBER_OF_DRIVERS; i++)
{
Zone newDriverZone = zonesToAdd[(int)i];
Bitmap zoneImg = zonesImages[(int)i];
newDriverZone.AddWindow(new DriverPositionWindow(zoneImg, new Rectangle(driverPositionPosition, driverPositionArea),LoadOCR));
newDriverZone.AddWindow(new DriverGapToLeaderWindow(zoneImg, new Rectangle(driverGapToLeaderPosition, driverGapToLeaderArea), LoadOCR));
newDriverZone.AddWindow(new DriverLapTimeWindow(zoneImg, new Rectangle(driverLapTimePosition, driverLapTimeArea), LoadOCR));
newDriverZone.AddWindow(new DriverDrsWindow(zoneImg, new Rectangle(driverDrsPosition, driverDrsArea), LoadOCR));
newDriverZone.AddWindow(new DriverTyresWindow(zoneImg, new Rectangle(driverTyresPosition, driverTyresArea), LoadOCR));
newDriverZone.AddWindow(new DriverNameWindow(zoneImg, new Rectangle(driverNamePosition, driverNameArea), LoadOCR));
newDriverZone.AddWindow(new DriverSectorWindow(zoneImg, new Rectangle(driverSector1Position, driverSector1Area),1, LoadOCR));
newDriverZone.AddWindow(new DriverSectorWindow(zoneImg, new Rectangle(driverSector2Position, driverSector2Area),2, LoadOCR));
newDriverZone.AddWindow(new DriverSectorWindow(zoneImg, new Rectangle(driverSector3Position, driverSector3Area),3, LoadOCR));
mainZone.AddZone(newDriverZone);
}//);
//MessageBox.Show("We have a main zone with " + MainZone.Zones.Count() + " Driver zones with " + MainZone.Zones[4].Windows.Count() + " windows each and we have " + Drivers.Count + " drivers");
mainZones.Add(mainZone);
} }
JsonElement driversElement = main.GetProperty("Drivers");
foreach (JsonElement driverElement in driversElement.EnumerateArray())
{
string driverName = driverElement.GetString();
driverListToFill.Add(driverName);
Storage.AddDriver(driverName);
}
mainZones.Add(mainZone);
} }
catch (IOException ex) catch (IOException ex)
{ {
@@ -148,6 +213,12 @@ namespace Test_Merge
{ {
MessageBox.Show("Invalid JSON format: " + ex.Message); MessageBox.Show("Invalid JSON format: " + ex.Message);
} }
int driverID = 0;
foreach (Zone z in mainZones[0].Zones)
{
driverID++;
z.ZoneImage.Save("LoadedDriver" + driverID + ".png");
}
return mainZones; return mainZones;
} }
/// <summary> /// <summary>
@@ -155,35 +226,72 @@ namespace Test_Merge
/// </summary> /// </summary>
/// <param name="idImage">The id of the image we are working with</param> /// <param name="idImage">The id of the image we are working with</param>
/// <returns>a string representation of all the returns</returns> /// <returns>a string representation of all the returns</returns>
public async Task<string> Decode(List<Zone> mainZones,List<string> drivers) public List<DriverData> Decode(List<Zone> mainZones, List<string> drivers)
{ {
string result = "";
List<DriverData> mainResults = new List<DriverData>(); List<DriverData> mainResults = new List<DriverData>();
//Decode //Decode
for (int mainZoneId = 0; mainZoneId < mainZones.Count; mainZoneId++) for (int mainZoneId = 0; mainZoneId < mainZones.Count; mainZoneId++)
{ {
switch (mainZoneId) switch (mainZoneId)
{ {
case 0: case 0:
//object lockObject = new object();
//Main Zone //Main Zone
foreach (Zone z in mainZones[mainZoneId].Zones) Parallel.For(0, mainZones[mainZoneId].Zones.Count, async i =>
//for (int i = 0; i < mainZones[mainZoneId].Zones.Count; i++)
{ {
mainResults.Add(await z.Decode(Drivers)); DriverData data = mainZones[mainZoneId].Zones[i].Decode(new List<string>(drivers));
} mainResults.Add(data);
DriverDataLogs[i].Add(data);
if (data.Position != -1 && DriverDataLogs[i].Count > 1)
{
//Tries to fix the tyres
if (data.CurrentTyre.NumberOfLaps > DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps + 3)
data.CurrentTyre.NumberOfLaps = DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps + 1;
//Checking if its a new lap
//If the third sector is filled but it was'nt the last time, then it means that a new Lap has been started
//Lap detection can be f***ed if the OCR takes so much time that an entire sector can be raced without us knowing.
if (
DriverDataLogs[i][DriverDataLogs[i].Count - 1].Sector3 != 0
&& DriverDataLogs[i][DriverDataLogs[i].Count - 2].Sector3 == 0
&& DriverDataLogs[i][DriverDataLogs[i].Count - 2].Position != -1
&& DriverDataLogs[i][DriverDataLogs[i].Count - 1].Position != -1)
{
DriverData stats = new DriverData();
stats = DriverDataLogs[i][DriverDataLogs[i].Count - 1];
DriverLaps[i]++;
Storage.AddDriverStat(stats, DriverLaps[i]);
}
//Checking if its a pitstop
//Forget this the best way to know if a tyre has been changed is if the number of laps is zero
if (data.CurrentTyre.Coumpound != Tyre.Type.Undefined && data.CurrentTyre.NumberOfLaps == 0 && DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps != 0)
{
Storage.AddPitstop(data.Name, DriverLaps[i] - 1, data.CurrentTyre.Coumpound.ToString());
//Driver laps -1 because it would take AT LEAST one lap for this program to detect a pitstop
}
}
DriverDataLogs[i].Add(data);
});
break; break;
//Next there could be a Title Zone and TrackInfoZone //Next there could be a Title Zone and TrackInfoZone
} }
} }
//mainResults = mainResults.OrderBy(driver => driver.Position >= 0).ThenBy(driver => driver.Position).ToList();
//Display mainResults = mainResults.OrderBy(driver => driver.Position).ToList();
foreach (DriverData driver in mainResults) return mainResults;
}
/// <summary>
/// Changes the image in all of the zones wich then will do the same for theyre own subzones and windows
/// </summary>
/// <param name="Image">The new Image from the F1TV data channel</param>
public void ChangeImage(Bitmap Image)
{
foreach (Zone z in MainZones)
{ {
result += driver.ToString(); z.Image = Image;
result += Environment.NewLine;
} }
return result;
} }
/// <summary> /// <summary>
/// Method that can be used to convert an amount of miliseconds into a more readable human form /// Method that can be used to convert an amount of miliseconds into a more readable human form
@@ -204,7 +312,7 @@ namespace Test_Merge
/// </summary> /// </summary>
/// <param name="idImage">the #id of the image we are working with</param> /// <param name="idImage">the #id of the image we are working with</param>
/// <returns>the drawed bitmap</returns> /// <returns>the drawed bitmap</returns>
public Bitmap Draw(Bitmap image,List<Zone> mainZones) public Bitmap Draw(Bitmap image, List<Zone> mainZones)
{ {
Graphics g = Graphics.FromImage(image); Graphics g = Graphics.FromImage(image);
+233 -61
View File
@@ -1,4 +1,10 @@
using System; /// Author : Maxime Rohmer
/// Date : 09/06/2023
/// File : Settings.cs
/// Brief : Class that controls the settings view
/// Version : Beta 1.0
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@@ -8,14 +14,14 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.IO; using System.IO;
using TrackTrends;
namespace Test_Merge namespace TrackTrends
{ {
public partial class Settings : Form public partial class Settings : Form
{ {
private string _grandPrixUrl = ""; private string _grandPrixUrl = "";
private string _grandPrixName = ""; private string _selectedConfigFile;
private int _grandPrixYear = 2000;
private List<string> _driverList = new List<string>(); private List<string> _driverList = new List<string>();
private F1TVEmulator Emulator = null; private F1TVEmulator Emulator = null;
@@ -32,22 +38,54 @@ namespace Test_Merge
List<Rectangle> WindowsToAdd = new List<Rectangle>(); List<Rectangle> WindowsToAdd = new List<Rectangle>();
public string GrandPrixUrl { get => _grandPrixUrl; private set => _grandPrixUrl = value; } public string GrandPrixUrl { get => _grandPrixUrl; private set => _grandPrixUrl = value; }
public string GrandPrixName { get => _grandPrixName; private set => _grandPrixName = value; }
public int GrandPrixYear { get => _grandPrixYear; private set => _grandPrixYear = value; }
public List<string> DriverList { get => _driverList; private set => _driverList = value; } public List<string> DriverList { get => _driverList; private set => _driverList = value; }
public string SelectedConfigFile { get => _selectedConfigFile; private set => _selectedConfigFile = value; }
//For the responsive content
Size oldSize = new Size();
Size oldGpbxPreviewSize = new Size();
Size oldGpbxWindowPreviewSize = new Size();
Size oldPbxPreviewSize = new Size();
Size oldPbxWindowPreviewSize = new Size();
public Settings() public Settings()
{ {
InitializeComponent(); InitializeComponent();
Load(); Load();
} }
/// <summary>
/// This methods regroups all the actions that the forms need to be doing at the first launch
/// </summary>
private void Load() private void Load()
{ {
RefreshUI(); RefreshUI();
oldSize = this.Size;
oldGpbxPreviewSize = gpbxPreview.Size;
oldGpbxWindowPreviewSize = gpbxWindowPreview.Size;
oldPbxPreviewSize = pbxPreview.Size;
oldPbxWindowPreviewSize = pbxWindowPreview.Size;
btnLoadPreset.Enabled = false;
btnDeletePreset.Enabled = false;
btnSavePreset.Enabled = false;
// I prefered regrouping all the tooltips here to make it easier to edit (there is 100% of thoses sentences containing typos so if you see one dont hesitate to edit those messages)
tip1.SetToolTip(btnCreatZone, "After clicking you can select two points in the image to set the bounds of the important data");
tip1.SetToolTip(btnCreateWindow, "After clicking this you will have to select all the windows that are important on the lower image. Refer to the documentation for more infos");
tip1.SetToolTip(btnRefresh, "Starts the emulator or refreshes the images if its already running");
tip1.SetToolTip(btnResetDriver, "Resets the driver if something went wrong or if you want to test an other URL");
tip1.SetToolTip(lsbDrivers, "The drivers that are on the image. Non-Case sensitive");
tip1.SetToolTip(tbxPresetName, "The name of the preset you want to save");
tip1.SetToolTip(pbxPreview, "What the emulator returns");
tip1.SetToolTip(pbxWindowPreview, "One of the driver zones that the program managed to slice from the main zone");
} }
/// <summary>
/// This is the main method that will be called anytime something changes on the view
/// It can be called at any time and will adapt the UI taking into account the state of the app
/// </summary>
private void RefreshUI() private void RefreshUI()
{ {
lsbDrivers.DataSource = null; lsbDrivers.DataSource = null;
lsbDrivers.DataSource = DriverList; lsbDrivers.DataSource = DriverList;
@@ -91,17 +129,26 @@ namespace Test_Merge
} }
if (Config != null) if (Config != null)
{ {
pbxMain.Image = Config.MainZone.Draw(); pbxPreview.Image = Config.MainZone.Draw();
if(Config.MainZone.Zones.Count > 0) if (Config.MainZone.Zones.Count > 0)
pbxDriverZone.Image = Config.MainZone.Zones[0].Draw(); pbxWindowPreview.Image = Config.MainZone.Zones[0].Draw();
} }
} }
/// <summary>
/// This will create a new zone but will require two points (one at each opposing sides and corners)
/// </summary>
/// <param name="p1">The first corner (usually top left)</param>
/// <param name="p2">The second corner (usually bottom right)</param>
private void CreateNewZone(Point p1, Point p2) private void CreateNewZone(Point p1, Point p2)
{ {
Rectangle dimensions = CreateAbsoluteRectangle(p1, p2); Rectangle dimensions = CreateAbsoluteRectangle(p1, p2);
Config = new ConfigurationTool((Bitmap)pbxMain.Image, dimensions); Config = new ConfigurationTool((Bitmap)pbxPreview.Image, dimensions);
RefreshUI(); RefreshUI();
} }
/// <summary>
/// Creates all the windows with an array of rectangles
/// </summary>
/// <param name="dimensions">An array that contains all the windows bounds and position (expects 9)</param>
private void CreateWindows(List<Rectangle> dimensions) private void CreateWindows(List<Rectangle> dimensions)
{ {
if (Config != null) if (Config != null)
@@ -109,30 +156,20 @@ namespace Test_Merge
Config.AddWindows(dimensions); Config.AddWindows(dimensions);
} }
} }
/// <summary>
/// Will just change the main URL
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tbxGpUrl_TextChanged(object sender, EventArgs e) private void tbxGpUrl_TextChanged(object sender, EventArgs e)
{ {
GrandPrixUrl = tbxGpUrl.Text; GrandPrixUrl = tbxGpUrl.Text;
} }
/// <summary>
private void tbxGpName_TextChanged(object sender, EventArgs e) /// Adds a driver into the driver list
{ /// </summary>
GrandPrixName = tbxGpName.Text; /// <param name="sender"></param>
} /// <param name="e"></param>
private void tbxGpYear_TextChanged(object sender, EventArgs e)
{
int year;
try
{
year = Convert.ToInt32(tbxGpYear.Text);
}
catch
{
year = 1545;
}
GrandPrixYear = year;
}
private void btnAddDriver_Click(object sender, EventArgs e) private void btnAddDriver_Click(object sender, EventArgs e)
{ {
string newDriver = tbxDriverName.Text; string newDriver = tbxDriverName.Text;
@@ -140,7 +177,11 @@ namespace Test_Merge
tbxDriverName.Text = ""; tbxDriverName.Text = "";
RefreshUI(); RefreshUI();
} }
/// <summary>
/// Removes a driver from the drivers list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRemoveDriver_Click(object sender, EventArgs e) private void btnRemoveDriver_Click(object sender, EventArgs e)
{ {
if (lsbDrivers.SelectedIndex >= 0) if (lsbDrivers.SelectedIndex >= 0)
@@ -149,6 +190,9 @@ namespace Test_Merge
} }
RefreshUI(); RefreshUI();
} }
/// <summary>
/// Will change everything that needs to be changed for when the users starts or stops creating a zone
/// </summary>
private void SwitchZoneCreation() private void SwitchZoneCreation()
{ {
if (CreatingZone) if (CreatingZone)
@@ -169,7 +213,7 @@ namespace Test_Merge
if (Emulator != null && Emulator.Ready) if (Emulator != null && Emulator.Ready)
{ {
Config = null; Config = null;
pbxMain.Image = Emulator.Screenshot(); pbxPreview.Image = Emulator.Screenshot();
} }
ZoneP1 = new Point(-1, -1); ZoneP1 = new Point(-1, -1);
@@ -179,6 +223,9 @@ namespace Test_Merge
} }
RefreshUI(); RefreshUI();
} }
/// <summary>
/// Will change everything that needs to be changed for when the users starts or stops creating a window
/// </summary>
private void SwitchWindowCreation() private void SwitchWindowCreation()
{ {
if (CreatingWindow) if (CreatingWindow)
@@ -210,14 +257,19 @@ namespace Test_Merge
{ {
SwitchWindowCreation(); SwitchWindowCreation();
} }
/// <summary>
/// If the user is supposed to create a zone, will record the position of the clicks
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pbxMain_MouseClick(object sender, MouseEventArgs e) private void pbxMain_MouseClick(object sender, MouseEventArgs e)
{ {
if (CreatingZone && pbxMain.Image != null) if (CreatingZone && pbxPreview.Image != null)
{ {
//Point coordinates = pbxMain.PointToClient(new Point(MousePosition.X, MousePosition.Y)); //Point coordinates = pbxMain.PointToClient(new Point(MousePosition.X, MousePosition.Y));
Point coordinates = e.Location; Point coordinates = e.Location;
float xOffset = (float)pbxMain.Image.Width / (float)pbxMain.Width; float xOffset = (float)pbxPreview.Image.Width / (float)pbxPreview.Width;
float yOffset = (float)pbxMain.Image.Height / (float)pbxMain.Height; float yOffset = (float)pbxPreview.Image.Height / (float)pbxPreview.Height;
Point newPoint = new Point(Convert.ToInt32((float)coordinates.X * xOffset), Convert.ToInt32((float)coordinates.Y * yOffset)); Point newPoint = new Point(Convert.ToInt32((float)coordinates.X * xOffset), Convert.ToInt32((float)coordinates.Y * yOffset));
//MessageBox.Show("Coordinates" + Environment.NewLine + "Old : " + coordinates.ToString() + Environment.NewLine + "New : " + newPoint.ToString()); //MessageBox.Show("Coordinates" + Environment.NewLine + "Old : " + coordinates.ToString() + Environment.NewLine + "New : " + newPoint.ToString());
@@ -235,18 +287,19 @@ namespace Test_Merge
RefreshUI(); RefreshUI();
} }
} }
private void pbxMain_Click(object sender, EventArgs e) /// <summary>
{ /// If the user is supposed to create a window, will record the position of the clicks
//Not the right one to use visibly /// </summary>
} /// <param name="sender"></param>
/// <param name="e"></param>
private void pbxDriverZone_MouseClick(object sender, MouseEventArgs e) private void pbxDriverZone_MouseClick(object sender, MouseEventArgs e)
{ {
if (CreatingWindow && pbxDriverZone.Image != null) if (CreatingWindow && pbxWindowPreview.Image != null)
{ {
Point coordinates = e.Location; Point coordinates = e.Location;
float xOffset = (float)pbxDriverZone.Image.Width / (float)pbxDriverZone.Width; float xOffset = (float)pbxWindowPreview.Image.Width / (float)pbxWindowPreview.Width;
float yOffset = (float)pbxDriverZone.Image.Height / (float)pbxDriverZone.Height; float yOffset = (float)pbxWindowPreview.Image.Height / (float)pbxWindowPreview.Height;
Point newPoint = new Point(Convert.ToInt32((float)coordinates.X * xOffset), Convert.ToInt32((float)coordinates.Y * yOffset)); Point newPoint = new Point(Convert.ToInt32((float)coordinates.X * xOffset), Convert.ToInt32((float)coordinates.Y * yOffset));
@@ -267,7 +320,7 @@ namespace Test_Merge
else else
{ {
WindowP1 = new Point(WindowP1.X, 0); WindowP1 = new Point(WindowP1.X, 0);
WindowP2 = new Point(WindowP2.X, pbxDriverZone.Image.Height); WindowP2 = new Point(WindowP2.X, pbxWindowPreview.Image.Height);
CreateWindows(WindowsToAdd); CreateWindows(WindowsToAdd);
SwitchWindowCreation(); SwitchWindowCreation();
} }
@@ -275,15 +328,18 @@ namespace Test_Merge
RefreshUI(); RefreshUI();
} }
} }
private void pbxDriverZone_Click(object sender, EventArgs e) /// <summary>
{ /// Creates a rectangle without caring about the order of the points.
//Not the right one to use visibly /// </summary>
} /// <param name="p1">First point. Can be top left or bottom right</param>
/// <param name="p2">Second point. Can be top left or bottom right</param>
/// <returns></returns>
private Rectangle CreateAbsoluteRectangle(Point p1, Point p2) private Rectangle CreateAbsoluteRectangle(Point p1, Point p2)
{ {
Point newP1 = new Point(); Point newP1 = new Point();
Point newP2 = new Point(); Point newP2 = new Point();
//Kind of a pain to have to do this but this lets the user do stupid things without the app crashing
if (p1.X < p2.X) if (p1.X < p2.X)
{ {
newP1.X = p1.X; newP1.X = p1.X;
@@ -307,10 +363,17 @@ namespace Test_Merge
} }
return new Rectangle(newP1.X, newP1.Y, newP2.X - newP1.X, newP2.Y - newP1.Y); return new Rectangle(newP1.X, newP1.Y, newP2.X - newP1.X, newP2.Y - newP1.Y);
} }
/// <summary>
/// Will refresh the emulator and will controll some of the controls
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btnRefresh_Click(object sender, EventArgs e) private async void btnRefresh_Click(object sender, EventArgs e)
{ {
btnRefresh.Enabled = false; btnRefresh.Enabled = false;
btnCreatZone.Enabled = false;
btnCreateWindow.Enabled = false;
btnResetDriver.Enabled = false;
if (Emulator == null || Emulator.GrandPrixUrl != tbxGpUrl.Text) if (Emulator == null || Emulator.GrandPrixUrl != tbxGpUrl.Text)
{ {
Emulator = new F1TVEmulator(tbxGpUrl.Text); Emulator = new F1TVEmulator(tbxGpUrl.Text);
@@ -325,6 +388,9 @@ namespace Test_Merge
string message; string message;
switch (errorCode) switch (errorCode)
{ {
case 100:
message = "Error " + errorCode + " Could not recover cookies. It could be because of an improper installation of python or bad cookies in the chrome database. Please try to log on to the F1TV using chrome again";
break;
case 101: case 101:
message = "Error " + errorCode + " Could not start the driver. It could be because an other instance is runnin make sure you closed them all before trying again"; message = "Error " + errorCode + " Could not start the driver. It could be because an other instance is runnin make sure you closed them all before trying again";
break; break;
@@ -348,27 +414,59 @@ namespace Test_Merge
break; break;
} }
MessageBox.Show(message); MessageBox.Show(message);
btnRefresh.Text = "Retry";
btnLoadPreset.Enabled = false;
btnDeletePreset.Enabled = false;
btnSavePreset.Enabled = false;
btnCreatZone.Enabled = false;
btnCreateWindow.Enabled = false;
btnResetDriver.Enabled = false;
} }
else else
{ {
pbxMain.Image = Emulator.Screenshot(); btnRefresh.Text = "Get a newer image";
pbxPreview.Image = Emulator.Screenshot();
btnLoadPreset.Enabled = true;
btnDeletePreset.Enabled = true;
btnSavePreset.Enabled = true;
btnCreatZone.Enabled = true;
btnCreateWindow.Enabled = true;
btnResetDriver.Enabled = true;
} }
} }
else else
{ {
pbxMain.Image = Emulator.Screenshot(); pbxPreview.Image = Emulator.Screenshot();
//I know im repeating myself. This part could use a bool variable that allows those buttons to be displayed but it was the fastest way to fix a bad behaviour in the app
btnLoadPreset.Enabled = true;
btnDeletePreset.Enabled = true;
btnSavePreset.Enabled = true;
btnCreatZone.Enabled = true;
btnCreateWindow.Enabled = true;
btnResetDriver.Enabled = true;
} }
btnRefresh.Enabled = true; btnRefresh.Enabled = true;
} }
/// <summary>
/// Will try to close the headless browser so the main form can launch a new one safely
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Settings_FormClosing(object sender, FormClosingEventArgs e) private void Settings_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Emulator != null) if (Emulator != null)
{ {
Emulator.Stop(); Emulator.Stop();
} }
Emulator = null;
GC.Collect();
} }
/// <summary>
/// Will reset the drivers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnResetDriver_Click(object sender, EventArgs e) private void btnResetDriver_Click(object sender, EventArgs e)
{ {
if (Emulator != null) if (Emulator != null)
@@ -376,33 +474,49 @@ namespace Test_Merge
Emulator.ResetDriver(); Emulator.ResetDriver();
} }
} }
/// <summary>
/// Saves the current presets as a new JSON file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSavePreset_Click(object sender, EventArgs e) private void btnSavePreset_Click(object sender, EventArgs e)
{ {
string presetName = tbxPresetName.Text; string presetName = tbxPresetName.Text;
if (Config != null) if (Config != null)
{ {
Config.SaveToJson(DriverList,presetName); Config.SaveToJson(DriverList, presetName);
} }
RefreshUI(); RefreshUI();
} }
/// <summary>
/// Will change the selected preset. Usefull if you close this page because then the main form will keep in memory your last choice
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lsbPresets_SelectedIndexChanged(object sender, EventArgs e) private void lsbPresets_SelectedIndexChanged(object sender, EventArgs e)
{ {
//Nothing if (lsbPresets.SelectedIndex >= 0)
SelectedConfigFile = (string)lsbPresets.Items[lsbPresets.SelectedIndex];
} }
/// <summary>
/// Will load an existing presets
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoadPreset_Click(object sender, EventArgs e) private void btnLoadPreset_Click(object sender, EventArgs e)
{ {
if (lsbPresets.SelectedIndex >= 0 && pbxMain.Image != null) //MessageBox.Show(lsbPresets.SelectedIndex.ToString());
if (lsbPresets.SelectedIndex >= 0 && pbxPreview.Image != null)
{ {
try try
{ {
Reader reader = new Reader(lsbPresets.Items[lsbPresets.SelectedIndex].ToString(), (Bitmap)pbxMain.Image,false); string fileName = lsbPresets.Items[lsbPresets.SelectedIndex].ToString();
Reader reader = new Reader(fileName, (Bitmap)pbxPreview.Image, false);
//MainZones #0 is the big main zone containing driver zones //MainZones #0 is the big main zone containing driver zones
Config = new ConfigurationTool((Bitmap)pbxMain.Image, reader.MainZones[0].Bounds); Config = new ConfigurationTool((Bitmap)pbxPreview.Image, reader.MainZones[0].Bounds);
Config.MainZone = reader.MainZones[0]; Config.MainZone = reader.MainZones[0];
DriverList = reader.Drivers; DriverList = reader.Drivers;
SelectedConfigFile = fileName;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -411,5 +525,63 @@ namespace Test_Merge
RefreshUI(); RefreshUI();
} }
} }
/// <summary>
/// This will be called everytime the form resizes. Here we are making the form responsive
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Settings_Resize(object sender, EventArgs e)
{
int xDiff = this.Width - oldSize.Width;
int yDiff = this.Height - oldSize.Height;
gpbxPreview.Size = new Size(oldGpbxPreviewSize.Width + xDiff, oldGpbxPreviewSize.Height + yDiff);
gpbxWindowPreview.Size = new Size(oldGpbxWindowPreviewSize.Width + xDiff, oldGpbxWindowPreviewSize.Height);
pbxPreview.Size = new Size(oldPbxPreviewSize.Width + xDiff, oldPbxPreviewSize.Height + yDiff);
pbxWindowPreview.Size = new Size(oldPbxWindowPreviewSize.Width + xDiff, oldPbxWindowPreviewSize.Height);
}
/// <summary>
/// Will delete an existing preset
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeletePreset_Click(object sender, EventArgs e)
{
int selectedIndex = lsbPresets.SelectedIndex;
if (selectedIndex >= 0)
{
string fileName = lsbPresets.Items[selectedIndex].ToString();
if (File.Exists(fileName))
{
File.Delete(fileName);
RefreshUI();
}
else
{
MessageBox.Show("Could not delete the preset because it does not exists");
}
}
}
/// <summary>
/// Sketchy method that is used to remove the borders from groupboxes... Yes its dumb but I dont think there is any other way
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void removeBorders(object sender, PaintEventArgs e)
{
GroupBox gpbx = (GroupBox)sender;
using (Pen pen = new Pen(gpbx.BackColor, 50))
{
e.Graphics.DrawRectangle(pen, 0, 0, gpbx.Width - 1, gpbx.Height - 1);
e.Graphics.DrawRectangle(pen, 0, 0, gpbx.Width - 1, gpbx.Height - 1);
}
using (var brush = new SolidBrush(gpbx.ForeColor))
{
var textPosition = new Point(5, 0); // Adjust the X and Y values as needed
e.Graphics.DrawString(gpbx.Text, gpbx.Font, brush, textPosition);
}
}
} }
} }
+262
View File
@@ -0,0 +1,262 @@
/// Author : Maxime Rohmer
/// Date : 09/08/2023
/// File : SqliteStorage.cs
/// Brief : Class that controls the sqlite database
/// Version : Beta 1.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.IO;
using System.Windows.Forms;
namespace TrackTrends
{
public class SqliteStorage
{
private const string DATABASE_FOLDER = "./Data";
private const string DATABASE_FILE = "/database.sqlite";
private const string CONNECTION_STRING = "Data Source=" + DATABASE_FOLDER + DATABASE_FILE + ";Version=3;";
private SQLiteConnection Connection;
/// <summary>
/// Creates a new Sqlite Storage and initialize the database
/// </summary>
public SqliteStorage()
{
Load();
}
/// <summary>
/// Loads a fresh new Database or create a new one if it does not exist.
/// </summary>
private void Load()
{
if (!Directory.Exists(DATABASE_FOLDER))
Directory.CreateDirectory(DATABASE_FOLDER);
if (!File.Exists(DATABASE_FOLDER + DATABASE_FILE))
{
SQLiteConnection.CreateFile(DATABASE_FOLDER + DATABASE_FILE);
}
else
{
//We are not using the existing DataBase
File.Delete(DATABASE_FOLDER + DATABASE_FILE);
}
Connection = new SQLiteConnection(CONNECTION_STRING);
Connection.Open();
//Create the drivers table
string createDriversTableQuery = @"CREATE TABLE IF NOT EXISTS Drivers
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
Name VARCHAR NOT NULL);";
using (var command = new SQLiteCommand(createDriversTableQuery, Connection))
{
command.ExecuteNonQuery();
}
//Create the drivers table
string createPitstopTableQuery = @"CREATE TABLE Pitstops
(Lap INTEGER NOT NULL,
DriverID INTEGER NOT NULL,
Tyre VARCHAR,
PRIMARY KEY (Lap,DriverID));";
using (var command = new SQLiteCommand(createPitstopTableQuery, Connection))
{
command.ExecuteNonQuery();
}
//Create the stats
string createStatsTableQuery = @"CREATE TABLE IF NOT EXISTS Stats
(Lap INTEGER NOT NULL,
DriverID INTEGER NOT NULL,
Tyre VARCHAR NOT NULL,
LapTime INTEGER NOT NULL,
Sector1 INTEGER NOT NULL,
Sector2 INTEGER NOT NULL,
Sector3 INTEGER NOT NULL,
GapToLeader INTEGER NOT NULL,
Position INTEGER NOT NULL,
PRIMARY KEY (Lap, DriverID));";
using (var command = new SQLiteCommand(createStatsTableQuery, Connection))
{
command.ExecuteNonQuery();
}
}
/// <summary>
/// Adds a driver into the drivers table. Meant to be used at the start of the programm
/// </summary>
/// <param name="name">The name of the driver. (non case sensitive)</param>
public void AddDriver(string name)
{
string insertQuery = "INSERT INTO Drivers (Name) VALUES (@name);";
using (var command = new SQLiteCommand(insertQuery,Connection))
{
command.Parameters.AddWithValue("@Name",name);
try
{
command.ExecuteNonQuery();
}
catch
{
//MessageBox.Show("An error has occured while trying to insert a new driver into de Database");
}
}
}
/// <summary>
/// Searches for a driver and returns its id if it has been found
/// </summary>
/// <param name="name">Name of the driver (non case sensitive)</param>
/// <returns></returns>
private int GetDriverID(string name)
{
string selectQuery = "SELECT ID FROM Drivers where Name LIKE @driverName";
int result = 0;
using (var command = new SQLiteCommand(selectQuery,Connection))
{
command.Parameters.AddWithValue("@driverName",name);
try
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result = reader.GetInt32(0);
}
}
}
catch
{
//MessageBox.Show("There has been an error while trying to retrieve the ID of a Driver from the database");
}
}
return result;
}
/// <summary>
/// Gets the sectors from a lapTime. Sectors are subdivisions of a laptime (could be usefull to validate one or the other)
/// </summary>
/// <param name="driverName">The name of the driver who has done the lap</param>
/// <param name="lap">The lap at wich the driver has done the time</param>
/// <returns>A list of the different sectors time in int (ms)</returns>
public List<int> GetSectorsFromLapTime(string driverName,int lap)
{
int driverId = GetDriverID(driverName);
string selectQuery = "SELECT Sector1,Sector2,Sector3 FROM Stats WHERE DriverID = @driverID AND Lap = @lap";
List<int> result = new List<int>();
using (var command = new SQLiteCommand(selectQuery, Connection))
{
command.Parameters.AddWithValue("@driverID", driverId);
command.Parameters.AddWithValue("@lap", lap);
try
{
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
result.Add(reader.GetInt32(0));
result.Add(reader.GetInt32(1));
result.Add(reader.GetInt32(2));
}
}
catch
{
//MessageBox.Show("There has been an error while trying to retrieve the ID of a Driver from the database");
}
}
return result;
}
/// <summary>
/// Get the laptime history of a driver
/// </summary>
/// <param name="driverName">The name of the driver</param>
/// <param name="numberOfLaptimes">The number of lapTimes you want</param>
/// <returns>A list of tuples with the lap and the laptime. It will only return the amount it found so even if you ask 5 expect getting less or even 0</returns>
public List<(int LapTime, int Lap)> GetDriverLaptimes(string driverName,int numberOfLaptimes)
{
int driverId = GetDriverID(driverName);
List<(int LapTime, int Lap)> lapData = new List<(int LapTime, int Lap)>();
string selectQuery = "Select LapTime,Lap from Stats WHERE DriverID = @driverID ORDER BY Lap DESC LIMIT @limit";
using (var command = new SQLiteCommand(selectQuery, Connection))
{
command.Parameters.AddWithValue("@driverID", driverId);
command.Parameters.AddWithValue("@limit", numberOfLaptimes);
try
{
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int lapTime = reader.GetInt32(0);
int lap = reader.GetInt32(1);
lapData.Add((lapTime, lap));
}
}
catch
{
//MessageBox.Show("There has been an error while trying to retrieve the ID of a Driver from the database");
}
}
return lapData;
}
/// <summary>
/// Add a pitstop into the db
/// </summary>
/// <param name="driverName">The name of the driver who made his pitstop</param>
/// <param name="lap">The lap where he stopped</param>
/// <param name="tyre">The tyre he took out</param>
public void AddPitstop(string driverName,int lap,string tyre)
{
string insertQuery = "INSERT INTO Pitstops (Lap,DriverID,Tyre) VALUES (@Lap,@DriverID,@Tyre)";
using (var command = new SQLiteCommand(insertQuery,Connection))
{
command.Parameters.AddWithValue("@Lap",lap);
command.Parameters.AddWithValue("@DriverID",GetDriverID(driverName));
command.Parameters.AddWithValue("@Tyre",tyre);
try
{
command.ExecuteNonQuery();
}
catch
{
//MessageBox.Show("An error has occured while trying to insert a new pitstop into the DB" + Environment.NewLine + "Request :"+ command.ToString());
}
}
}
/// <summary>
/// Adds drivers info into the DB (it should only be once per lap)
/// </summary>
/// <param name="data">The Driver data</param>
/// <param name="lap">The lap from wich the datas are from</param>
public void AddDriverStat(DriverData data,int lap)
{
string insertQuery = "INSERT INTO Stats (Lap,DriverID,Tyre,LapTime,Sector1,Sector2,Sector3,GapToLeader,Position) VALUES (@Lap,@DriverID,@Tyre,@LapTime,@Sector1,@Sector2,@Sector3,@GapToLeader,@Position);";
using (var command = new SQLiteCommand(insertQuery,Connection))
{
command.Parameters.AddWithValue("@Lap",lap);
command.Parameters.AddWithValue("@DriverID",GetDriverID(data.Name));
command.Parameters.AddWithValue("@Tyre",data.CurrentTyre.Coumpound.ToString());
command.Parameters.AddWithValue("@LapTime",data.LapTime);
command.Parameters.AddWithValue("@Sector1",data.Sector1);
command.Parameters.AddWithValue("@Sector2", data.Sector2);
command.Parameters.AddWithValue("@Sector3", data.Sector3);
command.Parameters.AddWithValue("@GapToLeader", data.GapToLeader);
command.Parameters.AddWithValue("@Position", data.Position);
try
{
command.ExecuteNonQuery();
}
catch
{
//MessageBox.Show("An error has occured while trying to insert infos about a driver");
}
}
}
}
}
+410 -51
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : Window.cs /// File : Window.cs
/// Brief : Default Window object that is mainly expected to be inherited. /// Brief : Default Window object that is mainly expected to be inherited.
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -15,10 +15,19 @@ using Tesseract;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
namespace Test_Merge namespace TrackTrends
{ {
public class Window public class Window
{ {
public const string STRING_DEBUG_FOLDER = "./GetString";
public const string LAPTIME_DEBUG_FOLDER = "./LapTime";
public const string GAPTOLEADER_DEBUG_FOLDER = "./Gap";
public const string SECTOR1_DEBUG_FOLDER = "./Sector1";
public const string SECTOR2_DEBUG_FOLDER = "./Sector2";
public const string SECTOR3_DEBUG_FOLDER = "./Sector3";
public const string DRS_DEBUG_FOLDER = "./DRS";
public const string TYRE_DEBUG_FOLDER = "./Tyre";
private Rectangle _bounds; private Rectangle _bounds;
private Bitmap _image; private Bitmap _image;
private string _name; private string _name;
@@ -28,6 +37,8 @@ namespace Test_Merge
public string Name { get => _name; protected set => _name = value; } public string Name { get => _name; protected set => _name = value; }
//This will have to be changed if you want to make it run on your machine //This will have to be changed if you want to make it run on your machine
public static DirectoryInfo TESS_DATA_FOLDER = new DirectoryInfo(@"C:\Users\Moi\Pictures\SeleniumScreens\TessData"); public static DirectoryInfo TESS_DATA_FOLDER = new DirectoryInfo(@"C:\Users\Moi\Pictures\SeleniumScreens\TessData");
//Debug
public static Random rnd = new Random();
public Bitmap WindowImage public Bitmap WindowImage
{ {
@@ -40,6 +51,12 @@ namespace Test_Merge
return sample; return sample;
} }
} }
/// <summary>
/// Creates a new Window
/// </summary>
/// <param name="image">The image of the parent zone</param>
/// <param name="bounds">The position and size of the window</param>
/// <param name="generateEngine">Does the window need to generate a tesseract engine (takes time and ressources)</param>
public Window(Bitmap image, Rectangle bounds, bool generateEngine = true) public Window(Bitmap image, Rectangle bounds, bool generateEngine = true)
{ {
Image = image; Image = image;
@@ -49,12 +66,32 @@ namespace Test_Merge
Engine = new TesseractEngine(TESS_DATA_FOLDER.FullName, "eng", EngineMode.Default); Engine = new TesseractEngine(TESS_DATA_FOLDER.FullName, "eng", EngineMode.Default);
Engine.DefaultPageSegMode = PageSegMode.SingleLine; Engine.DefaultPageSegMode = PageSegMode.SingleLine;
} }
//DEBUG
/*
if (!Directory.Exists(STRING_DEBUG_FOLDER))
Directory.CreateDirectory(STRING_DEBUG_FOLDER);
if (!Directory.Exists(LAPTIME_DEBUG_FOLDER))
Directory.CreateDirectory(LAPTIME_DEBUG_FOLDER);
if (!Directory.Exists(GAPTOLEADER_DEBUG_FOLDER))
Directory.CreateDirectory(GAPTOLEADER_DEBUG_FOLDER);
if (!Directory.Exists(SECTOR1_DEBUG_FOLDER))
Directory.CreateDirectory(SECTOR1_DEBUG_FOLDER);
if (!Directory.Exists(SECTOR2_DEBUG_FOLDER))
Directory.CreateDirectory(SECTOR2_DEBUG_FOLDER);
if (!Directory.Exists(SECTOR3_DEBUG_FOLDER))
Directory.CreateDirectory(SECTOR3_DEBUG_FOLDER);
if (!Directory.Exists(DRS_DEBUG_FOLDER))
Directory.CreateDirectory(DRS_DEBUG_FOLDER);
if (!Directory.Exists(TYRE_DEBUG_FOLDER))
Directory.CreateDirectory(TYRE_DEBUG_FOLDER);
*/
} }
/// <summary> /// <summary>
/// Method that will have to be used by the childrens to let the model make them decode the images they have /// Method that will have to be used by the childrens to let the model make them decode the images they have
/// </summary> /// </summary>
/// <returns>Returns an object because we dont know what kind of return it will be</returns> /// <returns>Returns an object because we dont know what kind of return it will be</returns>
public virtual async Task<Object> DecodePng() public virtual Object DecodePng()
{ {
return "NaN"; return "NaN";
} }
@@ -63,7 +100,7 @@ namespace Test_Merge
/// </summary> /// </summary>
/// <param name="driverList">This is a list of the different possible drivers in the race. It should not be too big but NEVER be too short</param> /// <param name="driverList">This is a list of the different possible drivers in the race. It should not be too big but NEVER be too short</param>
/// <returns>Returns an object because we dont know what kind of return it will be</returns> /// <returns>Returns an object because we dont know what kind of return it will be</returns>
public virtual async Task<Object> DecodePng(List<string> driverList) public virtual Object DecodePng(List<string> driverList)
{ {
return "NaN"; return "NaN";
} }
@@ -87,12 +124,15 @@ namespace Test_Merge
/// <param name="windowType">The type of window it is</param> /// <param name="windowType">The type of window it is</param>
/// <param name="Engine">The Tesseract Engine</param> /// <param name="Engine">The Tesseract Engine</param>
/// <returns>The time in milliseconds</returns> /// <returns>The time in milliseconds</returns>
public static async Task<int> GetTimeFromPng(Bitmap windowImage, OcrImage.WindowType windowType, TesseractEngine Engine) public static int GetTimeFromPng(Bitmap image, OcrImage.WindowType windowType, TesseractEngine Engine)
{ {
//Kind of a big method but it has a lot of error handling and has to work with three special cases //Kind of a big method but it has a lot of error handling and has to work with three special cases
string rawResult = ""; string rawResult = "";
int result = 0; int result = 0;
//Debug
int salt = rnd.Next(0, 999999);
switch (windowType) switch (windowType)
{ {
case OcrImage.WindowType.Sector: case OcrImage.WindowType.Sector:
@@ -113,7 +153,7 @@ namespace Test_Merge
} }
Bitmap enhancedImage = new OcrImage(windowImage).Enhance(windowType); Bitmap enhancedImage = new OcrImage(image).Enhance(windowType);
var tessImage = Pix.LoadFromMemory(ImageToByte(enhancedImage)); var tessImage = Pix.LoadFromMemory(ImageToByte(enhancedImage));
@@ -149,50 +189,378 @@ namespace Test_Merge
//removes any empty cells (tho this usually sign of a really bad OCR implementation tbh will have to be fixed higher in the chian) //removes any empty cells (tho this usually sign of a really bad OCR implementation tbh will have to be fixed higher in the chian)
rawNumbers.RemoveAll(x => ((string)x) == ""); rawNumbers.RemoveAll(x => ((string)x) == "");
if (rawNumbers.Count == 3) int minuts = 0;
int seconds = 0;
int miliseconds = 0;
switch (windowType)
{ {
//mm:ss:ms case OcrImage.WindowType.Sector:
result = (Convert.ToInt32(rawNumbers[0]) * 1000 * 60) + (Convert.ToInt32(rawNumbers[1]) * 1000) + Convert.ToInt32(rawNumbers[2]); //Usually there is supposed to be only 2 parts.
} if (rawNumbers.Count == 2)
else
{
if (rawNumbers.Count == 2)
{
//ss:ms
result = (Convert.ToInt32(rawNumbers[0]) * 1000) + Convert.ToInt32(rawNumbers[1]);
if (result > 999999)
{
//We know that we have way too much seconds to make a minut
//Its usually because the ":" have been interpreted as a number
int minuts = (int)(rawNumbers[0][0] - '0');
// rawNumbers[0][1] should contain the : that has been mistaken
int seconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString());
int ms = Convert.ToInt32(rawNumbers[1]);
result = (Convert.ToInt32(minuts) * 1000 * 60) + (Convert.ToInt32(seconds) * 1000) + Convert.ToInt32(ms);
}
}
else
{
if (rawNumbers.Count == 1)
{ {
//The perect case
try try
{ {
result = Convert.ToInt32(rawNumbers[0]); seconds = Convert.ToInt32(rawNumbers[0].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1].ToString());
} }
catch catch
{ {
//It can be because the input is empty or because its the LEADER bracket Console.WriteLine("Sector time convertion failed");
result = 0;
} }
} }
else else
{ {
//Auuuugh if (rawNumbers.Count == 1)
{
//Here it is a little harder... Usually its because a '.' has been overlooked or interpreted as a number
if (rawNumbers[0].Length == 6)
{
//The '.' has been understood as a number
try
{
seconds = Convert.ToInt32(rawNumbers[0][0].ToString() + rawNumbers[0][1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][3].ToString() + rawNumbers[0][4].ToString() + rawNumbers[0][5].ToString());
}
catch
{
Console.WriteLine("Sector time convertion failed");
}
}
else
{
if (rawNumbers[0].Length == 5)
{
//The '.' has been overlooked
try
{
seconds = Convert.ToInt32(rawNumbers[0][0].ToString() + rawNumbers[0][1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString() + rawNumbers[0][4].ToString());
}
catch
{
Console.WriteLine("Sector time convertion failed");
}
}
else
{
Console.WriteLine("Sector time convertion failed");
}
}
}
else
{
//The OCR detected more than 1 '.' wich is concerning because that means that something went really wrong
Console.WriteLine("Sector time convertion failed");
}
}
result = 0;
result += seconds * 1000;
result += miliseconds;
break;
case OcrImage.WindowType.LapTime:
if (rawNumbers.Count == 3)
{
//The normal way
try
{
minuts = Convert.ToInt32(rawNumbers[0].ToString());
seconds = Convert.ToInt32(rawNumbers[1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[2].ToString());
}
catch
{
Console.WriteLine("Lap time convertion failed");
}
}
else
{
if (rawNumbers.Count == 2)
{
//Either the ':' or the '.' has been missinterpreted
if (rawNumbers[0].Length > rawNumbers[1].Length)
{
//The ':' has been missinterpreted
if (rawNumbers[0].Length == 3)
{
//It has been forgotten
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][1].ToString() + rawNumbers[0][2].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1]);
}
catch
{
Console.WriteLine("Lap time convertion failed");
}
}
else
{
if (rawNumbers[0].Length == 4)
{
//I has been translated into an other number
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1]);
}
catch
{
Console.WriteLine("Lap time convertion failed");
}
}
else
{
//This could happen if the ':' has been missinterpreted with a lap time of over 9 minuts (HIGLY IMPROBABLE)
Console.WriteLine("Lap time convertion failed");
}
}
}
else
{
//The '.' has been missinterpreted
if (rawNumbers[1].Length == 5)
{
//It has been forgotten
minuts = Convert.ToInt32(rawNumbers[0].ToString());
seconds = Convert.ToInt32(rawNumbers[1][0].ToString() + rawNumbers[1][1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1][2].ToString() + rawNumbers[1][3].ToString() + rawNumbers[1][4].ToString());
}
else
{
if (rawNumbers[1].Length == 6)
{
try
{
//It has been interpreted as a number
minuts = Convert.ToInt32(rawNumbers[0].ToString());
seconds = Convert.ToInt32(rawNumbers[1][0].ToString() + rawNumbers[1][1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1][3].ToString() + rawNumbers[1][4].ToString() + rawNumbers[1][5].ToString());
}
catch
{
//It can happen and to be honest I dont know how to fix it
}
}
else
{
Console.WriteLine("Lap time convertion failed");
}
}
}
}
else
{
if (rawNumbers.Count == 1)
{
//Both the '.' and the ':' have been missinterpreted
if (rawNumbers[0].Length == 6)
{
//The just all have been forgotten
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][1].ToString() + rawNumbers[0][2].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][3].ToString() + rawNumbers[0][4].ToString() + rawNumbers[0][5].ToString());
}
catch
{
Console.WriteLine("Lap time convertion failed");
}
}
else
{
if (rawNumbers[0].Length == 7)
{
//The '.' or ':' have been interpreted as a number (usually the ':')
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][4].ToString() + rawNumbers[0][5].ToString() + rawNumbers[0][6].ToString());
}
catch
{
Console.WriteLine("Lap time convertion failed");
}
}
else
{
if (rawNumbers[0].Length == 8)
{
//Both have been interpreted as a number
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][5].ToString() + rawNumbers[0][6].ToString() + rawNumbers[0][7].ToString());
}
catch
{
Console.WriteLine("Lap time convertion failed");
}
}
else
{
//I dont know what could have happened
Console.WriteLine("Lap time convertion failed");
}
}
}
}
else
{
//I dont know what could have happened
Console.WriteLine("Lap time convertion failed");
}
}
}
result = 0;
result += minuts * 60 * 1000;
result += seconds * 1000;
result += miliseconds;
break;
case OcrImage.WindowType.Gap:
if (rawNumbers.Count == 2)
{
// This should be the x.xxx or a missed x:xx.xxx
if (rawNumbers[0].Length > 2)
{
//Its a missed x:xx.xxx
if (rawNumbers[0].Length == 3)
{
//It forgot the ":"
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][1].ToString() + rawNumbers[0][2].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1]);
}
catch
{
Console.WriteLine("Gap to leader convertion failed");
}
}
else
{
//The ":" has been mistaken as a number
if (rawNumbers[0].Length == 4)
{
try
{
minuts = Convert.ToInt32(rawNumbers[0][0].ToString());
seconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1]);
}
catch
{
Console.WriteLine("Gap to leader convertion failed");
}
}
else
{
Console.WriteLine("Gap to leader convertion failed");
}
}
}
else
{
//It should be a normal x.xxx or xx.xxx
try
{
seconds = Convert.ToInt32(rawNumbers[0].ToString());
miliseconds = Convert.ToInt32(rawNumbers[1].ToString());
}
catch
{
Console.WriteLine("Gap to leader convertion failed");
}
}
}
else
{
if (rawNumbers.Count == 1)
{
//can be anything depending on the size of the string
if (rawNumbers[0].Length == 4)
{
//We just missed the '.'
try
{
seconds = Convert.ToInt32(rawNumbers[0][0].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][1].ToString() + rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString());
}
catch
{
Console.WriteLine("Gap to leader convertion failed");
}
}
else
{
if (rawNumbers[0].Length == 5)
{
//We just missed the '.'
try
{
seconds = Convert.ToInt32(rawNumbers[0][0].ToString() + rawNumbers[0][1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[0][2].ToString() + rawNumbers[0][3].ToString() + rawNumbers[0][4].ToString());
}
catch
{
Console.WriteLine("Gap to leader convertion failed");
}
}
//There is just too much possibilities that it would be stupid to try and tell them appart so for now im leaving that as just an error
Console.WriteLine("Gap to leader convertion failed");
}
}
else
{
if (rawNumbers.Count == 3)
{
// This should be the x:xx.xxx
try
{
//Gaps cant be more than 9 minuts so if there is more than 1 digit it means that the '+' has been understood as an other number
if (rawNumbers[0].Length > 1)
rawNumbers[0] = rawNumbers[0][rawNumbers[0].Length - 1].ToString();
minuts = Convert.ToInt32(rawNumbers[0].ToString());
seconds = Convert.ToInt32(rawNumbers[1].ToString());
miliseconds = Convert.ToInt32(rawNumbers[2].ToString());
}
catch
{
Console.WriteLine("Gap to leader convertion failed");
}
}
}
}
result = 0;
result += minuts * 60 * 1000;
result += seconds * 1000;
result += miliseconds;
break;
default:
try
{
result = Convert.ToInt32(rawNumbers[0].ToString());
}
catch
{
result = 0; result = 0;
} }
} break;
} }
page.Dispose(); page.Dispose();
return result; return result;
} }
@@ -204,13 +572,16 @@ namespace Test_Merge
/// <param name="allowedChars">The list of allowed chars</param> /// <param name="allowedChars">The list of allowed chars</param>
/// <param name="windowType">The type of window the text is on. Depending on the context the OCR will behave differently</param> /// <param name="windowType">The type of window the text is on. Depending on the context the OCR will behave differently</param>
/// <returns>the string it found</returns> /// <returns>the string it found</returns>
public static async Task<string> GetStringFromPng(Bitmap WindowImage, TesseractEngine Engine, string allowedChars = "", OcrImage.WindowType windowType = OcrImage.WindowType.Text) public static string GetStringFromPng(Bitmap image, TesseractEngine Engine, string allowedChars = "", OcrImage.WindowType windowType = OcrImage.WindowType.Text)
{ {
string result = ""; string result = "";
//Debug
int salt = rnd.Next(0, 999999);
Engine.SetVariable("tessedit_char_whitelist", allowedChars); Engine.SetVariable("tessedit_char_whitelist", allowedChars);
Bitmap rawData = WindowImage; Bitmap rawData = image;
Bitmap enhancedImage = new OcrImage(rawData).Enhance(windowType); Bitmap enhancedImage = new OcrImage(rawData).Enhance(windowType);
Page page = Engine.Process(enhancedImage); Page page = Engine.Process(enhancedImage);
@@ -301,17 +672,5 @@ namespace Test_Merge
return d[string1.Length, string2.Length]; return d[string1.Length, string2.Length];
} }
public virtual string ToJSON()
{
string result = "";
result += "\"" + Name + "\"" + ":{" + Environment.NewLine;
result += "\t" + "\"x\":" + Bounds.X + "," + Environment.NewLine;
result += "\t" + "\"y\":" + Bounds.Y + "," + Environment.NewLine;
result += "\t" + "\"width\":" + Bounds.Width + Environment.NewLine;
result += "}";
return result;
}
} }
} }
+25 -77
View File
@@ -1,8 +1,8 @@
/// Author : Maxime Rohmer /// Author : Maxime Rohmer
/// Date : 08/05/2023 /// Date : 09/06/2023
/// File : Zone.cs /// File : Zone.cs
/// Brief : Class that contains all the methods and infos for a zone. This is designed to be potentially be inherited. /// Brief : Class that contains all the methods and infos for a zone. This is designed to be potentially be inherited.
/// Version : 0.1 /// Version : Beta 1.0
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -11,7 +11,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Test_Merge namespace TrackTrends
{ {
public class Zone public class Zone
{ {
@@ -38,7 +38,7 @@ namespace Test_Merge
set set
{ {
//It automatically sets the image for the contained windows and zones //It automatically sets the image for the contained windows and zones
_image = Image; _image = value;
foreach (Window w in Windows) foreach (Window w in Windows)
{ {
w.Image = ZoneImage; w.Image = ZoneImage;
@@ -49,12 +49,16 @@ namespace Test_Merge
} }
} }
} }
public Rectangle Bounds { get => _bounds; protected set => _bounds = value; } public Rectangle Bounds { get => _bounds; protected set => _bounds = value; }
public List<Zone> Zones { get => _zones; protected set => _zones = value; } public List<Zone> Zones { get => _zones; protected set => _zones = value; }
public List<Window> Windows { get => _windows; protected set => _windows = value; } public List<Window> Windows { get => _windows; protected set => _windows = value; }
public string Name { get => _name; protected set => _name = value; } public string Name { get => _name; protected set => _name = value; }
/// <summary>
/// Creates a new Zone
/// </summary>
/// <param name="image">Image of the parent zone</param>
/// <param name="bounds">The position and size of the zone</param>
/// <param name="name">THe name of the zone (usefull for the JSON formatting)</param>
public Zone(Bitmap image, Rectangle bounds, string name) public Zone(Bitmap image, Rectangle bounds, string name)
{ {
Windows = new List<Window>(); Windows = new List<Window>();
@@ -86,36 +90,36 @@ namespace Test_Merge
/// </summary> /// </summary>
/// <param name="driverList">A list of all the driver in the race to help with text recognition</param> /// <param name="driverList">A list of all the driver in the race to help with text recognition</param>
/// <returns>A driver data object that contains all the infos about a driver</returns> /// <returns>A driver data object that contains all the infos about a driver</returns>
public virtual async Task<DriverData> Decode(List<string> driverList) public virtual DriverData Decode(List<string> driverList)
{ {
int sectorCount = 0; int sectorCount = 0;
DriverData result = new DriverData(); DriverData result = new DriverData();
Parallel.ForEach(Windows, async w => foreach(Window w in Windows)
{ {
// A switch would be prettier but I dont think its supported in this C# version // A switch would be prettier but I dont think its supported in this C# version
if (w is DriverNameWindow) if (w is DriverNameWindow)
result.Name = (string)await (w as DriverNameWindow).DecodePng(driverList); result.Name = (string)(w as DriverNameWindow).DecodePng(driverList);
if (w is DriverDrsWindow) if (w is DriverDrsWindow)
result.DRS = (bool)await (w as DriverDrsWindow).DecodePng(); result.DRS = (bool)(w as DriverDrsWindow).DecodePng();
if (w is DriverGapToLeaderWindow) if (w is DriverGapToLeaderWindow)
result.GapToLeader = (int)await (w as DriverGapToLeaderWindow).DecodePng(); result.GapToLeader = (int)(w as DriverGapToLeaderWindow).DecodePng();
if (w is DriverLapTimeWindow) if (w is DriverLapTimeWindow)
result.LapTime = (int)await (w as DriverLapTimeWindow).DecodePng(); result.LapTime = (int)(w as DriverLapTimeWindow).DecodePng();
if (w is DriverPositionWindow) if (w is DriverPositionWindow)
result.Position = (int)await (w as DriverPositionWindow).DecodePng(); result.Position = (int)(w as DriverPositionWindow).DecodePng();
if (w is DriverSectorWindow) if (w is DriverSectorWindow)
{ {
sectorCount++; sectorCount++;
if (sectorCount == 1) if (sectorCount == 1)
result.Sector1 = (int)await (w as DriverSectorWindow).DecodePng(); result.Sector1 = (int)(w as DriverSectorWindow).DecodePng();
if (sectorCount == 2) if (sectorCount == 2)
result.Sector2 = (int)await (w as DriverSectorWindow).DecodePng(); result.Sector2 = (int)(w as DriverSectorWindow).DecodePng();
if (sectorCount == 3) if (sectorCount == 3)
result.Sector3 = (int)await (w as DriverSectorWindow).DecodePng(); result.Sector3 = (int)(w as DriverSectorWindow).DecodePng();
} }
if (w is DriverTyresWindow) if (w is DriverTyresWindow)
result.CurrentTyre = (Tyre)await (w as DriverTyresWindow).DecodePng(); result.CurrentTyre = (Tyre)(w as DriverTyresWindow).DecodePng();
}); }
return result; return result;
} }
public virtual Bitmap Draw() public virtual Bitmap Draw()
@@ -136,16 +140,16 @@ namespace Test_Merge
//If its the main zone we need to visualize the Zone bounds displayed //If its the main zone we need to visualize the Zone bounds displayed
if (Zones.Count > 0) if (Zones.Count > 0)
g.DrawRectangle(new Pen(Brushes.Violet, 5), Bounds); g.DrawRectangle(new Pen(new SolidBrush(Color.FromArgb(249,194,46)), 5), Bounds);
foreach (Zone z in Zones) foreach (Zone z in Zones)
{ {
Rectangle newBounds = new Rectangle(z.Bounds.X, z.Bounds.Y + Bounds.Y, z.Bounds.Width, z.Bounds.Height); Rectangle newBounds = new Rectangle(z.Bounds.X, z.Bounds.Y + Bounds.Y, z.Bounds.Width, z.Bounds.Height);
g.DrawRectangle(Pens.Red, newBounds); g.DrawRectangle(new Pen(new SolidBrush(Color.FromArgb(249, 194, 46)), 5), newBounds);
} }
foreach (Window w in Windows) foreach (Window w in Windows)
{ {
g.DrawRectangle(Pens.Blue, w.Bounds); g.DrawRectangle(new Pen(new SolidBrush(Color.FromArgb(252, 252, 252)), 5), w.Bounds);
} }
return img; return img;
} }
@@ -161,62 +165,6 @@ namespace Test_Merge
} }
Windows.Clear(); Windows.Clear();
} }
public virtual string ToJSON()
{
string result = "";
result += "\"" + Name + "\":{" + Environment.NewLine;
result += "\t" + "\"x\":" + Bounds.X + "," + Environment.NewLine;
result += "\t" + "\"y\":" + Bounds.Y + "," + Environment.NewLine;
result += "\t" + "\"width\":" + Bounds.Width + "," + Environment.NewLine;
result += "\t" + "\"height\":" + Bounds.Height;
if (Windows.Count != 0)
{
result += "," + Environment.NewLine;
result += "\t" + "\"Windows\":[" + Environment.NewLine;
result += "\t\t{" + Environment.NewLine;
int Wcount = 0;
foreach (Window w in Windows)
{
result += "\t\t" + w.ToJSON();
Wcount++;
if (Wcount != Windows.Count)
result += ",";
}
result += "\t\t}" + Environment.NewLine;
result += "\t" + "]" + Environment.NewLine;
}
else
{
result += Environment.NewLine;
}
if (Zones.Count != 0)
{
result += "," + Environment.NewLine;
result += "\t" + "\"Zones\":[" + Environment.NewLine;
result += "\t\t{" + Environment.NewLine;
int Zcount = 0;
//foreach (Zone z in Zones)
//{
result += "\t\t" + Zones[0].ToJSON();
Zcount++;
if (Zcount != Zones.Count)
//result += ",";
//}
result += "\t\t}" + Environment.NewLine;
result += "\t" + "]" + Environment.NewLine;
}
else
{
result += Environment.NewLine;
}
result += "}";
return result;
}
/// <summary> /// <summary>
/// Checks if the given Rectangle fits in the current zone /// Checks if the given Rectangle fits in the current zone
/// </summary> /// </summary>
Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 720 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 382 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 478 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 497 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 948 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 397 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 645 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 491 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 647 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 894 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 601 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Some files were not shown because too many files have changed in this diff Show More