Compare commits

...

22 Commits

Author SHA1 Message Date
669d26f595 Fixed a bug with opening a file when an entity-item was selected 2026-04-10 13:25:38 +03:00
fd488d8c9e Added functionality to check whether changed data is saved when exiting the program 2026-04-10 12:04:01 +03:00
54dbfbabf4 Parsing data for drawing Rectangle Hitbox 2026-04-09 17:55:17 +03:00
55aab3cac0 Save actual Rectengle Hitbox Data 2026-04-09 17:29:59 +03:00
f43795e1f4 Circle Hitbox functionality is fully ready. It must be done Rectangle Hitbox. 2026-04-08 17:10:49 +03:00
7e09343035 working on parsing ReferencePoint into CurrentIsoPoint 2026-04-07 17:35:30 +03:00
0545adee2a Ready to draw and save round hitboxes. It is necessary to complete the correct loading of round hitbox data 2026-04-03 17:59:08 +03:00
27bbcee37a Trying to write the correct formulas for drawing round hitboxes 2026-04-02 18:05:07 +03:00
58550ae93a Refactoring ClearButton. Made by drawing CircleHitbox. Need to finish doing HitboxCircleRenderingFunction and saving hitboxCircle when you put the second point 2026-04-01 18:20:08 +03:00
6665199d12 Added the function of drawing rectangular hitboxes, as well as the ability to erase and save the result. Drawing in any direction. 2026-03-29 23:14:42 +03:00
2686d036cf Added the function of drawing rectangular hitboxes, as well as the ability to erase and save the result. You need to draw from left to right 2026-03-29 22:47:57 +03:00
a0a69c3587 Working version of the refactoring DrawboxEditor. Added ToolBar in Editor 2026-03-24 17:19:32 +03:00
ab30acd69a Refactoring EditableCanvas in DrawboxEditable and other classes 2026-03-23 15:07:55 +03:00
3b81412eb2 New hitbox architecture. But need change function addListElement in class ListGUI and load in class Project 2025-06-18 00:28:19 +03:00
f5bd320061 New architecture of classes for switching the drawing modes of hitboxes/Dravboxes of entities 2025-03-27 01:41:22 +03:00
a929f86461 Working dynamic GUI layout 2025-01-05 19:06:41 +03:00
abbc64eead Fix hitbox. Nothing worked, now it is. 2024-12-01 23:26:50 +03:00
ce113cb96d Hitbox edits for new Entity fields 2024-11-19 15:06:53 +03:00
128948051e Merging hitbox-drawing and dev. Adding BufferedImage to Entity. Refactoring Entity parsing in to the Project and download ListGUI 2024-11-18 15:29:14 +03:00
d7b477f58d 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 2024-11-18 14:43:42 +03:00
3943a9a490 fix errors after code review, added entity height and width properties for inner editor use 2024-11-12 17:08:51 +07:00
6062a8e0d5 removed unnecessary Drawbox getter accidentally generated by IDE 2024-11-12 15:38:19 +07:00
38 changed files with 1191 additions and 562 deletions

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk-19">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-22">
<attributes>
<attribute name="module" value="true"/>
</attributes>

View File

@ -1,8 +1,9 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=15
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=22
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=15
org.eclipse.jdt.core.compiler.compliance=22
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
@ -11,4 +12,4 @@ org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=15
org.eclipse.jdt.core.compiler.source=22

BIN
res/.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 KiB

BIN
res/NewHueta.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 867 B

BIN
res/NewName.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 539 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
res/destroy1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
res/iloveimg-resized.zip Normal file

Binary file not shown.

BIN
res/newtest.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

View File

@ -1,23 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<objecttypes>
<objecttype name="misato" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="2 1 254 1 254 338 2 336"/>
<property name="hitbox" type="string" default="Circle 4 6 24"/>
</objecttype>
<objecttype name="starlight" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="2 1 253 1 254 468 2 490"/>
<property name="hitbox" type="string" default="Rectangle 0 0 76 119"/>
</objecttype>
<objecttype name="tavern" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="3 2 252 1 253 605 6 608"/>
<property name="hitbox" type="string" default="Rectangle 0 0 96 98"/>
</objecttype>
<objecttype name="TopHome" color="#a0a0a4">
<property name="class" type="string" default="Solid"/>
<property name="drawbox" type="string" default="3 2 252 1 253 605 6 608"/>
<property name="hitbox" type="string" default="Rectangle 0 0 96 98"/>
</objecttype>
<objecttype color="#a0a0a4" name="misato">
<property default="Solid" name="class" type="string"/>
<property default="3 4 197 3 168 191 72 189 " name="drawbox" type="string"/>
<property default="Circle -19 11 40" name="hitbox" type="string"/>
</objecttype>
<objecttype color="#a0a0a4" name="starlight">
<property default="Solid" name="class" type="string"/>
<property default="4 3 162 9 129 121 53 140 " name="drawbox" type="string"/>
<property default="Circle 14 3 28" name="hitbox" type="string"/>
</objecttype>
<objecttype color="#a0a0a4" name="tavern">
<property default="Solid" name="class" type="string"/>
<property default="93 47 303 55 245 301 90 286 " name="drawbox" type="string"/>
<property default="Rectangle 4036 2332 271 201" name="hitbox" type="string"/>
</objecttype>
<objecttype color="#a0a0a4" name="TopHome">
<property default="Solid" name="class" type="string"/>
<property default="3 2 252 1 253 605 6 608" name="drawbox" type="string"/>
<property default="Rectangle 2212 1964 183 31" name="hitbox" type="string"/>
</objecttype>
<objecttype color="000000" name="newtest">
<property default="solid" name="class" type="string"/>
<property default="252 116 505 120 500 247 235 237 " name="drawbox" type="string"/>
<property default="Circle 578 671 15" name="hitbox" type="string"/>
</objecttype>
</objecttypes>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 755 B

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
res/square1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@ -0,0 +1,18 @@
package events;
import model.Entity;
import model.Hitbox;
/*
* Structure-like class no getters
*/
public class EntityHitboxChangedEvent {
public Hitbox hitbox;
//storing entity object instead of just entity name will allow to get entity data without extra calls
public Entity owner;
public EntityHitboxChangedEvent(Hitbox hitbox, Entity owner) {
this.hitbox = hitbox;
this.owner = owner;
}
}

View File

@ -0,0 +1,7 @@
package events;
public interface EntityHitboxChangedListener {
void hitboxChanged(EntityHitboxChangedEvent event);
}

View File

@ -1,5 +1,6 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
@ -16,152 +17,25 @@ import javax.swing.JTabbedPane;
import events.EntityDrawboxChangedEvent;
import events.EntityDrawboxChangedListener;
import gui.render.DrawboxRectengleRenderingFunction;
import model.Drawbox;
import model.Point;
import repository.Project;
public class DrawboxEditor extends Editable {
private List<Point> drawboxPoints;
private List<Point> basePoints;
Logger logger = Logger.getLogger("gui.DrawboxRectangleEditor");
Point currentPoint = new Point(0, 0);
private List<EntityDrawboxChangedListener> listeners = new ArrayList<>();
DrawboxEditor(ListGUI listGUI) {
super(listGUI);
canvas = new EditableCanvas();
add(canvas);
//canvas.setBackground(Color.GRAY);
canvas.setDrawboxRectengleRenderingFunction();
canvas.setVisible(true);
logger.setLevel(Level.CONFIG);
}
@Override
public void drawing(Graphics2D g) {
Drawbox drawbox = entity.getDrawbox();
drawboxPoints = drawbox.getDrawboxlistPoints();
basePoints = drawbox.getbaseListPoints();
logger.finest("drawbox point size: "+ drawboxPoints.size());
for(Point p: drawboxPoints)
logger.finest("DrawBoxPoint: ["+ p.x + ":"+p.y+"]");
for(Point p: basePoints)
logger.finest("BasePoint: ["+ p.x + ":"+p.y+"]");
if(drawboxPoints.size() >= 1 && drawboxPoints.size() < 4) {
Point lastPoint = drawboxPoints.get(drawboxPoints.size()-1);
g.drawLine((int)lastPoint.x, (int)lastPoint.y, (int)currentPoint.x, (int)currentPoint.y);
for(int i = 0; i < drawboxPoints.size()-1;i++) {
int x1 = (int)drawboxPoints.get(i).x;
int y1 = (int)drawboxPoints.get(i).y;
int x2 = (int)drawboxPoints.get(i+1).x;
int y2 = (int)drawboxPoints.get(i+1).y;
g.drawLine(x1, y1, x2, y2);
}
} else {
for(int i = 0; i < drawboxPoints.size();i++) {
int x1 = (int)drawboxPoints.get(i % drawboxPoints.size()).x;
int y1 = (int)drawboxPoints.get(i % drawboxPoints.size()).y;
int x2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).x;
int y2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).y;
g.drawLine(x1, y1, x2, y2);
}
// ОТРИСОВКА ОСНОВАНИЯ
g.setColor(Color.BLUE);
for(int i = 0; i < basePoints.size()-1;i++) {
int x1 = (int)basePoints.get(i).x;
int y1 = (int)basePoints.get(i).y;
int x2 = (int)basePoints.get(i+1).x;
int y2 = (int)basePoints.get(i+1).y;
g.drawLine(x1, y1+3, x2, y2+3);
}
}
}
@Override
public void saveDataInEntity() {
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);
if(drawboxPoints.size() == 4) {
sortingDrawboxPoints();
saveDataInEntity();
//при выборе 4-й точки и формировании данных drawbox, уведомляем всех подписчит
if(listeners!=null) {
notifySubscribers();
}
}
}
}
/*Точки должны идти в определенном порядке:
* левая верхняя точка, правая верхняя, нижняя правая, нижняя левая;
* Обе нижние точки, т.е. 3 и 4 являются основанием - хардкод.
* P.s. возможно это не критично, и в сторе предусмотрено, что бы они сортировались,
* но на данном этапе на всякий случай стоит так поступить*/
private void sortingDrawboxPoints() {
//окей, это написано плохо, но... Похуй, пляшем)
Collections.sort(
drawboxPoints,
(point1, point2) -> Float.compare(point1.y, point2.y)
);
if(drawboxPoints.get(0).x>drawboxPoints.get(1).x) {
Collections.swap(drawboxPoints, 0, 1);
}
if(drawboxPoints.get(2).x<drawboxPoints.get(3).x) {
Collections.swap(drawboxPoints, 2, 3);
}
/*Багтест, проверка очередности построения точек
*
* System.out.println("_______________");
int i = 0;
for (Point point : drawboxPoints) {
System.out.println("Point["+i+"]: ("+point.x+" ; "+point.y+");");
i++;
}*/
}
@Override
public void mouseMoved(MouseEvent e) {
currentPoint.x = e.getX();
currentPoint.y = e.getY();
repaint();
}
public void subscribe(EntityDrawboxChangedListener listener) {
listeners.add(listener);
}
public void unsubscribe(EntityDrawboxChangedListener listener) {
listeners.remove(listener);
}
private void notifySubscribers() {
for (EntityDrawboxChangedListener listener : listeners) {
listener.drawboxChanged(
new EntityDrawboxChangedEvent(entity.getDrawbox(), entity)
);
}
}
// эта штука очищает точки при нажатии универскальной кнопки очистки в Main GUI. Это следует рефакторнуть и вместо передачи события сюда,
// обрабатывать его прямо в Main GUI(лямбдой) вызывая отсюда только метод в духе clearPoints()
@Override
public void actionPerformed(ActionEvent e) {
JTabbedPane parent = (JTabbedPane) getParent();
if(parent.getSelectedComponent() == this){
if(entity != null) {
entity.getDrawbox().getDrawboxlistPoints().clear();
entity.getDrawbox().getbaseListPoints().clear();
repaint();
}
}
}
}

View File

@ -1,7 +1,7 @@
package gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
@ -10,46 +10,51 @@ import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import model.Entity;
import repository.Project;
public abstract class Editable extends JPanel implements MouseListener, MouseMotionListener, ListSelectionListener, ActionListener {
public abstract class Editable extends JPanel implements ListSelectionListener {
protected ListGUI listGUI;
protected Entity entity;
protected String selectedEntityName;
protected BufferedImage image;
JPanel drawPanel;
EditableCanvas canvas;
JToolBar toolbar = new JToolBar("Toolbar",JToolBar.VERTICAL);
JButton clearLinesJButton;
private static Logger logger = Logger.getLogger("gui.Editable");
Editable(ListGUI listGUI){
this.listGUI = listGUI;
setLayout(new BorderLayout());
addMouseListener(this);
addMouseMotionListener(this);
clearLinesJButton = createButton("Clear lines",null,"res/destroy.png");
clearLinesJButton.addActionListener((e)->{
canvas.renderingFunction.functionClearJButton();
canvas.repaint();
});
toolbar.setBorder(BorderFactory.createLoweredBevelBorder());
toolbar.addSeparator();
toolbar.add(clearLinesJButton);
this.add(toolbar,BorderLayout.EAST);
toolbar.setPreferredSize(new Dimension(40,40));
// РАСКОММЕНТИТЬ ЕСЛИ НУЖНО ВЫВОДИТЬ ПОДРОБНЫЕ ЛОГИ
logger.setLevel(Level.ALL);
}
//Абстрактные методы
public abstract void drawing(Graphics2D g);
public abstract void saveDataInEntity();
//методы родительского класса Editable
//get,set для name
public String getName() {
return selectedEntityName;
}
@ -58,35 +63,11 @@ public abstract class Editable extends JPanel implements MouseListener, MouseMot
this.selectedEntityName = name;
}
//заполнить текущую сущность по имени.
public void setEntityByName(String name) throws Exception {
entity = Project.getInstance().getEntityByName(name);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
if(entity != null) {
drawing((Graphics2D)g);
}
}
// из mouse motion listener'a
@Override
public void mouseDragged(MouseEvent e) {}
// этих ребят нас обязывает создать MouseListener, так что они здесь
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void valueChanged(ListSelectionEvent e) {
@ -104,8 +85,23 @@ public abstract class Editable extends JPanel implements MouseListener, MouseMot
}
image = Project.getInstance().loadImageByName(selectedEntityName);
//TODO: if(image == null) вызов FileChooser'a и выбор изображения
this.repaint();
canvas.setEntity(entity);
canvas.setImage(image);
canvas.repaint();
// System.out.println(" Canvas image = " + canvas.image);
// System.out.println(" Canvas entity = " + canvas.entity);
// System.out.println(" Editable image = " + image);
// System.out.println(" Editable entity = " + entity);
}
}
JButton createButton(String text,ActionListener listener,String pathImage) {
JButton button = new JButton(new ImageIcon(pathImage));
button.addActionListener(listener);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
button.setPreferredSize(new Dimension(20, 20));
return button;
}
}

122
src/gui/EditableCanvas.java Normal file
View File

@ -0,0 +1,122 @@
package gui;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import gui.render.DrawboxRectengleRenderingFunction;
import gui.render.HitboxCircleRenderingFunction;
import gui.render.HitboxRectengleRenderingFunction;
import gui.render.ShapeRenderingFunction;
import model.Entity;
import repository.Project;
public class EditableCanvas extends JPanel implements MouseListener, MouseMotionListener {
DrawboxRectengleRenderingFunction drawboxRectengleRenderFunct;
HitboxRectengleRenderingFunction hitboxRectengleRenderFunct;
HitboxCircleRenderingFunction hitboxCircleRenderFunct;
ShapeRenderingFunction renderingFunction;
Entity entity;
BufferedImage image;
public EditableCanvas() {
drawboxRectengleRenderFunct = new DrawboxRectengleRenderingFunction();
hitboxRectengleRenderFunct = new HitboxRectengleRenderingFunction();
hitboxCircleRenderFunct = new HitboxCircleRenderingFunction();
drawboxRectengleRenderFunct.subscribe(Project.getInstance()); // подписка: Project получит данные ввиде обьекта Event, содержащий данные drawbox при отрисовке последней точки из 4-х.
hitboxRectengleRenderFunct.subscribe(Project.getInstance());
hitboxCircleRenderFunct.subscribe(Project.getInstance());
addMouseListener(this);
addMouseMotionListener(this);
}
public HitboxRectengleRenderingFunction getHitboxRectengleRenderFunct() {
return hitboxRectengleRenderFunct;
}
public void drawing(Graphics2D g) {
if(renderingFunction!=null&&entity!=null) {
renderingFunction.drawing(g);
}
}
public void setDrawboxRectengleRenderingFunction() {
renderingFunction = drawboxRectengleRenderFunct;
}
public void setHitboxRectengleRenderingFunction() {
renderingFunction = hitboxRectengleRenderFunct;
}
public void setHitboxCircleRenderingFunction() {
renderingFunction = hitboxCircleRenderFunct;
}
@Override
public void mouseMoved(MouseEvent e) {
//System.out.println("moved");
if(renderingFunction!=null&&entity!=null) {
//System.out.println("x="+e.getX()+"y="+e.getY());
renderingFunction.mouseMoved(e);
repaint();
}
}
@Override
public void mousePressed(MouseEvent e) {
//System.out.println("mousePressed");
if(renderingFunction!=null&&entity!=null) {
renderingFunction.mousePressed(e);
repaint();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(image!=null) {
g.drawImage(image, 0, 0, this);
g.setColor(Color.darkGray);
g.drawRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.RED);
g.fillOval(image.getWidth()/2, image.getHeight(), 2, 2);
g.setColor(Color.green);
}
if(entity != null) {
drawing((Graphics2D)g);
}
}
public void setEntity(Entity e) {
entity = e;
drawboxRectengleRenderFunct.setEntityInDrawboxRectengle(e);
hitboxRectengleRenderFunct.setEntityInHitboxRectengle(e);
hitboxCircleRenderFunct.setEntityInHitboxCircle(e);
}
public void setImage(BufferedImage image) {
this.image = image;
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}

View File

@ -1,47 +0,0 @@
package gui;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class HitboxCircleEditor extends Editable {
HitboxCircleEditor(ListGUI listGUI) {
super(listGUI);
// TODO Auto-generated constructor stub
}
@Override
public void drawing(Graphics2D g) {
// TODO Auto-generated method stub
}
@Override
public void saveDataInEntity() {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

96
src/gui/HitboxEditor.java Normal file
View File

@ -0,0 +1,96 @@
package gui;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JTabbedPane;
import javax.swing.event.ListSelectionEvent;
import events.EntityDrawboxChangedEvent;
import events.EntityDrawboxChangedListener;
import events.EntityHitboxChangedEvent;
import events.EntityHitboxChangedListener;
import model.Hitbox;
import model.HitboxCircle;
import model.HitboxRectangle;
import model.Point;
import repository.Project;
public class HitboxEditor extends Editable {
JButton changeInRectangleHitboxJButton;
JButton changeInCircleHitboxJButton;
HitboxEditor(ListGUI listGUI) {
super(listGUI);
canvas = new EditableCanvas();
add(canvas);
canvas.setHitboxRectengleRenderingFunction();
canvas.setVisible(true);
changeInRectangleHitboxJButton = super.createButton("Hitbox Rectangle",null,"res/square.png");
changeInCircleHitboxJButton = super.createButton("Hitbox circle",null,"res/circle.png");
toolbar.add(changeInRectangleHitboxJButton);
toolbar.add(changeInCircleHitboxJButton);
changeInRectangleHitboxJButton.addActionListener((e)->{
functionClearHitboxJButton();
entity.setHitbox(new HitboxRectangle("Rectangle",entity));
canvas.setHitboxRectengleRenderingFunction();
//Сделать создание нового Hitbox формы Rectengle
});
changeInCircleHitboxJButton.addActionListener((e)->{
functionClearHitboxJButton();
entity.setHitbox(new HitboxCircle("Circle",entity));
canvas.setHitboxCircleRenderingFunction();
//Сделать создание нового Hitbox формы Circle
});
}
public void functionClearHitboxJButton() {
if(entity != null) {
canvas.renderingFunction.functionClearJButton();
canvas.repaint();
}
}
//НАДО ДОБАВИТЬ ЧТО БЫ ПОД КОНЕЦ РИСОВАНИЯ ХИТБОКСА ОНО ВЫЗЫВАЛО ФУНКЦИЮ И ВСЕ СОХРАНЯЛО.
//СОХРАНЕНИЕ УЖЕ РЕАЛИЗОВАНО.
//НО НЕ ДОБАВЛЕН ВЫЗОВ ФУНКЦИИ И НЕ ОФОРМЛЕНА ПОДПИСКА
//UPD: вроде подписку оформил в MainGUI;
@Override
public void valueChanged(ListSelectionEvent e) {
if(e.getSource() instanceof JList) {
//TODO: надо бы элегантнее пробросить сюда ListGUI - просто передача его в аргументах немножко громоздкая
// как-то обыграть это через события?
// ps. попытки обратиться к eventSource проваливаются - ListGUI это панель, уже внутри которой лежит JList
selectedEntityName = listGUI.getSelectedName();
try {
entity = Project.getInstance().getEntityByName(selectedEntityName);
image = Project.getInstance().loadImageByName(selectedEntityName);
//TODO: if(image == null) вызов FileChooser'a и выбор изображения
canvas.setEntity(entity);
canvas.setImage(image);
if(entity.getHitbox().getShape().equals("Rectangle")) {
canvas.setHitboxRectengleRenderingFunction();
}
if(entity.getHitbox().getShape().equals("Circle")) {
canvas.setHitboxCircleRenderingFunction();
}
} catch (Exception e1) {
//logger.severe("Entity with name '"+selectedEntityName+"' was not found! Cannot display it on panel!");
}
canvas.repaint();
}
}
}

View File

@ -1,48 +0,0 @@
package gui;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class HitboxPoligonEditor extends Editable {
HitboxPoligonEditor(ListGUI listGUI) {
super(listGUI);
// TODO Auto-generated constructor stub
}
@Override
public void drawing(Graphics2D g) {
// TODO Auto-generated method stub
}
@Override
public void saveDataInEntity() {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

View File

@ -1,53 +0,0 @@
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;
public class HitboxRectangleEditor extends Editable {
HitboxRectangleEditor(ListGUI listGUI) {
super(listGUI);
// TODO Auto-generated constructor stub
}
@Override
public void drawing(Graphics2D g) {
// TODO Auto-generated method stub
}
@Override
public void saveDataInEntity() {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

View File

@ -1,14 +1,14 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -35,23 +35,23 @@ import listeners.RemoveListElementEntityListener;
import model.Drawbox;
import model.Entity;
import model.Hitbox;
import model.Point;
import repository.Project;
public class ListGUI extends JPanel {
private Map<String, Icon> iconMap = new HashMap<>();
JButton addListElementEntity;
JButton removeListElementEntity;
JButton addPicEntity;
JList list;
JScrollPane scroll;
ActionListener removeEntity;
ActionListener addEntity;
DefaultListModel<String> testModel;
JPanel gridButtonBar = new JPanel(new GridLayout(1, 2, 5, 0));
private static Logger logger = Logger.getLogger("gui.ListGUI");
public ListGUI() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(223,638));
try {
Project.getInstance().load();
} catch (SAXException | IOException | ParserConfigurationException e) {
@ -60,24 +60,21 @@ public class ListGUI extends JPanel {
JOptionPane.showMessageDialog(this, "Parser exception, cause: "+e);
}
String[] nameList = createNameList();
testModel = new DefaultListModel<>();
list = new JList(testModel);
list.setCellRenderer(new ListEntityRenderer());
addEntity = new CreateFrameAddElementListener(this);
removeEntity = new RemoveListElementEntityListener(this);
scroll = new JScrollPane(list);
scroll.setSize(new Dimension(223, 638));
scroll.setLocation(5, 5);
this.add(scroll);
add(scroll,BorderLayout.CENTER);
list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
addListElementEntity = createButton(5,645, addEntity,"res/addbutton.png");
removeListElementEntity = createButton(117,645,removeEntity,"res/deletebutton.png");
addListElementEntity = createButton(addEntity,"res/addbutton.png");
removeListElementEntity = createButton(removeEntity,"res/deletebutton.png");
add(gridButtonBar,BorderLayout.SOUTH);
/// ЧТОБЫ ОТКЛЮЧИТЬ ИЗБЫТОЧНЫЙ ВЫВОД В КОНСОЛЬ - НУЖНО СМЕНИТЬ УРОВЕНЬ ЛОГГИРОВАНИЯ В СТРОКЕ НИЖЕ
logger.setLevel(Level.FINEST);
@ -90,15 +87,9 @@ public class ListGUI extends JPanel {
return (String) list.getSelectedValue();
}
public void addListElement(String name, String solid) throws DuplicateEntryException {
// плейсхолдеры для новых хитбоксов и дроубоксов, иначе всё валится с NPE
List<Point> hitboxPoints = new LinkedList<Point>();
List<Point> drawboxPoints = new LinkedList<Point>();
Hitbox hitbox = new Hitbox("Rectangle", hitboxPoints);
Drawbox drawbox = new Drawbox(drawboxPoints);
// а тут уже создание новой сущности
Entity e = new Entity(name, hitbox, drawbox);
public void addListElement(String name, String solid) throws DuplicateEntryException {
Entity e = new Entity(name);
e.setType(solid);
logger.finer("Entity \""+name+"\" was created.");
Project.getInstance().addEntity(e);
@ -185,14 +176,13 @@ public class ListGUI extends JPanel {
}
}
private JButton createButton(int width,int height,ActionListener listener,String pathImage) {
private JButton createButton(ActionListener listener,String pathImage) {
JButton button = new JButton(new ImageIcon(pathImage));
button.setSize(110, 46);
button.setLocation(width, height);
button.setPreferredSize(new Dimension(100, 50));
button.addActionListener(listener);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
this.add(button);
gridButtonBar.add(button);
return button;
}

View File

@ -1,119 +1,104 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Box;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import listeners.OpenXMLFileButtonListener;
import repository.Project;
public class MainGUI extends JFrame{
JPanel gridButtonBar = new JPanel(new GridLayout(1, 3, 5, 0));
JPanel TopButtonBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
ListGUI list;
ActionListener OpenXMLFileButtonListener;
JButton openXMLJButton;
JButton saveXMLJButton;
JButton clearLinesJButton;
public static JTabbedPane editorPane;
public static JTabbedPane hitdrawPane;
List <Editable> listEditorPanel = new ArrayList<Editable>();
DrawboxEditor drawBoxPanel;
HitboxCircleEditor hitboxCirclePanel;
HitboxRectangleEditor hitboxRectanglePanel;
HitboxPoligonEditor hitboxPoligonPanel;
public static JTabbedPane editorPane;
DrawboxEditor drawBoxPanel;
HitboxEditor hitboxPanel;
public MainGUI() {
setTitle("Hitbox/Drawbox Editor");
setLayout(null);
setSize(1200,780);
setSize(1000,650);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if(Project.getInstance().changeOfXmlDOM == true) {
int confirmed = JOptionPane.showConfirmDialog(null,
"Сохранить файл перед выходом?", "Выход",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
Project.getInstance().writeXML();
}
}
System.exit(0);
}
});
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(800,600));
list = new ListGUI();
this.add(list);
list.setLayout(null);
list.setSize(230, 691);
list.setLocation(0, 47);
add(list,BorderLayout.WEST);
list.setVisible(true);
drawBoxPanel = new DrawboxEditor(list);
hitboxCirclePanel = new HitboxCircleEditor(list);
hitboxRectanglePanel = new HitboxRectangleEditor(list);
hitboxPoligonPanel = new HitboxPoligonEditor(list);
listEditorPanel.add(drawBoxPanel);
listEditorPanel.add(hitboxCirclePanel);
listEditorPanel.add(hitboxRectanglePanel);
listEditorPanel.add(hitboxPoligonPanel);
hitboxPanel = new HitboxEditor(list);
list.registerJListListener(drawBoxPanel);
list.registerJListListener(hitboxCirclePanel);
list.registerJListListener(hitboxPoligonPanel);
list.registerJListListener(hitboxRectanglePanel);
list.registerJListListener(hitboxPanel);
OpenXMLFileButtonListener = new OpenXMLFileButtonListener(list);
openXMLJButton = createButton("XML",5,5, OpenXMLFileButtonListener,"res/xml.png");
saveXMLJButton = createButton("Save",80,5,(e)-> Project.getInstance().writeXML(),"res/download.png");
clearLinesJButton = createButton("Clear lines",155,5,null,"res/destroy.png");
openXMLJButton = createButton("XML", OpenXMLFileButtonListener,"res/xml.png");
saveXMLJButton = createButton("Save",(e)-> Project.getInstance().writeXML(),"res/download.png");
clearLinesJButton.addActionListener(drawBoxPanel);
clearLinesJButton.addActionListener(hitboxCirclePanel);
clearLinesJButton.addActionListener(hitboxPoligonPanel);
clearLinesJButton.addActionListener(hitboxRectanglePanel);
gridButtonBar.add(openXMLJButton);
gridButtonBar.add(saveXMLJButton);
//gridButtonBar.add(clearLinesJButton);
TopButtonBar.add(gridButtonBar);
TopButtonBar.setBorder(BorderFactory.createLoweredBevelBorder());
add(TopButtonBar,BorderLayout.NORTH);
repaint();
editorPane = new JTabbedPane();
editorPane.setVisible(true);
add(editorPane,BorderLayout.CENTER);
this.add(editorPane = createPane(editorPane, 230, 50));
editorPane.addTab("Hitbox", hitdrawPane = createPane(hitdrawPane,10, 10));
editorPane.addTab("Drawbox", drawBoxPanel);
hitdrawPane.addTab(null, new ImageIcon("res/square.png"),hitboxRectanglePanel, null);
hitdrawPane.addTab(null, new ImageIcon("res/circle.png"),hitboxCirclePanel, null);
hitdrawPane.addTab(null, new ImageIcon("res/formless.png"),hitboxPoligonPanel, null);
hitdrawPane.setTabPlacement(JTabbedPane.LEFT);
//Оформление подписок к издателям.
drawBoxPanel.subscribe(Project.getInstance()); // подписка: Project получит данные ввиде обьекта Event, содержащий аднные drawbox при отрисовке последней точки из 4-х.
editorPane.addTab("Hitbox", hitboxPanel);
repaint();
}
@Override
public void paint(Graphics g){
super.paint(g);
g.drawLine(0, 72, 1200, 72);
super.paint(g);
}
public JTabbedPane createPane(JTabbedPane pane, int x, int y) {
pane = new JTabbedPane();
pane.setSize(new Dimension(950, 688));
pane.setLocation(new Point(x, y));
pane.setVisible(true);
return pane;
}
private JButton createButton(String text,int width,int height,ActionListener listener,String pathImage) {
private JButton createButton(String text,ActionListener listener,String pathImage) {
JButton button = new JButton(new ImageIcon(pathImage));
button.setSize(68, 34);
button.setLocation(width, height);
button.addActionListener(listener);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
this.add(button);
button.setPreferredSize(new Dimension(72, 38));
return button;
}
}

View File

@ -0,0 +1,155 @@
package gui.render;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import events.EntityDrawboxChangedEvent;
import events.EntityDrawboxChangedListener;
import model.Drawbox;
import model.Entity;
import model.HitboxRectangle;
import model.Point;
public class DrawboxRectengleRenderingFunction implements ShapeRenderingFunction {
private List<Point> drawboxPoints;
private List<Point> basePoints;
Point currentPoint = new Point(0, 0);
private List<EntityDrawboxChangedListener> listeners = new ArrayList<>();
Entity entity;
Logger logger = Logger.getLogger("gui.DrawboxRectangleEditor");
public DrawboxRectengleRenderingFunction() {
}
@Override
public void drawing(Graphics2D g) {
Drawbox drawbox = entity.getDrawbox();
drawboxPoints = drawbox.getDrawboxlistPoints();
basePoints = drawbox.getbaseListPoints();
logger.finest("drawbox point size: "+ drawboxPoints.size());
for(Point p: drawboxPoints)
logger.finest("DrawBoxPoint: ["+ p.x + ":"+p.y+"]");
for(Point p: basePoints)
logger.finest("BasePoint: ["+ p.x + ":"+p.y+"]");
if(drawboxPoints.size() >= 1 && drawboxPoints.size() < 4) {
Point lastPoint = drawboxPoints.get(drawboxPoints.size()-1);
g.drawLine((int)lastPoint.x, (int)lastPoint.y, (int)currentPoint.x, (int)currentPoint.y);
for(int i = 0; i < drawboxPoints.size()-1;i++) {
int x1 = (int)drawboxPoints.get(i).x;
int y1 = (int)drawboxPoints.get(i).y;
int x2 = (int)drawboxPoints.get(i+1).x;
int y2 = (int)drawboxPoints.get(i+1).y;
g.drawLine(x1, y1, x2, y2);
}
} else {
for(int i = 0; i < drawboxPoints.size();i++) {
int x1 = (int)drawboxPoints.get(i % drawboxPoints.size()).x;
int y1 = (int)drawboxPoints.get(i % drawboxPoints.size()).y;
int x2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).x;
int y2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).y;
g.drawLine(x1, y1, x2, y2);
}
// ОТРИСОВКА ОСНОВАНИЯ
g.setColor(Color.BLUE);
for(int i = 0; i < basePoints.size()-1;i++) {
int x1 = (int)basePoints.get(i).x;
int y1 = (int)basePoints.get(i).y;
int x2 = (int)basePoints.get(i+1).x;
int y2 = (int)basePoints.get(i+1).y;
g.drawLine(x1, y1+3, x2, y2+3);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if(drawboxPoints.size() < 4) {
Point p = new Point(e.getX(), e.getY());
drawboxPoints.add(p);
if(drawboxPoints.size() == 4) {
sortingDrawboxPoints();
saveDataInEntity();
//при выборе 4-й точки и формировании данных drawbox, уведомляем всех подписчит
if(listeners!=null) {
notifySubscribers();
}
}
}
}
@Override
public void mouseMoved(MouseEvent e) {
currentPoint.x = e.getX();
currentPoint.y = e.getY();
}
/*Точки должны идти в определенном порядке:
* левая верхняя точка, правая верхняя, нижняя правая, нижняя левая;
* Обе нижние точки, т.е. 3 и 4 являются основанием - хардкод.
* P.s. возможно это не критично, и в сторе предусмотрено, что бы они сортировались,
* но на данном этапе на всякий случай стоит так поступить*/
private void sortingDrawboxPoints() {
//окей, это написано плохо, но... Похуй, пляшем)
Collections.sort(
drawboxPoints,
(point1, point2) -> Float.compare(point1.y, point2.y)
);
if(drawboxPoints.get(0).x>drawboxPoints.get(1).x) {
Collections.swap(drawboxPoints, 0, 1);
}
if(drawboxPoints.get(2).x<drawboxPoints.get(3).x) {
Collections.swap(drawboxPoints, 2, 3);
}
/*Багтест, проверка очередности построения точек
*
* System.out.println("_______________");
int i = 0;
for (Point point : drawboxPoints) {
System.out.println("Point["+i+"]: ("+point.x+" ; "+point.y+");");
i++;
}*/
}
public void subscribe(EntityDrawboxChangedListener listener) {
listeners.add(listener);
}
public void unsubscribe(EntityDrawboxChangedListener listener) {
listeners.remove(listener);
}
//
private void notifySubscribers() {
for (EntityDrawboxChangedListener listener : listeners) {
listener.drawboxChanged(
new EntityDrawboxChangedEvent(entity.getDrawbox(), entity)
);
}
}
public void saveDataInEntity() {
entity.setDrawbox(new Drawbox(drawboxPoints));
}
public void setEntityInDrawboxRectengle(Entity e) {
entity = e;
}
public void functionClearJButton() {
if(entity != null) {
entity.getDrawbox().getDrawboxlistPoints().clear();
entity.getDrawbox().getbaseListPoints().clear();
}
}
}

View File

@ -0,0 +1,101 @@
package gui.render;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import events.EntityHitboxChangedEvent;
import events.EntityHitboxChangedListener;
import model.Entity;
import model.HitboxCircle;
import model.Point;
public class HitboxCircleRenderingFunction implements ShapeRenderingFunction {
Point firstIsoPoint = null;
Point currentIsoPoint = new Point(0,0);
int currentDiametrX=0;
Entity entity;
private List<EntityHitboxChangedListener> listeners = new ArrayList<>();
public void setEntityInHitboxCircle(Entity e) {
entity = e;
}
@Override
public void drawing(Graphics2D g) {
HitboxCircle nowHitbox = (HitboxCircle)entity.getHitbox();
if(nowHitbox.getRadius()!=0) {
g.drawOval((int)nowHitbox.getCurrentRefPoint().x, (int)(nowHitbox.getCurrentRefPoint().y-(nowHitbox.getDiametrY()/2)), (int)nowHitbox.getDiametrX(), (int)(nowHitbox.getDiametrY()));
// System.out.println("READY: diametrX = "+nowHitbox.getDiametrX()+ ". diametrY = "+nowHitbox.getDiametrY());
// System.out.println("READY: coordX = "+(int)nowHitbox.getCurrentRefPoint().x+ ". coordY = "+(int)(nowHitbox.getCurrentRefPoint().y-(nowHitbox.getDiametrY()/2)));
}else if(firstIsoPoint != null) {
currentDiametrX = Math.abs((int)firstIsoPoint.x-(int)currentIsoPoint.x);
// System.out.println("CURRENT: coordX = "+(int)firstIsoPoint.x+ ". coordX = "+(int)(firstIsoPoint.y-currentDiametrX/4));
// System.out.println("CURRENT: diametrX = "+currentDiametrX+ ". diametrY = "+currentDiametrX/2);
g.drawOval((int)firstIsoPoint.x, (int)(firstIsoPoint.y-currentDiametrX/4), (int)currentDiametrX, (int)currentDiametrX/2);
}
}
@Override
public void mousePressed(MouseEvent e) {
HitboxCircle nowHitbox = (HitboxCircle)entity.getHitbox();
if(nowHitbox.getRadius()==0 && firstIsoPoint == null) {
firstIsoPoint = new Point(e.getX(), e.getY());
}else if(nowHitbox.getRadius()==0 && firstIsoPoint != null) {
//Формула высчитывания радиуса из диаметров circle.
nowHitbox.getCurrentRefPoint().setXY(firstIsoPoint.x, firstIsoPoint.y);
nowHitbox.setDiametrXY(Math.abs(firstIsoPoint.x-e.getX()),Math.abs((firstIsoPoint.x-e.getX())/2));
System.out.println("X = "+nowHitbox.getDiametrX()+ ". Y = "+nowHitbox.getDiametrY());
float temp = (float)Math.sqrt(2);
nowHitbox.setRadius((nowHitbox.getDiametrY()/2)*temp);
// высчитываем в параметры хитбокссеркла нужный радиус и текущую реф поинт.
// Не забываем высчитать реф поинт хитбокса относительно текущей.
// после чего вызываем listPointsToString и нотифай, который отправляет данные на сохранение
notifySubscribers();
//возвращаем локальные данные текущего рисования хитбокса в нулевые значения.
//необходимо, что бы при переходе в новый обьект, при создании хитбокса, очистился кэш канваса.
firstIsoPoint = null;
currentDiametrX = 0;
}
}
@Override
public void mouseMoved(MouseEvent e) {
currentIsoPoint.x = e.getX();
currentIsoPoint.y = e.getY();
}
public void functionClearHitboxJButton() {
HitboxCircle nowHitbox = (HitboxCircle)entity.getHitbox();
}
@Override
public void functionClearJButton() {
firstIsoPoint = null;
currentIsoPoint = new Point(0,0);
currentDiametrX = 0;
HitboxCircle nowhitbox = (HitboxCircle)entity.getHitbox();
nowhitbox.setRadius(0);
System.err.println("radius: "+nowhitbox.getRadius());
}
public void subscribe(EntityHitboxChangedListener listener) {
listeners.add(listener);
}
public void unsubscribe(EntityHitboxChangedListener listener) {
listeners.remove(listener);
}
private void notifySubscribers() {
for (EntityHitboxChangedListener listener : listeners) {
listener.hitboxChanged(
new EntityHitboxChangedEvent(entity.getHitbox(), entity)
);
}
}
}

View File

@ -0,0 +1,162 @@
package gui.render;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import events.EntityHitboxChangedEvent;
import events.EntityHitboxChangedListener;
import model.Entity;
import model.Hitbox;
import model.HitboxRectangle;
import model.Point;
public class HitboxRectengleRenderingFunction implements ShapeRenderingFunction {
Point firstIsoPoint = null;
Point currentIsoPoint = new Point(0,0);
Point firstCartesianPoint = new Point(0,0), currentCartesianPoint = new Point(0,0);
private List<EntityHitboxChangedListener> listeners = new ArrayList<>();
Entity entity;
private List<Point> LocalListPointsIso = new ArrayList<Point>();
private List<Point> LocalListPointsCartesian = new ArrayList<Point>();
public List<Point> getLocalListPointsIso() {
return LocalListPointsIso;
}
public List<Point> getLocalListPointsCartesian() {
return LocalListPointsCartesian;
}
private void setFirstIsoPointIsNull(){
firstIsoPoint = null;
}
@Override
public void drawing(Graphics2D g) {
HitboxRectangle nowHitbox = (HitboxRectangle)entity.getHitbox();
int x1,y1,x2,y2;
if(nowHitbox.getListPointsIso().size() == 4) {
drawingLinesFromListPoints(nowHitbox.getListPointsIso(),g);
}
if(firstIsoPoint!=null&&nowHitbox.getListPointsIso().size() == 0) {
drawingLinesFromListPoints(LocalListPointsIso,g);
}
}
public void drawingLinesFromListPoints(List<Point> listPointsIso, Graphics2D g) {
int x1,y1,x2,y2;
int size = listPointsIso.size();
for(int i = 0; i < size;i++) {
x1 = (int)listPointsIso.get(i % size).x;
y1 = (int)listPointsIso.get(i % size).y;
x2 = (int)listPointsIso.get((i+1) % size).x;
y2 = (int)listPointsIso.get((i+1) % size).y;
g.drawLine(x1, y1, x2, y2);
}
x1 = (int)listPointsIso.get(0).x;
y1 = (int)listPointsIso.get(0).y;
x2 = (int)listPointsIso.get(3).x;
y2 = (int)listPointsIso.get(3).y;
g.drawLine(x1, y1, x2, y2);
}
@Override
public void mousePressed(MouseEvent e) {
//System.out.println("mousePressed");
//System.out.println("mouseClicked");
HitboxRectangle nowHitbox = (HitboxRectangle)entity.getHitbox();
if(nowHitbox.getListPointsIso().size() == 0 && firstIsoPoint == null) {
initListsPoints();
firstIsoPoint = new Point(currentIsoPoint.x,currentIsoPoint.y);
LocalListPointsIso.get(0).setXY(firstIsoPoint.x, firstIsoPoint.y);
firstCartesianPoint = Hitbox.isometricToCartesian(firstIsoPoint.x, firstIsoPoint.y,firstCartesianPoint);
LocalListPointsCartesian.get(0).setXY(firstCartesianPoint.x, firstCartesianPoint.y);
System.out.println("mouseClicked Event 1 TIME: "+LocalTime.now());
}else if(nowHitbox.getListPointsIso().size() == 0 && firstIsoPoint != null) {
nowHitbox.getListPointsIso().addAll(LocalListPointsIso);
nowHitbox.getListPointsCartesian().addAll(LocalListPointsCartesian);
System.out.println("mouseClicked Event 2 TIME: "+LocalTime.now());
notifySubscribers();
//очистка кэша
firstIsoPoint = null;
LocalListPointsIso.clear();
LocalListPointsCartesian.clear();
}
}
@Override
public void mouseMoved(MouseEvent e) {
currentIsoPoint.x = e.getX();
currentIsoPoint.y = e.getY();
HitboxRectangle nowHitbox = (HitboxRectangle)entity.getHitbox();
if(entity!=null) {
if(firstIsoPoint != null && nowHitbox.getListPointsIso().size() == 0) {
//System.out.println("firstPoint("+firstIsoPoint.x+";"+firstIsoPoint.y+");");
currentCartesianPoint = Hitbox.isometricToCartesian(currentIsoPoint.x, currentIsoPoint.y, currentCartesianPoint);
LocalListPointsCartesian.get(0).setXY(firstCartesianPoint.x, firstCartesianPoint.y);
LocalListPointsCartesian.get(1).setXY(currentCartesianPoint.x, firstCartesianPoint.y);
LocalListPointsCartesian.get(2).setXY(currentCartesianPoint.x, currentCartesianPoint.y);
LocalListPointsCartesian.get(3).setXY(firstCartesianPoint.x, currentCartesianPoint.y);
convertCartesianPointsToIso();
}
}
}
public void setEntityInHitboxRectengle(Entity e) {
entity = e;
}
public void subscribe(EntityHitboxChangedListener listener) {
listeners.add(listener);
}
public void unsubscribe(EntityHitboxChangedListener listener) {
listeners.remove(listener);
}
private void notifySubscribers() {
for (EntityHitboxChangedListener listener : listeners) {
listener.hitboxChanged(
new EntityHitboxChangedEvent(entity.getHitbox(), entity)
);
}
}
public void initListsPoints() {
if(LocalListPointsIso.size()<1) {
for(int i=0;i<4;i++) {
LocalListPointsIso.add(new Point(currentIsoPoint.x,currentIsoPoint.y));
}
}
if(LocalListPointsCartesian.size()<1) {
for(int i=0;i<4;i++) {
LocalListPointsCartesian.add(new Point(0,0));
}
}
}
public void convertCartesianPointsToIso() {
Point cartesianPoint;
for (int i = 0 ; i<4;i++) {
cartesianPoint = LocalListPointsCartesian.get(i);
Hitbox.cartesianToIsometric(cartesianPoint.x,cartesianPoint.y,LocalListPointsIso.get(i));
}
}
@Override
public void functionClearJButton() {
HitboxRectangle nowHitbox = (HitboxRectangle)entity.getHitbox();
nowHitbox.getListPointsIso().clear();
nowHitbox.getListPointsCartesian().clear();
LocalListPointsCartesian.clear();
LocalListPointsIso.clear();
setFirstIsoPointIsNull();
}
}

View File

@ -0,0 +1,12 @@
package gui.render;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
public interface ShapeRenderingFunction {
void drawing(Graphics2D g);
public void mousePressed(MouseEvent e);
public void mouseMoved(MouseEvent e);
public void functionClearJButton();
//private void notifySubscribers() ?? надо ли? подумать
}

View File

@ -4,8 +4,12 @@ import java.util.ArrayList;
import java.util.List;
public class Drawbox {
private List<Point> drawboxlistPoints ;//для прямоугольника дравбокса.
private List<Point> baseListPoints ;//2 точки для линии основания
private List<Point> drawboxlistPoints = new ArrayList<Point>();//для прямоугольника дравбокса.
private List<Point> baseListPoints = new ArrayList<Point>();//2 точки для линии основания
public Drawbox(){
}
public Drawbox(List<Point> drawboxlistPoints){
this.drawboxlistPoints = new ArrayList<Point>(drawboxlistPoints) ;
@ -15,8 +19,6 @@ public class Drawbox {
public Drawbox(String informationDrawbox){
if(informationDrawbox!= null) {
drawboxlistPoints = new ArrayList<Point>();
baseListPoints = new ArrayList<Point>();
String[] informations = informationDrawbox.split(" ");
parseStringToDrawbox(informations);
createBasePoint();
@ -44,9 +46,12 @@ public class Drawbox {
}
}
}
//Возвращает все точки дравбокса через пробел.
@Override
/* @Override
public String toString() {
}
*/
//Возвращает все точки дравбокса через пробел.
public String listPointsToString() {
String stringDrawbox="";
for (Point point : drawboxlistPoints) {
stringDrawbox+=((int)point.x)+" "+((int)point.y)+" "; //(int) because it is for XML
@ -54,6 +59,7 @@ public class Drawbox {
return stringDrawbox;
}
public List<Point> getDrawboxlistPoints() {
return drawboxlistPoints;
}

View File

@ -7,18 +7,29 @@ public class Entity {
private Drawbox thisDrawbox;
private Hitbox thisHitbox;
private String type;
private BufferedImage sprite;
private BufferedImage thisImage;
private int width = 0;
private int height = 0;
public Entity(String name,String drawbox,String hitbox) {
public Entity(String name, String drawbox, String hitbox, BufferedImage sprite) {
thisName = new String(name);
thisDrawbox = new Drawbox(drawbox);
thisHitbox = new Hitbox(hitbox);
setImage(sprite); // updates entity width and height, should be called before creating hitbox
if(hitbox != null) {
String[] dataHitbox = hitbox.split(" ");
System.out.println("Создается обьект /"+name+"/. Shape Hitbox = /"+dataHitbox[0]+"/. Размер dataHitbox = /"+dataHitbox.length+"/.");
if(dataHitbox[0].equals("Rectangle")) {
thisHitbox = new HitboxRectangle(dataHitbox,this);
}else if(dataHitbox[0].equals("Circle")) {
thisHitbox = new HitboxCircle(dataHitbox,this);
}
}
}
public Entity(String name, Hitbox hitbox, Drawbox drawbox) {
// при добавлении новой сущности по умолчанию создается у нее прямоугольный хитбокс
public Entity(String name) {
this.thisName = name;
this.thisHitbox = hitbox;
this.thisDrawbox = drawbox;
this.thisHitbox = new HitboxRectangle("Rectangle",this);
this.thisDrawbox = new Drawbox();
}
public void setName(String outName) {
@ -37,8 +48,8 @@ public class Entity {
thisDrawbox = outDrawbox;
};
public void setHitbox(Hitbox outHitbox) {
thisHitbox = outHitbox;
public void setHitbox(Hitbox inputHitbox) {
thisHitbox = inputHitbox;
};
public String getName() {
@ -53,24 +64,41 @@ public class Entity {
return thisHitbox;
};
public Drawbox getThisDrawbox() {
return thisDrawbox;
}
/** @return BufferedImage object or null if an image is not set */
public BufferedImage getImage() {
return sprite;
return thisImage;
}
/** NOTE: Image setter updates entity width and height */
public void setImage(BufferedImage sprite) {
this.sprite = sprite;
this.thisImage = sprite;
if(sprite != null) {
width = sprite.getHeight();
height = sprite.getHeight();
}
}
public void PrintEntity() {
System.out.println("---------------------");
System.out.println("Name: "+thisName);
this.thisDrawbox.printToConsole();
this.thisHitbox.printToConsole();
thisDrawbox.printToConsole();
thisHitbox.printToConsole();
System.out.println("---------------------");
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}

View File

@ -3,82 +3,87 @@ package model;
import java.util.ArrayList;
import java.util.List;
public class Hitbox {
private String shape = null;// shape - Форма хитбокса. Понадобится при написании сохранения. Один из параметров в xml-file.
private List<Point> listPoints = null;//для прямоугольника - 4 точки. Для круга - надо посмотреть.
public abstract class Hitbox {
String shape = null;// shape - Форма хитбокса. Понадобится при написании сохранения. Один из параметров в xml-file.
Point referencePoint = new Point(0, 0); //Точка отсчета хитбокса, от нее рассчитывается высота+ширина/радиус(при круге) хитбокса.
Entity owner;
public Hitbox(String shape,List<Point> listPoints){
public Hitbox(){
}
//Либо так передавать shape, либо создать setShape. Но по сути shape определяется при создании обьекта, и тогда set - предоставление не нужных возможностей.
public Hitbox(String shape){
this.shape = new String(shape);
this.listPoints = new ArrayList<Point>(listPoints) ;
}
public Hitbox(String informationHitbox){
//informationHitbox - default="Rectangle 0 0 96 98"
//Предварительно, я бы сказал что вообще этот конструктор бесполезен и его можно удалить,
// т.к. Hitbox конструктор вызывается из дочерних элементов, а они уже владеют всей необходимой инфой, и entity owner задают сами
// кстати забавно. сейчас устанавливается entity через serOwnerEntity, но как будто этот метод тоже излишек, ведь владелец хитбокса только один.
//Но нет. у нас может быть хитбокс создан программно раньше entity, помню было такое где то, так что этот метод еще обоснован.
public Hitbox(String informationHitbox, Entity owner){
if(informationHitbox!= null) {
listPoints = new ArrayList<Point>();
setOwnerEntity(owner);
String[] informations = informationHitbox.split(" ");
//в 0-м индексе всегда идет название фигуры.Так сделан наш xml.
shape = new String(informations[0]);
//заполняем лист точками. Пока что делаю тупо и топорно. Хардкод. Потом можно переделать.
if(shape.equals("Rectangle")) {
parseStringToRectangleHitbox(informations);
}else if(shape.equals("Circle")) {
parseStringToCircleHitbox(informations);
}
}
}
private void parseStringToRectangleHitbox(String[] informations) {
//составляем точки по которым строится прямоугольник, и запихиваем их в лист с точками
for(int i = 1;i<informations.length;i+=2) {
float x = Float.parseFloat(informations[i]);
float y = Float.parseFloat(informations[i+1]);
Point point = new Point(x, y);
listPoints.add(point);
}
public abstract String listPointsToString();
/**
* @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;
}
private void parseStringToCircleHitbox(String[] informations) {
//ЭТО ХАРДКОД.ДА.Но в данном случае, имхо, разумный(в каком то смысле).
//первая точка где строится круг
float x1 = Float.parseFloat(informations[1]);
float y1 = Float.parseFloat(informations[2]);
Point point1 = new Point(x1, y1);
//вторая точка x2 - диаметр, а y2 = 0, потому что нам на него пофиг.
//Просто же не создавать для круга новый класс хитбокса? Нет. Так что так.
float x2 = Float.parseFloat(informations[3]);
Point point2 = new Point(x2, 0);
listPoints.add(point2);
/**
* @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;
}
public void setOwnerEntity(Entity owner) {
this.owner = owner;
}
public Entity getOwnerEntity() {
return owner;
}
public void addPoint(Point point) {
listPoints.add(point);
}
public void clearPoints() {
listPoints.clear();
}
public String getShape() {
return shape;
}
public List<Point> getListPoints() {
return listPoints;
}
public void calculationReferencePoint() {}
//not the same as toString()! the latter is for XML while printToConsole() is for console
public void printToConsole() {
System.out.println();
/*System.out.println();
System.out.println("|||Hitbox:");
if(shape!=null&&listPoints!=null) {
System.out.println("shape: " + shape);
for(Point point: listPoints) {
if(shape!=null&&listPointsCartesian!=null) {
System.out.println("Shape: " + shape);
System.out.println("Cartesian: ");
for(Point point: listPointsCartesian) {
System.out.print("("+point.x+";"+point.y+") ");
System.out.println("");
}
System.out.println();
System.out.println("-----------");
System.out.println("Iso: ");
for(Point point: listPointsIso){
System.out.print("("+point.x+";"+point.y+") ");
System.out.println("");
}
System.out.println(" ");
}else {
System.out.println("null");
}
}*/
}
//дописать функцию возвращения listPonts и shape(форма), если будет нужно.
// так же при написании функции возвращения нужных координат, надо их сделать целочисленными.

View File

@ -0,0 +1,82 @@
package model;
public class HitboxCircle extends Hitbox {
private float radiusHitbox;
private float diametrX,diametrY;
Point cartesianCenterImagePoint= new Point(0,0);
//currentRefPoint - точка хранящая изометрические(экранные) коорды, от которой рисуется овал
private Point currentRefPoint= new Point(0,0);
public HitboxCircle(String[] dataHitbox, Entity owner){
super(dataHitbox[0]);
setOwnerEntity(owner);
parseStringToCircleHitbox(dataHitbox);
}
public HitboxCircle(String shape, Entity owner){
super(shape);
setOwnerEntity(owner);
radiusHitbox = 0;
}
private void parseStringToCircleHitbox(String[] informations) {
float temp = (float)Math.sqrt(2);
referencePoint.x = Float.parseFloat(informations[1]);
referencePoint.y = Float.parseFloat(informations[2]);
radiusHitbox = Float.parseFloat(informations[3]);
diametrX = radiusHitbox/temp*4;
diametrY = radiusHitbox/temp*2;
cartesianCenterImagePoint = isometricToCartesian(owner.getImage().getWidth()/2,owner.getImage().getHeight(),cartesianCenterImagePoint);
Point cartesianCenterRefPoint = new Point(cartesianCenterImagePoint.x-referencePoint.x, cartesianCenterImagePoint.y-referencePoint.y);
Point isoCenterRefPoint = new Point(0,0);
isoCenterRefPoint = cartesianToIsometric(cartesianCenterRefPoint.x,cartesianCenterRefPoint.y,isoCenterRefPoint);
currentRefPoint.x = isoCenterRefPoint.x-diametrY;
currentRefPoint.y = isoCenterRefPoint.y-diametrY/2;
System.out.println("----------------------------");
System.out.println("Entity = "+owner.getName());
System.out.println("refCartEntPoint X ="+cartesianCenterRefPoint.x+"||cartesianCenterRefPoint Y ="+cartesianCenterRefPoint.y);
System.out.println("CartCenterImage X ="+cartesianCenterImagePoint.x+"||CartCenterImage Y ="+cartesianCenterImagePoint.y);
System.out.println("refIsoEntPoint X ="+currentRefPoint.x+"||refIsoEntPoint Y ="+currentRefPoint.y);
System.out.println("diametrY "+ diametrY);
System.out.println(" ");
}
@Override
public String listPointsToString() {
Point cartesianCenterRefPoint = new Point(0, 0);
cartesianCenterImagePoint = isometricToCartesian(owner.getImage().getWidth()/2,owner.getImage().getHeight(),cartesianCenterImagePoint);
cartesianCenterRefPoint = isometricToCartesian(currentRefPoint.x+diametrY,currentRefPoint.y+(diametrY/2),cartesianCenterRefPoint);
System.out.println("");
referencePoint.x = cartesianCenterImagePoint.x-cartesianCenterRefPoint.x;
referencePoint.y = cartesianCenterImagePoint.y-cartesianCenterRefPoint.y;
System.out.println("----------------------------");
System.out.println("Entity = "+owner.getName());
System.out.println("refCartEntPoint X ="+cartesianCenterRefPoint.x+"||cartesianCenterRefPoint Y ="+cartesianCenterRefPoint.y);
System.out.println("CartCenterImage X ="+cartesianCenterImagePoint.x+"||CartCenterImage Y ="+cartesianCenterImagePoint.y);
System.out.println("refIsoEntPoint X ="+currentRefPoint.x+"||refIsoEntPoint Y ="+currentRefPoint.y);
System.out.println("diametrY "+ diametrY);
System.out.println(" ");
return "Circle "+(int)referencePoint.x+" "+(int)referencePoint.y+" "+(int)radiusHitbox;
}
public float getRadius() {
return radiusHitbox;
}
public void setDiametrXY(float diametrX, float diametrY) {
this.diametrX = diametrX;
this.diametrY = diametrY;
}
public float getDiametrX() {
return diametrX;
}
public float getDiametrY() {
return diametrY;
}
public void setRadius(float radius) {
radiusHitbox = radius;
}
public Point getCurrentRefPoint() {
return currentRefPoint;
}
}

View File

@ -0,0 +1,122 @@
package model;
import java.util.ArrayList;
import java.util.List;
public class HitboxRectangle extends Hitbox {
private List<Point> listPointsIso = new ArrayList<Point>();
private List<Point> listPointsCartesian = new ArrayList<Point>();
private float widthHitbox = 0,heightHitbox = 0; // Ширина и высота хитбокса в декартовых координатах.
public HitboxRectangle(String shape, Entity owner){
super(shape);
setOwnerEntity(owner);
}
public HitboxRectangle(String shape,List<Point> listPointsIso,List<Point> listPointsCartesian){
super(shape);
this.listPointsIso = listPointsIso;
this.listPointsCartesian = listPointsCartesian;
initListsPoints();
}
//informationHitbox - default="Rectangle 0 0 96 98"
public HitboxRectangle(String[] dataHitbox, Entity owner){
super(dataHitbox[0]);
setOwnerEntity(owner);
initListsPoints();
//в 0-м индексе всегда идет название фигуры.Так сделан наш xml.
parseStringToRectangleHitbox(dataHitbox);
createCartesianPointsFromWidthAndHeigh();
convertCartesianPointsToIso();
printToConsole();
}
public 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[] dataHitbox) {
referencePoint.x = Float.parseFloat(dataHitbox[1]);
referencePoint.y = Float.parseFloat(dataHitbox[2]);
widthHitbox = Float.parseFloat(dataHitbox[3]);
heightHitbox = Float.parseFloat(dataHitbox[4]);
}
//тут не правильно реализована функция, т.к. до сих пор нигде не используется. Надо переделать будет.
public void convertIsoPointsToCartesian() {
Point isoPoint;
for (int i = 0 ; i<4;i++) {
isoPoint = listPointsIso.get(i);
cartesianToIsometric(isoPoint.x,isoPoint.y,listPointsCartesian.get(i));
}
}
//+++++++
public void convertCartesianPointsToIso() {
Point cartesianPoint;
for (int i = 0 ; i<4;i++) {
cartesianPoint = listPointsCartesian.get(i);
cartesianToIsometric(cartesianPoint.x,cartesianPoint.y,listPointsIso.get(i));
}
}
//+++++++
private void createCartesianPointsFromWidthAndHeigh(){
Point cartesianCenterImagePoint = new Point(0, 0);
isometricToCartesian(owner.getImage().getWidth()/2,owner.getImage().getHeight(),cartesianCenterImagePoint);
Point cartesianCenterRefPoint = new Point(cartesianCenterImagePoint.x-referencePoint.x, cartesianCenterImagePoint.y-referencePoint.y);
listPointsCartesian.clear();
listPointsCartesian.add(new Point(cartesianCenterRefPoint.x-widthHitbox,cartesianCenterRefPoint.y));
listPointsCartesian.add(new Point(cartesianCenterRefPoint.x,cartesianCenterRefPoint.y));
listPointsCartesian.add(new Point(cartesianCenterRefPoint.x,cartesianCenterRefPoint.y-heightHitbox));
listPointsCartesian.add(new Point(cartesianCenterRefPoint.x-widthHitbox,cartesianCenterRefPoint.y-heightHitbox));
}
public List<Point> getListPointsIso() {
return listPointsIso;
}
public List<Point> getListPointsCartesian() {
return listPointsCartesian;
}
@Override
public String listPointsToString() {
System.out.println("Парсинг данных");
parseCartesianListPointsToWidthHeight();
calculationReferencePoint();
return "Rectangle "+(int)referencePoint.x+" "+(int)referencePoint.y+" "+(int)widthHitbox+" "+(int)heightHitbox;
}
public void parseCartesianListPointsToWidthHeight() {
widthHitbox = Math.abs(listPointsCartesian.get(0).x-listPointsCartesian.get(1).x);
heightHitbox = Math.abs(listPointsCartesian.get(1).y-listPointsCartesian.get(2).y);
}
@Override
public void calculationReferencePoint() {
Point bottomPoint = new Point(0,0);
for(Point currentPoint: listPointsIso) {
if(bottomPoint.y<currentPoint.y) {
bottomPoint.x=currentPoint.x;
bottomPoint.y=currentPoint.y;
}
}
bottomPoint = isometricToCartesian(bottomPoint.x,bottomPoint.y,bottomPoint);
Point cartesianCenterImagePoint= new Point(0,0);
cartesianCenterImagePoint = isometricToCartesian(owner.getImage().getWidth()/2,owner.getImage().getHeight(),cartesianCenterImagePoint);
referencePoint.x = cartesianCenterImagePoint.x-bottomPoint.x;
referencePoint.y = cartesianCenterImagePoint.y-bottomPoint.y;
}
}

View File

@ -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;
}
}

View File

@ -8,4 +8,8 @@ public class Point {
x = mainX;
y = mainY;
}
public void setXY(float x, float y){
this.x = x;
this.y = y;
}
}

View File

@ -32,6 +32,8 @@ import org.xml.sax.SAXException;
import events.EntityDrawboxChangedEvent;
import events.EntityDrawboxChangedListener;
import events.EntityHitboxChangedEvent;
import events.EntityHitboxChangedListener;
import exception.DuplicateEntryException;
import launch.Launcher;
import model.Entity;
@ -41,7 +43,7 @@ import model.Entity;
* Класс данных, который оперирует их сохранением, загрузкой, и хранением в памяти.
* ВАЖНО: данный класс хранит так же актуальную копию XML-представления файла
* */
public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
public class Project implements Iterable<Entity>, EntityDrawboxChangedListener, EntityHitboxChangedListener {
/**
* Путь к XML по-умолчанию.
@ -50,7 +52,10 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
* */
public static final String DEFAULT_XML_PATH = "res/"; //TODO: make an actual path to example objecttypes in the root of the project
public static final String DEFAULT_XML_FILENAME = "objecttypes.xml";
/**
* Переменная которая отслеживает, были ли произведены изменения XML-Dom-дерева.
* */
public static boolean changeOfXmlDOM = false;
static Project thisProject;
private List <Entity> listEntity = new ArrayList<Entity>();
private String path = DEFAULT_XML_PATH;
@ -125,7 +130,7 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
}
/**
* Загружает типы сущностей из файла с заданным именем и расположением.<br>
* Загружает типы сущностей из файла с заданным именем и расположением.<br>0
* */
public void load() throws SAXException, IOException, ParserConfigurationException {
listEntity.clear();
@ -174,9 +179,8 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
}
}
Entity e = new Entity(entityName, newDrawbox, newHitbox);
Entity e = new Entity(entityName, newDrawbox, newHitbox, sprite);
e.setType(type);
e.setImage(sprite);
listEntity.add(e);
}
}
@ -194,6 +198,7 @@ public class Project implements Iterable<Entity>, 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!");
@ -237,16 +242,17 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
Element drawboxProperty = document.createElement("property");
drawboxProperty.setAttribute("name", "drawbox");
drawboxProperty.setAttribute("type", "string");
drawboxProperty.setAttribute("default", ""); // empty, because on creation there is no drawbox yet
drawboxProperty.setAttribute("default", "0 0 0 0 0 0 0 0"); // empty, because on creation there is no drawbox yet
objecttypeElement.appendChild(drawboxProperty);
// format: <property name="hitbox" type="string" default="HITBOX_TYPE OFFSET_X OFFSET_Y SIZE"/>
Element hitboxProperty = document.createElement("property");
hitboxProperty.setAttribute("name", "hitbox");
hitboxProperty.setAttribute("type", "string");
hitboxProperty.setAttribute("default", ""); // empty, no hitbox yet
hitboxProperty.setAttribute("default", "Rectangle 0 0 0 0"); // empty, no hitbox yet
objecttypeElement.appendChild(hitboxProperty);
changeOfXmlDOM = true;
//printXMlToConsole(); //DEBUG!
}
@ -296,10 +302,11 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new FileOutputStream(getXMLPath() + getXMLFileName()));
transformer.transform(source, result);
JOptionPane.showMessageDialog(null, "Бугага, сохранилось!", "Success", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Бугагашеньки, сохранилось!", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (TransformerException | FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Saving project is unsuccsessfull! Erorr is: "+e, "Project save unsuccsesfull", JOptionPane.ERROR_MESSAGE);
}
changeOfXmlDOM = false;
}
public void PrintEntitys() {
@ -355,10 +362,32 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
//we have hitbox, drawbox and class, gotta set the right one
Element propertyElement = ((Element)properties.item(i));
if (propertyElement.getAttribute("name").equals("drawbox")) {
propertyElement.setAttribute("default", event.owner.getDrawbox().toString());
propertyElement.setAttribute("default", event.owner.getDrawbox().listPointsToString());
}
}
}
changeOfXmlDOM = true;
}
/**
* Получение события при отрисовке нового Hitbox, для изменения XML-дерева.
* Объект event хранит в себе ссылку на новый объект Hitbox и объект entity, для которой он был создан.
* */
@Override
public void hitboxChanged(EntityHitboxChangedEvent event) {
String entityName = event.owner.getName();
Node entityToUpdate = getEntityXMLNodeByName(entityName);
NodeList properties = entityToUpdate.getChildNodes();
for(int i = 0; i < properties.getLength(); i++) {
if(properties.item(i) instanceof Element) { // ignoring #text nodes
//we have hitbox, drawbox and class, gotta set the right one
Element propertyElement = ((Element)properties.item(i));
if (propertyElement.getAttribute("name").equals("hitbox")) {
propertyElement.setAttribute("default", event.owner.getHitbox().listPointsToString());
}
}
}
changeOfXmlDOM = true;
}
private Node getEntityXMLNodeByName(String name) { //returns entitie's objecttype node
@ -388,6 +417,8 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
stripEmptyElements(child);
}
}
}
//в момент окончания рисования, в зависимости в какой мы рисуем вкладке хитбокса,
//в зависимости от того в какой панельке(jpanel)и подклассе интерфейса Editable