Compare commits

10 Commits
Author SHA1 Message Date
stammingerpa92423 f8977976b2 Mit Cosmetics 2024-12-18 00:37:36 +01:00
moeckelda95243 ada8284535 16.12.24 22:39 Graphic manschma noch überforderet 2024-12-16 22:40:09 +01:00
Paul-1108 a7efee2023 Puffer Check
Bild Übergabe Check

Noch offen: Merge mit Bildanalyse und Zeichnen

16.12.2024 21:35
2024-12-16 21:36:19 +01:00
Paul-1108 789f9e56f1 Funktionierender Puffer
Bild wird nicht korrekt gespeichert
16.12.2024 16:48
2024-12-16 16:48:48 +01:00
Paul-1108 736154abf4 Funktionierender Puffer
16.12.2024 15.06
Siuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
2024-12-16 15:07:13 +01:00
stammingerpa92423 4e6a0ed98a Puffer Versuch
Speicher läuft voll
16.12.2024 03:30
2024-12-16 03:32:20 +01:00
moeckelda95243 b05c2a8319 Version 13.12 Fehler: getP1 und getP2 geben 0,0 zurück obwohl bis dahin noch richtige Koordinaten in currentPositionP1 -P2 gespeichert sind 2024-12-13 16:30:28 +01:00
Paul-1108 739a7e129c V2.2 des Gameloop und Logic
11.12.24 16:45
2024-12-11 16:46:05 +01:00
Paul-1108 32bad236ed V2 des Gameloop und Logic
sollte gehen
11.12.24 14:13
2024-12-11 14:16:46 +01:00
moeckelda95243 5f211026e4 Version 04.12 "vollständiges Programm mit Fehlern" 2024-12-04 17:07:47 +01:00
15 changed files with 616 additions and 322 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_23" default="true" project-jdk-name="openjdk-23" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" default="true" project-jdk-name="openjdk-23" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+76 -61
View File
@@ -4,9 +4,18 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="4d75e996-cee4-4ec6-b802-5b56d0c0eac4" name="Changes" comment="Version 27.11 (&quot;fertiger&quot; Tracker)">
<list default="true" id="4d75e996-cee4-4ec6-b802-5b56d0c0eac4" name="Changes" comment="Puffer Versuch&#10;Speicher läuft voll&#10;16.12.2024 03:30">
<change afterPath="$PROJECT_DIR$/Welcome0.png" afterDir="false" />
<change afterPath="$PROJECT_DIR$/Welcome1.png" afterDir="false" />
<change afterPath="$PROJECT_DIR$/Welcome2.png" afterDir="false" />
<change afterPath="$PROJECT_DIR$/Welcome3.png" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/Tracker.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/Tracker.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/CamPuffer.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/CamPuffer.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/GameLoop.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/GameLoop.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/GraphicsProgram.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/GraphicsProgram.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/ImgAnalyzer.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/ImgAnalyzer.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/Player.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/Player.java" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -32,41 +41,72 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"Application.GTCar.executor": "Run",
"Application.GraphicsProgram.executor": "Run",
"Application.Tracker.executor": "Run",
"Downloaded.Files.Path.Enabled": "false",
"Repository.Attach.Annotations": "false",
"Repository.Attach.JavaDocs": "false",
"Repository.Attach.Sources": "false",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"com.codeium.enabled": "true",
"git-widget-placeholder": "master",
"kotlin-language-version-configured": "true",
"last_opened_file_path": "C:/Users/david/Documents/Uni/GTCar/opencv/build/java/opencv-4100.jar",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"project.structure.last.edited": "Libraries",
"project.structure.proportion": "0.15",
"project.structure.side.proportion": "0.24022989",
"vue.rearranger.settings.migration": "true"
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;Application.GraphicsProgram.executor&quot;: &quot;Run&quot;,
&quot;Application.Main.executor&quot;: &quot;Run&quot;,
&quot;Application.Tracker.executor&quot;: &quot;Run&quot;,
&quot;Downloaded.Files.Path.Enabled&quot;: &quot;false&quot;,
&quot;Repository.Attach.Annotations&quot;: &quot;false&quot;,
&quot;Repository.Attach.JavaDocs&quot;: &quot;false&quot;,
&quot;Repository.Attach.Sources&quot;: &quot;false&quot;,
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;com.codeium.enabled&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;master&quot;,
&quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;C:/Users/paul3/OneDrive/Dokumente/Studium BME/Semester 3/Interaktion/opencv/build/java/opencv-4100.jar&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;project.structure.last.edited&quot;: &quot;Libraries&quot;,
&quot;project.structure.proportion&quot;: &quot;0.15&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.24022989&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}]]></component>
<component name="RunManager">
<configuration name="GTCar" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="Tracker" />
}</component>
<component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\paul3\OneDrive\Dokumente\Studium BME\Semester 2\Praktikum Programmieren 2 A\Interaktion_GTCaar" />
</key>
</component>
<component name="RunManager" selected="Application.Main">
<configuration name="ImgAnalyzer" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="ImgAnalyzer" />
<module name="GTCar_V2_maven" />
<option name="VM_PARAMETERS" value="-Djava.library.path=C:\Users\david\Documents\Uni\GTCar\opencv\build\java\x64" />
<option name="PROGRAM_PARAMETERS" value="-Djava.library.path=&quot;C:\Users\paul3\OneDrive\Dokumente\Studium BME\Semester 3\Interaktion\opencv\build\java\x64&quot;" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="Main" />
<module name="GTCar_V2_maven" />
<option name="PROGRAM_PARAMETERS" value="-Djava.library.path=&quot;C:\Users\paul3\OneDrive\Dokumente\Studium BME\Semester 3\Interaktion\opencv\build\java\x64&quot;" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<list>
<item itemvalue="Application.Main" />
<item itemvalue="Application.ImgAnalyzer" />
</list>
<recent_temporary>
<list>
<item itemvalue="Application.Main" />
<item itemvalue="Application.ImgAnalyzer" />
</list>
</recent_temporary>
</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-9f38398b9061-39b83d9b5494-intellij.indexing.shared.core-IU-241.15989.150" />
<option value="bundled-js-predefined-1d06a55b98c1-91d5c284f522-JavaScript-IU-241.15989.150" />
</set>
</attachedChunks>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
@@ -77,7 +117,9 @@
<option name="presentableId" value="Default" />
<updated>1732108904989</updated>
<workItem from="1732108906083" duration="758000" />
<workItem from="1732113837570" duration="20534000" />
<workItem from="1732113837570" duration="5187000" />
<workItem from="1734302243298" duration="10745000" />
<workItem from="1734469984979" duration="8232000" />
</task>
<task id="LOCAL-00001" summary="First Commit Test">
<option name="closed" value="true" />
@@ -95,31 +137,7 @@
<option name="project" value="LOCAL" />
<updated>1732118799936</updated>
</task>
<task id="LOCAL-00003" summary="Version 23.11 (Grafics update)">
<option name="closed" value="true" />
<created>1732368525825</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1732368525826</updated>
</task>
<task id="LOCAL-00004" summary="Version 27.11">
<option name="closed" value="true" />
<created>1732703104268</created>
<option name="number" value="00004" />
<option name="presentableId" value="LOCAL-00004" />
<option name="project" value="LOCAL" />
<updated>1732703104268</updated>
</task>
<task id="LOCAL-00005" summary="Version 27.11 (&quot;fertiger&quot; Tracker)">
<option name="closed" value="true" />
<created>1732706211714</created>
<option name="number" value="00005" />
<option name="presentableId" value="LOCAL-00005" />
<option name="project" value="LOCAL" />
<updated>1732706211714</updated>
</task>
<option name="localTasksCounter" value="6" />
<option name="localTasksCounter" value="3" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@@ -139,9 +157,6 @@
<component name="VcsManagerConfiguration">
<MESSAGE value="First Commit Test" />
<MESSAGE value="Version 20.11" />
<MESSAGE value="Version 23.11 (Grafics update)" />
<MESSAGE value="Version 27.11" />
<MESSAGE value="Version 27.11 (&quot;fertiger&quot; Tracker)" />
<option name="LAST_COMMIT_MESSAGE" value="Version 27.11 (&quot;fertiger&quot; Tracker)" />
<option name="LAST_COMMIT_MESSAGE" value="Version 20.11" />
</component>
</project>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

+127
View File
@@ -0,0 +1,127 @@
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.highgui.HighGui;
import org.opencv.videoio.Videoio;
import java.util.LinkedList;
public class CamPuffer implements Runnable {
static {
try {
System.load("C:\\Users\\paul3\\OneDrive\\Dokumente\\Studium BME\\Semester 3\\Interaktion\\GTCar V3\\opencv\\build\\java\\x64\\opencv_java4100.dll");
System.out.println("OpenCV manuell geladen!");
} catch (UnsatisfiedLinkError e) {
System.err.println("Fehler beim Laden der OpenCV-Bibliothek: " + e.getMessage());
}
}
private final int CAM; // Kamera-ID (0 für Webcam, 1 für andere Cams)
private final int EXP; // Belichtungszeit
private final int FPS;
private final int THV;
private volatile boolean running = true;
private final Object lock = new Object(); // Lock für Thread-Sicherheit
private Mat currentMat = new Mat();
private final Rect roi = new Rect(200, 150, 240, 180); // Region of Interest
private boolean hasStartedCapturing = false;
private final LinkedList<Mat> frameBuffer = new LinkedList<>();
private final int MAX_BUFFER_SIZE = 10; // Maximale Anzahl an Bildern im Puffer
public CamPuffer(int CAM, int EXP, int FPS, int THV) {
this.CAM = CAM;
this.EXP = EXP;
this.FPS = FPS;
this.THV = THV;
}
@Override
public void run() {
VideoCapture capture = setUp();
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
return;
}
Mat frame = new Mat();
capture.read(frame);
hasStartedCapturing = true;
long lastGcTime = System.currentTimeMillis();
try {
while (running) {
//long startTime = System.currentTimeMillis();
capture.read(frame); // Bild einlesen
currentMat = frame;
if (frame.empty()) {
System.out.println("Fehler: Kein Bild von der Kamera erhalten.");
break;
}
updateCurrentMat(frame);
// Speicherbereinigung alle 1000 ms (1 Sekunde)
if (System.currentTimeMillis() - lastGcTime > 1000) {
System.gc(); // Triggern des Garbage Collectors
lastGcTime = System.currentTimeMillis();
//System.out.println("Garbage Collection durchgeführt.");
}
}
} finally {
// Matrizen explizit freigeben
frame.release();
capture.release();
}
}
public void updateCurrentMat(Mat img) {
Mat frameCopy = img.clone();
synchronized (frameBuffer) {
if (frameBuffer.size() >= MAX_BUFFER_SIZE) {
frameBuffer.poll().release(); // Ältesten Frame entfernen
}
frameBuffer.add(frameCopy); // Neuen Frame hinzufügen
currentMat = frameCopy;
}
}
public Mat getCurrentMat() {
synchronized (frameBuffer) {
if (!frameBuffer.isEmpty()) {
return frameBuffer.pollLast().clone(); // Rückgabe des neuesten Frames
}
}
return new Mat(); // Rückgabe eines leeren Frames, falls der Puffer leer ist
}
public void stop() {
running = false;
}
private VideoCapture setUp() {
System.out.println("Laden von OpenCV");
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture capture = new VideoCapture(CAM);
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
}
capture.set(Videoio.CAP_PROP_BUFFERSIZE, 3);
capture.set(Videoio.CAP_PROP_EXPOSURE, EXP);
capture.set(Videoio.CAP_PROP_FPS, FPS);
System.out.println("Kamera geöffnet und eingerichtet");
return capture;
}
}
+51 -12
View File
@@ -1,21 +1,60 @@
import processing.core.PApplet;
import java.awt.*;
import java.util.LinkedList;
import java.util.Queue;
public class GameLogic {
public class GameLogic extends PApplet {
private final int width;
private final int height;
private int[][] pitch;
public GameLogic(int width, int height){
this.width = width;
this.height = height;
pitch = new int[width][height];
public static void main(String[] args) {
PApplet.main("GameLogic");
}
public boolean checkPlayer(Point point, int id){
return false;
private static final int MAX_TRAIL_SIZE = 100; // Maximale Größe des Trails
private Queue<int[]> trail = new LinkedList<>();
private Point testPoint = new Point(200, 200);
public void settings() {
size(800, 600);
}
public void setup() {
fillTrail(); // Beispielpfad erstellen
noLoop(); // Zeichnen nur bei Bedarf
}
private void fillTrail() {
// Beispielhafte Füllung der Spur (maximale Größe beachten)
for (int i = 0; i < MAX_TRAIL_SIZE; i++) {
trail.add(new int[]{50 + i * 5, 300}); // Punkte entlang der x-Achse
}
}
// Methode zum Hinzufügen eines neuen Punkts, begrenzt auf MAX_TRAIL_SIZE
public void addToTrail(int x, int y) {
if (trail.size() >= MAX_TRAIL_SIZE) {
trail.poll(); // Entferne das älteste Element, wenn die maximale Größe erreicht ist
}
trail.add(new int[]{x, y});
}
public boolean doCheckExtern(Queue<int[]> trail, Point point) {
return doCheck(trail, point);
}
public boolean doCheck(Queue<int[]> trail, Point point) {
int particleSize = 10;
// Zeichne den Pfad auf das Canvas nur, wenn nötig
background(255); // Weißer Hintergrund
for (int[] coordinates : trail) {
int x = coordinates[0];
int y = coordinates[1];
fill(0); // Schwarz
rect(x, y, particleSize, particleSize);
}
// Überprüfe die Pixelwerte am Testpunkt
int c = get(point.x, point.y); // Farbwert abrufen
return (c == color(0)); // Schwarz bedeutet Kollision
}
}
+43 -57
View File
@@ -1,13 +1,24 @@
import org.opencv.highgui.HighGui;
import processing.core.PApplet;
import java.awt.Point;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Thread.sleep;
public class GameLoop {
int activePlayer = 0;
Tracker tracker;
private final int CAM = 0; // Kamera-ID (0 für Webcam, 1 für andere Cams)
private final int EXP = -8; // Belichtungszeit (idealerweise: 0)
private final int FPS = 20; // FPS
private final int THV = 240;
private final int TRAIL_LENGTH = 50;
ImgAnalyzer tracker;
CamPuffer camPuffer;
GraphicsProgram graphics;
@@ -17,73 +28,48 @@ public class GameLoop {
Player player2;
public GameLoop(){
player1 = new Player(0, "ip", 9000);
player2 = new Player(1, "ip", 9000);
tracker = new Tracker();
player1 = new Player(0, TRAIL_LENGTH);
player2 = new Player(1, TRAIL_LENGTH);
camPuffer = new CamPuffer(CAM, EXP, FPS, THV);
Thread pufferThread = new Thread(camPuffer);
pufferThread.start();
graphics = new GraphicsProgram();
String[] args = {"GraphicsProgram"};
PApplet.runSketch(args, graphics);
gl = new GameLogic(1080,720);
tracker = new ImgAnalyzer(camPuffer, THV, graphics);
Thread trackerThread = new Thread(tracker::run);
trackerThread.start();
/*
gl = new GameLogic();
String[] args_ = {"GameLogic"};
PApplet.runSketch(args_, gl); */
run();
}
private void run(){
while(camPuffer.getCurrentMat().elemSize() == 0){
System.out.println("Camera booting up");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
graphics.nextGameState();
//Hier kommt Morphing rein
graphics.nextGameState();
while(true){
communicate();
List<Point> positions = track();
if(checkP1(positions.get(0))){
break;
}
if(checkP2(positions.get(1))){
break;
}
addPositions(positions);
draw();
}
}
private void communicate() {
//offen für Auto Kommunikation
}
private boolean checkP1(Point point){
if(gl.checkPlayer(point, 0)){
return true;
}
else {
return false;
}
}
private boolean checkP2(Point point){
if(gl.checkPlayer(point, 0)){
return true;
}
else {
return false;
}
}
private void addPositions(List positions){
}
private List<Point> track(){
Point p1 = tracker.getP1();
Point p2 = tracker.getP2();
player1.setKoords(p1.x, p1.y);
player2.setKoords(p2.x, p2.y);
List<Point> output = new ArrayList<>();
output.set(0, p1);
output.add(p2);
return output;
}
private void draw(){
graphics.drawTrail(player1.getTrail(), 0);
graphics.drawTrail(player2.getTrail(), 1);
}
}
+139 -28
View File
@@ -2,49 +2,160 @@ import processing.core.PApplet;
import processing.core.PImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
public class GraphicsProgram extends PApplet {
PImage imgBlue;
PImage imgRed;
private LinkedList<int[]> player1Trail = new LinkedList<>(); // Liste für Spieler 1
private LinkedList<int[]> player2Trail = new LinkedList<>(); // Liste für Spieler 2
private final int TRAIL_LENGTH = 150;
private int trailCounter = 17;
private int distanceTh = 100;
private int gameState = 0; //0 für Welcome, 1 für Morphing, 2 für Game, 3 für Gameover
private float startingTime = System.currentTimeMillis();
PImage img1;
PImage img2;
PImage backgroundImage;
LinkedList<PImage> cameraLoadingImages = new LinkedList<>();
public static void main(String[] args) {
PApplet.main("GraficsProgram");
PApplet.main("GraphicsProgram");
}
public void settings() {
size(800, 600);
imgBlue = loadImage("TrailBlue");
imgRed = loadImage("TrailRed");
fullScreen();
}
public void setup() {
backgroundImage = loadImage("Background.png");
backgroundImage.resize(1792, 1024);
img1 = loadImage("TrailBlue.png");
img2 = loadImage("TrailRed.png");
cameraLoadingImages.add(loadImage("Welcome0.png"));
cameraLoadingImages.add(loadImage("Welcome1.png"));
cameraLoadingImages.add(loadImage("Welcome2.png"));
cameraLoadingImages.add(loadImage("Welcome3.png"));
}
public void draw() {
if (gameState == 0) {
drawWelcome();
}
if (gameState == 1) {
setUpMorphing();
}
if (gameState == 2) {
gameScreen();
}
if (gameState == 3) {
gameOverScreen();
}
}
public void drawWelcome() {
int waitingTime = (int) (System.currentTimeMillis() / 1000);
switch (waitingTime % 4) {
case 0:
image(cameraLoadingImages.get(0), 0, 0);
break;
case 1:
image(cameraLoadingImages.get(1), 0, 0);
break;
case 2:
image(cameraLoadingImages.get(2), 0, 0);
break;
case 3:
image(cameraLoadingImages.get(3), 0, 0);
}
}
private void setUpMorphing() {
}
private void gameScreen() {
image(backgroundImage, 0, 0); // Hintergrund zeichnen
strokeWeight(20); // Linienstärke festlegen
// Linien für Spieler 1 zeichnen
stroke(0, 0, 255); // Blau
drawTrail(player1Trail, 1);
// Linien für Spieler 2 zeichnen
stroke(255, 0, 0); // Rot
drawTrail(player2Trail, 2);
}
private void gameOverScreen() {
}
public void nextGameState() {
gameState++;
}
// Methode, um Linien für eine gegebene Trail-Liste zu zeichnen
private void drawTrail(LinkedList<int[]> trail, int player) {
if (trail.size() < 4) return; // Mindestens 2 Punkte nötig, um Linien zu zeichnen
for (int i = 0; i < trail.size() - 1; i++) {
if (player == 1){
stroke(170-(255/trail.size() * i),0,255/2 + (255/trail.size() * i)/2);
} else if (player == 2){
stroke(255, 170-(255/trail.size() * i), 0);
}
int[] current = new int[2];
try {
current = trail.get(i);
} catch (NullPointerException e) {
System.out.println("Index 1 out of bounds");
continue;
}
int[] next = new int[2];
try {
next = trail.get(i + 1);
} catch (NullPointerException e) {
System.out.println("Index 2 out of bounds");
continue;
}
// Null-Check für die Punkte
if (current != null && next != null) {
if (current[0] - next[0] > -distanceTh && current[0] - next[0] < distanceTh && current[1] - next[1] > -distanceTh && current[1] - next[1] < distanceTh) {
line(current[0], current[1], next[0], next[1]);
}
}
}
}
public void drawTrail(Queue<int[]> trail, int playerID){
int particleSize = 5;
background(255);
for (int[] koordinates : new LinkedList<>(trail)) {
int x = koordinates[0];
int y = koordinates[1];
if(playerID == 0){
image(imgBlue, x, y, particleSize, particleSize);
} else if (playerID == 1) {
image(imgRed, x, y, particleSize, particleSize);
}else{
fill(0, 255, 0);
rect(x, y, particleSize, particleSize);
// Methode zum Aktualisieren der Trails für beide Spieler
public void updateTrail(int x1, int y1, int x2, int y2) {
if (x1 >= 0 && y1 >= 0) {
addToTrail(player1Trail, x1, y1);
}
if (x2 >= 0 && y2 >= 0) {
addToTrail(player2Trail, x2, y2);
}
particleSize ++;
}
// Methode zum Hinzufügen eines Punktes zur Trail-Liste und Begrenzung auf 20 Einträge
private void addToTrail(LinkedList<int[]> trail, int x, int y) {
if (trailCounter % 7 == 0) {
if (x >= 0 && y >= 0) {
trail.add(new int[]{x, y});
if (trail.size() > TRAIL_LENGTH) {
trail.removeFirst();
}
}
}
trailCounter++;
}
public void drawEvent(){
}
}
+157
View File
@@ -0,0 +1,157 @@
import org.opencv.core.*;
import org.opencv.videoio.VideoCapture;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.videoio.Videoio;
import processing.core.PApplet;
import java.util.*;
import java.awt.Point;
public class ImgAnalyzer {
private final int THV; // Threshold
private Point currentPositionP1 = new Point(0, 0);
private Point currentPositionP2 = new Point(0, 0);
Queue<int[]> trails = new LinkedList<>();
private final int TRAIL_LENGTH = 90;
private final CamPuffer camPuffer;
private GraphicsProgram playerGraphics;
public ImgAnalyzer(CamPuffer cP, int threshold, GraphicsProgram graphicsProgram) {
THV = threshold;
camPuffer = cP;
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
playerGraphics = graphicsProgram;
}
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public void run() {
/*
while (camPuffer.getCurrentMat().elemSize() == 0) {
System.out.println("Warten auf das erste Bild...");
try {
Thread.sleep(3000); // Kurze Pause, um CPU-Belastung zu vermeiden
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
*/
Mat currentImg = new Mat();
Mat grayFrame = new Mat();
Mat thresholdFrame = new Mat();
while (true) {
try {
currentImg = camPuffer.getCurrentMat();
if(currentImg.elemSize() != 0) {
// In Graustufen konvertieren
Imgproc.cvtColor(currentImg, grayFrame, Imgproc.COLOR_BGR2GRAY);
// Threshold anwenden
Imgproc.threshold(grayFrame, thresholdFrame, THV, 255, Imgproc.THRESH_BINARY);
//Ausgabe des Bildes zum Prüfen
HighGui.imshow("ThunfischHighGui", thresholdFrame);
HighGui.waitKey(1);
//Ende Bildausgabe */
}
} catch (Exception e) {
}
if (currentImg != null) {
List<Point> positions = trackPositions(thresholdFrame);
if (positions.size() >= 2) {
currentPositionP1 = positions.get(0);
currentPositionP2 = positions.get(1);
//System.out.println("currentPositionP1: " + currentPositionP1 + " currentPositionP2: " + currentPositionP2);
}
trails.add(new int[]{currentPositionP1.x, currentPositionP1.y, currentPositionP2.x, currentPositionP2.y});
if(trails.size() > TRAIL_LENGTH){
trails.poll();
}
playerGraphics.updateTrail(currentPositionP1.x, currentPositionP1.y, currentPositionP2.x, currentPositionP2.y);
//playerGraphics.draw();
}
/*org.opencv.core.Point pp1 = new org.opencv.core.Point(currentPositionP1.x, currentPositionP1.y);
Imgproc.circle(currentImg, pp1, 10, new Scalar(255,0,0), -1);
org.opencv.core.Point pp2 = new org.opencv.core.Point(currentPositionP2.x, currentPositionP2.y);
Imgproc.circle(currentImg, pp2, 10, new Scalar(0,0,255), -1);
if(currentImg.elemSize() != 0) {
HighGui.imshow("el thunfisch", currentImg);
} */
}
}
private List<Point> trackPositions(Mat thresholdFrame) {
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
// Finde Konturen
Imgproc.findContours(thresholdFrame, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Liste für die Positionen und zugehörige Pixelanzahl
List<Point> positions = new ArrayList<>();
List<Double> whitePixelCounts = new ArrayList<>();
for (MatOfPoint contour : contours) {
Moments moments = Imgproc.moments(contour);
if (moments.get_m00() != 0) {
// Berechne den Mittelpunkt der Kontur
int cx = (int) (moments.get_m10() / moments.get_m00());
int cy = (int) (moments.get_m01() / moments.get_m00());
// Berechne die Anzahl der weißen Pixel in der Kontur
Mat mask = Mat.zeros(thresholdFrame.size(), CvType.CV_8UC1);
Imgproc.drawContours(mask, List.of(contour), 0, new Scalar(255), -1); // Fülle die Kontur mit Weiß
double whitePixels = Core.sumElems(mask).val[0] / 255.0; // Summe der Pixelwerte durch 255 (1 Pixel = 255)
// Speichere Position und Pixelanzahl
positions.add(new Point(cx, cy));
whitePixelCounts.add(whitePixels);
}
}
// Sortiere die Positionen basierend auf der Anzahl weißer Pixel (absteigend)
List<Point> sortedPositions = new ArrayList<>();
while (!whitePixelCounts.isEmpty()) {
int maxIndex = whitePixelCounts.indexOf(Collections.max(whitePixelCounts));
sortedPositions.add(positions.get(maxIndex));
positions.remove(maxIndex);
whitePixelCounts.remove(maxIndex);
}
// Gib die Positionen der zwei größten Konturen zurück
return sortedPositions.subList(0, Math.min(sortedPositions.size(), 2));
}
public synchronized Point getP1() {
return currentPositionP1;
}
public Point getP2() {
return currentPositionP2;
}
}
+3
View File
@@ -1,2 +1,5 @@
public class Main {
public static void main(String[] args){
GameLoop gl = new GameLoop();
}
}
+16 -25
View File
@@ -1,3 +1,4 @@
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
@@ -6,51 +7,41 @@ public class Player {
private final int ID;
private int x;
private int y;
private final int TRAIL_LENGTH;
Queue<int[]> trail = new LinkedList<>();
ArduinoCommunication arduinoCommunicator;
private final int TRAIL_LENGTH = 30;
// Konstruktor
public Player(int id, String finalIpAddress, int finalPortNr) {
public Player(int id, int trailLength) {
this.ID = id;
arduinoCommunicator = new ArduinoCommunication(finalIpAddress, finalPortNr);
this.TRAIL_LENGTH = trailLength;
trail.add(new int[]{0,0});
}
public int getX(){
return x;
}
//fügt 2 Koordinaten zum Trail hinzu nd verhindert, dass dieser zulang wird
public int getY(){
return y;
}
//fügt 2 Koordinaten zum Trail hinzu und verhindert, dass dieser zu lang wird
public void setKoords(int x, int y){
addToTrail(x,y);
this.x = x;
this.y = y;
}
private void addToTrail(int x, int y) {
this.trail.add(new int[]{x, y});
if(trail.size() > TRAIL_LENGTH){
trail.poll();
trail.add(new int[]{x, y});
if (trail.size() > TRAIL_LENGTH) {
trail.poll(); // Entfernt das älteste Element
}
}
public Queue<int[]> getTrail(){
return trail;
}
public void sendToCar(int light, double steer, double speed){
arduinoCommunicator.sendMessage(light, steer, speed);
}
//gibt aktuelle Position aus
public void printPosition() {
System.out.println(trail);
}
}
-135
View File
@@ -1,135 +0,0 @@
import org.opencv.core.*;
import org.opencv.videoio.VideoCapture;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.videoio.Videoio;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Comparator;
public class Tracker {
private final int CAM = 1; // Kamera-ID (0 für Webcam, 1 für andere Cams)
private final int EXP = 0; // Belichtungszeit (idealerweise: 0)
private final int FPS = 60; // FPS
private final int THV = 250;
private Point currentPositionP1 = new Point(0, 0);
private Point currentPositionP2 = new Point(0, 0);
public Tracker() {}
public static void main(String[] args) {
Tracker tracker = new Tracker();
tracker.run();
}
private void run() {
VideoCapture capture = setUp();
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
return;
}
Mat frame = new Mat();
Mat grayFrame = new Mat();
Mat thresholdFrame = new Mat();
while (true) {
if (capture.read(frame)) {
// Konvertiere in Graustufen und wende Threshold an
Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(grayFrame, thresholdFrame, THV, 255, Imgproc.THRESH_BINARY);
// Tracke die Positionen der beiden größten Objekte
List<Point> positions = trackPositions(thresholdFrame);
if (positions.size() >= 2) {
currentPositionP1 = positions.get(0);
currentPositionP2 = positions.get(1);
System.out.println("P1 - X: " + currentPositionP1.x + " Y: " + currentPositionP1.y + " P2 - X: " + currentPositionP2.x + " Y: " + currentPositionP2.y);
}
drawMarkers(frame);
HighGui.imshow("GTCar", frame);
if (HighGui.waitKey(1) == 27) {
break;
}
} else {
System.out.println("Fehler: Das Kamerabild konnte nicht gelesen werden.");
break;
}
}
}
private List<Point> trackPositions(Mat thresholdFrame) {
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
// Finde Konturen
Imgproc.findContours(thresholdFrame, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Sortiere Konturen nach Fläche (absteigend)
contours.sort((c1, c2) -> Double.compare(Imgproc.contourArea(c2), Imgproc.contourArea(c1)));
// Speichere die Positionen der zwei größten Konturen
List<Point> positions = new ArrayList<>();
for (int i = 0; i < Math.min(contours.size(), 2); i++) {
Moments moments = Imgproc.moments(contours.get(i));
if (moments.get_m00() != 0) {
int cx = (int) (moments.get_m10() / moments.get_m00());
int cy = (int) (moments.get_m01() / moments.get_m00());
positions.add(new Point(cx, cy));
}
}
return positions;
}
private void drawMarkers(Mat frame) {
// Größe der Quadrate
int size = 10;
// Blaues Quadrat an currentPositionP1
if (currentPositionP1 != null) {
Point topLeftP1 = new Point(currentPositionP1.x - size, currentPositionP1.y - size);
Point bottomRightP1 = new Point(currentPositionP1.x + size, currentPositionP1.y + size);
Imgproc.rectangle(frame, topLeftP1, bottomRightP1, new Scalar(255, 0, 0), -1); // Blau, gefüllt
}
// Rotes Quadrat an currentPositionP2
if (currentPositionP2 != null) {
Point topLeftP2 = new Point(currentPositionP2.x - size, currentPositionP2.y - size);
Point bottomRightP2 = new Point(currentPositionP2.x + size, currentPositionP2.y + size);
Imgproc.rectangle(frame, topLeftP2, bottomRightP2, new Scalar(0, 0, 255), -1); // Rot, gefüllt
}
}
private VideoCapture setUp() {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture capture = new VideoCapture(CAM);
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
}
capture.set(Videoio.CAP_PROP_EXPOSURE, EXP);
capture.set(Videoio.CAP_PROP_FPS, FPS);
return capture;
}
}