From d7b477f58d27479afad347822656743951e5f412 Mon Sep 17 00:00:00 2001 From: Fp_Sviat Date: Mon, 18 Nov 2024 14:43:42 +0300 Subject: [PATCH] Implemented the data model and drawing of rectangular hitboxes, IsometricCoordsConverter functions have been transferred to Hitbox class as static, since they are generally needed for hitboxes only --- res/objecttypes.xml | 42 ++++---- src/gui/DrawboxEditor.java | 3 +- src/gui/HitboxRectangleEditor.java | 81 +++++++++++---- src/gui/ListGUI.java | 9 +- src/gui/PropertyFrameAddElement.java | 2 +- src/model/Drawbox.java | 10 +- src/model/Entity.java | 14 +++ src/model/Hitbox.java | 133 ++++++++++++++++++------ src/model/IsometricCoordsConverter.java | 25 ----- src/model/Point.java | 4 + src/repository/Project.java | 1 + 11 files changed, 216 insertions(+), 108 deletions(-) delete mode 100644 src/model/IsometricCoordsConverter.java diff --git a/res/objecttypes.xml b/res/objecttypes.xml index 93b9ada..3d5ddee 100644 --- a/res/objecttypes.xml +++ b/res/objecttypes.xml @@ -1,23 +1,23 @@ - + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/src/gui/DrawboxEditor.java b/src/gui/DrawboxEditor.java index ba85cf3..52b0171 100644 --- a/src/gui/DrawboxEditor.java +++ b/src/gui/DrawboxEditor.java @@ -80,9 +80,10 @@ public class DrawboxEditor extends Editable { entity.setDrawbox(new Drawbox(drawboxPoints)); } - + @Override public void mousePressed(MouseEvent e) { + if(drawboxPoints.size() < 4) { Point p = new Point(e.getX(), e.getY()); drawboxPoints.add(p); diff --git a/src/gui/HitboxRectangleEditor.java b/src/gui/HitboxRectangleEditor.java index 2d6f5f7..a5bd8f5 100644 --- a/src/gui/HitboxRectangleEditor.java +++ b/src/gui/HitboxRectangleEditor.java @@ -3,50 +3,95 @@ package gui; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JPanel; +import javax.swing.JTabbedPane; + +import model.Hitbox; +import model.Point; + public class HitboxRectangleEditor extends Editable { - + Point firstIsoPoint = null; + Point currentIsoPoint = null; + Point firstCartesianPoint = new Point(0,0), currentCartesianPoint = new Point(0,0); + Hitbox nowHitbox = entity.getHitbox(); + HitboxRectangleEditor(ListGUI listGUI) { super(listGUI); - // TODO Auto-generated constructor stub + // TODO Auto-generated cons2tructor stub } @Override public void drawing(Graphics2D g) { - // TODO Auto-generated method stub + if(firstIsoPoint != null) { + int x1,y1,x2,y2; + int size = nowHitbox.getListPointsIso().size(); + for(int i = 0; i < size;i++) { + x1 = (int)nowHitbox.getListPointsIso().get(i % size).x; + y1 = (int)nowHitbox.getListPointsIso().get(i % size).y; + x2 = (int)nowHitbox.getListPointsIso().get((i+1) % size).x; + y2 = (int)nowHitbox.getListPointsIso().get((i+1) % size).y; + g.drawLine(x1, y1, x2, y2); + } + x1 = (int)nowHitbox.getListPointsIso().get(0).x; + y1 = (int)nowHitbox.getListPointsIso().get(0).y; + x2 = (int)nowHitbox.getListPointsIso().get(3).x; + y2 = (int)nowHitbox.getListPointsIso().get(3).y; + g.drawLine(x1, y1, x2, y2); + } } @Override public void saveDataInEntity() { - // TODO Auto-generated method stub - + // saveDataInEntity - сохранение данных в сущности. + //Она нам тут не нужна. + //Все данные и так лежат где необходимо, используя ссылки. } @Override public void mouseClicked(MouseEvent e) { - // TODO Auto-generated method stub - + if(firstIsoPoint == null) { + firstIsoPoint = new Point(currentIsoPoint.x,currentIsoPoint.y); + firstCartesianPoint = Hitbox.isometricToCartesian(firstIsoPoint.x, firstIsoPoint.y,firstCartesianPoint); + }else{ + /* + * В данном месте при нажатии закрепляющей точки, необходимо вызывать функцию, + * которая будет формировать из текущих декартовых координат: + * 1. Точку старта и ширину с высотой. + * 2. Так же необходимо реализовать слушатель сохранения новых хитбоксов в дерево. + * + * */ + + repaint(); + } } @Override public void mouseMoved(MouseEvent e) { - // TODO Auto-generated method stub - + currentIsoPoint.x = e.getX(); + currentIsoPoint.y = e.getY(); + if(firstIsoPoint != null) { + currentCartesianPoint = Hitbox.isometricToCartesian(currentIsoPoint.x, currentIsoPoint.y, currentCartesianPoint); + nowHitbox.getListPointsCartesian().get(0).setXY(firstCartesianPoint.x, firstCartesianPoint.y); + nowHitbox.getListPointsCartesian().get(1).setXY(currentCartesianPoint.x, firstCartesianPoint.y); + nowHitbox.getListPointsCartesian().get(2).setXY(currentCartesianPoint.x, currentCartesianPoint.y); + nowHitbox.getListPointsCartesian().get(3).setXY(firstCartesianPoint.x, currentCartesianPoint.y); + nowHitbox.convertCartesianPointsToIso(); + repaint(); + } } @Override public void actionPerformed(ActionEvent e) { - // TODO Auto-generated method stub - + JTabbedPane parent = (JTabbedPane) getParent(); + if(parent.getSelectedComponent() == this){ + if(entity != null) { + firstIsoPoint = null; + currentIsoPoint = null; + repaint(); + } + } } diff --git a/src/gui/ListGUI.java b/src/gui/ListGUI.java index c703bb5..2a14e5b 100644 --- a/src/gui/ListGUI.java +++ b/src/gui/ListGUI.java @@ -6,6 +6,7 @@ import java.awt.Image; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -91,12 +92,12 @@ public class ListGUI extends JPanel { return (String) list.getSelectedValue(); } + + //ТУТ МОЖЕТ БЫТЬ ТРАБЛ Т,К, СОЗДАНИЕ ХИТБОКСА - ХАРДКОД. Он может быть не только Rectangle public void addListElement(String name,String solid) throws DuplicateEntryException { // плейсхолдеры для новых хитбоксов и дроубоксов, иначе всё валится с NPE - List hitboxPoints = new LinkedList(); - List drawboxPoints = new LinkedList(); - Hitbox hitbox = new Hitbox("Rectangle", hitboxPoints); - Drawbox drawbox = new Drawbox(drawboxPoints); + Hitbox hitbox = new Hitbox(); + Drawbox drawbox = new Drawbox(); // а тут уже создание новой сущности Entity e = new Entity(name, hitbox, drawbox); diff --git a/src/gui/PropertyFrameAddElement.java b/src/gui/PropertyFrameAddElement.java index 204599e..fc7c1e5 100644 --- a/src/gui/PropertyFrameAddElement.java +++ b/src/gui/PropertyFrameAddElement.java @@ -22,7 +22,7 @@ public class PropertyFrameAddElement extends JFrame { ActionListener copyImageToFile; JLabel nameLabel,typeLabel,imageLabel; public PropertyFrameAddElement(ListGUI listGUI) { - + this.setTitle("Add Entity"); this.setLayout(null); this.setSize(400,250); diff --git a/src/model/Drawbox.java b/src/model/Drawbox.java index b02235b..dd5128e 100644 --- a/src/model/Drawbox.java +++ b/src/model/Drawbox.java @@ -4,8 +4,12 @@ import java.util.ArrayList; import java.util.List; public class Drawbox { - private List drawboxlistPoints ;//для прямоугольника дравбокса. - private List baseListPoints ;//2 точки для линии основания + private List drawboxlistPoints = new ArrayList();//для прямоугольника дравбокса. + private List baseListPoints = new ArrayList();//2 точки для линии основания + + public Drawbox(){ + + } public Drawbox(List drawboxlistPoints){ this.drawboxlistPoints = new ArrayList(drawboxlistPoints) ; @@ -15,8 +19,6 @@ public class Drawbox { public Drawbox(String informationDrawbox){ if(informationDrawbox!= null) { - drawboxlistPoints = new ArrayList(); - baseListPoints = new ArrayList(); String[] informations = informationDrawbox.split(" "); parseStringToDrawbox(informations); createBasePoint(); diff --git a/src/model/Entity.java b/src/model/Entity.java index 82786ec..4914c41 100644 --- a/src/model/Entity.java +++ b/src/model/Entity.java @@ -1,21 +1,27 @@ package model; +import java.awt.image.BufferedImage; + public class Entity { private String thisName; private Drawbox thisDrawbox; private Hitbox thisHitbox; private String type; + private BufferedImage thisImage; + //private public Entity(String name,String drawbox,String hitbox) { thisName = new String(name); thisDrawbox = new Drawbox(drawbox); thisHitbox = new Hitbox(hitbox); + thisHitbox.setOwnerEntity(this); } public Entity(String name, Hitbox hitbox, Drawbox drawbox) { this.thisName = name; this.thisHitbox = hitbox; this.thisDrawbox = drawbox; + thisHitbox.setOwnerEntity(this); } public void setName(String outName) { @@ -38,6 +44,10 @@ public class Entity { thisHitbox = outHitbox; }; + public void setImage(BufferedImage outImage) { + thisImage = outImage; + }; + public String getName() { return thisName; }; @@ -50,6 +60,10 @@ public class Entity { return thisHitbox; }; + public BufferedImage getImage() { + return thisImage; + }; + public void PrintEntity() { System.out.println("---------------------"); System.out.println("Name: "+thisName); diff --git a/src/model/Hitbox.java b/src/model/Hitbox.java index de3aa36..ecdea1d 100644 --- a/src/model/Hitbox.java +++ b/src/model/Hitbox.java @@ -5,72 +5,137 @@ import java.util.List; public class Hitbox { private String shape = null;// shape - Форма хитбокса. Понадобится при написании сохранения. Один из параметров в xml-file. - private List listPoints = null;//для прямоугольника - 4 точки. Для круга - надо посмотреть. + private List listPointsIso = new ArrayList(); + private List listPointsCartesian = new ArrayList(); + private Point referencePoint = new Point(0, 0); //Точка отсчета хитбокса, от нее рассчитывается высота+ширина/радиус(при круге) хитбокса. + private float widthHitbox = 0,heightHitbox = 0; // Ширина и высота хитбокса в декартовых координатах. + private float radiusHitbox = 0; + private Entity owner; - public Hitbox(String shape,List listPoints){ - this.shape = new String(shape); - this.listPoints = new ArrayList(listPoints) ; + public Hitbox(){ + initListsPoints(); + } + public Hitbox(String shape,List listPointsIso,List listPointsCartesian){ + this.shape = new String(shape); + this.listPointsIso = listPointsIso; + this.listPointsCartesian = listPointsCartesian; + initListsPoints(); } - public Hitbox(String informationHitbox){ if(informationHitbox!= null) { - listPoints = new ArrayList(); + initListsPoints(); String[] informations = informationHitbox.split(" "); //в 0-м индексе всегда идет название фигуры.Так сделан наш xml. shape = new String(informations[0]); - //заполняем лист точками. Пока что делаю тупо и топорно. Хардкод. Потом можно переделать. if(shape.equals("Rectangle")) { parseStringToRectangleHitbox(informations); + createCartesianPointsFromWidthAndHeigh(); + convertCartesianPointsToIso(); }else if(shape.equals("Circle")) { parseStringToCircleHitbox(informations); - } + } + } + } + + private void initListsPoints() { + if(listPointsIso.size()<1) { + for(int i=0;i<4;i++) { + listPointsIso.add(new Point(0,0)); + } + } + if(listPointsCartesian.size()<1) { + for(int i=0;i<4;i++) { + listPointsCartesian.add(new Point(0,0)); + } } } + private void parseStringToRectangleHitbox(String[] informations) { - //составляем точки по которым строится прямоугольник, и запихиваем их в лист с точками - for(int i = 1;i getListPoints() { - return listPoints; + public List getListPointsIso() { + return listPointsIso; + } + public List getListPointsCartesian() { + return listPointsCartesian; } //not the same as toString()! the latter is for XML while printToConsole() is for console public void printToConsole() { System.out.println(); System.out.println("|||Hitbox:"); - if(shape!=null&&listPoints!=null) { +/* if(shape!=null&&listPoints!=null) { System.out.println("shape: " + shape); for(Point point: listPoints) { System.out.print("("+point.x+";"+point.y+") "); @@ -78,7 +143,7 @@ public class Hitbox { System.out.println(); }else { System.out.println("null"); - } + }*/ } //дописать функцию возвращения listPonts и shape(форма), если будет нужно. // так же при написании функции возвращения нужных координат, надо их сделать целочисленными. diff --git a/src/model/IsometricCoordsConverter.java b/src/model/IsometricCoordsConverter.java deleted file mode 100644 index c7838f0..0000000 --- a/src/model/IsometricCoordsConverter.java +++ /dev/null @@ -1,25 +0,0 @@ -package model; - -public class IsometricCoordsConverter { - - /** - * @param result - Point object to store the result - * @return x and y converted to isometic coords - * */ - public static Point cartesianToIsometric(float cartX, float cartY, Point result) { - result.x = cartX - cartY; - result.y = (cartX + cartY) / 2; - return result; - } - - /** - * @param result - Point object to store the result - * @return x and y converted to cartesian coords - * */ - public static Point isometricToCartesian(float x, float y, Point result) { - result.x = (2 * y + x) / 2; - result.y = (2 * y - x) / 2; - return result; - } - -} diff --git a/src/model/Point.java b/src/model/Point.java index a0221b7..c92d293 100644 --- a/src/model/Point.java +++ b/src/model/Point.java @@ -8,4 +8,8 @@ public class Point { x = mainX; y = mainY; } + public void setXY(float x, float y){ + this.x = x; + this.y = y; + } } diff --git a/src/repository/Project.java b/src/repository/Project.java index 3223def..e163b65 100644 --- a/src/repository/Project.java +++ b/src/repository/Project.java @@ -190,6 +190,7 @@ public class Project implements Iterable, EntityDrawboxChangedListener { if (!imageFile.exists()) throw new FileNotFoundException(); BufferedImage image = ImageIO.read(imageFile); + return image; } catch (FileNotFoundException fe) { logger.warning("Image file \""+path+name+'.'+extension+"\" is not found!");