file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ParallelActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/ParallelActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.SameTypeOutputTypeFunction;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Action;
import static games.rednblack.editor.graph.actions.ActionFieldType.Parallel;
public class ParallelActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ParallelActionNodeConfiguration() {
super("ParallelAction", "Parallel", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action0", "Action 0", true, Action));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action1", "Action 1", true, Action));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", new SameTypeOutputTypeFunction<>("action0"), Parallel, Action));
}
}
| 1,104 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
EntityNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/EntityNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Entity;
public class EntityNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public EntityNodeConfiguration() {
super("Entity", "Entity", "Entity");
addNodeOutput(
new GraphNodeOutputImpl<>("entity", "Entity",
Entity));
}
}
| 614 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
RotateToActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/RotateToActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class RotateToActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public RotateToActionNodeConfiguration() {
super("RotateToAction", "Rotate To", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("degree", "Degree", true, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,091 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
FadeInActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/FadeInActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Float;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class FadeInActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public FadeInActionNodeConfiguration() {
super("FadeInAction", "Fade In", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", true, Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
} | 1,002 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ForeverActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/ForeverActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Action;
public class ForeverActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ForeverActionNodeConfiguration() {
super("ForeverAction", "Forever", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action0", "Action", true, Action));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 784 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
MoveToActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/MoveToActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class MoveToActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public MoveToActionNodeConfiguration() {
super("MoveToAction", "Move To", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("position", "Position", true, ActionFieldType.Vector2, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,089 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SizeByActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/SizeByActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class SizeByActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public SizeByActionNodeConfiguration() {
super("SizeByAction", "Size By", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("size", "Size", true, ActionFieldType.Vector2, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,082 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ScaleByActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/ScaleByActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class ScaleByActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ScaleByActionNodeConfiguration() {
super("ScaleByAction", "Scale By", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("scale", "Scale", true, ActionFieldType.Vector2, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,087 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AlphaActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/AlphaActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Float;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class AlphaActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public AlphaActionNodeConfiguration() {
super("AlphaAction", "Alpha", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("alpha", "Alpha", true, Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,118 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
RepeatActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/RepeatActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Action;
import static games.rednblack.editor.graph.actions.ActionFieldType.Param;
public class RepeatActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public RepeatActionNodeConfiguration() {
super("RepeatAction", "Repeat", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("count", "Count", true, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action0", "Action", true, Action));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
} | 988 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SequenceActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/SequenceActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.SameTypeOutputTypeFunction;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Action;
import static games.rednblack.editor.graph.actions.ActionFieldType.Sequence;
public class SequenceActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public SequenceActionNodeConfiguration() {
super("SequenceAction", "Sequence", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action0", "Action 0", true, Action));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action1", "Action 1", true, Action));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", new SameTypeOutputTypeFunction<>("action0"), Action, Sequence));
}
}
| 1,104 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AddActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/AddActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Action;
import static games.rednblack.editor.graph.actions.ActionFieldType.Entity;
public class AddActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public AddActionNodeConfiguration() {
super("Function", "Add Action", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("action", "Action", true, Action));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("entity", "Entity", true, Entity));
}
} | 809 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ScaleToActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/ScaleToActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class ScaleToActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ScaleToActionNodeConfiguration() {
super("ScaleToAction", "Scale To", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("scale", "Scale", true, ActionFieldType.Vector2, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,087 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
FadeOutActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/FadeOutActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Float;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class FadeOutActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public FadeOutActionNodeConfiguration() {
super("FadeOutAction", "Fade Out", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", true, Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,007 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
RotateByActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/RotateByActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class RotateByActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public RotateByActionNodeConfiguration() {
super("RotateByAction", "Rotate By", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("degree", "Degree", true, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,091 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SizeToActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/SizeToActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class SizeToActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public SizeToActionNodeConfiguration() {
super("SizeToAction", "Size To", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("size", "Size", true, ActionFieldType.Vector2, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,082 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
MoveByActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/MoveByActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class MoveByActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public MoveByActionNodeConfiguration() {
super("MoveByAction", "Move By", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("position", "Position", true, ActionFieldType.Vector2, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,089 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ColorActionNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/ColorActionNodeConfiguration.java | package games.rednblack.editor.graph.actions.config;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.*;
public class ColorActionNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ColorActionNodeConfiguration() {
super("ColorAction", "Color", "Action");
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("color", "Color", true, Color, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("duration", "Duration", false, ActionFieldType.Float, Param));
addNodeInput(
new GraphNodeInputImpl<ActionFieldType>("interpolation", "Interpolation", false, Interpolation, Param));
addNodeOutput(
new GraphNodeOutputImpl<>("action", "Action", Action));
}
}
| 1,060 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueFloatNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/value/ValueFloatNodeConfiguration.java | package games.rednblack.editor.graph.actions.config.value;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
public class ValueFloatNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ValueFloatNodeConfiguration() {
super("ValueFloat", "Float", "Value");
addNodeOutput(
new GraphNodeOutputImpl<ActionFieldType>("value", "Value", ActionFieldType.Float));
}
}
| 558 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueVector2NodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/value/ValueVector2NodeConfiguration.java | package games.rednblack.editor.graph.actions.config.value;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Vector2;
public class ValueVector2NodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ValueVector2NodeConfiguration() {
super("ValueVector2", "Vector2", "Value");
addNodeOutput(
new GraphNodeOutputImpl<ActionFieldType>("value", "Value", Vector2));
}
}
| 628 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueBooleanNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/value/ValueBooleanNodeConfiguration.java | package games.rednblack.editor.graph.actions.config.value;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
public class ValueBooleanNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ValueBooleanNodeConfiguration() {
super("ValueBoolean", "Boolean", "Value");
addNodeOutput(
new GraphNodeOutputImpl<ActionFieldType>("value", "Value", ActionFieldType.Boolean));
}
}
| 566 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueColorNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/value/ValueColorNodeConfiguration.java | package games.rednblack.editor.graph.actions.config.value;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Color;
public class ValueColorNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ValueColorNodeConfiguration() {
super("ValueColor", "Color", "Value");
addNodeOutput(
new GraphNodeOutputImpl<ActionFieldType>("value", "Value", Color));
}
}
| 617 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueInterpolationNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/value/ValueInterpolationNodeConfiguration.java | package games.rednblack.editor.graph.actions.config.value;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
import static games.rednblack.editor.graph.actions.ActionFieldType.Interpolation;
public class ValueInterpolationNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ValueInterpolationNodeConfiguration() {
super("ValueInterpolation", "Interpolation", "Math");
addNodeOutput(
new GraphNodeOutputImpl<ActionFieldType>("value", "Value", Interpolation));
}
}
| 663 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueParamNodeConfiguration.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/config/value/ValueParamNodeConfiguration.java | package games.rednblack.editor.graph.actions.config.value;
import games.rednblack.editor.graph.GraphNodeOutputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.config.NodeConfigurationImpl;
public class ValueParamNodeConfiguration extends NodeConfigurationImpl<ActionFieldType> {
public ValueParamNodeConfiguration() {
super("ValueParam", "Param", "Value");
addNodeOutput(
new GraphNodeOutputImpl<ActionFieldType>("value", "Value", ActionFieldType.Param));
}
} | 556 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ValueInterpolationBoxProducer.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/producer/ValueInterpolationBoxProducer.java | package games.rednblack.editor.graph.actions.producer;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisSelectBox;
import games.rednblack.editor.graph.GraphBox;
import games.rednblack.editor.graph.GraphBoxImpl;
import games.rednblack.editor.graph.GraphBoxOutputConnector;
import games.rednblack.editor.graph.GraphBoxPartImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.data.NodeConfiguration;
import games.rednblack.editor.graph.producer.ValueGraphBoxProducer;
import games.rednblack.editor.renderer.utils.InterpolationMap;
import games.rednblack.h2d.common.view.ui.StandardWidgetsFactory;
import java.util.Map;
public class ValueInterpolationBoxProducer extends ValueGraphBoxProducer<ActionFieldType> {
public ValueInterpolationBoxProducer(NodeConfiguration<ActionFieldType> configuration) {
super(configuration);
}
@Override
public GraphBox<ActionFieldType> createPipelineGraphBox(Skin skin, String id, Map<String, String> data) {
String name = data.get("interpolation");
return createGraphBox(skin, id, name);
}
@Override
public GraphBox<ActionFieldType> createDefault(Skin skin, String id) {
return createGraphBox(skin, id, "linear");
}
private GraphBox<ActionFieldType> createGraphBox(Skin skin, String id, String interpolation) {
GraphBoxImpl<ActionFieldType> end = new GraphBoxImpl<>(id, configuration, skin);
end.addGraphBoxPart(createValuePart(skin, interpolation));
return end;
}
private GraphBoxPartImpl<ActionFieldType> createValuePart(Skin skin, String interpolation) {
VisSelectBox<String> selectBox = StandardWidgetsFactory.createSelectBox(String.class);
Array<String> names = new Array<>();
InterpolationMap.map.keySet().forEach(names::add);
selectBox.setItems(names);
selectBox.setSelected(interpolation);
GraphBoxPartImpl<ActionFieldType> addPart = new GraphBoxPartImpl<>(selectBox, new GraphBoxPartImpl.Callback() {
@Override
public void serialize(Map<String, String> object) {
object.put("interpolation", selectBox.getSelected());
}
});
addPart.setOutputConnector(GraphBoxOutputConnector.Side.Right, configuration.getNodeOutputs().get("value"));
return addPart;
}
@Override
public boolean isUnique() {
return false;
}
}
| 2,527 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
EventActionBoxProducer.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/producer/EventActionBoxProducer.java | package games.rednblack.editor.graph.actions.producer;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.kotcrab.vis.ui.widget.VisValidatableTextField;
import games.rednblack.editor.graph.*;
import games.rednblack.editor.graph.data.FieldType;
import games.rednblack.editor.graph.data.NodeConfiguration;
import games.rednblack.editor.graph.producer.ValueGraphBoxProducer;
import games.rednblack.editor.view.ui.validator.StringNameValidator;
import java.util.Map;
public class EventActionBoxProducer<T extends FieldType> extends ValueGraphBoxProducer<T> {
public EventActionBoxProducer(NodeConfiguration<T> configuration) {
super(configuration);
}
@Override
public GraphBox<T> createPipelineGraphBox(Skin skin, String id, Map<String, String> data) {
String name = data.get("v");
return createGraphBox(skin, id, name);
}
@Override
public GraphBox<T> createDefault(Skin skin, String id) {
return createGraphBox(skin, id, "");
}
private GraphBox<T> createGraphBox(Skin skin, String id, String name) {
GraphBoxImpl<T> end = new GraphBoxImpl<T>(id, configuration, skin);
end.addGraphBoxPart(createValuePart(skin, name));
return end;
}
private GraphBoxPartImpl<T> createValuePart(Skin skin, String name) {
final VisValidatableTextField v1Input = new VisValidatableTextField(new StringNameValidator()) {
@Override
public float getPrefWidth() {
return 80;
}
};
v1Input.setText(name);
v1Input.addListener(
new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
v1Input.fire(new GraphChangedEvent(false, true));
}
});
HorizontalGroup horizontalGroup = new HorizontalGroup();
horizontalGroup.addActor(new Label("Name: ", skin));
horizontalGroup.addActor(v1Input);
GraphBoxPartImpl<T> colorPart = new GraphBoxPartImpl<T>(horizontalGroup,
new GraphBoxPartImpl.Callback() {
@Override
public void serialize(Map<String, String> object) {
object.put("v", v1Input.getText());
}
});
colorPart.setOutputConnector(GraphBoxOutputConnector.Side.Right, configuration.getNodeOutputs().get("action"));
return colorPart;
}
@Override
public boolean isUnique() {
return false;
}
}
| 2,806 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ArrayActionBoxProducer.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/graph/actions/producer/ArrayActionBoxProducer.java | package games.rednblack.editor.graph.actions.producer;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.kotcrab.vis.ui.widget.VisTextButton;
import games.rednblack.editor.graph.GraphBoxImpl;
import games.rednblack.editor.graph.GraphBoxPartImpl;
import games.rednblack.editor.graph.GraphChangedEvent;
import games.rednblack.editor.graph.GraphNodeInputImpl;
import games.rednblack.editor.graph.actions.ActionFieldType;
import games.rednblack.editor.graph.data.GraphNodeInput;
import games.rednblack.editor.graph.data.NodeConfiguration;
import games.rednblack.editor.graph.producer.GraphBoxProducerImpl;
import games.rednblack.h2d.common.view.ui.StandardWidgetsFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import static games.rednblack.editor.graph.actions.ActionFieldType.Action;
public class ArrayActionBoxProducer extends GraphBoxProducerImpl<ActionFieldType> {
private Class<? extends NodeConfiguration<ActionFieldType>> configurationType;
public ArrayActionBoxProducer(Class<? extends NodeConfiguration<ActionFieldType>> type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
super(type.getDeclaredConstructor().newInstance());
configurationType = type;
}
@Override
public GraphBoxImpl<ActionFieldType> createPipelineGraphBox(Skin skin, String id, Map<String, String> data) {
GraphBoxImpl<ActionFieldType> graphBox = null;
int pins = Integer.parseInt(data.get("pins"));
try {
graphBox = createPipelineGraphBoxConfig(skin, id, configurationType.getDeclaredConstructor().newInstance());
if (pins != graphBox.getInputs().size()) {
for (int i = 0; i < pins - 2; i++) {
addPin(skin, graphBox);
}
}
addPart(skin, graphBox);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return graphBox;
}
@Override
public GraphBoxImpl<ActionFieldType> createDefault(Skin skin, String id) {
Map<String, String> data = new HashMap<>();
data.put("pins", String.valueOf(2));
return createPipelineGraphBox(skin, id, data);
}
private void addPart(Skin skin, GraphBoxImpl<ActionFieldType> graphBox) {
Map<String, GraphNodeInput<ActionFieldType>> inputs = graphBox.getConfiguration().getNodeInputs();
VisTextButton addButton = StandardWidgetsFactory.createTextButton("+ Add Pin");
VisTextButton removeButton = StandardWidgetsFactory.createTextButton("- Remove Pin");
removeButton.setDisabled(inputs.size() <= 2);
addButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
addPin(skin, graphBox);
addButton.fire(new GraphChangedEvent(true, false));
if (inputs.size() > 2) {
removeButton.setDisabled(false);
}
}
});
addButton.addListener(new ClickListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.cancel();
return true;
}
});
GraphBoxPartImpl<ActionFieldType> addPart = new GraphBoxPartImpl<>(addButton, null);
graphBox.addHeaderGraphBoxPart(addPart);
removeButton.addListener(new ClickListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.cancel();
return true;
}
});
removeButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Map<String, GraphNodeInput<ActionFieldType>> inputs = graphBox.getConfiguration().getNodeInputs();
GraphNodeInput<ActionFieldType> n = inputs.get("action" + (inputs.size() - 1));
inputs.remove(n.getFieldId());
graphBox.removeGraphBoxPart(inputs.size());
graphBox.invalidate();
addButton.fire(new GraphChangedEvent(true, false));
if (inputs.size() == 2) {
removeButton.setDisabled(true);
}
}
});
GraphBoxPartImpl<ActionFieldType> removePart = new GraphBoxPartImpl<>(removeButton, null);
graphBox.addFooterGraphBoxPart(removePart);
graphBox.setSerializeCallback(object -> {
object.put("pins", String.valueOf(inputs.size()));
});
}
private void addPin(Skin skin, GraphBoxImpl<ActionFieldType> graphBox){
Map<String, GraphNodeInput<ActionFieldType>> inputs = graphBox.getConfiguration().getNodeInputs();
GraphNodeInputImpl<ActionFieldType> n = new GraphNodeInputImpl<>("action" + inputs.size(), "Action " + inputs.size(), true, Action);
inputs.put(n.getFieldId(), n);
graphBox.addInputGraphPart(skin, n);
graphBox.invalidate();
}
}
| 5,502 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
GroupRegexHighlightRule.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/code/GroupRegexHighlightRule.java | package games.rednblack.editor.code;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.util.highlight.Highlight;
import com.kotcrab.vis.ui.util.highlight.HighlightRule;
import com.kotcrab.vis.ui.widget.HighlightTextArea;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Highlighter rule using regex to detect text matches and select a single group
*/
public class GroupRegexHighlightRule implements HighlightRule {
private Color[] colors;
private Pattern pattern;
private int[] groups;
public GroupRegexHighlightRule (String regex) {
pattern = Pattern.compile(regex);
}
public GroupRegexHighlightRule colors(Color... colors) {
this.colors = colors;
return this;
}
public GroupRegexHighlightRule groups(int... groups) {
this.groups = groups;
return this;
}
@Override
public void process (HighlightTextArea textArea, Array<Highlight> highlights) {
Matcher matcher = pattern.matcher(textArea.getText());
while (matcher.find()) {
for (int i = 0; i < groups.length; i++) {
int group = groups[i];
Color color = colors[i];
if (group <= matcher.groupCount() && matcher.start(group) < matcher.end(group))
highlights.add(new Highlight(color, matcher.start(group), matcher.end(group)));
}
}
}
}
| 1,473 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
MultilineRegexHighlightRule.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/code/MultilineRegexHighlightRule.java | package games.rednblack.editor.code;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.util.highlight.Highlight;
import com.kotcrab.vis.ui.util.highlight.HighlightRule;
import com.kotcrab.vis.ui.widget.HighlightTextArea;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MultilineRegexHighlightRule implements HighlightRule {
private Color color;
private Pattern pattern;
public MultilineRegexHighlightRule (Color color, String regex) {
this.color = color;
pattern = Pattern.compile(regex, Pattern.MULTILINE);
}
@Override
public void process (HighlightTextArea textArea, Array<Highlight> highlights) {
Matcher matcher = pattern.matcher(textArea.getText());
while (matcher.find()) {
highlights.add(new Highlight(color, matcher.start(), matcher.end()));
}
}
}
| 923 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
GLSLSyntax.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/code/syntax/GLSLSyntax.java | package games.rednblack.editor.code.syntax;
import com.badlogic.gdx.graphics.Color;
import games.rednblack.editor.code.MultilineRegexHighlightRule;
/*
GLSL syntax highlight rules: https://github.com/euler0/sublime-glsl
*/
public class GLSLSyntax extends ProgrammingSyntax {
public GLSLSyntax() {
//Precision
regex(Color.valueOf("BED6FF"), "\\b(precision|highp|mediump|lowp)");
//Control
regex(Color.valueOf("66CCB3"), "\\b(break|case|continue|default|discard|do|else|for|if|return|switch|while)\\b");
//types
regex(Color.valueOf("EFC090"), "\\b(void|bool|int|uint|float|double|vec[2|3|4]|dvec[2|3|4]|bvec[2|3|4]|ivec[2|3|4]|uvec[2|3|4]|mat[2|3|4]|mat2x2|mat2x3|mat2x4|mat3x2|mat3x3|mat3x4|mat4x2|mat4x3|mat4x4|dmat2|dmat3|dmat4|dmat2x2|dmat2x3|dmat2x4|dmat3x2|dmat3x3|dmat3x4|dmat4x2|dmat4x3|dmat4x4|sampler[1|2|3]D|image[1|2|3]D|samplerCube|imageCube|sampler2DRect|image2DRect|sampler[1|2]DArray|image[1|2]DArray|samplerBuffer|imageBuffer|sampler2DMS|image2DMS|sampler2DMSArray|image2DMSArray|samplerCubeArray|imageCubeArray|sampler[1|2]DShadow|sampler2DRectShadow|sampler[1|2]DArrayShadow|samplerCubeShadow|samplerCubeArrayShadow|isampler[1|2|3]D|iimage[1|2|3]D|isamplerCube|iimageCube|isampler2DRect|iimage2DRect|isampler[1|2]DArray|iimage[1|2]DArray|isamplerBuffer|iimageBuffer|isampler2DMS|iimage2DMS|isampler2DMSArray|iimage2DMSArray|isamplerCubeArray|iimageCubeArray|atomic_uint|usampler[1|2|3]D|uimage[1|2|3]D|usamplerCube|uimageCube|usampler2DRect|uimage2DRect|usampler[1|2]DArray|uimage[1|2]DArray|usamplerBuffer|uimageBuffer|usampler2DMS|uimage2DMS|usampler2DMSArray|uimage2DMSArray|usamplerCubeArray|uimageCubeArray|struct)\\b");
//modifiers
regex(Color.valueOf("CC66A8"), "\\b(layout|attribute|centroid|sampler|patch|const|flat|in|inout|invariant|noperspective|out|smooth|uniform|varying|buffer|shared|coherent|readonly|writeonly|volatile|restrict)\\b");
//GL variables
regex(Color.valueOf("66CC80"), "\\b(gl_BackColor|gl_BackLightModelProduct|gl_BackLightProduct|gl_BackMaterial|gl_BackSecondaryColor|gl_ClipDistance|gl_ClipPlane|gl_ClipVertex|gl_Color|gl_DepthRange|gl_DepthRangeParameters|gl_EyePlaneQ|gl_EyePlaneR|gl_EyePlaneS|gl_EyePlaneT|gl_Fog|gl_FogCoord|gl_FogFragCoord|gl_FogParameters|gl_FragColor|gl_FragCoord|gl_FragData|gl_FragDepth|gl_FrontColor|gl_FrontFacing|gl_FrontLightModelProduct|gl_FrontLightProduct|gl_FrontMaterial|gl_FrontSecondaryColor|gl_InstanceID|gl_Layer|gl_LightModel|gl_LightModelParameters|gl_LightModelProducts|gl_LightProducts|gl_LightSource|gl_LightSourceParameters|gl_MaterialParameters|gl_ModelViewMatrix|gl_ModelViewMatrixInverse|gl_ModelViewMatrixInverseTranspose|gl_ModelViewMatrixTranspose|gl_ModelViewProjectionMatrix|gl_ModelViewProjectionMatrixInverse|gl_ModelViewProjectionMatrixInverseTranspose|gl_ModelViewProjectionMatrixTranspose|gl_MultiTexCoord[0-7]|gl_Normal|gl_NormalMatrix|gl_NormalScale|gl_ObjectPlaneQ|gl_ObjectPlaneR|gl_ObjectPlaneS|gl_ObjectPlaneT|gl_Point|gl_PointCoord|gl_PointParameters|gl_PointSize|gl_Position|gl_PrimitiveIDIn|gl_ProjectionMatrix|gl_ProjectionMatrixInverse|gl_ProjectionMatrixInverseTranspose|gl_ProjectionMatrixTranspose|gl_SecondaryColor|gl_TexCoord|gl_TextureEnvColor|gl_TextureMatrix|gl_TextureMatrixInverse|gl_TextureMatrixInverseTranspose|gl_TextureMatrixTranspose|gl_Vertex|gl_VertexID)\\b");
//GL constants
regex(Color.valueOf("9966CC"), "\\b(gl_MaxClipPlanes|gl_MaxCombinedTextureImageUnits|gl_MaxDrawBuffers|gl_MaxFragmentUniformComponents|gl_MaxLights|gl_MaxTextureCoords|gl_MaxTextureImageUnits|gl_MaxTextureUnits|gl_MaxVaryingFloats|gl_MaxVertexAttribs|gl_MaxVertexTextureImageUnits|gl_MaxVertexUniformComponents)\\b");
//GL functions
regex(Color.valueOf("CC8F66"), "\\b(abs|acos|all|any|asin|atan|ceil|clamp|cos|cross|degrees|dFdx|dFdy|distance|dot|equal|exp|exp2|faceforward|floor|fract|ftransform|fwidth|greaterThan|greaterThanEqual|inversesqrt|length|lessThan|lessThanEqual|log|log2|matrixCompMult|max|min|mix|mod|noise[1-4]|normalize|not|notEqual|outerProduct|pow|radians|reflect|refract|shadow1D|shadow1DLod|shadow1DProj|shadow1DProjLod|shadow2D|shadow2DLod|shadow2DProj|shadow2DProjLod|sign|sin|smoothstep|sqrt|step|tan|texture1D|texture1DLod|texture1DProj|texture1DProjLod|texture2D|texture2DLod|texture2DProj|texture2DProjLod|texture3D|texture3DLod|texture3DProj|texture3DProjLod|textureCube|textureCubeLod|transpose)\\b");
//Comments
regex(Color.valueOf("75715E"), "/\\*(?:.|[\\n\\r])*?\\*/");
addRule(new MultilineRegexHighlightRule(Color.valueOf("75715E"), "^\\s*//.*$"));
//Preprocessor
addRule(new MultilineRegexHighlightRule(Color.valueOf("75715E"), "^\\s*#\\s*(define|undef|if|ifdef|ifndef|else|elif|endif|error|pragma|extension|version|line)\\b"));
}
}
| 4,843 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ProgrammingSyntax.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/code/syntax/ProgrammingSyntax.java | package games.rednblack.editor.code.syntax;
import com.kotcrab.vis.ui.util.highlight.Highlighter;
public abstract class ProgrammingSyntax extends Highlighter {
}
| 164 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TypingLabelSyntax.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/code/syntax/TypingLabelSyntax.java | package games.rednblack.editor.code.syntax;
import com.badlogic.gdx.graphics.Color;
import com.kotcrab.vis.ui.util.highlight.Highlighter;
import games.rednblack.editor.code.GroupRegexHighlightRule;
public class TypingLabelSyntax extends Highlighter {
public TypingLabelSyntax() {
String typingLabelToken = "EASE|ENDEASE|HANG|ENDHANG|JUMP|ENDJUMP|SHAKE|ENDSHAKE|SICK|ENDSICK|SLIDE|ENDSLIDE"
+ "|WAVE|ENDWAVE|WIND|ENDWIND|RAINBOW|ENDRAINBOW|GRADIENT|ENDGRADIENT|FADE|ENDFADE"
+ "|BLINK|ENDBLINK|WAIT|SPEED|SLOWER|SLOW|NORMAL|FAST|FASTER|COLOR|CLEARCOLOR|ENDCOLOR"
+ "|VAR|EVENT|RESET|SKIP";
GroupRegexHighlightRule tokenRegex = new GroupRegexHighlightRule("\\{(" + typingLabelToken + ")(=(.*?))?\\}")
.colors(Color.valueOf("66CCB3"), Color.valueOf("BED6FF"))
.groups(1, 3);
addRule(tokenRegex);
}
}
| 912 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
PluginManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/PluginManager.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.proxy;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisImageButton;
import games.rednblack.editor.controller.commands.PluginItemCommand;
import games.rednblack.editor.factory.ItemFactory;
import games.rednblack.editor.renderer.SceneLoader;
import games.rednblack.editor.renderer.data.LayerItemVO;
import games.rednblack.editor.renderer.data.ProjectInfoVO;
import games.rednblack.editor.renderer.data.SceneVO;
import games.rednblack.editor.utils.runtime.EntityUtils;
import games.rednblack.editor.view.menu.HyperLap2DMenuBarMediator;
import games.rednblack.editor.view.stage.Sandbox;
import games.rednblack.editor.view.stage.SandboxMediator;
import games.rednblack.editor.view.stage.UIStage;
import games.rednblack.editor.view.ui.FollowersUIMediator;
import games.rednblack.editor.view.ui.UIDropDownMenu;
import games.rednblack.editor.view.ui.UIDropDownMenuMediator;
import games.rednblack.editor.view.ui.box.UILayerBoxMediator;
import games.rednblack.editor.view.ui.box.UIToolBoxMediator;
import games.rednblack.h2d.common.IItemCommand;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.factory.IFactory;
import games.rednblack.h2d.common.plugins.H2DPlugin;
import games.rednblack.h2d.common.plugins.PluginAPI;
import games.rednblack.h2d.common.proxy.CursorManager;
import games.rednblack.h2d.common.view.tools.Tool;
import games.rednblack.h2d.common.vo.CursorData;
import games.rednblack.h2d.common.vo.EditorConfigVO;
import games.rednblack.h2d.common.vo.ProjectVO;
import games.rednblack.h2d.common.vo.SceneConfigVO;
import games.rednblack.puremvc.Facade;
import games.rednblack.puremvc.Proxy;
import java.util.*;
/**
* Created by azakhary on 7/24/2015.
*/
public class PluginManager extends Proxy implements PluginAPI {
private static final String TAG = PluginManager.class.getCanonicalName();
public static final String NAME = TAG;
private ArrayList<H2DPlugin> plugins = new ArrayList<>();
private String pluginDir, cacheDir;
private HashSet<Integer> pluginEntities;
public PluginManager() {
super(NAME, null);
}
public H2DPlugin registerPlugin(H2DPlugin plugin) {
plugins.add(plugin);
return plugin;
}
public void initPlugin(H2DPlugin plugin) {
if(plugins.contains(plugin)) return;
registerPlugin(plugin);
plugin.setAPI(this);
plugin.initPlugin();
}
public void dropDownActionSets(Set<Integer> selectedEntities, Array<String> actionsSet) {
for(H2DPlugin plugin: plugins) {
plugin.onDropDownOpen(selectedEntities, actionsSet);
}
}
public void setDropDownItemName(String action, String name) {
UIDropDownMenuMediator dropDownMenuMediator = facade.retrieveMediator(UIDropDownMenuMediator.NAME);
dropDownMenuMediator.getViewComponent().setActionName(action, name);
}
@Override
public String getProjectPath() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectPath();
}
@Override
public TextureAtlas.AtlasRegion getProjectTextureRegion(String regionName) {
ResourceManager resourceManager = facade.retrieveProxy(ResourceManager.NAME);
return (TextureAtlas.AtlasRegion) resourceManager.getTextureRegion(regionName);
}
@Override
public void reLoadProject() {
Sandbox sandbox = Sandbox.getInstance();
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
projectManager.openProjectAndLoadAllData(projectManager.getCurrentProjectPath());
sandbox.loadCurrentProject();
facade.sendNotification(ProjectManager.PROJECT_DATA_UPDATED);
}
@Override
public void saveProject() {
Sandbox sandbox = Sandbox.getInstance();
SceneDataManager sceneDataManager = facade.retrieveProxy(SceneDataManager.NAME);
SceneVO vo = sandbox.sceneVoFromItems();
sceneDataManager.saveScene(vo);
}
@Override
public void revertibleCommand(IItemCommand command, Object body) {
Object payload = PluginItemCommand.build(command, body);
facade.sendNotification(MsgAPI.ACTION_PLUGIN_PROXY_COMMAND, payload);
}
@Override
public void removeFollower(int entity) {
FollowersUIMediator followersUIMediator = Facade.getInstance().retrieveMediator(FollowersUIMediator.NAME);
followersUIMediator.removeFollower(entity);
}
public void addMenuItem(String menu, String subMenuName, String notificationName) {
HyperLap2DMenuBarMediator hyperlap2DMenuBarMediator = facade.retrieveMediator(HyperLap2DMenuBarMediator.NAME);
hyperlap2DMenuBarMediator.addMenuItem(menu, subMenuName, notificationName);
}
@Override
public void addTool(String toolName, VisImageButton.VisImageButtonStyle toolBtnStyle, boolean addSeparator, Tool tool) {
UIToolBoxMediator uiToolBoxMediator = facade.retrieveMediator(UIToolBoxMediator.NAME);
uiToolBoxMediator.addTool(toolName, toolBtnStyle, addSeparator, tool);
Map.Entry<String, Tool> toolPair = new Map.Entry<String, Tool>() {
@Override
public String getKey() {
return toolName;
}
@Override
public Tool getValue() {
return tool;
}
@Override
public Tool setValue(Tool value) {
Tool old = getValue();
setValue(value);
return old;
}
};
facade.sendNotification(MsgAPI.NEW_TOOL_ADDED, toolPair);
}
@Override
public void toolHotSwap(Tool tool) {
SandboxMediator sandboxMediator = facade.retrieveMediator(SandboxMediator.NAME);
sandboxMediator.toolHotSwap(tool);
}
@Override
public void toolHotSwapBack() {
SandboxMediator sandboxMediator = facade.retrieveMediator(SandboxMediator.NAME);
sandboxMediator.toolHotSwapBack();
}
public void setPluginDir(String pluginDir) {
this.pluginDir = pluginDir;
}
@Override
public String getPluginDir() {
return pluginDir;
}
public void setCacheDir(String cacheDir) {
this.cacheDir = cacheDir;
}
@Override
public String getCacheDir() {
return cacheDir;
}
@Override
public SceneLoader getSceneLoader() {
return Sandbox.getInstance().getSceneControl().sceneLoader;
}
@Override
public Facade getFacade() {
return facade;
}
@Override
public com.artemis.World getEngine() {
return getSceneLoader().getEngine();
}
@Override
public Stage getUIStage() {
return Sandbox.getInstance().getUIStage();
}
@Override
public IFactory getItemFactory() {
return ItemFactory.get();
}
public boolean isEntityVisible(int e) {
LayerItemVO layer = EntityUtils.getEntityLayer(e);
return layer != null && layer.isVisible;
}
@Override
public HashSet<Integer> getProjectEntities() {
Sandbox sandbox = Sandbox.getInstance();
return sandbox.getSelector().getAllFreeItems();
}
@Override
public void showPopup(HashMap<String, String> actionsSet, Object observable) {
UIDropDownMenu uiDropDownMenu = new UIDropDownMenu();
actionsSet.entrySet().forEach(entry -> uiDropDownMenu.setActionName(entry.getKey(), entry.getValue()));
Array<String> actions = new Array<>();
actionsSet.keySet().forEach(key -> actions.add(key));
uiDropDownMenu.setActionList(actions);
Sandbox sandbox = Sandbox.getInstance();
UIStage uiStage = sandbox.getUIStage();
uiDropDownMenu.setX(sandbox.getInputX());
uiDropDownMenu.setY(uiStage.getHeight() - sandbox.getInputY() - uiDropDownMenu.getHeight());
getUIStage().addActor(uiDropDownMenu);
UIDropDownMenuMediator dropDownMenuMediator = facade.retrieveMediator(UIDropDownMenuMediator.NAME);
dropDownMenuMediator.setCurrentObservable(observable);
}
@Override
public void setCursor(CursorData cursorData, TextureRegion region) {
CursorManager cursorManager = Facade.getInstance().retrieveProxy(CursorManager.NAME);
cursorManager.setCursor(cursorData, region);
}
@Override
public String getCurrentSelectedLayerName() {
UILayerBoxMediator uiLayerBoxMediator = facade.retrieveMediator(UILayerBoxMediator.NAME);
return uiLayerBoxMediator.getViewComponent().getCurrentSelectedLayer().getLayerName();
}
@Override
public EditorConfigVO getEditorConfig() {
SettingsManager settingsManager = facade.retrieveProxy(SettingsManager.NAME);
return settingsManager.editorConfigVO;
}
@Override
public SceneConfigVO getCurrentSceneConfigVO() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentSceneConfigVO();
}
@Override
public ProjectInfoVO getCurrentProjectInfoVO() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectInfoVO();
}
@Override
public ProjectVO getCurrentProjectVO() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectVO();
}
}
| 10,461 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SettingsManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/SettingsManager.java | package games.rednblack.editor.proxy;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import games.rednblack.editor.CustomExceptionHandler;
import games.rednblack.editor.Main;
import games.rednblack.editor.renderer.utils.HyperJson;
import games.rednblack.editor.utils.HyperLap2DUtils;
import games.rednblack.editor.utils.KeyBindingsLayout;
import games.rednblack.h2d.common.vo.EditorConfigVO;
import games.rednblack.puremvc.Facade;
import games.rednblack.puremvc.Proxy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import java.io.*;
import java.util.List;
public class SettingsManager extends Proxy {
private static final String TAG = SettingsManager.class.getCanonicalName();
public static final String NAME = TAG;
private String DEFAULT_FOLDER = "HyperLap2D";
private String defaultWorkspacePath;
public EditorConfigVO editorConfigVO;
public File[] pluginDirs;
public File cacheDir;
public SettingsManager() {
super(NAME, null);
initWorkspace();
}
@Override
public void onRegister() {
super.onRegister();
KeyBindingsLayout.init();
}
private void initWorkspace() {
try {
editorConfigVO = getEditorConfig();
String myDocPath = HyperLap2DUtils.MY_DOCUMENTS_PATH;
defaultWorkspacePath = myDocPath + File.separator + DEFAULT_FOLDER;
FileUtils.forceMkdir(new File(defaultWorkspacePath));
FileUtils.forceMkdir(new File(HyperLap2DUtils.getKeyMapPath()));
pluginDirs = new File[]{new File(Main.getJarContainingFolder(Main.class) + File.separator + "plugins"),
new File(HyperLap2DUtils.getRootPath() + File.separator + "plugins"),
new File(System.getProperty("user.dir") + File.separator + "plugins")};
cacheDir = new File(HyperLap2DUtils.getRootPath() + File.separator + "cache");
FileUtils.forceMkdir(cacheDir);
} catch (IOException e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
e.printStackTrace();
String stacktrace = result.toString();
CustomExceptionHandler.showErrorDialog(null, stacktrace);
}
}
public FileHandle getWorkspacePath() {
if (!editorConfigVO.lastOpenedSystemPath.isEmpty()) {
return new FileHandle(editorConfigVO.lastOpenedSystemPath);
}
return new FileHandle(defaultWorkspacePath);
}
public FileHandle getImportPath() {
if (!editorConfigVO.lastImportedSystemPath.isEmpty()) {
return new FileHandle(editorConfigVO.lastImportedSystemPath);
}
return null;
}
public String[] getKeyMappingFiles() {
File mappingDir = new File(HyperLap2DUtils.getKeyMapPath());
String[] extensions = new String[]{"keymap"};
List<File> files = (List<File>) FileUtils.listFiles(mappingDir, extensions, true);
String[] maps = new String[files.size() + 1];
maps[0] = "default";
for (int i = 0; i < files.size(); i++) {
maps[i + 1] = FilenameUtils.removeExtension(files.get(i).getName());
}
return maps;
}
private EditorConfigVO getEditorConfig() {
EditorConfigVO editorConfig = new EditorConfigVO();
String configFilePath = HyperLap2DUtils.getRootPath() + File.separator + "configs" + File.separator + EditorConfigVO.EDITOR_CONFIG_FILE;
File configFile = new File(configFilePath);
if (!configFile.exists()) {
try {
FileUtils.writeStringToFile(new File(configFilePath), editorConfig.constructJsonString(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Json json = HyperJson.getJson();
String editorConfigJson;
try {
editorConfigJson = FileUtils.readFileToString(configFile, "utf-8");
editorConfig = json.fromJson(EditorConfigVO.class, editorConfigJson);
} catch (IOException e) {
e.printStackTrace();
}
}
return editorConfig;
}
public void setLastOpenedPath(String path) {
editorConfigVO.lastOpenedSystemPath = path;
saveEditorConfig();
}
public void setLastImportedPath(String path) {
editorConfigVO.lastImportedSystemPath = path;
saveEditorConfig();
}
public void saveEditorConfig() {
try {
String configFilePath = HyperLap2DUtils.getRootPath() + File.separator + "configs" + File.separator + EditorConfigVO.EDITOR_CONFIG_FILE;
FileUtils.writeStringToFile(new File(configFilePath), editorConfigVO.constructJsonString(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 5,016 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
CommandManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/CommandManager.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.proxy;
import games.rednblack.editor.controller.commands.HistoricRevertibleCommand;
import games.rednblack.editor.controller.commands.RevertibleCommand;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.puremvc.Proxy;
import java.util.ArrayList;
public class CommandManager extends Proxy {
private static final String TAG = CommandManager.class.getCanonicalName();
public static final String NAME = TAG;
private int cursor = -1;
private int modifiedCursor = 0;
final private ArrayList<RevertibleCommand> commands = new ArrayList<>();
public CommandManager() {
super(NAME, null);
}
public void addCommand(RevertibleCommand revertibleCommand) {
//remove all commands after the cursor
for(int i = commands.size()-1; i > cursor; i--) {
commands.remove(i);
}
commands.add(revertibleCommand);
cursor = commands.indexOf(revertibleCommand);
if (revertibleCommand instanceof HistoricRevertibleCommand) {
modifiedCursor++;
autoSave();
}
updateWindowTitle();
}
public void undoCommand() {
if(cursor < 0){
updateWindowTitle();
return;
}
RevertibleCommand command = commands.get(cursor);
if(command.isStateDone()) {
command.callUndoAction();
command.setStateDone(false);
}
cursor--;
if (command instanceof HistoricRevertibleCommand) {
modifiedCursor--;
autoSave();
}
updateWindowTitle();
}
public void saveEvent() {
modifiedCursor = 0;
updateWindowTitle();
}
public void updateWindowTitle() {
WindowTitleManager windowTitleManager = facade.retrieveProxy(WindowTitleManager.NAME);
windowTitleManager.appendSaveHintTitle(isModified());
}
public boolean isModified() {
return Math.abs(modifiedCursor) > 0;
}
public void redoCommand() {
if(cursor + 1 >= commands.size()) return;
RevertibleCommand command = commands.get(cursor+1);
if(!command.isStateDone()) {
cursor++;
command.callDoAction();
command.setStateDone(true);
if (command instanceof HistoricRevertibleCommand) {
modifiedCursor++;
autoSave();
}
updateWindowTitle();
}
}
public void clearHistory() {
cursor = -1;
commands.clear();
modifiedCursor = 1;
updateWindowTitle();
}
public void initHistory() {
clearHistory();
modifiedCursor = 0;
updateWindowTitle();
}
private void autoSave() {
SettingsManager settingsManager = facade.retrieveProxy(SettingsManager.NAME);
if (settingsManager.editorConfigVO.autoSave)
facade.sendNotification(MsgAPI.AUTO_SAVE_PROJECT);
}
}
| 3,788 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
FontManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/FontManager.java | package games.rednblack.editor.proxy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import games.rednblack.editor.utils.AppConfig;
import games.rednblack.editor.utils.NativeDialogs;
import games.rednblack.puremvc.Facade;
import games.rednblack.puremvc.Proxy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.SystemUtils;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.*;
/**
* Created by azakhary on 4/24/2015.
*/
public class FontManager extends Proxy {
private static final String TAG = FontManager.class.getCanonicalName();
public static final String NAME = TAG;
private static final String cache_name = "hyperlap2d-fonts-cache";
private Preferences prefs;
private HashMap<String, String> systemFontMap = new HashMap<>();
public FontManager() {
super(NAME, null);
}
@Override
public void onRegister() {
super.onRegister();
prefs = Gdx.app.getPreferences(cache_name);
generateFontsMap();
}
public String[] getSystemFontsPaths() {
String[] result;
if (SystemUtils.IS_OS_WINDOWS) {
result = new String[1];
String path = System.getenv("WINDIR");
result[0] = path + "\\" + "Fonts";
return result;
} else if (SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_MAC) {
result = new String[3];
result[0] = System.getProperty("user.home") + File.separator + "Library/Fonts";
result[1] = "/Library/Fonts";
result[2] = "/System/Library/Fonts";
return result;
} else if (SystemUtils.IS_OS_LINUX) {
String[] pathsToCheck = {
System.getProperty("user.home") + File.separator + ".local/share/fonts",
"/usr/share/fonts/truetype",
"/usr/share/fonts/TTF"
};
ArrayList<String> resultList = new ArrayList<>();
for (int i = pathsToCheck.length - 1; i >= 0; i--) {
String path = pathsToCheck[i];
File tmp = new File(path);
if (tmp.exists() && tmp.isDirectory() && tmp.canRead()) {
resultList.add(path);
}
}
if (resultList.isEmpty()) {
NativeDialogs.showError("No Font detected on your System.\n"
+ SystemUtils.OS_NAME + " " + SystemUtils.OS_VERSION
+ " (HyperLap2D v" + AppConfig.getInstance().versionString + ")");
result = new String[0];
}
else {
result = new String[resultList.size()];
result = resultList.toArray(result);
}
return result;
}
return null;
}
public List<File> getSystemFontFiles() {
// only retrieving ttf files
String[] extensions = new String[]{"ttf", "TTF"};
String[] paths = getSystemFontsPaths();
ArrayList<File> files = new ArrayList<>();
for (int i = 0; i < paths.length; i++) {
File fontDirectory = new File(paths[i]);
if (!fontDirectory.exists()) break;
files.addAll(FileUtils.listFiles(fontDirectory, extensions, true));
}
return files;
}
public void preCacheSystemFontsMap() {
List<File> fontFiles = getSystemFontFiles();
for (File file : fontFiles) {
Font f;
try {
if (!systemFontMap.containsValue(file.getAbsolutePath())) {
f = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(file.getAbsolutePath()));
systemFontMap.put(f.getName(), file.getAbsolutePath());
}
} catch (FontFormatException | IOException e) {
System.err.println("Could not load " + file.getName() + " font file.");
}
}
prefs.put(systemFontMap);
prefs.flush();
}
public void loadCachedSystemFontMap() {
systemFontMap = (HashMap<String, String>) prefs.get();
}
public void generateFontsMap() {
loadCachedSystemFontMap();
preCacheSystemFontsMap();
}
public HashMap<String, String> getFontsMap() {
return systemFontMap;
}
public Array<String> getFontNamesFromMap() {
AlphabeticalComparator comparator = new AlphabeticalComparator();
Array<String> fontNames = new Array<>();
for (Map.Entry<String, String> entry : systemFontMap.entrySet()) {
fontNames.add(entry.getKey());
}
fontNames.sort(comparator);
return fontNames;
}
public FileHandle getTTFByName(String fontName) {
return new FileHandle(systemFontMap.get(fontName));
}
public String getShortName(String longName) {
String path = systemFontMap.get(longName);
return FilenameUtils.getBaseName(path);
}
public String getFontFilePath(String fontFaily) {
return systemFontMap.get(fontFaily);
}
public static class AlphabeticalComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
}
| 5,494 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ResourceManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/ResourceManager.java | package games.rednblack.editor.proxy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.SkinLoader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.*;
import com.esotericsoftware.spine.SkeletonJson;
import com.kotcrab.vis.ui.VisUI;
import games.rednblack.h2d.extension.bvb.BVBDataObject;
import games.rednblack.talos.runtime.ParticleEffectDescriptor;
import games.rednblack.talos.runtime.ParticleEffectInstancePool;
import games.rednblack.talos.runtime.bvb.BVB;
import games.rednblack.talos.runtime.utils.ShaderDescriptor;
import games.rednblack.talos.runtime.utils.VectorField;
import dev.lyze.gdxtinyvg.TinyVG;
import games.rednblack.editor.renderer.data.*;
import games.rednblack.editor.renderer.resources.FontSizePair;
import games.rednblack.editor.renderer.resources.IResourceRetriever;
import games.rednblack.editor.renderer.utils.*;
import games.rednblack.editor.view.stage.Sandbox;
import games.rednblack.editor.view.ui.widget.actors.basic.WhitePixel;
import games.rednblack.h2d.extension.spine.ResourceRetrieverAttachmentLoader;
import games.rednblack.h2d.extension.spine.SpineDataObject;
import games.rednblack.h2d.extension.spine.SpineDrawableLogic;
import games.rednblack.h2d.extension.spine.SpineItemType;
import games.rednblack.h2d.extension.talos.ResourceRetrieverAssetProvider;
import games.rednblack.h2d.extension.talos.TalosItemType;
import games.rednblack.h2d.extension.tinyvg.TinyVGItemType;
import games.rednblack.h2d.extension.tinyvg.TinyVGUtils;
import games.rednblack.puremvc.Proxy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
/**
* Created by azakhary on 4/26/2015.
*/
public class ResourceManager extends Proxy implements IResourceRetriever {
public String packResolutionName = "orig";
private static final String TAG = ResourceManager.class.getCanonicalName();
public static final String NAME = TAG;
private final HashMap<String, ParticleEffectPool> particleEffects = new HashMap<>(1);
private final HashMap<String, ParticleEffectInstancePool> talosVFXs = new HashMap<>(1);
private final HashMap<String, TextureAtlas> currentProjectAtlas = new HashMap<>(1);
private final HashMap<String, BVBDataObject> spineAnimAtlases = new HashMap<>();
private final HashMap<String, Array<TextureAtlas.AtlasRegion>> spriteAnimAtlases = new HashMap<>();
private final HashMap<FontSizePair, BitmapFont> fonts = new HashMap<>();
private final HashMap<String, BitmapFont> bitmapFonts = new HashMap<>();
private final HashMap<String, ShaderProgram> shaderPrograms = new HashMap<>(1);
private final HashMap<String, TinyVG> tinyVGs = new HashMap<>(1);
private final HashMap<String, TinyVG> originalTinyVGs = new HashMap<>(1);
private TextureAtlas.AtlasRegion defaultRegion;
private ResolutionManager resolutionManager;
private SettingsManager settingsManager;
private PixmapPacker fontPacker;
public ResourceManager() {
super(NAME, null);
}
@Override
public void onRegister() {
super.onRegister();
resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
settingsManager = facade.retrieveProxy(SettingsManager.NAME);
TextureArrayPolygonSpriteBatch.getMaxTextureUnits();
WhitePixel.initializeShared();
PixmapPacker packer = new PixmapPacker(4096, 4096, Pixmap.Format.RGBA8888, 1, false, new PixmapPacker.SkylineStrategy());
packer.setTransparentColor(Color.WHITE);
packer.getTransparentColor().a = 0;
FreeTypeFontGenerator dejaVuSansGenerator = new FreeTypeFontGenerator(Gdx.files.internal("freetypefonts/DejaVuSans.ttf")) /*{
@Override
protected BitmapFont newBitmapFont(BitmapFont.BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) {
return new ThreadSafeBitmapFont(data, pageRegions, integer);
}
}*/;
FreeTypeFontGenerator monoGenerator = new FreeTypeFontGenerator(Gdx.files.internal("freetypefonts/FiraCode-Regular.ttf"))/*{
@Override
protected BitmapFont newBitmapFont(BitmapFont.BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) {
return new ThreadSafeBitmapFont(data, pageRegions, integer);
}
}*/;
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.characters += "⌘⇧⌥\u25CF\u2022";
parameter.kerning = true;
parameter.renderCount = 1;
parameter.packer = packer;
parameter.minFilter = Texture.TextureFilter.Linear;
parameter.magFilter = Texture.TextureFilter.Linear;
parameter.gamma = 0.6f;
parameter.hinting = FreeTypeFontGenerator.Hinting.None;
parameter.size = (int) (16 / settingsManager.editorConfigVO.uiScaleDensity);
BitmapFont defaultMono = monoGenerator.generateFont(parameter);
defaultMono.setFixedWidthGlyphs(parameter.characters);
defaultMono.setUseIntegerPositions(false);
defaultMono.getData().setScale(settingsManager.editorConfigVO.uiScaleDensity);
monoGenerator.dispose();
parameter.size = (int) (11 / settingsManager.editorConfigVO.uiScaleDensity);
BitmapFont small = dejaVuSansGenerator.generateFont(parameter);
small.setUseIntegerPositions(false);
small.getData().setScale(settingsManager.editorConfigVO.uiScaleDensity);
parameter.size = (int) (13 / settingsManager.editorConfigVO.uiScaleDensity);
BitmapFont defaultFont = dejaVuSansGenerator.generateFont(parameter);
defaultFont.setUseIntegerPositions(false);
defaultFont.getData().setScale(settingsManager.editorConfigVO.uiScaleDensity);
parameter.size = (int) (16 / settingsManager.editorConfigVO.uiScaleDensity);
BitmapFont big = dejaVuSansGenerator.generateFont(parameter);
big.setUseIntegerPositions(false);
big.getData().setScale(settingsManager.editorConfigVO.uiScaleDensity);
dejaVuSansGenerator.dispose();
/*TextureRegion dejavuRegion = new TextureRegion(new Texture(Gdx.files.internal("style/default-font-32.png")));
ShadedDistanceFieldFont smallDistanceField = new ShadedDistanceFieldFont(Gdx.files.internal("style/default-font-32.fnt"), dejavuRegion);
smallDistanceField.setDistanceFieldSmoothing(6);
smallDistanceField.getData().setScale(0.35f);
ShadedDistanceFieldFont defaultDistanceField = new ShadedDistanceFieldFont(Gdx.files.internal("style/default-font-32.fnt"), dejavuRegion);
defaultDistanceField.setDistanceFieldSmoothing(6);
defaultDistanceField.getData().setScale(0.4f);
ShadedDistanceFieldFont bigDistanceField = new ShadedDistanceFieldFont(Gdx.files.internal("style/default-font-32.fnt"), dejavuRegion);
bigDistanceField.setDistanceFieldSmoothing(6);
bigDistanceField.getData().setScale(0.5f);*/
/* Create the ObjectMap and add the fonts to it */
ObjectMap<String, Object> fontMap = new ObjectMap<>();
fontMap.put("small-font", small);
fontMap.put("default-font", defaultFont);
fontMap.put("big-font", big);
fontMap.put("default-mono-font", defaultMono);
SkinLoader.SkinParameter skinParameter = new SkinLoader.SkinParameter(fontMap);
AssetManager assetManager = new AssetManager();
assetManager.setLoader(Skin.class, new H2DSkinLoader(assetManager.getFileHandleResolver()));
assetManager.load("style/uiskin.json", Skin.class, skinParameter);
assetManager.finishLoading();
Skin skin = assetManager.get("style/uiskin.json");
VisUI.load(skin);
VisUI.setDefaultTitleAlign(Align.center);
defaultRegion = VisUI.getSkin().getAtlas().findRegion("missing-image");
fontPacker = new PixmapPacker(4096, 4096, Pixmap.Format.RGBA8888, 1, false, new PixmapPacker.SkylineStrategy());
fontPacker.setTransparentColor(Color.WHITE);
fontPacker.getTransparentColor().a = 0;
}
@Override
public TextureRegion getTextureRegion(String name) {
for (TextureAtlas atlas : currentProjectAtlas.values()) {
TextureRegion region = atlas.findRegion(name);
if (region != null)
return region;
}
return defaultRegion;
}
@Override
public TextureAtlas getTextureAtlas(String atlasName) {
return currentProjectAtlas.get(atlasName);
}
@Override
public ParticleEffect getParticleEffect(String name) {
return particleEffects.get(name).obtain();
}
/**
* Sets working resolution, please set before doing any loading
* @param resolution String resolution name, default is "orig" later use resolution names created in editor
*/
public void setWorkingResolution(String resolution) {
ResolutionEntryVO resolutionObject = getProjectVO().getResolution("resolutionName");
if(resolutionObject != null) {
packResolutionName = resolution;
}
}
@Override
public Object getExternalItemType(int itemType, String name) {
switch (itemType) {
case SpineItemType.SPINE_TYPE:
return spineAnimAtlases.get(name);
case TalosItemType.TALOS_TYPE:
return talosVFXs.get(name);
case TinyVGItemType.TINYVG_TYPE:
return tinyVGs.get(name);
default:
return null;
}
}
public TinyVG getOriginalTinyVG(String name) {
return originalTinyVGs.get(name);
}
@Override
public Array<TextureAtlas.AtlasRegion> getSpriteAnimation(String animationName) {
return spriteAnimAtlases.get(animationName);
}
@Override
public BitmapFont getFont(String fontName, int fontSize, boolean mono) {
FontSizePair pair = new FontSizePair(fontName, fontSize, mono);
return fonts.get(pair);
}
@Override
public BitmapFont getBitmapFont(String fontName) {
return bitmapFonts.get(fontName);
}
@Override
public boolean hasTextureRegion(String regionName) {
for (TextureAtlas atlas : currentProjectAtlas.values()) {
if (atlas.findRegion(regionName) != null)
return true;
}
return false;
}
@Override
public ProjectInfoVO getProjectVO() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectInfoVO();
}
@Override
public SceneVO getSceneVO(String name) {
SceneDataManager sceneDataManager = facade.retrieveProxy(SceneDataManager.NAME);
// TODO: this should be cached
FileHandle file = Gdx.files.internal(sceneDataManager.getCurrProjectScenePathByName(name));
Json json = HyperJson.getJson();
return json.fromJson(SceneVO.class, file.readString());
}
public void loadCurrentProjectData(String projectPath, String curResolution) {
packResolutionName = curResolution;
loadCurrentProjectAssets(projectPath + "/assets/" + curResolution + "/pack");
loadCurrentProjectParticles(projectPath + File.separator + ProjectManager.PARTICLE_DIR_PATH);
loadCurrentProjectTalosVFXs(projectPath + File.separator + ProjectManager.TALOS_VFX_DIR_PATH);
loadCurrentProjectSpineAnimations(projectPath + File.separator + ProjectManager.SPINE_DIR_PATH);
loadCurrentProjectSpriteAnimations(projectPath + File.separator + ProjectManager.SPRITE_DIR_PATH);
loadCurrentProjectBitmapFonts(projectPath + File.separator + ProjectManager.BITMAP_FONTS_DIR_PATH);
loadCurrentProjectTinyVGs(projectPath + File.separator + ProjectManager.TINY_VG_DIR_PATH);
loadCurrentProjectFonts();
loadCurrentProjectShaders(projectPath + File.separator + ProjectManager.SHADER_DIR_PATH);
removeInvalidResourceReferences();
}
public void loadCurrentProjectBitmapFonts(String path) {
bitmapFonts.clear();
FileHandle sourceDir = new FileHandle(path);
for (FileHandle entry : sourceDir.list()) {
File file = entry.file();
String filename = file.getName();
if (file.isDirectory() || filename.endsWith(".DS_Store")) continue;
Array<TextureRegion> pages = new Array<>();
BitmapFont.BitmapFontData bitmapFontData = new BitmapFont.BitmapFontData(Gdx.files.internal(file.getAbsolutePath()), false);
for (String page : bitmapFontData.imagePaths) {
pages.add(getTextureRegion(FilenameUtils.getBaseName(page)));
}
BitmapFont bitmapFont = new BitmapFont(bitmapFontData, pages, false);
bitmapFonts.put(bitmapFont.getData().name, bitmapFont);
}
}
public void loadCurrentProjectTinyVGs(String path) {
tinyVGs.clear();
originalTinyVGs.clear();
FileHandle sourceDir = new FileHandle(path);
for (FileHandle entry : sourceDir.list()) {
File file = entry.file();
String filename = file.getName();
if (file.isDirectory() || filename.endsWith(".DS_Store")) continue;
tinyVGs.put(entry.nameWithoutExtension(), TinyVGUtils.load(entry));
originalTinyVGs.put(entry.nameWithoutExtension(), TinyVGUtils.load(entry));
}
}
private void loadCurrentProjectParticles(String path) {
particleEffects.clear();
FileHandle sourceDir = new FileHandle(path);
for (FileHandle entry : sourceDir.list()) {
File file = entry.file();
String filename = file.getName();
if (file.isDirectory() || filename.endsWith(".DS_Store")) continue;
ParticleEffect particleEffect = new ParticleEffect();
particleEffect.loadEmitters(Gdx.files.internal(file.getAbsolutePath()));
for (TextureAtlas atlas : currentProjectAtlas.values()) {
try {
particleEffect.loadEmitterImages(atlas, "");
break;
} catch (Exception ignore) { }
}
ParticleEffectPool effectPool = new ParticleEffectPool(particleEffect, 1, games.rednblack.editor.renderer.resources.ResourceManager.PARTICLE_POOL_SIZE);
particleEffects.put(filename, effectPool);
}
}
private void loadCurrentProjectTalosVFXs(String path) {
talosVFXs.clear();
talosResPath = path;
FileHandle sourceDir = new FileHandle(path);
for (FileHandle entry : sourceDir.list()) {
File file = entry.file();
String filename = file.getName();
if (file.isDirectory() || filename.endsWith(".DS_Store") || !filename.endsWith("p")) continue;
ResourceRetrieverAssetProvider assetProvider = new ResourceRetrieverAssetProvider(this);
assetProvider.setAssetHandler(ShaderDescriptor.class, this::findShaderDescriptorOnLoad);
assetProvider.setAssetHandler(VectorField.class, this::findVectorFieldDescriptorOnLoad);
ParticleEffectDescriptor effectDescriptor = new ParticleEffectDescriptor();
effectDescriptor.setAssetProvider(assetProvider);
effectDescriptor.load(Gdx.files.internal(file.getAbsolutePath()));
talosVFXs.put(filename, new ParticleEffectInstancePool(effectDescriptor, 1, games.rednblack.editor.renderer.resources.ResourceManager.PARTICLE_POOL_SIZE));
}
}
private ObjectMap<String, ShaderDescriptor> shaderDescriptorObjectMap = new ObjectMap<>();
private String talosResPath;
private ShaderDescriptor findShaderDescriptorOnLoad (String assetName) {
ShaderDescriptor asset = shaderDescriptorObjectMap.get(assetName);
if (asset == null) {
//Look in all paths, and hopefully load the requested asset, or fail (crash)
final FileHandle file = new FileHandle(talosResPath + File.separator + assetName);
asset = new ShaderDescriptor();
if (file.exists()) {
asset.setData(file.readString());
}
}
return asset;
}
private ObjectMap<String, VectorField> vectorFieldDescriptorObjectMap = new ObjectMap<>();
private VectorField findVectorFieldDescriptorOnLoad (String assetName) {
VectorField asset = vectorFieldDescriptorObjectMap.get(assetName);
if (asset == null) {
final FileHandle file = new FileHandle(talosResPath + File.separator + assetName + ".fga");
if (file.exists()) {
asset = new VectorField(file);
} else {
asset = new VectorField();
}
}
return asset;
}
private void loadCurrentProjectSpineAnimations(String path) {
spineAnimAtlases.clear();
FileHandle sourceDir = new FileHandle(path);
SpineDrawableLogic spineDrawableLogic = (SpineDrawableLogic) Sandbox.getInstance().sceneControl.sceneLoader.getExternalItemType(SpineItemType.SPINE_TYPE).getDrawable();
for (FileHandle entry : sourceDir.list()) {
if (entry.file().isDirectory()) {
String animName = FilenameUtils.removeExtension(entry.file().getName());
FileHandle animJsonFile = Gdx.files.internal(entry.file().getAbsolutePath() + File.separator + animName + ".json");
BVBDataObject spineDataObject = new BVBDataObject();
spineDataObject.skeletonJson = new SkeletonJson(new ResourceRetrieverAttachmentLoader(animName, this, spineDrawableLogic));
spineDataObject.skeletonData = spineDataObject.skeletonJson.readSkeletonData(animJsonFile);
FileHandle bvb = Gdx.files.internal(entry.file().getAbsolutePath() + File.separator + animName + "-bvb.json");
if (bvb.exists())
spineDataObject.bvbData = HyperJson.getJson().fromJson(BVB.class, bvb);
spineAnimAtlases.put(animName, spineDataObject);
}
}
}
private void loadCurrentProjectSpriteAnimations(String path) {
spriteAnimAtlases.clear();
FileHandle sourceDir = new FileHandle(path);
for (FileHandle entry : sourceDir.list()) {
if (entry.file().isDirectory()) {
String animName = FilenameUtils.removeExtension(entry.file().getName());
Array<TextureAtlas.AtlasRegion> regions = null;
for (TextureAtlas atlas : currentProjectAtlas.values()) {
regions = atlas.findRegions(animName);
if (regions.size > 0)
break;
}
if (regions != null)
spriteAnimAtlases.put(animName, regions);
}
}
}
public void loadCurrentProjectAssets(String packFolderPath) {
for (TextureAtlas atlas : currentProjectAtlas.values()) {
atlas.dispose();
}
currentProjectAtlas.clear();
FileHandle folder = new FileHandle(packFolderPath);
for (FileHandle file : folder.list()) {
if (file.extension().equals("atlas")) {
String name = file.nameWithoutExtension().equals("pack") ? "main" : file.nameWithoutExtension();
currentProjectAtlas.put(name, new TextureAtlas(file));
}
}
}
public ArrayList<FontSizePair> getProjectRequiredFontsList() {
ObjectSet<FontSizePair> fontsToLoad = new ObjectSet<>();
for (int i = 0; i < getProjectVO().scenes.size(); i++) {
SceneVO scene = getSceneVO(getProjectVO().scenes.get(i).sceneName);
CompositeItemVO composite = scene.composite;
if (composite == null) {
continue;
}
Array<FontSizePair> fonts = composite.getRecursiveFontList();
for (CompositeItemVO library : getProjectVO().libraryItems.values()) {
Array<FontSizePair> libFonts = library.getRecursiveFontList();
fontsToLoad.addAll(libFonts);
}
fontsToLoad.addAll(fonts);
}
ArrayList<FontSizePair> result = new ArrayList<>();
for (FontSizePair fontSizePair : fontsToLoad)
result.add(fontSizePair);
return result;
}
public void loadCurrentProjectFonts() {
fonts.clear();
ArrayList<FontSizePair> requiredFonts = getProjectRequiredFontsList();
for (int i = 0; i < requiredFonts.size(); i++) {
FontSizePair pair = requiredFonts.get(i);
FileHandle fontFile;
try {
fontFile = getTTFSafely(pair.fontName);
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = Math.round(pair.fontSize * resolutionManager.getCurrentMul());
parameter.packer = fontPacker;
BitmapFont font = generator.generateFont(parameter);
font.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
font.setUseIntegerPositions(false);
fonts.put(pair, font);
generator.dispose();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadCurrentProjectShaders(String path) {
Iterator<Entry<String, ShaderProgram>> it = shaderPrograms.entrySet().iterator();
while (it.hasNext()) {
Entry<String, ShaderProgram> pair = it.next();
pair.getValue().dispose();
it.remove();
}
shaderPrograms.clear();
path += File.separator;
FileHandle sourceDir = new FileHandle(path);
for (FileHandle entry : sourceDir.list()) {
File file = entry.file();
String filename = file.getName().replace(".vert", "").replace(".frag", "");
if (file.isDirectory() || filename.endsWith(".DS_Store") || shaderPrograms.containsKey(filename)) continue;
// check if pair exists.
if(Gdx.files.internal(path + filename + ".vert").exists() && Gdx.files.internal(path + filename + ".frag").exists()) {
ShaderProgram shaderProgram = ShaderCompiler.compileShader(Gdx.files.internal(path + filename + ".vert"), Gdx.files.internal(path + filename + ".frag"));
if (!shaderProgram.isCompiled()) {
System.out.println("Error compiling shader: " + shaderProgram.getLog());
}
shaderPrograms.put(filename, shaderProgram);
}
}
}
public void reloadShader(String shaderName) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
String shader = projectManager.getCurrentProjectPath() + File.separator
+ ProjectManager.SHADER_DIR_PATH + File.separator + shaderName;
if(Gdx.files.internal(shader + ".vert").exists() && Gdx.files.internal(shader + ".frag").exists()) {
ShaderProgram shaderProgram = ShaderCompiler.compileShader(Gdx.files.internal(shader + ".vert"), Gdx.files.internal(shader + ".frag"));
if (shaderProgram.isCompiled()) {
shaderPrograms.remove(shaderName).dispose();
shaderPrograms.put(shaderName, shaderProgram);
} else {
System.out.println("Error compiling shader: " + shaderProgram.getLog());
}
}
}
public FileHandle getTTFSafely(String fontName) throws IOException {
FontManager fontManager = facade.retrieveProxy(FontManager.NAME);
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
String expectedPath = projectManager.getFreeTypeFontPath() + File.separator + fontName + ".ttf";
FileHandle expectedFile = Gdx.files.internal(expectedPath);
if (!expectedFile.exists()) {
// let's check if system fonts fot it
HashMap<String, String> fonts = fontManager.getFontsMap();
if (fonts.containsKey(fontName)) {
File source = new File(fonts.get(fontName));
FileUtils.copyFile(source, expectedFile.file());
expectedFile = Gdx.files.internal(expectedPath);
} else {
throw new FileNotFoundException(fontName);
}
}
return expectedFile;
}
public void flushAllUnusedFonts() {
//List of fonts that are required to be in memory
ArrayList<FontSizePair> requiredFonts = getProjectRequiredFontsList();
ArrayList<FontSizePair> fontsInMemory = new ArrayList<>(fonts.keySet());
for (FontSizePair font : fontsInMemory) {
if (!requiredFonts.contains(font)) {
fonts.remove(font);
}
}
}
public boolean isFontLoaded(String shortName, int fontSize, boolean mono) {
return fonts.containsKey(new FontSizePair(shortName, fontSize, mono));
}
public void prepareEmbeddingFont(String fontfamily, int fontSize, boolean mono) {
flushAllUnusedFonts();
if (isFontLoaded(fontfamily, fontSize, mono)) {
return;
}
FontManager fontManager = facade.retrieveProxy(FontManager.NAME);
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = fontSize;
parameter.packer = fontPacker;
parameter.mono = mono;
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontManager.getTTFByName(fontfamily));
BitmapFont font = generator.generateFont(parameter);
font.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
font.setUseIntegerPositions(false);
if (mono)
font.setFixedWidthGlyphs(FreeTypeFontGenerator.DEFAULT_CHARS);
fonts.put(new FontSizePair(fontfamily, parameter.size, mono), font);
generator.dispose();
}
public HashMap<String, BVBDataObject> getProjectSpineAnimationsList() {
return spineAnimAtlases;
}
public HashMap<String, Array<TextureAtlas.AtlasRegion>> getProjectSpriteAnimationsList() {
return spriteAnimAtlases;
}
public HashMap<String, ParticleEffectPool> getProjectParticleList() {
return particleEffects;
}
public HashMap<String, ParticleEffectInstancePool> getProjectTalosList() {
return talosVFXs;
}
public HashMap<String, BitmapFont> getBitmapFontList() {
return bitmapFonts;
}
public HashMap<String, TinyVG> getTinyVGList() {
return tinyVGs;
}
@Override
public ResolutionEntryVO getLoadedResolution() {
if(packResolutionName.equals("orig")) {
return getProjectVO().originalResolution;
}
return getProjectVO().getResolution(packResolutionName);
}
@Override
public ShaderProgram getShaderProgram(String shaderName) {
return shaderPrograms.get(shaderName);
}
public void addShaderProgram(String name, ShaderProgram shaderProgram) {
shaderPrograms.put(name, shaderProgram);
}
public void removeShaderProgram(String shaderName) {
shaderPrograms.remove(shaderName);
}
public HashMap<String, ShaderProgram> getShaders() {
return shaderPrograms;
}
public void removeInvalidResourceReferences() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
HashSet<String> invalidImages = new HashSet<>();
for (TexturePackVO packVO : projectManager.currentProjectInfoVO.imagesPacks.values()) {
invalidImages.clear();
for (String region : packVO.regions) {
if (!hasTextureRegion(region))
invalidImages.add(region);
}
if (invalidImages.size() > 0)
packVO.regions.removeAll(invalidImages);
}
for (TexturePackVO packVO : projectManager.currentProjectInfoVO.animationsPacks.values()) {
invalidImages.clear();
for (String region : packVO.regions) {
if (!hasTextureRegion(region))
invalidImages.add(region);
}
if (invalidImages.size() > 0)
packVO.regions.removeAll(invalidImages);
}
}
}
| 29,232 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
WindowTitleManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/WindowTitleManager.java | package games.rednblack.editor.proxy;
import com.badlogic.gdx.Gdx;
import games.rednblack.editor.view.ui.UIWindowTitle;
import games.rednblack.editor.view.ui.UIWindowTitleMediator;
import games.rednblack.puremvc.Proxy;
public class WindowTitleManager extends Proxy {
private static final String TAG = WindowTitleManager.class.getCanonicalName();
public static final String NAME = TAG;
private String currentWindowTitle = "";
public WindowTitleManager() {
super(NAME, null);
}
public void setWindowTitle(String title) {
currentWindowTitle = title;
Gdx.graphics.setTitle(currentWindowTitle);
UIWindowTitleMediator uiWindowTitleMediator = facade.retrieveMediator(UIWindowTitleMediator.NAME);
UIWindowTitle uiWindowTitle = uiWindowTitleMediator.getViewComponent();
uiWindowTitle.setTitle(currentWindowTitle);
}
public void appendSaveHintTitle(boolean isModified) {
String title;
if (!isModified) {
title = currentWindowTitle;
} else {
title = "\u25CF " + currentWindowTitle;
}
Gdx.graphics.setTitle(title);
UIWindowTitleMediator uiWindowTitleMediator = facade.retrieveMediator(UIWindowTitleMediator.NAME);
UIWindowTitle uiWindowTitle = uiWindowTitleMediator.getViewComponent();
uiWindowTitle.setTitle(title);
}
}
| 1,387 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ProjectManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/ProjectManager.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.proxy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.kotcrab.vis.ui.util.dialog.Dialogs;
import games.rednblack.editor.data.manager.PreferencesManager;
import games.rednblack.editor.data.migrations.ProjectVersionMigrator;
import games.rednblack.editor.renderer.data.*;
import games.rednblack.editor.renderer.resources.FontSizePair;
import games.rednblack.editor.renderer.utils.HyperJson;
import games.rednblack.editor.utils.HyperLap2DUtils;
import games.rednblack.editor.utils.RecursiveFileSuffixFilter;
import games.rednblack.editor.view.menu.HyperLap2DMenuBar;
import games.rednblack.editor.view.stage.Sandbox;
import games.rednblack.editor.view.ui.dialog.SettingsDialog;
import games.rednblack.editor.view.ui.settings.LivePreviewSettings;
import games.rednblack.editor.view.ui.settings.ProjectExportSettings;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.ProgressHandler;
import games.rednblack.h2d.common.vo.ProjectVO;
import games.rednblack.h2d.common.vo.SceneConfigVO;
import games.rednblack.h2d.common.vo.TexturePackerVO;
import games.rednblack.puremvc.Proxy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.lwjgl.util.tinyfd.TinyFileDialogs;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ProjectManager extends Proxy {
private static final String TAG = ProjectManager.class.getCanonicalName();
public static final String NAME = TAG;
private static final String EVENT_PREFIX = "games.rednblack.editor.proxy.ProjectManager";
public static final String PROJECT_OPENED = EVENT_PREFIX + ".PROJECT_OPENED";
public static final String PROJECT_DATA_UPDATED = EVENT_PREFIX + ".PROJECT_DATA_UPDATED";
public static final String IMAGE_DIR_PATH = "assets/orig/images";
public static final String SPINE_DIR_PATH = "assets/spine-animations";
public static final String SPRITE_DIR_PATH = "assets/sprite-animations";
public static final String PARTICLE_DIR_PATH = "assets/particles";
public static final String TALOS_VFX_DIR_PATH = "assets/talos-vfx";
public static final String SHADER_DIR_PATH = "assets/shaders";
public static final String FONTS_DIR_PATH = "assets/freetypefonts";
public static final String BITMAP_FONTS_DIR_PATH = "assets/bitmapfonts";
public static final String TINY_VG_DIR_PATH = "assets/tinyvg";
public ProjectVO currentProjectVO;
public ProjectInfoVO currentProjectInfoVO;
private String currentProjectPath;
public ProjectManager() {
super(NAME, null);
}
private ProjectExportSettings projectExportSettings;
private LivePreviewSettings livePreviewSettings;
private Thread fileWatcherThread;
@Override
public void onRegister() {
super.onRegister();
projectExportSettings = new ProjectExportSettings();
livePreviewSettings = new LivePreviewSettings();
}
@Override
public void onRemove() {
super.onRemove();
}
public ProjectVO getCurrentProjectVO() {
return currentProjectVO;
}
public ProjectInfoVO getCurrentProjectInfoVO() {
return currentProjectInfoVO;
}
public void createEmptyProject(String projectPath, int width, int height, int pixelPerWorldUnit) throws IOException {
String projectName = new File(projectPath).getName();
String projPath = FilenameUtils.normalize(projectPath);
FileUtils.forceMkdir(new File(projPath));
FileUtils.forceMkdir(new File(projPath + File.separator + "export"));
FileUtils.forceMkdir(new File(projPath + File.separator + "assets"));
FileUtils.forceMkdir(new File(projPath + File.separator + "scenes"));
FileUtils.forceMkdir(new File(projPath + File.separator + "assets/orig"));
FileUtils.forceMkdir(new File(projPath + File.separator + "assets/orig/images"));
FileUtils.forceMkdir(new File(projPath + File.separator + "assets/orig/pack"));
Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
FileHandle whitePixel = new FileHandle(projPath + File.separator + "assets/orig/images" + File.separator + "white-pixel.png");
PixmapIO.writePNG(whitePixel, pixmap);
// create project file
ProjectVO projVo = new ProjectVO();
projVo.projectName = projectName;
projVo.projectVersion = ProjectVersionMigrator.dataFormatVersion;
// create project info file
ProjectInfoVO projInfoVo = new ProjectInfoVO();
projInfoVo.originalResolution.name = "orig";
projInfoVo.originalResolution.width = width;
projInfoVo.originalResolution.height = height;
projInfoVo.pixelToWorld = pixelPerWorldUnit;
TexturePackVO mainPack = new TexturePackVO();
mainPack.name = "main";
mainPack.regions.add("white-pixel");
projInfoVo.imagesPacks.put("main", mainPack);
TexturePackVO mainAnimPack = new TexturePackVO();
mainAnimPack.name = "main";
projInfoVo.animationsPacks.put("main", mainAnimPack);
//TODO: add project orig resolution setting
currentProjectVO = projVo;
currentProjectInfoVO = projInfoVo;
currentProjectPath = projPath;
SceneDataManager sceneDataManager = facade.retrieveProxy(SceneDataManager.NAME);
sceneDataManager.createNewScene("MainScene");
FileUtils.writeStringToFile(new File(projPath + "/project.h2d"), projVo.constructJsonString(), "utf-8");
FileUtils.writeStringToFile(new File(projPath + "/project.dt"), projInfoVo.constructJsonString(), "utf-8");
}
public void openProjectFromPath(String path) {
FileHandle projectFile = new FileHandle(path);
if (!projectFile.exists() || !projectFile.extension().equals("h2d")
|| !projectFile.file().canRead() || !projectFile.file().canWrite())
return;
FileHandle projectFolder = projectFile.parent();
String projectName = projectFolder.name();
SettingsManager settingsManager = facade.retrieveProxy(SettingsManager.NAME);
settingsManager.setLastOpenedPath(projectFolder.parent().path());
// here we load all data
openProjectAndLoadAllData(projectFolder.path());
Sandbox.getInstance().loadCurrentProject();
facade.sendNotification(ProjectManager.PROJECT_OPENED);
//Set title with opened file path
setWindowTitle(getFormattedTitle(path));
}
public void openProjectAndLoadAllData(String projectPath) {
openProjectAndLoadAllData(projectPath, null);
}
public void openProjectAndLoadAllData(String projectPath, String resolution) {
String prjFilePath = projectPath + "/project.h2d";
FileHandle projectFile = Gdx.files.internal(prjFilePath);
if (!projectFile.exists() || !projectFile.extension().equals("h2d")
|| !projectFile.file().canRead() || !projectFile.file().canWrite())
return;
PreferencesManager prefs = PreferencesManager.getInstance();
prefs.buildRecentHistory();
prefs.pushHistory(prjFilePath);
facade.sendNotification(HyperLap2DMenuBar.RECENT_LIST_MODIFIED);
File prjFile = new File(prjFilePath);
if (!prjFile.isDirectory()) {
String projectContents = null;
try {
projectContents = FileUtils.readFileToString(projectFile.file(), "utf-8");
Json json = HyperJson.getJson();
json.setIgnoreUnknownFields(true);
ProjectVO vo = json.fromJson(ProjectVO.class, projectContents);
goThroughVersionMigrationProtocol(projectPath, vo);
currentProjectVO = vo;
String prjInfoFilePath = projectPath + "/project.dt";
FileHandle projectInfoFile = Gdx.files.internal(prjInfoFilePath);
String projectInfoContents = FileUtils.readFileToString(projectInfoFile.file(), "utf-8");
currentProjectInfoVO = json.fromJson(ProjectInfoVO.class, projectInfoContents);
projectExportSettings.setSettings(vo);
facade.sendNotification(SettingsDialog.ADD_SETTINGS, projectExportSettings);
livePreviewSettings.setSettings(vo);
facade.sendNotification(SettingsDialog.ADD_SETTINGS, livePreviewSettings);
} catch (IOException e) {
e.printStackTrace();
}
ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
if (resolution == null) {
resolutionManager.currentResolutionName = currentProjectVO.lastOpenResolution.isEmpty() ? "orig" : currentProjectVO.lastOpenResolution;
} else {
resolutionManager.currentResolutionName = resolution;
currentProjectVO.lastOpenResolution = resolutionManager.currentResolutionName;
}
currentProjectPath = projectPath;
saveCurrentProject();
checkForConsistency(projectPath);
loadProjectData(projectPath);
try {
addFileWatcher(projectPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void addFileWatcher(String projectPath) {
stopFileWatcher();
if (fileWatcherThread != null) return;
Path directory = Paths.get(projectPath);
fileWatcherThread = new Thread(new Runnable() {
@Override
public void run() {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
registerAll(directory, watchService);
while (true) {
WatchKey key;
try {
// Poll for file system events
key = watchService.poll(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return;
}
if (key == null) {
// No events within the timeout period
continue;
}
List<WatchEvent<?>> events = key.pollEvents();
for (int i = 0; i < events.size(); i++) {
WatchEvent<?> event = events.get(i);
WatchEvent.Kind<?> kind = event.kind();
Path fileName = (Path) event.context();
Path filePath = ((Path) key.watchable()).resolve(fileName);
File file = filePath.toFile();
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.PROJECT_FILE_CREATED, file));
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.PROJECT_FILE_DELETED, file));
} else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.PROJECT_FILE_MODIFIED, file));
}
}
// Reset the key
boolean valid = key.reset();
if (!valid) {
break; // Exit the loop if the key is no longer valid
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, "FileWatcherThread");
fileWatcherThread.setDaemon(true);
fileWatcherThread.start();
}
public void stopFileWatcher() {
if (fileWatcherThread == null) return;
fileWatcherThread.interrupt();
fileWatcherThread = null;
}
private void registerAll(final Path start, final WatchService watchService) throws Exception {
// Register the directory and its subdirectories recursively
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
return FileVisitResult.CONTINUE;
}
});
}
private void goThroughVersionMigrationProtocol(String projectPath, ProjectVO projectVo) {
ProjectVersionMigrator pvm = new ProjectVersionMigrator(projectPath, projectVo);
pvm.start();
}
private void checkForConsistency(String projectPath) {
// check if current project requires cleanup
FileHandle sourceDir = new FileHandle(projectPath + "/scenes/");
for (FileHandle entry : sourceDir.list(HyperLap2DUtils.DT_FILTER)) {
if (!entry.file().isDirectory()) {
Json json = HyperJson.getJson();
json.setIgnoreUnknownFields(true);
SceneVO sceneVO = json.fromJson(SceneVO.class, entry);
if (sceneVO.composite == null) continue;
Array<MainItemVO> items = sceneVO.composite.getAllItems();
for (CompositeItemVO libraryItem : currentProjectInfoVO.libraryItems.values()) {
if (libraryItem == null) continue;
items = libraryItem.getAllItems();
}
}
}
}
public void loadProjectData(String projectPath) {
// All legit loading assets
ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
File pack = new File(currentProjectPath + "/assets/" + resolutionManager.currentResolutionName + "/pack/pack.atlas");
if (!pack.exists()) {
System.err.println("Main Pack not found! Trying to recovery...");
resolutionManager.rePackProjectImagesForAllResolutionsSync();
}
ResourceManager resourceManager = facade.retrieveProxy(ResourceManager.NAME);
resourceManager.loadCurrentProjectData(projectPath, resolutionManager.currentResolutionName);
}
public void saveCurrentProject() {
try {
FileUtils.writeStringToFile(new File(currentProjectPath + "/project.h2d"), currentProjectVO.constructJsonString(), "utf-8");
FileUtils.writeStringToFile(new File(currentProjectPath + "/project.dt"), currentProjectInfoVO.constructJsonString(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveCurrentProject(SceneVO vo) {
saveCurrentProject();
SceneDataManager sceneDataManager = facade.retrieveProxy(SceneDataManager.NAME);
sceneDataManager.saveScene(vo);
}
public void saveProjectAs() {
facade.sendNotification(MsgAPI.SHOW_BLACK_OVERLAY);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
String selected = TinyFileDialogs.tinyfd_selectFolderDialog("Choose destination directory...", currentProjectPath);
if (selected != null) {
FileHandle fileHandle = new FileHandle(selected);
if (fileHandle.isDirectory() && fileHandle.list().length == 0) {
FileHandle source = new FileHandle(currentProjectPath);
try {
FileUtils.copyDirectory(source.file(), fileHandle.file(), null);
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.SHOW_NOTIFICATION, "Project saved successfully"));
} catch (IOException e) {
e.printStackTrace();
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.SHOW_NOTIFICATION, "ERROR: Unable to copy files!"));
}
} else {
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.SHOW_NOTIFICATION, "ERROR: Please choose an empty directory!"));
}
}
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.HIDE_BLACK_OVERLAY));
});
executor.shutdown();
}
public void copyImageFilesForAllResolutionsIntoProject(Array<FileHandle> files, Boolean performResize, ProgressHandler handler) {
copyImageFilesIntoProject(files, currentProjectInfoVO.originalResolution, performResize, handler);
int totalWarnings = 0;
for (int i = 0; i < currentProjectInfoVO.resolutions.size; i++) {
ResolutionEntryVO resolutionEntryVO = currentProjectInfoVO.resolutions.get(i);
totalWarnings += copyImageFilesIntoProject(files, resolutionEntryVO, performResize, handler);
}
if (totalWarnings > 0) {
Dialogs.showOKDialog(Sandbox.getInstance().getUIStage(), "Warning", totalWarnings + " images were not resized for smaller resolutions due to already small size ( < 3px )");
}
}
/**
* @param files
* @param resolution
* @param performResize
* @return number of images that did needed to be resized but failed
*/
private int copyImageFilesIntoProject(Array<FileHandle> files, ResolutionEntryVO resolution, Boolean performResize, ProgressHandler handler) {
float ratio = ResolutionManager.getResolutionRatio(resolution, currentProjectInfoVO.originalResolution);
String targetPath = currentProjectPath + "/assets/" + resolution.name + "/images";
float perCopyPercent = 95.0f / files.size;
int resizeWarningsCount = 0;
for (FileHandle handle : files) {
if (!HyperLap2DUtils.PNG_FILTER.accept(null, handle.name())) {
continue;
}
try {
BufferedImage bufferedImage;
if (performResize) {
bufferedImage = ResolutionManager.imageResize(handle.file(), ratio);
if (bufferedImage == null) {
System.out.println(handle.file());
bufferedImage = ImageIO.read(handle.file());
resizeWarningsCount++;
}
} else {
bufferedImage = ImageIO.read(handle.file());
}
File target = new File(targetPath);
if (!target.exists()) {
File newFile = new File(targetPath);
newFile.mkdir();
}
ImageIO.write(bufferedImage, "png", new File(targetPath + "/" + handle.name()));
} catch (IOException e) {
e.printStackTrace();
}
handler.progressChanged(perCopyPercent);
}
return resizeWarningsCount;
}
public String getFreeTypeFontPath() {
return currentProjectPath + File.separator + FONTS_DIR_PATH;
}
public void exportProject() {
String defaultBuildPath = currentProjectPath + "/export";
exportPacks(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportPacks(currentProjectVO.projectMainExportPath);
}
exportAnimations(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportAnimations(currentProjectVO.projectMainExportPath);
}
exportParticles(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportParticles(currentProjectVO.projectMainExportPath);
}
exportTalosVFX(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportTalosVFX(currentProjectVO.projectMainExportPath);
}
exportShaders(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportShaders(currentProjectVO.projectMainExportPath);
}
prepareFontsForExport();
exportFonts(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportFonts(currentProjectVO.projectMainExportPath);
}
exportBitmapFonts(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportBitmapFonts(currentProjectVO.projectMainExportPath);
}
exportTinyVG(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
exportTinyVG(currentProjectVO.projectMainExportPath);
}
SceneDataManager sceneDataManager = facade.retrieveProxy(SceneDataManager.NAME);
sceneDataManager.buildScenes(defaultBuildPath);
if (!currentProjectVO.projectMainExportPath.isEmpty()) {
sceneDataManager.buildScenes(currentProjectVO.projectMainExportPath);
}
}
private void exportShaders(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle shadersDirectory = origDirectoryHandle.child("shaders");
File fileTarget = new File(targetPath + "/" + shadersDirectory.name());
try {
FileUtils.copyDirectory(shadersDirectory.file(), fileTarget);
} catch (IOException ignore) {
}
}
private void exportParticles(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle particlesDirectory = origDirectoryHandle.child("particles");
File fileTarget = new File(targetPath + "/" + particlesDirectory.name());
try {
FileUtils.copyDirectory(particlesDirectory.file(), fileTarget);
} catch (IOException ignore) {
}
}
private void exportTalosVFX(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle particlesDirectory = origDirectoryHandle.child("talos-vfx");
File fileTarget = new File(targetPath + "/" + "talos-vfx");
try {
FileFilter talosSuffixFilter = new RecursiveFileSuffixFilter(".p", ".shdr", ".fga");
FileUtils.copyDirectory(particlesDirectory.file(), fileTarget, talosSuffixFilter);
} catch (IOException ignore) {
}
}
private void prepareFontsForExport() {
FontManager fontManager = facade.retrieveProxy(FontManager.NAME);
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle fontsDirectory = origDirectoryHandle.child("freetypefonts");
for (FileHandle fontFile : fontsDirectory.list()) {
if (!fontFile.isDirectory())
fontFile.delete();
}
ResourceManager resourceManager = facade.retrieveProxy(ResourceManager.NAME);
ArrayList<FontSizePair> requiredFonts = resourceManager.getProjectRequiredFontsList();
for (FontSizePair font : requiredFonts) {
try {
HashMap<String, String> fonts = fontManager.getFontsMap();
if (fonts.containsKey(font.fontName)) {
FileHandle source = new FileHandle(fonts.get(font.fontName));
FileHandle dest = new FileHandle(fontsDirectory.path() + File.separator + font.fontName + ".ttf");
FileUtils.copyFile(source.file(), dest.file());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void exportBitmapFonts(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle fontsDirectory = origDirectoryHandle.child("bitmapfonts");
File fileTarget = new File(targetPath + "/" + fontsDirectory.name());
try {
FileUtils.copyDirectory(fontsDirectory.file(), fileTarget);
} catch (IOException ignore) {
}
}
private void exportTinyVG(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle fontsDirectory = origDirectoryHandle.child("tinyvg");
File fileTarget = new File(targetPath + "/" + fontsDirectory.name());
try {
FileUtils.copyDirectory(fontsDirectory.file(), fileTarget);
} catch (IOException ignore) {
}
}
private void exportFonts(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle origDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle fontsDirectory = origDirectoryHandle.child("freetypefonts");
File fileTarget = new File(targetPath + "/" + fontsDirectory.name());
try {
FileUtils.copyDirectory(fontsDirectory.file(), fileTarget);
} catch (IOException ignore) {
}
}
private void exportAnimations(String targetPath) {
exportSpineAnimationForResolution(targetPath);
}
private void exportSpineAnimationForResolution(String targetPath) {
String spineSrcPath = currentProjectPath + "/assets" + File.separator + "spine-animations";
try {
FileUtils.forceMkdir(new File(targetPath + File.separator + "spine-animations"));
File fileSrc = new File(spineSrcPath);
String finalTarget = targetPath + File.separator + "spine-animations";
File fileTargetSpine = new File(finalTarget);
FileFilter jsonSuffixFilter = new RecursiveFileSuffixFilter(".json");
FileUtils.copyDirectory(fileSrc, fileTargetSpine, jsonSuffixFilter);
} catch (IOException e) {
e.printStackTrace();
}
}
private void exportPacks(String targetPath) {
String srcPath = currentProjectPath + "/assets";
FileHandle assetDirectoryHandle = Gdx.files.absolute(srcPath);
FileHandle[] assetDirectories = assetDirectoryHandle.list();
for (FileHandle assetDirectory : assetDirectories) {
if (assetDirectory.isDirectory()) {
FileHandle assetDirectoryFileHandle = Gdx.files.absolute(assetDirectory.path());
FileHandle[] packFiles = assetDirectoryFileHandle.child("pack").list();
for (FileHandle packFile : packFiles) {
File fileTarget = new File(targetPath + "/" + assetDirectory.name() + "/" + packFile.name());
try {
FileUtils.copyFile(packFile.file(), fileTarget);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void setExportPaths(String path) {
currentProjectVO.projectMainExportPath = path;
}
public void setTexturePackerVO(TexturePackerVO texturePackerVO) {
TexturePackerVO vo = currentProjectVO.texturePackerVO;
vo.duplicate = texturePackerVO.duplicate;
vo.filterMag = texturePackerVO.filterMag;
vo.filterMin = texturePackerVO.filterMin;
vo.maxHeight = texturePackerVO.maxHeight;
vo.maxWidth = texturePackerVO.maxWidth;
vo.square = texturePackerVO.square;
vo.legacy = texturePackerVO.legacy;
}
public Settings getTexturePackerSettings() {
TexturePackerVO vo = currentProjectVO.texturePackerVO;
Settings settings = new Settings();
settings.maxHeight = Integer.parseInt(vo.maxHeight);
settings.maxWidth = Integer.parseInt(vo.maxWidth);
settings.duplicatePadding = vo.duplicate;
settings.filterMag = TexturePackerVO.filterMap.get(vo.filterMag);
settings.filterMin = TexturePackerVO.filterMap.get(vo.filterMin);
settings.square = vo.square;
settings.flattenPaths = true;
settings.legacyOutput = vo.legacy;
return settings;
}
public void createNewProject(String projectPath, int originWidth, int originHeight, int pixelPerWorldUnit) {
if (projectPath == null || projectPath.equals("")) {
return;
}
String projectName = new File(projectPath).getName();
if (projectName.equals("")) {
return;
}
try {
createEmptyProject(projectPath, originWidth, originHeight, pixelPerWorldUnit);
openProjectAndLoadAllData(projectPath);
String workSpacePath = projectPath.substring(0, projectPath.lastIndexOf(projectName));
if (workSpacePath.length() > 0) {
SettingsManager settingsManager = facade.retrieveProxy(SettingsManager.NAME);
settingsManager.setLastOpenedPath(workSpacePath);
}
Sandbox.getInstance().loadCurrentProject();
facade.sendNotification(PROJECT_OPENED);
//Set title with opened file path
setWindowTitle(getFormattedTitle(projectPath));
} catch (IOException e) {
e.printStackTrace();
}
}
private String getFormattedTitle(String path) {
//App Name + path to opened file
return currentProjectVO.projectName + " [ " + getCurrentSceneConfigVO().sceneName + " ] - " + path;
}
public void changeSceneWindowTitle() {
setWindowTitle(getFormattedTitle(currentProjectPath));
}
private void setWindowTitle(String title) {
WindowTitleManager windowTitleManager = facade.retrieveProxy(WindowTitleManager.NAME);
windowTitleManager.setWindowTitle(title);
}
public SceneConfigVO getCurrentSceneConfigVO() {
if (currentProjectVO == null)
return null;
for (int i = 0; i < currentProjectVO.sceneConfigs.size(); i++) {
if (currentProjectVO.sceneConfigs.get(i).sceneName.equals(Sandbox.getInstance().getSceneControl().getCurrentSceneVO().sceneName)) {
return currentProjectVO.sceneConfigs.get(i);
}
}
SceneConfigVO newConfig = new SceneConfigVO();
newConfig.sceneName = Sandbox.getInstance().getSceneControl().getCurrentSceneVO().sceneName;
currentProjectVO.sceneConfigs.add(newConfig);
return newConfig;
}
public String getCurrentProjectPath() {
return currentProjectPath;
}
public String getCurrentRawImagesPath() {
return currentProjectPath + File.separator + "assets" + File.separator + "orig" + File.separator + "images";
}
public void deleteRegionFromPack(HashMap<String, TexturePackVO> map, String region) {
for (TexturePackVO vo : map.values())
vo.regions.remove(region);
}
} | 32,723 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ResolutionManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/ResolutionManager.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.proxy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.tools.texturepacker.TexturePacker;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.kotcrab.vis.ui.util.dialog.Dialogs;
import com.mortennobel.imagescaling.ResampleOp;
import games.rednblack.editor.renderer.data.ProjectInfoVO;
import games.rednblack.editor.renderer.data.ResolutionEntryVO;
import games.rednblack.editor.renderer.data.TexturePackVO;
import games.rednblack.editor.utils.HyperLap2DUtils;
import games.rednblack.editor.utils.NinePatchUtils;
import games.rednblack.editor.view.stage.Sandbox;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.ProgressHandler;
import games.rednblack.puremvc.Facade;
import games.rednblack.puremvc.Proxy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ResolutionManager extends Proxy {
public interface RepackCallback {
void onRepack(boolean success);
}
private static final String TAG = ResolutionManager.class.getCanonicalName();
public static final String NAME = TAG;
public static final String RESOLUTION_LIST_CHANGED = "games.rednblack.editor.proxy.ResolutionManager" + ".RESOLUTION_LIST_CHANGED";
private static final String EXTENSION_9PATCH = ".9.png";
public String currentResolutionName;
private float currentPercent = 0.0f;
private ProgressHandler handler;
public ResolutionManager() {
super(NAME, null);
}
public static BufferedImage imageResize(File file, float ratio) {
BufferedImage destinationBufferedImage = null;
try {
BufferedImage sourceBufferedImage = ImageIO.read(file);
if (ratio == 1.0) {
return sourceBufferedImage;
}
// When image has to be resized smaller then 3 pixels we should leave it as is, as to ResampleOP limitations
// But it should also trigger a warning dialog at the and of the import, to notify the user of non resized images.
if (sourceBufferedImage.getWidth() * ratio < 3 || sourceBufferedImage.getHeight() * ratio < 3) {
return null;
}
int newWidth = Math.max(3, Math.round(sourceBufferedImage.getWidth() * ratio));
int newHeight = Math.max(3, Math.round(sourceBufferedImage.getHeight() * ratio));
String name = file.getName();
Integer[] patches = null;
if (name.endsWith(EXTENSION_9PATCH)) {
patches = NinePatchUtils.findPatches(sourceBufferedImage);
sourceBufferedImage = NinePatchUtils.removePatches(sourceBufferedImage);
newWidth = Math.round(sourceBufferedImage.getWidth() * ratio);
newHeight = Math.round(sourceBufferedImage.getHeight() * ratio);
System.out.println(sourceBufferedImage.getWidth());
destinationBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = destinationBufferedImage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g2.drawImage(sourceBufferedImage, 0, 0, newWidth, newHeight, null);
g2.dispose();
} else {
// resize with bilinear filter
ResampleOp resampleOp = new ResampleOp(newWidth, newHeight);
destinationBufferedImage = resampleOp.filter(sourceBufferedImage, null);
}
if (patches != null) {
destinationBufferedImage = NinePatchUtils.convertTo9Patch(destinationBufferedImage, patches, ratio);
}
} catch (IOException ignored) {
}
return destinationBufferedImage;
}
public static float getResolutionRatio(ResolutionEntryVO resolution, ResolutionEntryVO originalResolution) {
float a;
float b;
switch (resolution.base) {
default:
case 0:
a = resolution.width;
b = originalResolution.width;
break;
case 1:
a = resolution.height;
b = originalResolution.height;
break;
}
return a / b;
}
@Override
public void onRegister() {
super.onRegister();
}
public void createNewResolution(ResolutionEntryVO resolutionEntryVO) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
projectManager.getCurrentProjectInfoVO().resolutions.add(resolutionEntryVO);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
// create new folder structure
String projPath = projectManager.getCurrentProjectPath();
String sourcePath = projPath + "/" + "assets/orig/images";
String targetPath = projPath + "/" + "assets/" + resolutionEntryVO.name + "/images";
createIfNotExist(sourcePath);
createIfNotExist(projPath + "/" + "assets/" + resolutionEntryVO.name + "/pack");
copyTexturesFromTo(sourcePath, targetPath);
int resizeWarnings = resizeTextures(targetPath, resolutionEntryVO);
rePackProjectImages(resolutionEntryVO);
changePercentBy(5);
if (resizeWarnings > 0) {
Dialogs.showOKDialog(Sandbox.getInstance().getUIStage(), "Warning", resizeWarnings + " images were not resized for smaller resolutions due to already small size ( < 3px )");
}
Facade.getInstance().sendNotification(RESOLUTION_LIST_CHANGED);
});
executor.execute(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
projectManager.saveCurrentProject();
// handler.progressComplete();
});
executor.shutdown();
}
private void changePercentBy(float value) {
currentPercent += value;
//handler.progressChanged(currentPercent);
}
public void rePackProjectImages(ResolutionEntryVO resEntry) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
TexturePacker.Settings settings = projectManager.getTexturePackerSettings();
String sourcePath = projectManager.getCurrentProjectPath() + "/assets/" + resEntry.name + "/images";
String outputPath = projectManager.getCurrentProjectPath() + "/assets/" + resEntry.name + "/pack";
FileHandle sourceDir = new FileHandle(sourcePath);
File outputDir = new File(outputPath);
try {
FileUtils.forceMkdir(outputDir);
FileUtils.cleanDirectory(outputDir);
} catch (IOException e) {
e.printStackTrace();
}
ObjectMap<String, TexturePacker> packerMap = new ObjectMap<>();
ObjectMap<String, String> regionsReverse = new ObjectMap<>();
for (TexturePackVO packVO : projectManager.currentProjectInfoVO.imagesPacks.values()) {
String name = packVO.name.equals("main") ? "pack" : packVO.name;
packerMap.put(name, new TexturePacker(settings));
for (String region : packVO.regions)
regionsReverse.put(region, name);
}
for (TexturePackVO packVO : projectManager.currentProjectInfoVO.animationsPacks.values()) {
String name = packVO.name.equals("main") ? "pack" : packVO.name;
if (packerMap.get(name) == null)
packerMap.put(name, new TexturePacker(settings));
for (String region : packVO.regions)
regionsReverse.put(region, name);
}
for (FileHandle entry : sourceDir.list()) {
if (entry.extension().equals("png")) {
String name = regionsReverse.get(entry.nameWithoutExtension().replace(".9", "").replaceAll("_[0-9]+", ""));
name = name == null ? "pack" : name;
TexturePacker tp = packerMap.get(name);
tp.addImage(entry.file());
}
}
for (String name : packerMap.keys()) {
TexturePacker tp = packerMap.get(name);
tp.pack(outputDir, name);
}
}
private int resizeTextures(String path, ResolutionEntryVO resolution) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
float ratio = getResolutionRatio(resolution, projectManager.getCurrentProjectInfoVO().originalResolution);
FileHandle targetDir = new FileHandle(path);
FileHandle[] entries = targetDir.list(HyperLap2DUtils.PNG_FILTER);
float perResizePercent = 95.0f / entries.length;
int resizeWarnings = 0;
for (FileHandle entry : entries) {
try {
File file = entry.file();
File destinationFile = new File(path + "/" + file.getName());
BufferedImage resizedImage = ResolutionManager.imageResize(file, ratio);
if (resizedImage == null) {
resizeWarnings++;
ImageIO.write(ImageIO.read(file), "png", destinationFile);
} else {
ImageIO.write(ResolutionManager.imageResize(file, ratio), "png", destinationFile);
}
} catch (IOException e) {
e.printStackTrace();
}
changePercentBy(perResizePercent);
}
return resizeWarnings;
}
private void copyTexturesFromTo(String fromPath, String toPath) {
FileHandle sourceDir = new FileHandle(fromPath);
FileHandle[] entries = sourceDir.list(HyperLap2DUtils.PNG_FILTER);
float perCopyPercent = 10.0f / entries.length;
for (FileHandle entry : entries) {
File file = entry.file();
String filename = file.getName();
File target = new File(toPath + "/" + filename);
try {
FileUtils.copyFile(file, target);
} catch (IOException e) {
e.printStackTrace();
}
}
changePercentBy(perCopyPercent);
}
private File createIfNotExist(String dirPath) {
File theDir = new File(dirPath);
boolean result = false;
// if the directory does not exist, create it
if (!theDir.exists()) {
result = theDir.mkdir();
}
if (result)
return theDir;
else return null;
}
public void resizeImagesTmpDirToResolution(String packName, File sourceFolder, ResolutionEntryVO resolution, File targetFolder) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
float ratio = ResolutionManager.getResolutionRatio(resolution, projectManager.getCurrentProjectInfoVO().originalResolution);
if (targetFolder.exists()) {
try {
FileUtils.cleanDirectory(targetFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
// now pack
TexturePacker.Settings settings = projectManager.getTexturePackerSettings();
TexturePacker tp = new TexturePacker(settings);
for (final File fileEntry : sourceFolder.listFiles()) {
if (!fileEntry.isDirectory()) {
BufferedImage bufferedImage = ResolutionManager.imageResize(fileEntry, ratio);
tp.addImage(bufferedImage, FilenameUtils.removeExtension(fileEntry.getName()));
}
}
tp.pack(targetFolder, packName);
}
public float getCurrentMul() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
ResolutionEntryVO curRes = projectManager.getCurrentProjectInfoVO().getResolution(currentResolutionName);
float mul = 1f;
if (!currentResolutionName.equals("orig")) {
if (curRes.base == 0) {
mul = (float) curRes.width / (float) projectManager.getCurrentProjectInfoVO().originalResolution.width;
} else {
mul = (float) curRes.height / (float) projectManager.getCurrentProjectInfoVO().originalResolution.height;
}
}
return mul;
}
public void rePackProjectImagesForAllResolutions(boolean reloadProjectData) {
rePackProjectImagesForAllResolutions(reloadProjectData, null);
}
public void rePackProjectImagesForAllResolutions(boolean reloadProjectData, RepackCallback callback) {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.SHOW_LOADING_DIALOG));
try {
rePackProjectImagesForAllResolutionsSync();
Gdx.app.postRunnable(() -> facade.sendNotification(MsgAPI.HIDE_LOADING_DIALOG));
if (callback != null)
callback.onRepack(true);
} catch (Exception e) {
if (callback != null)
callback.onRepack(false);
}
if (reloadProjectData) {
Gdx.app.postRunnable(() -> {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
ResourceManager resourceManager = facade.retrieveProxy(ResourceManager.NAME);
resourceManager.loadCurrentProjectData(projectManager.getCurrentProjectPath(), currentResolutionName);
Sandbox.getInstance().loadCurrentProject();
facade.sendNotification(ProjectManager.PROJECT_DATA_UPDATED);
});
}
});
executor.shutdown();
}
public void rePackProjectImagesForAllResolutionsSync() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
rePackProjectImages(projectManager.getCurrentProjectInfoVO().originalResolution);
for (ResolutionEntryVO resolutionEntryVO : projectManager.getCurrentProjectInfoVO().resolutions) {
rePackProjectImages(resolutionEntryVO);
}
}
public void deleteResolution(ResolutionEntryVO resolutionEntryVO) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
try {
FileUtils.deleteDirectory(new File(projectManager.getCurrentProjectPath() + "/assets/" + resolutionEntryVO.name));
} catch (IOException ignored) {
ignored.printStackTrace();
}
currentResolutionName = getOriginalResolution().name;
ProjectInfoVO projectInfo = projectManager.getCurrentProjectInfoVO();
projectInfo.resolutions.removeValue(resolutionEntryVO, false);
Facade.getInstance().sendNotification(RESOLUTION_LIST_CHANGED);
projectManager.saveCurrentProject();
projectManager.openProjectAndLoadAllData(projectManager.getCurrentProjectPath(), "orig");
}
public Array<ResolutionEntryVO> getResolutions() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectInfoVO().resolutions;
}
public ResolutionEntryVO getOriginalResolution() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectInfoVO().originalResolution;
}
public ResolutionEntryVO getCurrentResolution() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
for (ResolutionEntryVO res : projectManager.getCurrentProjectInfoVO().resolutions) {
if (res.name.equals(currentResolutionName)) {
return res;
}
}
return getOriginalResolution();
}
}
| 17,038 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SceneDataManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/proxy/SceneDataManager.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.proxy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import games.rednblack.editor.renderer.data.CompositeItemVO;
import games.rednblack.editor.renderer.data.MainItemVO;
import games.rednblack.editor.renderer.data.SceneVO;
import games.rednblack.editor.renderer.utils.HyperJson;
import games.rednblack.puremvc.Proxy;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by sargis on 3/23/15.
*/
public class SceneDataManager extends Proxy {
private static final String TAG = SceneDataManager.class.getCanonicalName();
public static final String NAME = TAG;
public SceneDataManager() {
super(NAME, null);
}
public SceneVO createNewScene(String name) {
SceneVO vo = new SceneVO();
vo.sceneName = name;
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
try {
String projPath = projectManager.getCurrentProjectPath();
FileUtils.writeStringToFile(new File(projPath + "/project.dt"), projectManager.currentProjectInfoVO.constructJsonString(), "utf-8");
FileUtils.writeStringToFile(new File(projPath + "/scenes/" + vo.sceneName + ".dt"), vo.constructJsonString(), "utf-8");
projectManager.currentProjectInfoVO.scenes.add(vo);
} catch (IOException e) {
e.printStackTrace();
}
return vo;
}
public String getCurrProjectScenePathByName(String sceneName) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
return projectManager.getCurrentProjectPath() + "/scenes/" + sceneName + ".dt";
}
public void saveScene(SceneVO vo) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
try {
FileUtils.writeStringToFile(new File(projectManager.getCurrentProjectPath() + "/scenes/" + vo.sceneName + ".dt"),
vo.constructJsonString(), "utf-8");
CommandManager commandManager = facade.retrieveProxy(CommandManager.NAME);
commandManager.saveEvent();
} catch (IOException e) {
e.printStackTrace();
}
}
public void deleteCurrentScene() {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
if (projectManager.currentProjectVO.lastOpenScene.equals("MainScene")) {
return;
}
deleteScene(projectManager.currentProjectVO.lastOpenScene);
}
private void deleteScene(String sceneName) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
ArrayList<SceneVO> scenes = projectManager.currentProjectInfoVO.scenes;
SceneVO sceneToDelete = null;
for (SceneVO scene : scenes) {
if (scene.sceneName.equals(sceneName)) {
sceneToDelete = scene;
break;
}
}
if (sceneToDelete != null) {
scenes.remove(sceneToDelete);
}
projectManager.currentProjectInfoVO.scenes = scenes;
String projPath = projectManager.getCurrentProjectPath();
try {
FileUtils.writeStringToFile(new File(projPath + "/project.dt"), projectManager.currentProjectInfoVO.constructJsonString(), "utf-8");
FileUtils.forceDelete(new File(projPath + "/scenes/" + sceneName + ".dt"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void buildScenes(String targetPath) {
ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
String srcPath = projectManager.getCurrentProjectPath() + "/scenes";
FileHandle scenesDirectoryHandle = Gdx.files.absolute(srcPath);
try {
for (File scene : scenesDirectoryHandle.file().listFiles()) {
File fileTarget = new File(targetPath + File.separator + scenesDirectoryHandle.name() + File.separator + scene.getName());
Json json = HyperJson.getJson();
SceneVO sceneToExport = json.fromJson(SceneVO.class, FileUtils.readFileToString(scene, "utf-8"));
clearCompositesForExport(sceneToExport.composite);
FileUtils.writeStringToFile(fileTarget, sceneToExport.constructJsonString(), "utf-8");
}
} catch (IOException e) {
e.printStackTrace();
}
//copy project dt
try {
FileUtils.copyFile(new File(projectManager.getCurrentProjectPath() + "/project.dt"), new File(targetPath + "/project.dt"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void clearCompositesForExport(CompositeItemVO compositeVO) {
if (compositeVO == null)
return;
compositeVO.sStickyNotes.clear();
Array<MainItemVO> sComposites = compositeVO.content.get(CompositeItemVO.class.getName());
if (sComposites != null) {
for (MainItemVO mainItemVO : sComposites) {
CompositeItemVO c = (CompositeItemVO) mainItemVO;
clearCompositesForExport(c);
}
}
}
}
| 6,126 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
KeyboardListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/KeyboardListener.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.event;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener;
import com.kotcrab.vis.ui.widget.VisTextField;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 4/15/2015.
*/
public class KeyboardListener implements EventListener {
private final String eventName;
private final boolean handleFocus;
private String lastValue;
public KeyboardListener(String eventName) {
this(eventName, true);
}
public KeyboardListener(String eventName, boolean focus) {
this.eventName = eventName;
this.handleFocus = focus;
}
@Override
public boolean handle(Event event) {
if (handleFocus && event instanceof FocusListener.FocusEvent) {
handleFocusListener((FocusListener.FocusEvent) event);
return true;
}
if (event instanceof InputEvent) {
handleInputListener((InputEvent) event);
return true;
}
return false;
}
private void handleInputListener(InputEvent event) {
switch (event.getType()) {
case keyUp:
if (event.getKeyCode() == Input.Keys.ENTER || event.getKeyCode() == Input.Keys.NUMPAD_ENTER) {
keyboardHandler((VisTextField) event.getTarget());
}
break;
}
}
private void handleFocusListener(FocusListener.FocusEvent event) {
VisTextField field = (VisTextField) event.getTarget();
if(event.isFocused()) {
//it was a focus in event, which is no change, but needs to update lastValue to track changes
lastValue = field.getText();
return;
}
switch (event.getType()) {
case keyboard:
keyboardHandler(field);
break;
case scroll:
break;
}
}
private void keyboardHandler(VisTextField target) {
if(!target.isInputValid()) {
return;
}
// check for change
if(lastValue != null && lastValue.equals(target.getText())) {
// no change = no event;
return;
}
lastValue = target.getText();
Facade facade = Facade.getInstance();
facade.sendNotification(eventName, target.getText());
}
} | 3,331 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
NumberSelectorOverlapListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/NumberSelectorOverlapListener.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.kotcrab.vis.ui.widget.spinner.Spinner;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 6/12/2015.
*/
public class NumberSelectorOverlapListener extends ChangeListener {
private final String eventName;
public NumberSelectorOverlapListener(String eventName) {
this.eventName = eventName;
}
@Override
public void changed(ChangeEvent event, Actor actor) {
Facade facade = Facade.getInstance();
facade.sendNotification(eventName, ((Spinner)actor).getTextField().getText());
}
}
| 1,507 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SelectBoxChangeListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/SelectBoxChangeListener.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.kotcrab.vis.ui.widget.VisSelectBox;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 4/16/2015.
*/
public class SelectBoxChangeListener extends ChangeListener {
private final String eventName;
private String lastSelected = "";
public SelectBoxChangeListener(String eventName) {
this.eventName = eventName;
}
@Override
public void changed(ChangeEvent changeEvent, Actor actor) {
Facade facade = Facade.getInstance();
String selected = (String) ((VisSelectBox) actor).getSelected();
if(!lastSelected.equals(selected)) {
lastSelected = selected;
facade.sendNotification(eventName, selected);
}
}
}
| 1,673 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
MenuItemListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/MenuItemListener.java | package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import games.rednblack.puremvc.Facade;
/**
* Created by CyberJoe on 4/21/2015.
*/
public class MenuItemListener extends ChangeListener {
private final String menuCommand;
private final String menuType;
private final Object data;
private final Facade facade;
public MenuItemListener(String menuCommand) {
this(menuCommand, null, null);
}
public MenuItemListener(String menuCommand, String data) {
this(menuCommand, data, null);
}
public MenuItemListener(String menuCommand, Object data, String menuType) {
this.menuCommand = menuCommand;
this.data = data;
this.menuType = menuType;
facade = Facade.getInstance();
}
@Override
public void changed(ChangeEvent event, Actor actor) {
if(menuType == null) {
if(data == null) {
facade.sendNotification(menuCommand);
} else {
facade.sendNotification(menuCommand, data);
}
} else {
facade.sendNotification(menuCommand, data, menuType);
}
}
} | 1,243 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ButtonToNotificationListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/ButtonToNotificationListener.java | package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 7/2/2015.
*/
public class ButtonToNotificationListener extends ClickListener{
private String notificationName;
private Object payload;
public ButtonToNotificationListener(String notificationName) {
this.notificationName = notificationName;
}
public ButtonToNotificationListener(String notificationName, Object payload) {
this.notificationName = notificationName;
this.payload = payload;
}
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
super.touchUp(event, x, y, pointer, button);
Facade.getInstance().sendNotification(notificationName, payload);
}
}
| 884 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
EditableSelectBoxChangeListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/EditableSelectBoxChangeListener.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import games.rednblack.editor.view.ui.widget.EditableSelectBox;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 4/30/2015.
*/
public class EditableSelectBoxChangeListener extends ChangeListener {
private final String eventName;
private String lastSelected = "";
public EditableSelectBoxChangeListener(String eventName) {
this.eventName = eventName;
}
@Override
public void changed(ChangeEvent changeEvent, Actor actor) {
Facade facade = Facade.getInstance();
String selected = ((EditableSelectBox) actor).getSelected();
if(!lastSelected.equals(selected)) {
lastSelected = selected;
facade.sendNotification(eventName, selected);
}
}
} | 1,701 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ClickNotifier.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/ClickNotifier.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 4/29/2015.
*/
public class ClickNotifier extends ClickListener {
private final String eventName;
public ClickNotifier(String eventName) {
this.eventName = eventName;
}
@Override
public void clicked(InputEvent event, float x, float y) {
Facade facade = Facade.getInstance();
facade.sendNotification(eventName);
}
}
| 1,389 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
CheckBoxChangeListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/games/rednblack/editor/event/CheckBoxChangeListener.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.event;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.kotcrab.vis.ui.widget.VisCheckBox;
import games.rednblack.puremvc.Facade;
/**
* Created by azakhary on 4/16/2015.
*/
public class CheckBoxChangeListener extends ChangeListener {
private final String eventName, type;
public CheckBoxChangeListener(String eventName) {
this(eventName, null);
}
public CheckBoxChangeListener(String eventName, String type) {
this.eventName = eventName;
this.type = type;
}
@Override
public void changed(ChangeEvent changeEvent, Actor actor) {
Facade facade = Facade.getInstance();
facade.sendNotification(eventName, ((VisCheckBox) actor).isChecked(), type);
}
} | 1,629 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
GLESUtil.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/com/badlogic/gdx/backends/lwjgl3/GLESUtil.java | package com.badlogic.gdx.backends.lwjgl3;
import org.lwjgl.opengles.*;
import org.lwjgl.system.Callback;
import java.io.PrintStream;
import static org.lwjgl.opengl.GL30C.GL_CONTEXT_FLAGS;
import static org.lwjgl.opengl.GL43C.*;
import static org.lwjgl.opengl.GL43C.GL_DEBUG_SOURCE_OTHER;
import static org.lwjgl.system.APIUtil.apiLog;
import static org.lwjgl.system.APIUtil.apiUnknownToken;
import static org.lwjgl.system.MemoryUtil.NULL;
public class GLESUtil {
/** Enables or disables GL debug messages for the specified severity level. Returns false if the severity level could not be
* set (e.g. the NOTIFICATION level is not supported by the ARB and AMD extensions).
*
* See {@link Lwjgl3ApplicationConfiguration#enableGLDebugOutput(boolean, PrintStream)} */
public static boolean setGLESDebugMessageControl (Lwjgl3ApplicationGLESFix.GLDebugMessageSeverity severity, boolean enabled) {
GLESCapabilities caps = GLES.getCapabilities();
final int GL_DONT_CARE = 0x1100; // not defined anywhere yet
if (caps.GLES32) {
GLES32.glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, severity.gl43, 0, enabled);
return true;
}
return false;
}
public static Callback setupDebugMessageCallback(PrintStream stream) {
GLESCapabilities caps = GLES.getCapabilities();
if (caps.GLES32) {
apiLog("[GLES] Using OpenGL ES 3.2 for error logging.");
GLDebugMessageCallback proc = GLDebugMessageCallback.create((source, type, id, severity, length, message, userParam) -> {
stream.println("[LWJGL] OpenGL ES debug message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getDebugSource(source));
printDetail(stream, "Type", getDebugType(type));
printDetail(stream, "Severity", getDebugSeverity(severity));
printDetail(stream, "Message", GLDebugMessageCallback.getMessage(length, message));
});
GLES32.glDebugMessageCallback(proc, NULL);
if ((GLES32.glGetInteger(GL_CONTEXT_FLAGS) & GL_CONTEXT_FLAG_DEBUG_BIT) == 0) {
apiLog("[GLES] Warning: A non-debug context may not produce any debug output.");
GLES32.glEnable(GL_DEBUG_OUTPUT);
}
return proc;
}
apiLog("[GLES] No debug output implementation is available.");
return null;
}
private static void printDetail(PrintStream stream, String type, String message) {
stream.printf("\t%s: %s\n", type, message);
}
private static String getDebugSource(int source) {
switch (source) {
case GL_DEBUG_SOURCE_API:
return "API";
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
return "WINDOW SYSTEM";
case GL_DEBUG_SOURCE_SHADER_COMPILER:
return "SHADER COMPILER";
case GL_DEBUG_SOURCE_THIRD_PARTY:
return "THIRD PARTY";
case GL_DEBUG_SOURCE_APPLICATION:
return "APPLICATION";
case GL_DEBUG_SOURCE_OTHER:
return "OTHER";
default:
return apiUnknownToken(source);
}
}
private static String getDebugType(int type) {
switch (type) {
case GL_DEBUG_TYPE_ERROR:
return "ERROR";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
return "DEPRECATED BEHAVIOR";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
return "UNDEFINED BEHAVIOR";
case GL_DEBUG_TYPE_PORTABILITY:
return "PORTABILITY";
case GL_DEBUG_TYPE_PERFORMANCE:
return "PERFORMANCE";
case GL_DEBUG_TYPE_OTHER:
return "OTHER";
case GL_DEBUG_TYPE_MARKER:
return "MARKER";
default:
return apiUnknownToken(type);
}
}
private static String getDebugSeverity(int severity) {
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH:
return "HIGH";
case GL_DEBUG_SEVERITY_MEDIUM:
return "MEDIUM";
case GL_DEBUG_SEVERITY_LOW:
return "LOW";
case GL_DEBUG_SEVERITY_NOTIFICATION:
return "NOTIFICATION";
default:
return apiUnknownToken(severity);
}
}
}
| 4,517 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
Lwjgl3ApplicationGLESFix.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/src/main/java/com/badlogic/gdx/backends/lwjgl3/Lwjgl3ApplicationGLESFix.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl3;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.nio.IntBuffer;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.backends.lwjgl3.audio.Lwjgl3Audio;
import com.badlogic.gdx.backends.lwjgl3.audio.OpenALLwjgl3Audio;
import com.badlogic.gdx.graphics.glutils.GLVersion;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.opengl.AMDDebugOutput;
import org.lwjgl.opengl.ARBDebugOutput;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.opengl.KHRDebug;
import org.lwjgl.system.Callback;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.backends.lwjgl3.audio.mock.MockAudio;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.SharedLibraryLoader;
import org.lwjgl.system.Configuration;
public class Lwjgl3ApplicationGLESFix implements Lwjgl3ApplicationBase {
private final Lwjgl3ApplicationConfiguration config;
final Array<Lwjgl3Window> windows = new Array<Lwjgl3Window>();
private volatile Lwjgl3Window currentWindow;
private Lwjgl3Audio audio;
private final Files files;
private final Net net;
private final ObjectMap<String, Preferences> preferences = new ObjectMap<String, Preferences>();
private final Lwjgl3Clipboard clipboard;
private int logLevel = LOG_INFO;
private ApplicationLogger applicationLogger;
private volatile boolean running = true;
private final Array<Runnable> runnables = new Array<Runnable>();
private final Array<Runnable> executedRunnables = new Array<Runnable>();
private final Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
private static GLFWErrorCallback errorCallback;
private static GLVersion glVersion;
private static Callback glDebugCallback;
private final Sync sync;
static void initializeGlfw () {
if (errorCallback == null) {
if (SharedLibraryLoader.isMac) loadGlfwAwtMacos();
Lwjgl3NativesLoader.load();
errorCallback = GLFWErrorCallback.createPrint(Lwjgl3ApplicationConfiguration.errorStream);
GLFW.glfwSetErrorCallback(errorCallback);
if (SharedLibraryLoader.isMac) GLFW.glfwInitHint(GLFW.GLFW_ANGLE_PLATFORM_TYPE, GLFW.GLFW_ANGLE_PLATFORM_TYPE_METAL);
GLFW.glfwInitHint(GLFW.GLFW_JOYSTICK_HAT_BUTTONS, GLFW.GLFW_FALSE);
if (!GLFW.glfwInit()) {
throw new GdxRuntimeException("Unable to initialize GLFW");
}
}
}
static void loadANGLE () {
try {
Class angleLoader = Class.forName("com.badlogic.gdx.backends.lwjgl3.angle.ANGLELoader");
Method load = angleLoader.getMethod("load");
load.invoke(angleLoader);
} catch (ClassNotFoundException t) {
return;
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load ANGLE.", t);
}
}
static void postLoadANGLE () {
try {
Class angleLoader = Class.forName("com.badlogic.gdx.backends.lwjgl3.angle.ANGLELoader");
Method load = angleLoader.getMethod("postGlfwInit");
load.invoke(angleLoader);
} catch (ClassNotFoundException t) {
return;
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load ANGLE.", t);
}
}
static void loadGlfwAwtMacos () {
try {
Class loader = Class.forName("com.badlogic.gdx.backends.lwjgl3.awt.GlfwAWTLoader");
Method load = loader.getMethod("load");
File sharedLib = (File)load.invoke(loader);
Configuration.GLFW_LIBRARY_NAME.set(sharedLib.getAbsolutePath());
Configuration.GLFW_CHECK_THREAD0.set(false);
} catch (ClassNotFoundException t) {
return;
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load GLFW AWT for macOS.", t);
}
}
public Lwjgl3ApplicationGLESFix(ApplicationListener listener) {
this(listener, new Lwjgl3ApplicationConfiguration());
}
public Lwjgl3ApplicationGLESFix(ApplicationListener listener, Lwjgl3ApplicationConfiguration config) {
if (config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) loadANGLE();
initializeGlfw();
setApplicationLogger(new Lwjgl3ApplicationLogger());
this.config = config = Lwjgl3ApplicationConfiguration.copy(config);
if (config.title == null) config.title = listener.getClass().getSimpleName();
Gdx.app = this;
if (!config.disableAudio) {
try {
this.audio = createAudio(config);
} catch (Throwable t) {
log("Lwjgl3Application", "Couldn't initialize audio, disabling audio", t);
this.audio = new MockAudio();
}
} else {
this.audio = new MockAudio();
}
Gdx.audio = audio;
this.files = Gdx.files = createFiles();
this.net = Gdx.net = new Lwjgl3Net(config);
this.clipboard = new Lwjgl3Clipboard();
this.sync = new Sync();
Lwjgl3Window window = createWindow(config, listener, 0);
if (config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) postLoadANGLE();
windows.add(window);
try {
loop();
cleanupWindows();
} catch (Throwable t) {
if (t instanceof RuntimeException)
throw (RuntimeException)t;
else
throw new GdxRuntimeException(t);
} finally {
cleanup();
}
}
protected void loop () {
Array<Lwjgl3Window> closedWindows = new Array<Lwjgl3Window>();
while (running && windows.size > 0) {
// FIXME put it on a separate thread
audio.update();
boolean haveWindowsRendered = false;
closedWindows.clear();
int targetFramerate = -2;
for (Lwjgl3Window window : windows) {
window.makeCurrent();
currentWindow = window;
if (targetFramerate == -2) targetFramerate = window.getConfig().foregroundFPS;
synchronized (lifecycleListeners) {
haveWindowsRendered |= window.update();
}
if (window.shouldClose()) {
closedWindows.add(window);
}
}
GLFW.glfwPollEvents();
boolean shouldRequestRendering;
synchronized (runnables) {
shouldRequestRendering = runnables.size > 0;
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
}
for (Runnable runnable : executedRunnables) {
runnable.run();
}
if (shouldRequestRendering) {
// Must follow Runnables execution so changes done by Runnables are reflected
// in the following render.
for (Lwjgl3Window window : windows) {
if (!window.getGraphics().isContinuousRendering()) window.requestRendering();
}
}
for (Lwjgl3Window closedWindow : closedWindows) {
if (windows.size == 1) {
// Lifecycle listener methods have to be called before ApplicationListener methods. The
// application will be disposed when _all_ windows have been disposed, which is the case,
// when there is only 1 window left, which is in the process of being disposed.
for (int i = lifecycleListeners.size - 1; i >= 0; i--) {
LifecycleListener l = lifecycleListeners.get(i);
l.pause();
l.dispose();
}
lifecycleListeners.clear();
}
closedWindow.dispose();
windows.removeValue(closedWindow, false);
}
if (!haveWindowsRendered) {
// Sleep a few milliseconds in case no rendering was requested
// with continuous rendering disabled.
try {
Thread.sleep(1000 / config.idleFPS);
} catch (InterruptedException e) {
// ignore
}
} else if (targetFramerate > 0) {
sync.sync(targetFramerate); // sleep as needed to meet the target framerate
}
}
}
protected void cleanupWindows () {
synchronized (lifecycleListeners) {
for (LifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.pause();
lifecycleListener.dispose();
}
}
for (Lwjgl3Window window : windows) {
window.dispose();
}
windows.clear();
}
protected void cleanup () {
Lwjgl3Cursor.disposeSystemCursors();
audio.dispose();
errorCallback.free();
errorCallback = null;
if (glDebugCallback != null) {
glDebugCallback.free();
glDebugCallback = null;
}
GLFW.glfwTerminate();
}
@Override
public ApplicationListener getApplicationListener () {
return currentWindow.getListener();
}
@Override
public Graphics getGraphics () {
return currentWindow.getGraphics();
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Input getInput () {
return currentWindow.getInput();
}
@Override
public Files getFiles () {
return files;
}
@Override
public Net getNet () {
return net;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public ApplicationType getType () {
return ApplicationType.Desktop;
}
@Override
public int getVersion () {
return 0;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
@Override
public Preferences getPreferences (String name) {
if (preferences.containsKey(name)) {
return preferences.get(name);
} else {
Preferences prefs = new Lwjgl3Preferences(
new Lwjgl3FileHandle(new File(config.preferencesDirectory, name), config.preferencesFileType));
preferences.put(name, prefs);
return prefs;
}
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
}
}
@Override
public void exit () {
running = false;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Lwjgl3Audio createAudio (Lwjgl3ApplicationConfiguration config) {
return new OpenALLwjgl3Audio(config.audioDeviceSimultaneousSources, config.audioDeviceBufferCount,
config.audioDeviceBufferSize);
}
@Override
public Lwjgl3Input createInput (Lwjgl3Window window) {
return new DefaultLwjgl3Input(window);
}
protected Files createFiles () {
return new Lwjgl3Files();
}
/** Creates a new {@link Lwjgl3Window} using the provided listener and {@link Lwjgl3WindowConfiguration}.
*
* This function only just instantiates a {@link Lwjgl3Window} and returns immediately. The actual window creation is postponed
* with {@link Application#postRunnable(Runnable)} until after all existing windows are updated. */
public Lwjgl3Window newWindow (ApplicationListener listener, Lwjgl3WindowConfiguration config) {
Lwjgl3ApplicationConfiguration appConfig = Lwjgl3ApplicationConfiguration.copy(this.config);
appConfig.setWindowConfiguration(config);
if (appConfig.title == null) appConfig.title = listener.getClass().getSimpleName();
return createWindow(appConfig, listener, windows.get(0).getWindowHandle());
}
private Lwjgl3Window createWindow (final Lwjgl3ApplicationConfiguration config, ApplicationListener listener,
final long sharedContext) {
final Lwjgl3Window window = new Lwjgl3Window(listener, config, this);
if (sharedContext == 0) {
// the main window is created immediately
createWindow(window, config, sharedContext);
} else {
// creation of additional windows is deferred to avoid GL context trouble
postRunnable(new Runnable() {
public void run () {
createWindow(window, config, sharedContext);
windows.add(window);
}
});
}
return window;
}
void createWindow (Lwjgl3Window window, Lwjgl3ApplicationConfiguration config, long sharedContext) {
long windowHandle = createGlfwWindow(config, sharedContext);
window.create(windowHandle);
window.setVisible(config.initialVisible);
for (int i = 0; i < 2; i++) {
window.getGraphics().gl20.glClearColor(config.initialBackgroundColor.r, config.initialBackgroundColor.g, config.initialBackgroundColor.b,
config.initialBackgroundColor.a);
window.getGraphics().gl20.glClear(GL11.GL_COLOR_BUFFER_BIT);
GLFW.glfwSwapBuffers(windowHandle);
}
}
static long createGlfwWindow (Lwjgl3ApplicationConfiguration config, long sharedContextWindow) {
GLFW.glfwDefaultWindowHints();
GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE);
GLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, config.windowResizable ? GLFW.GLFW_TRUE : GLFW.GLFW_FALSE);
GLFW.glfwWindowHint(GLFW.GLFW_MAXIMIZED, config.windowMaximized ? GLFW.GLFW_TRUE : GLFW.GLFW_FALSE);
GLFW.glfwWindowHint(GLFW.GLFW_AUTO_ICONIFY, config.autoIconify ? GLFW.GLFW_TRUE : GLFW.GLFW_FALSE);
GLFW.glfwWindowHint(GLFW.GLFW_RED_BITS, config.r);
GLFW.glfwWindowHint(GLFW.GLFW_GREEN_BITS, config.g);
GLFW.glfwWindowHint(GLFW.GLFW_BLUE_BITS, config.b);
GLFW.glfwWindowHint(GLFW.GLFW_ALPHA_BITS, config.a);
GLFW.glfwWindowHint(GLFW.GLFW_STENCIL_BITS, config.stencil);
GLFW.glfwWindowHint(GLFW.GLFW_DEPTH_BITS, config.depth);
GLFW.glfwWindowHint(GLFW.GLFW_SAMPLES, config.samples);
if (config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.GL30) {
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, config.gles30ContextMajorVersion);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, config.gles30ContextMinorVersion);
if (SharedLibraryLoader.isMac) {
// hints mandatory on OS X for GL 3.2+ context creation, but fail on Windows if the
// WGL_ARB_create_context extension is not available
// see: http://www.glfw.org/docs/latest/compat.html
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_FORWARD_COMPAT, GLFW.GLFW_TRUE);
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE);
}
} else {
if (config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) {
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_CREATION_API, GLFW.GLFW_EGL_CONTEXT_API);
GLFW.glfwWindowHint(GLFW.GLFW_CLIENT_API, GLFW.GLFW_OPENGL_ES_API);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 2);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 0);
}
}
if (config.transparentFramebuffer) {
GLFW.glfwWindowHint(GLFW.GLFW_TRANSPARENT_FRAMEBUFFER, GLFW.GLFW_TRUE);
}
if (config.debug) {
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_DEBUG_CONTEXT, GLFW.GLFW_TRUE);
}
long windowHandle = 0;
if (config.fullscreenMode != null) {
GLFW.glfwWindowHint(GLFW.GLFW_REFRESH_RATE, config.fullscreenMode.refreshRate);
windowHandle = GLFW.glfwCreateWindow(config.fullscreenMode.width, config.fullscreenMode.height, config.title,
config.fullscreenMode.getMonitor(), sharedContextWindow);
//On Ubuntu >= 22.04 with Nvidia GPU drivers and X11 display server there's a bug with EGL Context API
//If the windows creation has failed for this reason try to create it again with the native context
if (windowHandle == 0 && config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) {
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_CREATION_API, GLFW.GLFW_NATIVE_CONTEXT_API);
windowHandle = GLFW.glfwCreateWindow(config.fullscreenMode.width, config.fullscreenMode.height, config.title, config.fullscreenMode.getMonitor(), sharedContextWindow);
}
} else {
GLFW.glfwWindowHint(GLFW.GLFW_DECORATED, config.windowDecorated ? GLFW.GLFW_TRUE : GLFW.GLFW_FALSE);
windowHandle = GLFW.glfwCreateWindow(config.windowWidth, config.windowHeight, config.title, 0, sharedContextWindow);
//On Ubuntu >= 22.04 with Nvidia GPU drivers and X11 display server there's a bug with EGL Context API
//If the windows creation has failed for this reason try to create it again with the native context
if (windowHandle == 0 && config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) {
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_CREATION_API, GLFW.GLFW_NATIVE_CONTEXT_API);
windowHandle = GLFW.glfwCreateWindow(config.windowWidth, config.windowHeight, config.title, 0, sharedContextWindow);
}
}
if (windowHandle == 0) {
throw new GdxRuntimeException("Couldn't create window");
}
Lwjgl3Window.setSizeLimits(windowHandle, config.windowMinWidth, config.windowMinHeight, config.windowMaxWidth,
config.windowMaxHeight);
if (config.fullscreenMode == null) {
if (config.windowX == -1 && config.windowY == -1) {
int windowWidth = Math.max(config.windowWidth, config.windowMinWidth);
int windowHeight = Math.max(config.windowHeight, config.windowMinHeight);
if (config.windowMaxWidth > -1) windowWidth = Math.min(windowWidth, config.windowMaxWidth);
if (config.windowMaxHeight > -1) windowHeight = Math.min(windowHeight, config.windowMaxHeight);
long monitorHandle = GLFW.glfwGetPrimaryMonitor();
if (config.windowMaximized && config.maximizedMonitor != null) {
monitorHandle = config.maximizedMonitor.monitorHandle;
}
IntBuffer areaXPos = BufferUtils.createIntBuffer(1);
IntBuffer areaYPos = BufferUtils.createIntBuffer(1);
IntBuffer areaWidth = BufferUtils.createIntBuffer(1);
IntBuffer areaHeight = BufferUtils.createIntBuffer(1);
GLFW.glfwGetMonitorWorkarea(monitorHandle, areaXPos, areaYPos, areaWidth, areaHeight);
GLFW.glfwSetWindowPos(windowHandle, Math.max(0, areaXPos.get(0) + areaWidth.get(0) / 2 - windowWidth / 2),
Math.max(0, areaYPos.get(0) + areaHeight.get(0) / 2 - windowHeight / 2));
} else {
GLFW.glfwSetWindowPos(windowHandle, config.windowX, config.windowY);
}
if (config.windowMaximized) {
GLFW.glfwMaximizeWindow(windowHandle);
}
}
if (config.windowIconPaths != null) {
Lwjgl3Window.setIcon(windowHandle, config.windowIconPaths, config.windowIconFileType);
}
GLFW.glfwMakeContextCurrent(windowHandle);
GLFW.glfwSwapInterval(config.vSyncEnabled ? 1 : 0);
if (config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) {
try {
Class gles = Class.forName("org.lwjgl.opengles.GLES");
gles.getMethod("createCapabilities").invoke(gles);
} catch (Throwable e) {
throw new GdxRuntimeException("Couldn't initialize GLES", e);
}
} else {
GL.createCapabilities();
}
initiateGL(config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20);
//TODO fix glVersion.getVendorString() to glVersion.getVersionString() in 1.12.2
if (!glVersion.isVersionEqualToOrHigher(2, 0))
throw new GdxRuntimeException("OpenGL 2.0 or higher with the FBO extension is required. OpenGL version: "
+ glVersion.getVendorString() + "\n" + glVersion.getDebugVersionString());
if (config.glEmulation != Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20 && !supportsFBO()) {
throw new GdxRuntimeException("OpenGL 2.0 or higher with the FBO extension is required. OpenGL version: "
+ glVersion.getVendorString() + ", FBO extension: false\n" + glVersion.getDebugVersionString());
}
if (config.debug) {
if (config.glEmulation == Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20) {
glDebugCallback = GLESUtil.setupDebugMessageCallback(config.debugStream);
GLESUtil.setGLESDebugMessageControl(GLDebugMessageSeverity.NOTIFICATION, false);
} else {
glDebugCallback = GLUtil.setupDebugMessageCallback(config.debugStream);
setGLDebugMessageControl(GLDebugMessageSeverity.NOTIFICATION, false);
}
}
return windowHandle;
}
private static void initiateGL (boolean useGLES20) {
if (!useGLES20) {
String versionString = GL11.glGetString(GL11.GL_VERSION);
String vendorString = GL11.glGetString(GL11.GL_VENDOR);
String rendererString = GL11.glGetString(GL11.GL_RENDERER);
glVersion = new GLVersion(Application.ApplicationType.Desktop, versionString, vendorString, rendererString);
} else {
try {
Class gles = Class.forName("org.lwjgl.opengles.GLES20");
Method getString = gles.getMethod("glGetString", int.class);
String versionString = (String)getString.invoke(gles, GL11.GL_VERSION);
String vendorString = (String)getString.invoke(gles, GL11.GL_VENDOR);
String rendererString = (String)getString.invoke(gles, GL11.GL_RENDERER);
glVersion = new GLVersion(Application.ApplicationType.Desktop, versionString, vendorString, rendererString);
} catch (Throwable e) {
throw new GdxRuntimeException("Couldn't get GLES version string.", e);
}
}
}
private static boolean supportsFBO () {
// FBO is in core since OpenGL 3.0, see https://www.opengl.org/wiki/Framebuffer_Object
return glVersion.isVersionEqualToOrHigher(3, 0) || GLFW.glfwExtensionSupported("GL_EXT_framebuffer_object")
|| GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object");
}
public enum GLDebugMessageSeverity {
HIGH(GL43.GL_DEBUG_SEVERITY_HIGH, KHRDebug.GL_DEBUG_SEVERITY_HIGH, ARBDebugOutput.GL_DEBUG_SEVERITY_HIGH_ARB, AMDDebugOutput.GL_DEBUG_SEVERITY_HIGH_AMD),
MEDIUM(GL43.GL_DEBUG_SEVERITY_MEDIUM, KHRDebug.GL_DEBUG_SEVERITY_MEDIUM, ARBDebugOutput.GL_DEBUG_SEVERITY_MEDIUM_ARB, AMDDebugOutput.GL_DEBUG_SEVERITY_MEDIUM_AMD),
LOW(GL43.GL_DEBUG_SEVERITY_LOW, KHRDebug.GL_DEBUG_SEVERITY_LOW, ARBDebugOutput.GL_DEBUG_SEVERITY_LOW_ARB, AMDDebugOutput.GL_DEBUG_SEVERITY_LOW_AMD),
NOTIFICATION(GL43.GL_DEBUG_SEVERITY_NOTIFICATION, KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION, -1, -1);
final int gl43, khr, arb, amd;
GLDebugMessageSeverity (int gl43, int khr, int arb, int amd) {
this.gl43 = gl43;
this.khr = khr;
this.arb = arb;
this.amd = amd;
}
}
/** Enables or disables GL debug messages for the specified severity level. Returns false if the severity level could not be
* set (e.g. the NOTIFICATION level is not supported by the ARB and AMD extensions).
*
* See {@link Lwjgl3ApplicationConfiguration#enableGLDebugOutput(boolean, PrintStream)} */
public static boolean setGLDebugMessageControl (GLDebugMessageSeverity severity, boolean enabled) {
GLCapabilities caps = GL.getCapabilities();
final int GL_DONT_CARE = 0x1100; // not defined anywhere yet
if (caps.OpenGL43) {
GL43.glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, severity.gl43, (IntBuffer)null, enabled);
return true;
}
if (caps.GL_KHR_debug) {
KHRDebug.glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, severity.khr, (IntBuffer)null, enabled);
return true;
}
if (caps.GL_ARB_debug_output && severity.arb != -1) {
ARBDebugOutput.glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, severity.arb, (IntBuffer)null, enabled);
return true;
}
if (caps.GL_AMD_debug_output && severity.amd != -1) {
AMDDebugOutput.glDebugMessageEnableAMD(GL_DONT_CARE, severity.amd, (IntBuffer)null, enabled);
return true;
}
return false;
}
}
| 28,932 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TiledPanelMediator.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/TiledPanelMediator.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.plugin.tiled;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import games.rednblack.editor.renderer.data.TexturePackVO;
import games.rednblack.h2d.extension.spine.SpineItemType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Target;
import com.kotcrab.vis.ui.util.dialog.Dialogs;
import com.kotcrab.vis.ui.util.dialog.OptionDialogAdapter;
import games.rednblack.editor.plugin.tiled.data.AlternativeAutoTileVO;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.plugin.tiled.data.TileVO;
import games.rednblack.editor.plugin.tiled.manager.AutoGridTileManager;
import games.rednblack.editor.plugin.tiled.tools.DeleteTileTool;
import games.rednblack.editor.plugin.tiled.tools.DrawTileTool;
import games.rednblack.editor.plugin.tiled.view.SpineDrawable;
import games.rednblack.editor.plugin.tiled.view.tabs.SettingsTab;
import games.rednblack.editor.renderer.components.DimensionsComponent;
import games.rednblack.editor.renderer.factory.EntityFactory;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.ResourcePayloadObject;
import games.rednblack.puremvc.Mediator;
import games.rednblack.puremvc.interfaces.INotification;
import games.rednblack.puremvc.util.Interests;
/**
* Created by mariam on 2/2/2016.
*/
public class TiledPanelMediator extends Mediator<TiledPanel> {
private static final String TAG = TiledPanelMediator.class.getCanonicalName();
public static final String NAME = TAG;
private TiledPlugin tiledPlugin;
private DragAndDrop.Target targetGrid;
private DragAndDrop.Target targetAutoGrid;
private AutoGridTileManager autoGridTileManager;
public TiledPanelMediator(TiledPlugin tiledPlugin) {
super(NAME, new TiledPanel(tiledPlugin));
this.tiledPlugin = tiledPlugin;
autoGridTileManager = new AutoGridTileManager(tiledPlugin);
viewComponent.initLockView();
}
@Override
public void listNotificationInterests(Interests interests) {
interests.add(MsgAPI.SCENE_LOADED,
TiledPlugin.TILE_ADDED,
TiledPlugin.TILE_SELECTED,
TiledPlugin.ACTION_DELETE_TILE);
interests.add(TiledPlugin.ACTION_DELETE_TILE_ALL,
TiledPlugin.ACTION_SET_GRID_SIZE_FROM_LIST,
TiledPlugin.ACTION_SET_OFFSET,
TiledPlugin.OPEN_DROP_DOWN);
interests.add(TiledPlugin.AUTO_TILE_SELECTED,
TiledPlugin.ACTION_DELETE_AUTO_TILE,
TiledPlugin.AUTO_OPEN_DROP_DOWN,
TiledPlugin.AUTO_FILL_TILES);
interests.add(TiledPlugin.ACTION_SETUP_ALTERNATIVES_AUTO_TILE,
TiledPlugin.GRID_CHANGED,
SettingsTab.OK_BTN_CLICKED,
TiledPlugin.ACTION_SET_GRID_SIZE_FROM_ITEM);
interests.add(MsgAPI.IMAGE_BUNDLE_DROP_SINGLE,
MsgAPI.ACTION_DELETE_IMAGE_RESOURCE,
MsgAPI.TOOL_SELECTED,
MsgAPI.ACTION_KEY_DOWN);
}
@Override
public void handleNotification(INotification notification) {
super.handleNotification(notification);
String tileName;
switch (notification.getName()) {
case MsgAPI.SCENE_LOADED:
tiledPlugin.isSceneLoaded = true;
tiledPlugin.initSaveData();
viewComponent.initView();
targetGrid = initTarget(targetGrid, viewComponent.getDropTable(), false);
targetAutoGrid = initTarget(targetAutoGrid, viewComponent.getAutoGridDropTable(), true);
com.artemis.World engine = tiledPlugin.getAPI().getEngine();
viewComponent.setEngine(engine);
viewComponent.setFixedPosition();
break;
case MsgAPI.IMAGE_BUNDLE_DROP_SINGLE:
// aliasing the drop from the main project
case TiledPlugin.TILE_ADDED:
Object[] payload = notification.getBody();
tileName = (String) payload[0];
int type = (int) payload[1];
boolean isAutoTilesTarget = (boolean) payload[2];
if (isAutoTilesTarget) {
// we only add tiles that have not been added previously
if (tiledPlugin.dataToSave.containsAutoTile(tileName)) return;
// retract the images for the auto-tiles
retractAutoTiles(tileName);
viewComponent.addAutoTile(tileName, type);
tiledPlugin.dataToSave.addAutoTile(tileName, type);
} else {
// we only add tiles that have not been added previously
if (tiledPlugin.dataToSave.containsTile(tileName)) return;
viewComponent.addTile(tileName, type);
tiledPlugin.dataToSave.addTile(tileName, type);
facade.sendNotification(MsgAPI.UPDATE_RESOURCES_LIST);
}
tiledPlugin.saveDataManager.save();
break;
case TiledPlugin.TILE_SELECTED:
case TiledPlugin.AUTO_TILE_SELECTED:
if (viewComponent.isAutoGridTilesTabSelected()) {
viewComponent.selectAutoTile(notification.getBody());
} else {
viewComponent.selectTile(notification.getBody());
}
break;
case TiledPlugin.AUTO_FILL_TILES:
autoGridTileManager.autoFill();
break;
case TiledPlugin.OPEN_DROP_DOWN:
tileName = notification.getBody();
HashMap<String, String> actionsSet = new HashMap<>();
actionsSet.put(TiledPlugin.ACTION_SET_GRID_SIZE_FROM_LIST, "Set grid size");
actionsSet.put(TiledPlugin.ACTION_DELETE_TILE, "Delete");
actionsSet.put(TiledPlugin.ACTION_DELETE_TILE_ALL, "Delete all...");
actionsSet.put(TiledPlugin.ACTION_OPEN_OFFSET_PANEL, "Set offset");
tiledPlugin.facade.sendNotification(TiledPlugin.TILE_SELECTED, tiledPlugin.dataToSave.getTile(tileName));
tiledPlugin.getAPI().showPopup(actionsSet, tileName);
break;
case TiledPlugin.AUTO_OPEN_DROP_DOWN:
tileName = notification.getBody();
HashMap<String, String> autoActionsSet = new HashMap<>();
autoActionsSet.put(TiledPlugin.ACTION_SET_GRID_SIZE_FROM_LIST, "Set grid size");
autoActionsSet.put(TiledPlugin.ACTION_DELETE_AUTO_TILE, "Delete");
// autoActionsSet.put(TiledPlugin.ACTION_OPEN_OFFSET_PANEL, "Set offset");
autoActionsSet.put(TiledPlugin.ACTION_SETUP_ALTERNATIVES_AUTO_TILE, "Setup alternatives");
tiledPlugin.facade.sendNotification(TiledPlugin.AUTO_TILE_SELECTED, tiledPlugin.dataToSave.getAutoTile(tileName));
tiledPlugin.getAPI().showPopup(autoActionsSet, tileName);
break;
case MsgAPI.ACTION_DELETE_IMAGE_RESOURCE:
tileName = notification.getBody();
tiledPlugin.facade.sendNotification(TiledPlugin.ACTION_DELETE_TILE, tileName);
tiledPlugin.facade.sendNotification(TiledPlugin.ACTION_DELETE_AUTO_TILE, tileName);
break;
case TiledPlugin.ACTION_SET_GRID_SIZE_FROM_LIST:
float width = 0;
float height = 0;
if (tiledPlugin.isAutoGridTilesTabSelected()) {
AutoTileVO t = tiledPlugin.dataToSave.getAutoTile(notification.getBody());
TextureRegion r = tiledPlugin.pluginRM.getTextureRegion(t.regionName, t.entityType);
width = r.getRegionWidth() / TiledPlugin.AUTO_TILE_COLS;
height = r.getRegionHeight() / TiledPlugin.AUTO_TILE_ROWS;
} else {
TileVO t = tiledPlugin.dataToSave.getTile(notification.getBody());
if (t.entityType == SpineItemType.SPINE_TYPE) {
SpineDrawable spineDrawable = tiledPlugin.pluginRM.getSpineDrawable(t.regionName);
width = spineDrawable.width;
height = spineDrawable.height;
} else {
TextureRegion r = tiledPlugin.pluginRM.getTextureRegion(t.regionName, t.entityType);
width = r.getRegionWidth();
height = r.getRegionHeight();
}
}
tiledPlugin.dataToSave.setGrid(width / tiledPlugin.getPixelToWorld(), height / tiledPlugin.getPixelToWorld());
tiledPlugin.facade.sendNotification(TiledPlugin.GRID_CHANGED);
break;
case TiledPlugin.ACTION_DELETE_TILE:
String tn = notification.getBody();
if (!tiledPlugin.dataToSave.containsTile(tn)) return;
tiledPlugin.dataToSave.removeTile(tn);
tiledPlugin.saveDataManager.save();
tiledPlugin.setSelectedTileVO(new TileVO());
viewComponent.removeTile();
facade.sendNotification(MsgAPI.UPDATE_RESOURCES_LIST);
break;
case TiledPlugin.ACTION_DELETE_AUTO_TILE:
String tn2 = notification.getBody();
if (!tiledPlugin.dataToSave.containsAutoTile(tn2)) return;
tiledPlugin.dataToSave.removeAutoTile(tn2);
tiledPlugin.saveDataManager.save();
tiledPlugin.setSelectedAutoTileVO(new AutoTileVO());
for (AutoTileVO autoTile : tiledPlugin.dataToSave.getAutoTiles()) {
Iterator<AlternativeAutoTileVO> iter = autoTile.alternativeAutoTileList.iterator();
while (iter.hasNext()) {
AlternativeAutoTileVO alternativeAutoTileVO = iter.next();
if (alternativeAutoTileVO.region.equals(tn2)) {
iter.remove();
}
}
}
viewComponent.removeAutoTile();
tiledPlugin.facade.sendNotification(TiledPlugin.ACTION_RECALC_PERCENT_ALTERNATIVES_AUTO_TILE);
facade.sendNotification(MsgAPI.UPDATE_RESOURCES_LIST);
break;
case TiledPlugin.ACTION_DELETE_TILE_ALL:
Dialogs.showOptionDialog(tiledPlugin.getAPI().getUIStage(), "Delete all...", "Do you really want to delete all tiles?",
Dialogs.OptionDialogType.YES_NO, new OptionDialogAdapter() {
@Override
public void yes () {
tiledPlugin.dataToSave.removeAllTiles();
tiledPlugin.saveDataManager.save();
tiledPlugin.setSelectedTileVO(new TileVO());
viewComponent.removeAllTiles();
facade.sendNotification(MsgAPI.UPDATE_RESOURCES_LIST);
}
@Override
public void no () {
}
});
break;
case MsgAPI.TOOL_SELECTED:
String body = notification.getBody();
switch (body) {
case DeleteTileTool.NAME:
case DrawTileTool.NAME:
if(viewComponent.isOpen) {
break;
}
viewComponent.show(tiledPlugin.getAPI().getUIStage());
if(tiledPlugin.isSceneLoaded) {
viewComponent.setFixedPosition();
}
break;
default:
viewComponent.hide();
break;
}
break;
case SettingsTab.OK_BTN_CLICKED:
tiledPlugin.dataToSave.setParameterVO(notification.getBody());
tiledPlugin.saveDataManager.save();
break;
case TiledPlugin.GRID_CHANGED:
viewComponent.reInitGridSettings();
tiledPlugin.saveDataManager.save();
break;
case TiledPlugin.ACTION_SET_GRID_SIZE_FROM_ITEM:
int observable = notification.getBody();
DimensionsComponent dimensionsComponent = ComponentRetriever.get(observable, DimensionsComponent.class, tiledPlugin.getAPI().getEngine());
tiledPlugin.dataToSave.setGrid(dimensionsComponent.width, dimensionsComponent.height);
tiledPlugin.facade.sendNotification(TiledPlugin.GRID_CHANGED);
break;
case MsgAPI.ACTION_KEY_DOWN:
int keyCode = notification.getBody();
if (Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT)) {
if (keyCode == Input.Keys.B) {
facade.sendNotification(MsgAPI.TOOL_CLICKED, DrawTileTool.NAME);
}
}
break;
}
}
/**
* Retracts all auto-tiles from the given auto-tile-template.
*
* @param tileName The name of the tile from that the auto-tiles are retracted from.
*/
private void retractAutoTiles(String tileName) {
TextureRegion tr = tiledPlugin.getAPI().getSceneLoader().getRm().getTextureRegion(tileName);
tr.getTexture().getTextureData().prepare();
Pixmap pixmap = tr.getTexture().getTextureData().consumePixmap();
String name = tileName;
int tileW = tr.getRegionWidth() / TiledPlugin.AUTO_TILE_COLS;
int tileH = tr.getRegionHeight() / TiledPlugin.AUTO_TILE_ROWS;
int maxX = tr.getRegionWidth() + tr.getRegionX();
int maxY = tr.getRegionHeight() + tr.getRegionY();
//Create new atlas packing settings if doesn't exists
String atlasName = name + TiledPlugin.AUTO_TILE_ATLAS_SUFFIX;
TexturePackVO texturePackVO = tiledPlugin.getAPI().getCurrentProjectInfoVO().imagesPacks.get(atlasName);
if (texturePackVO == null) {
texturePackVO = new TexturePackVO();
texturePackVO.name = atlasName;
tiledPlugin.getAPI().getCurrentProjectInfoVO().imagesPacks.put(texturePackVO.name, texturePackVO);
}
int i = 0;
for (int x = tr.getRegionX(); x < maxX; x += tileW) {
for (int y = tr.getRegionY(); y < maxY; y += tileH) {
// skip non used
if (i != 4 && i != 9 && i != 14 && i != 19 && i != 49 && i != 50 && i != 51) {
int w = x + tileW <= pixmap.getWidth() ? tileW : pixmap.getWidth() - x;
int h = y + tileH <= pixmap.getHeight() ? tileH : pixmap.getHeight() - y;
Pixmap tilePixmap = new Pixmap(w, h, Pixmap.Format.RGBA8888);
tilePixmap.drawPixmap(pixmap, 0, 0, x, y, w, h);
String tilePngName = name + i;
String imagesPath = tiledPlugin.getCurrentRawImagesPath() + File.separator + tilePngName + ".png";
FileHandle path = new FileHandle(imagesPath);
PixmapIO.writePNG(path, tilePixmap);
tilePixmap.dispose();
texturePackVO.regions.add(tilePngName);
}
i++;
}
}
// create mini image
Pixmap tilePixmap = new Pixmap(tileW, tileH, Pixmap.Format.RGBA8888);
tilePixmap.drawPixmap(pixmap, tr.getRegionX(), tr.getRegionY(), tr.getRegionWidth(), tr.getRegionHeight(), 0, 0, tileW, tileH);
String miniImageName = name + TiledPlugin.AUTO_TILE_MINI_SUFFIX;
String imagesPath = tiledPlugin.getCurrentRawImagesPath() + File.separator + miniImageName + ".png";
FileHandle path = new FileHandle(imagesPath);
PixmapIO.writePNG(path, tilePixmap);
tilePixmap.dispose();
pixmap.dispose();
texturePackVO.regions.add(miniImageName);
facade.sendNotification(MsgAPI.UPDATE_ATLAS_PACK_LIST);
facade.sendNotification(MsgAPI.ACTION_REPACK);
}
private Target initTarget(Target targetGrid, Table dropTable, boolean isAutoGridTarget) {
if (targetGrid != null)
tiledPlugin.facade.sendNotification(MsgAPI.REMOVE_TARGET, targetGrid);
targetGrid = new DragAndDrop.Target(dropTable) {
@Override
public boolean drag(DragAndDrop.Source source, DragAndDrop.Payload payload, float x, float y, int pointer) {
return true;
}
@Override
public void drop(DragAndDrop.Source source, DragAndDrop.Payload payload, float x, float y, int pointer) {
ResourcePayloadObject resourcePayloadObject = (ResourcePayloadObject) payload.getObject();
int type = mapClassNameToEntityType(resourcePayloadObject.className);
if (type == EntityFactory.UNKNOWN_TYPE) return; //only some resources can become a tile!
String tileName = resourcePayloadObject.name;
// we send a notifier even in the case when the tile is not already added
tiledPlugin.facade.sendNotification(TiledPlugin.TILE_ADDED, new Object[]{tileName, type, isAutoGridTarget});
if (type == EntityFactory.IMAGE_TYPE) {
// ensure that all selected images are dropped
// the respective listener is responsible for dropping one-by-one, since he tracks the selected ones
tiledPlugin.facade.sendNotification(MsgAPI.IMAGE_BUNDLE_DROP, new Object[]{tileName, type, isAutoGridTarget});
}
}
};
tiledPlugin.facade.sendNotification(MsgAPI.ADD_TARGET, targetGrid);
return targetGrid;
}
private int mapClassNameToEntityType(String className) {
if (className.endsWith(".ImageResource"))
return EntityFactory.IMAGE_TYPE;
else if (className.endsWith(".SpriteResource"))
return EntityFactory.SPRITE_TYPE;
else if (className.endsWith(".SpineResource"))
return SpineItemType.SPINE_TYPE;
return EntityFactory.UNKNOWN_TYPE;
}
}
| 19,529 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TiledPanel.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/TiledPanel.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.plugin.tiled;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisTable;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.plugin.tiled.data.TileVO;
import games.rednblack.editor.plugin.tiled.manager.ResourcesManager;
import games.rednblack.editor.plugin.tiled.view.tabs.AbstractGridTilesTab;
import games.rednblack.editor.plugin.tiled.view.tabs.AutoGridTilesTab;
import games.rednblack.editor.plugin.tiled.view.tabs.GridTilesTab;
import games.rednblack.editor.plugin.tiled.view.tabs.SettingsTab;
import games.rednblack.h2d.common.UIDraggablePanel;
import games.rednblack.h2d.common.view.ui.widget.imagetabbedpane.ImageTab;
import games.rednblack.h2d.common.view.ui.widget.imagetabbedpane.ImageTabbedPane;
import games.rednblack.h2d.common.view.ui.widget.imagetabbedpane.ImageTabbedPaneListener;
import games.rednblack.puremvc.Facade;
/**
* Created by mariam on 2/2/2016.
*/
public class TiledPanel extends UIDraggablePanel {
public static final float GRID_WIDTH = 240f;
public static final float GRID_HEIGHT = 250f;
public static final float DROP_WIDTH = 240f;
public static final float DROP_HEIGHT = 140f;
public static final float SETTINGS_WIDTH = 240f;
public static final float SETTINGS_HEIGHT = 150f;
public TiledPlugin tiledPlugin;
private Facade facade;
protected ImageTabbedPane tabbedPane;
protected VisTable tabTable; //table inside of each tab
protected Table paneTable; //table for 'tabs' row
private GridTilesTab tilesTab;
private SettingsTab settingsTab;
private AutoGridTilesTab autoGridTilesTab;
private VisTable mainTable;
private com.artemis.World engine;
private ResourcesManager resourcesManager;
private boolean isAutoGridTabSelected;
public TiledPanel(TiledPlugin tiledPlugin) {
super("Tiles");
this.tiledPlugin = tiledPlugin;
facade = tiledPlugin.facade;
mainTable = new VisTable();
add(mainTable)
.padLeft(-2)
.padRight(2);
tabTable = new VisTable();
}
public void initView() {
if (resourcesManager == null)
this.resourcesManager = tiledPlugin.pluginRM;
mainTable.clear();
tabbedPane = new ImageTabbedPane();
paneTable = tabbedPane.getTable();
mainTable.add(paneTable).growX();
mainTable.row();
tabTable.clear();
paneTable.row();
paneTable.add(tabTable)
.left()
.top()
.row();
tabbedPane.addListener(new ImageTabbedPaneListener() {
@Override
public void switchedTab (ImageTab tab) {
if (tab == null) {
return;
}
float WIDTH = 0;
float HEIGHT = 0;
if (tab instanceof SettingsTab) {
WIDTH = SETTINGS_WIDTH;
HEIGHT = SETTINGS_HEIGHT;
} else if (tab instanceof AbstractGridTilesTab) {
isAutoGridTabSelected = tab instanceof AutoGridTilesTab;
tiledPlugin.setAutoGridTilesTabSelected(isAutoGridTabSelected);
if (((AbstractGridTilesTab<?>) tab).isDrop) {
WIDTH = DROP_WIDTH;
HEIGHT = DROP_HEIGHT;
} else {
WIDTH = GRID_WIDTH;
HEIGHT = GRID_HEIGHT;
}
}
Table content = tab.getContentTable();
tabTable.clearChildren();
tabTable.add(content)
.width(WIDTH)
.height(HEIGHT)
.row();
float prevHeight = getHeight();
pack();
float heightDiff = getHeight() - prevHeight;
setY(getY() - heightDiff);
}
@Override
public void removedTab(ImageTab tab) {
}
@Override
public void removedAllTabs() {
}
});
initTabs();
}
public boolean isAutoGridTilesTabSelected() {
return isAutoGridTabSelected;
}
public void setFixedPosition() {
setPosition(56f, 765f - getPrefHeight());
}
public Table getDropTable() {
return tilesTab.getContentTable();
}
public Table getAutoGridDropTable() {
return autoGridTilesTab.getContentTable();
}
public void reInitGridSettings() {
settingsTab.resetGridCategory();
}
public void addTile(String tileName, int type) {
tilesTab.addTile(tileName, type);
}
public void addAutoTile(String tileName, int type) {
autoGridTilesTab.addTile(tileName, type);
}
public void selectTile(TileVO tileVO) {
tilesTab.selectTile(tileVO);
}
public void selectAutoTile(AutoTileVO tileVO) {
autoGridTilesTab.selectTile(tileVO);
}
public void removeTile() {
tilesTab.removeTile();
reInitTabTable(tilesTab);
tilesTab.scrollTiles();
}
public void removeAllTiles() {
tilesTab.removeAllTiles();
reInitTabTable(tilesTab);
tilesTab.scrollTiles();
}
public void removeAutoTile() {
autoGridTilesTab.removeTile();
reInitTabTable(autoGridTilesTab);
autoGridTilesTab.scrollTiles();
}
private void initTabs() {
tilesTab = new GridTilesTab(this, 0);
tilesTab.initView();
tabbedPane.insert(tilesTab.getTabIndex(), tilesTab);
settingsTab = new SettingsTab(this, "Settings", 1);
settingsTab.initView();
tabbedPane.insert(settingsTab.getTabIndex(), settingsTab);
autoGridTilesTab = new AutoGridTilesTab(this, "Auto Tiling", 2);
autoGridTilesTab.initView();
tabbedPane.insert(autoGridTilesTab.getTabIndex(), autoGridTilesTab);
// reinit the currently visible tab
if (isAutoGridTabSelected) {
reInitTabTable(autoGridTilesTab);
} else {
reInitTabTable(tilesTab);
}
}
public void reInitTabTable(AbstractGridTilesTab<?> tab) {
isAutoGridTabSelected = tab instanceof AutoGridTilesTab;
tiledPlugin.setAutoGridTilesTabSelected(isAutoGridTabSelected);
float width = tab.isDrop ? DROP_WIDTH : GRID_WIDTH;
float height = tab.isDrop ? DROP_HEIGHT : GRID_HEIGHT;
tabTable.clear();
tabTable.add(tab.getContentTable())
.width(width)
.height(height);
tabTable.pack();
pack();
}
public void initLockView() {
mainTable.clear();
mainTable.add(new VisLabel("no scenes open")).right();
}
public void setEngine(com.artemis.World engine) {
this.engine = engine;
}
public Facade getFacade() {
return facade;
}
}
| 7,900 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TiledPlugin.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/TiledPlugin.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *****************************************************************************
*/
package games.rednblack.editor.plugin.tiled;
import java.io.File;
import java.util.Set;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.widget.VisImageButton;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.plugin.tiled.data.TileVO;
import games.rednblack.editor.plugin.tiled.manager.ResourcesManager;
import games.rednblack.editor.plugin.tiled.offset.OffsetPanel;
import games.rednblack.editor.plugin.tiled.offset.OffsetPanelMediator;
import games.rednblack.editor.plugin.tiled.save.DataToSave;
import games.rednblack.editor.plugin.tiled.save.SaveDataManager;
import games.rednblack.editor.plugin.tiled.tools.DeleteTileTool;
import games.rednblack.editor.plugin.tiled.tools.DrawTileTool;
import games.rednblack.editor.plugin.tiled.view.dialog.AlternativeAutoTileDialogMediator;
import games.rednblack.editor.plugin.tiled.view.dialog.ImportTileSetDialogMediator;
import games.rednblack.editor.renderer.components.MainItemComponent;
import games.rednblack.editor.renderer.components.TextureRegionComponent;
import games.rednblack.editor.renderer.components.TransformComponent;
import games.rednblack.editor.renderer.components.ZIndexComponent;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.MenuAPI;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.plugins.H2DPluginAdapter;
import net.mountainblade.modular.annotations.Implementation;
/**
* Created by mariam on 2/2/2016.
*/
@Implementation(authors = "azakhary", version = "0.0.1")
public class TiledPlugin extends H2DPluginAdapter {
//-------notifications---------//
public static final String CLASS_NAME = "games.rednblack.editor.plugin.tiled";
public static final String TILE_ADDED = CLASS_NAME + ".TILE_ADDED";
public static final String TILE_SELECTED = CLASS_NAME + ".TILE_SELECTED";
public static final String AUTO_TILE_SELECTED = CLASS_NAME + ".AUTO_TILE_SELECTED";
public static final String AUTO_FILL_TILES = CLASS_NAME + ".FILL_AUTO_TILE";
public static final String OPEN_DROP_DOWN = CLASS_NAME + ".OPEN_DROP_DOWN";
public static final String AUTO_OPEN_DROP_DOWN = CLASS_NAME + ".AUTO_OPEN_DROP_DOWN";
public static final String GRID_CHANGED = CLASS_NAME + ".GRID_CHANGED";
public static final String IMPORT_TILESET_PANEL_OPEN = CLASS_NAME + ".IMPORT_TILESET_PANEL_OPEN";
public static final String ACTION_DELETE_TILE = CLASS_NAME + ".ACTION_DELETE_TILE";
public static final String ACTION_DELETE_AUTO_TILE = CLASS_NAME + ".ACTION_DELETE_AUTO_TILE";
public static final String ACTION_DELETE_TILE_ALL = CLASS_NAME + ".ACTION_DELETE_TILE_ALL";
public static final String ACTION_SET_OFFSET = CLASS_NAME + ".ACTION_SET_OFFSET";
public static final String ACTION_OPEN_OFFSET_PANEL = CLASS_NAME + ".ACTION_OPEN_OFFSET_PANEL";
public static final String TILE_GRID_OFFSET_ADDED = CLASS_NAME + ".TILE_GRID_OFFSET_ADDED";
public static final String ACTION_SET_GRID_SIZE_FROM_ITEM = CLASS_NAME + ".ACTION_SET_GRID_SIZE_FROM_ITEM";
public static final String ACTION_SET_GRID_SIZE_FROM_LIST = CLASS_NAME + ".ACTION_SET_GRID_SIZE_FROM_LIST";
public static final String ACTION_SAVE_ALTERNATIVES_AUTO_TILE = CLASS_NAME + ".ACTION_SAVE_ALTERNATIVES_AUTO_TILE";
public static final String ACTION_SETUP_ALTERNATIVES_AUTO_TILE = CLASS_NAME + ".ACTION_SETUP_ALTERNATIVES_AUTO_TILE";
public static final String ACTION_RECALC_PERCENT_ALTERNATIVES_AUTO_TILE = CLASS_NAME + ".ACTION_RECALC_PERCENT_ALTERNATIVES_AUTO_TILE";
//-------end--------//
public static final String TILE_TAG = "TILE";
public static final String ROW = "ROW";
public static final String COLUMN = "COLUMN";
public static final String REGION = "REGION";
public static final String ORIG_AUTO_TILE = "ORIG_AUTO_TILE";
public static final String AUTO_TILE_TAG = "AUTO_TILE";
public static final String AUTO_TILE_ATLAS_SUFFIX = "-autotile";
public static final String AUTO_TILE_MINI_SUFFIX = "-mini";
public static final String AUTO_TILE_DRAW_SUFFIX = "18";
public static final int AUTO_TILE_ROWS = 5;
public static final int AUTO_TILE_COLS = 11;
public DataToSave dataToSave;
public SaveDataManager saveDataManager;
public boolean isSceneLoaded = false;
public DrawTileTool drawTileTool;
public DeleteTileTool deleteTileTool;
public ResourcesManager pluginRM;
public OffsetPanel offsetPanel;
private TileVO selectedTileVO;
private AutoTileVO selectedAutoTileVO;
private ObjectMap<String, String> currentEntityCustomVariables;
private MainItemComponent currentEntityMainItemComponent;
private TransformComponent currentEntityTransformComponent;
private boolean isAutoGridTabSelected;
public TiledPlugin() {
super(CLASS_NAME);
selectedTileVO = new TileVO();
selectedAutoTileVO = new AutoTileVO();
currentEntityCustomVariables = new ObjectMap<>();
}
@Override
public void initPlugin() {
facade.registerMediator(new TiledPanelMediator(this));
facade.registerMediator(new ImportTileSetDialogMediator(pluginAPI, facade));
facade.registerMediator(new AlternativeAutoTileDialogMediator(this));
pluginRM = new ResourcesManager(this);
offsetPanel = new OffsetPanel(this);
facade.registerMediator(new OffsetPanelMediator(this));
initTools();
Skin skin = VisUI.getSkin();
VisImageButton.VisImageButtonStyle tileAddButtonStyle = new VisImageButton.VisImageButtonStyle();
tileAddButtonStyle.up = skin.getDrawable("toolbar-normal");
tileAddButtonStyle.down = skin.getDrawable("toolbar-down");
tileAddButtonStyle.checked = skin.getDrawable("toolbar-down");
tileAddButtonStyle.over = skin.getDrawable("toolbar-over");
tileAddButtonStyle.imageUp = new TextureRegionDrawable(pluginRM.getTextureRegion("tool-tilebrush", -1));
pluginAPI.addTool(DrawTileTool.NAME, tileAddButtonStyle, true, drawTileTool);
VisImageButton.VisImageButtonStyle tileDeleteButtonStyle = new VisImageButton.VisImageButtonStyle();
tileDeleteButtonStyle.up = skin.getDrawable("toolbar-normal");
tileDeleteButtonStyle.down = skin.getDrawable("toolbar-down");
tileDeleteButtonStyle.checked = skin.getDrawable("toolbar-down");
tileDeleteButtonStyle.over = skin.getDrawable("toolbar-over");
tileDeleteButtonStyle.imageUp = new TextureRegionDrawable(pluginRM.getTextureRegion("tool-tileeraser", -1));
pluginAPI.addTool(DeleteTileTool.NAME, tileDeleteButtonStyle, false, deleteTileTool);
pluginAPI.setDropDownItemName(ACTION_SET_GRID_SIZE_FROM_ITEM, "Set tile grid size");
pluginAPI.addMenuItem(MenuAPI.RESOURCE_MENU, "Import Tile Set...", IMPORT_TILESET_PANEL_OPEN);
facade.sendNotification(MsgAPI.ADD_RESOURCES_BOX_FILTER, new TilesResourceFilter(this));
}
@Override
public void onDropDownOpen(Set<Integer> selectedEntities, Array<String> actionsSet) {
if(selectedEntities.size() == 1) {
actionsSet.add(ACTION_SET_GRID_SIZE_FROM_ITEM);
}
}
public void initSaveData() {
saveDataManager = new SaveDataManager(pluginAPI.getProjectPath());
dataToSave = saveDataManager.dataToSave;
}
private void initTools() {
drawTileTool = new DrawTileTool(this);
deleteTileTool = new DeleteTileTool(this);
}
public int getPluginEntityWithParams(int row, int column) {
for (int entity : pluginAPI.getProjectEntities()) {
if(!isTile(entity)) continue;
boolean isEntityVisible = pluginAPI.isEntityVisible(entity);
if (!isEntityVisible || !isOnCurrentSelectedLayer(entity)) continue;
currentEntityMainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class, getAPI().getEngine());
currentEntityCustomVariables = currentEntityMainItemComponent.customVariables;
if (Integer.parseInt(currentEntityCustomVariables.get(ROW)) == row
&& Integer.parseInt(currentEntityCustomVariables.get(COLUMN)) == column) {
return entity;
}
}
return -1;
}
public int getPluginEntityWithCoords(float x, float y) {
for (int entity : pluginAPI.getProjectEntities()) {
if (!isTile(entity)) continue;
boolean isEntityVisible = pluginAPI.isEntityVisible(entity);
if (!isEntityVisible || !isOnCurrentSelectedLayer(entity)) continue;
currentEntityTransformComponent = ComponentRetriever.get(entity, TransformComponent.class, getAPI().getEngine());
Rectangle tmp = new Rectangle(
currentEntityTransformComponent.x,
currentEntityTransformComponent.y,
dataToSave.getParameterVO().gridWidth,
dataToSave.getParameterVO().gridHeight);
if (tmp.contains(x, y)) {
return entity;
}
}
return -1;
}
public float getPixelToWorld() {
return pluginAPI.getSceneLoader().getRm().getProjectVO().pixelToWorld;
}
public boolean isTile(int entity) {
if (entity == -1)
return false;
return ComponentRetriever.get(entity, MainItemComponent.class, getAPI().getEngine()).tags.contains(TILE_TAG);
}
public boolean isOnCurrentSelectedLayer(int entity) {
ZIndexComponent entityZComponent = ComponentRetriever.get(entity, ZIndexComponent.class, getAPI().getEngine());
return entityZComponent.getLayerName().equals(pluginAPI.getCurrentSelectedLayerName());
}
public void setSelectedTileName (String regionName) {
selectedTileVO.regionName = regionName;
}
public String getSelectedTileName() {
if (isAutoGridTabSelected) {
return selectedAutoTileVO.regionName;
}
return selectedTileVO.regionName;
}
/**
* Explicitly returns the selected auto tile name, regardless of whether the auto grid tab is shown or any other.
*
* @return The selected auto tile name.
*/
public String getSelectedAutoTileName() {
return selectedAutoTileVO.regionName;
}
public int getSelectedTileType() {
return selectedTileVO.entityType;
}
public Vector2 getSelectedTileGridOffset() {
return selectedTileVO.gridOffset;
}
public void setSelectedTileGridOffset (Vector2 gridOffset) {
selectedTileVO.gridOffset = gridOffset;
}
public TileVO getSelectedTileVO() {
return selectedTileVO;
}
public void setSelectedTileVO(TileVO selectedTileVO) {
this.selectedTileVO = selectedTileVO;
}
public AutoTileVO getSelectedAutoTileVO() {
return selectedAutoTileVO;
}
public void setSelectedAutoTileVO(AutoTileVO selectedAutoTileVO) {
this.selectedAutoTileVO = selectedAutoTileVO;
}
public void applySelectedTileGridOffset() {
pluginAPI.getProjectEntities().forEach(entity -> {
if (!(isTile(entity))) return;
TextureRegionComponent textureRegionComponent = ComponentRetriever.get(entity, TextureRegionComponent.class, getAPI().getEngine());
TransformComponent transformComponent = ComponentRetriever.get(entity, TransformComponent.class, getAPI().getEngine());
if (selectedTileVO.regionName.equals(textureRegionComponent.regionName)) {
transformComponent.x -= selectedTileVO.gridOffset.x;
transformComponent.y -= selectedTileVO.gridOffset.y;
}
});
saveOffsetChanges();
}
public boolean isAutoGridTilesTabSelected() {
return isAutoGridTabSelected;
}
public void setAutoGridTilesTabSelected(boolean isAutoGridTabSelected) {
this.isAutoGridTabSelected = isAutoGridTabSelected;
}
private void saveOffsetChanges() {
dataToSave.setTileGridOffset(selectedTileVO);
saveDataManager.save();
}
public String getCurrentRawImagesPath() {
return getAPI().getProjectPath() + File.separator + "assets" + File.separator + "orig" + File.separator + "images";
}
}
| 13,559 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TilesResourceFilter.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/TilesResourceFilter.java | package games.rednblack.editor.plugin.tiled;
import games.rednblack.editor.renderer.factory.EntityFactory;
import games.rednblack.h2d.common.filters.IAbstractResourceFilter;
import games.rednblack.h2d.extension.spine.SpineItemType;
public class TilesResourceFilter extends IAbstractResourceFilter {
private final TiledPlugin tiledPlugin;
public TilesResourceFilter(TiledPlugin tiledPlugin) {
super("Filter Tiles", "filter-tiles");
this.tiledPlugin = tiledPlugin;
}
@Override
public boolean filterResource(String resName, int entityType) {
if (entityType == EntityFactory.IMAGE_TYPE
|| entityType == EntityFactory.SPRITE_TYPE
|| entityType == SpineItemType.SPINE_TYPE) {
return tiledPlugin.dataToSave.containsAutoTile(resName) || tiledPlugin.dataToSave.containsTile(resName);
}
return false;
}
}
| 908 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TileVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/TileVO.java | package games.rednblack.editor.plugin.tiled.data;
import com.badlogic.gdx.math.Vector2;
import games.rednblack.editor.renderer.factory.EntityFactory;
/**
* Created by mariam on 5/13/16.
*/
public class TileVO implements TextureRegionVO {
public String regionName = "";
public Vector2 gridOffset;
public int entityType = EntityFactory.IMAGE_TYPE;
public TileVO() {
gridOffset = new Vector2();
}
public TileVO(String regionName) {
this.regionName = regionName;
gridOffset = new Vector2();
}
public TileVO(String regionName, Vector2 offset) {
this.regionName = regionName;
this.gridOffset = offset;
}
@Override
public String getRegionName() {
return regionName;
}
@Override
public int getEntityType() {
return entityType;
}
}
| 764 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AlternativeAutoTileVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/AlternativeAutoTileVO.java | package games.rednblack.editor.plugin.tiled.data;
/**
* This class represents an alternative to an auto-tile. It contains a region to paint when selected and a probabilty to be selected.
*
* @author Jan-Thierry Wegener
*/
public class AlternativeAutoTileVO {
/**
* The region to paint when selected.
*/
public String region = "";
/**
* The probability to be selected by the auto-tile drawing strategy.
*/
public Float percent = Float.valueOf(0.0f);
public AlternativeAutoTileVO() {
}
/**
* Creates a new alternative from the given region and probability.
*
* @param region The region to paint.
* @param percent The probability to be selected.
*/
public AlternativeAutoTileVO(String region, Float percent) {
this.region = region;
this.percent = percent;
}
/**
* Creates a new alternative from the given region and probability.
*
* @param region The region to paint.
* @param percent The probability to be selected.
*/
public AlternativeAutoTileVO(String region, String percent) {
this.region = region;
this.percent = Float.valueOf(percent);
}
}
| 1,107 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
CategoryVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/CategoryVO.java | package games.rednblack.editor.plugin.tiled.data;
import com.badlogic.gdx.utils.Array;
/**
* Created by mariam on 2/5/16.
*/
public class CategoryVO {
public String title = "size";
public Array<AttributeVO> attributes;
public CategoryVO(String title, Array<AttributeVO> attributes) {
this.title = title;
this.attributes = attributes;
}
}
| 376 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AutoTileVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/AutoTileVO.java | package games.rednblack.editor.plugin.tiled.data;
import com.badlogic.gdx.math.Vector2;
import games.rednblack.editor.renderer.factory.EntityFactory;
public class AutoTileVO implements TextureRegionVO {
public String regionName = "";
public Vector2 gridOffset;
public int entityType = EntityFactory.IMAGE_TYPE;
/**
* The list of alternative auto-tiles.
*/
public final DefaultValueList<AlternativeAutoTileVO> alternativeAutoTileList = new DefaultValueList<>();
public AutoTileVO() {
gridOffset = new Vector2();
}
public AutoTileVO(String regionName) {
this.regionName = regionName;
gridOffset = new Vector2();
}
public AutoTileVO(String regionName, Vector2 offset) {
this.regionName = regionName;
this.gridOffset = offset;
}
@Override
public String getRegionName() {
return regionName;
}
@Override
public int getEntityType() {
return entityType;
}
}
| 896 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AttributeVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/AttributeVO.java | package games.rednblack.editor.plugin.tiled.data;
/**
* Created by mariam on 3/31/16.
*/
public class AttributeVO {
public String title;
public float value;
public boolean acceptNegativeValues;
public AttributeVO() {
}
public AttributeVO(String title) {
this.title = title+": ";
}
public AttributeVO(String title, boolean acceptNegativeValues) {
this.title = title+": ";
this.acceptNegativeValues = acceptNegativeValues;
}
public AttributeVO(String title, float value) {
this.value = value;
this.title = title+": ";
}
public AttributeVO(String title, float value, boolean acceptNegativeValues) {
this.title = title+": ";
this.value = value;
this.acceptNegativeValues = acceptNegativeValues;
}
}
| 820 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ParameterVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/ParameterVO.java | package games.rednblack.editor.plugin.tiled.data;
/**
* Created by mariam on 3/31/16.
*/
public class ParameterVO {
public float gridWidth; //in world units
public float gridHeight; //in world units
public ParameterVO() {
}
}
| 247 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
TextureRegionVO.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/TextureRegionVO.java | package games.rednblack.editor.plugin.tiled.data;
public interface TextureRegionVO {
public String getRegionName();
public int getEntityType();
}
| 153 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
DefaultValueList.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/data/DefaultValueList.java | package games.rednblack.editor.plugin.tiled.data;
import java.util.ArrayList;
/**
* A list that provides a default value when the index is out-of-upper-bound.
*
* @author Jan-Thierry Wegener
*
* @param <E> The list element type.
*/
public class DefaultValueList<E> extends ArrayList<E> {
/**
*
*/
private static final long serialVersionUID = 1L;
public DefaultValueList() {
super();
}
/**
* Returns the element at the given index or the default value if the index is greater than or equal to the size.
*
* @param index The index of the element.
* @param defaultValue The default element if the index is out-of-upper-bound.
*
* @return The element at the given index or the default value.
*/
public E get(int index, E defaultValue) {
if (index >= size()) {
return defaultValue;
}
return super.get(index);
}
}
| 862 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
Attribute.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/Attribute.java | package games.rednblack.editor.plugin.tiled.view;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.kotcrab.vis.ui.util.FloatDigitsOnlyFilter;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisTextField;
import games.rednblack.editor.plugin.tiled.data.AttributeVO;
/**
* Created by mariam on 2/5/16.
*/
public class Attribute extends Table {
public Attribute(AttributeVO attributeVO) {
add(new VisLabel(attributeVO.title));
VisTextField visTextField = new VisTextField();
visTextField.setTextFieldFilter(new FloatDigitsOnlyFilter(attributeVO.acceptNegativeValues));
visTextField.setMaxLength(5);
visTextField.setText(attributeVO.value+"");
visTextField.setTextFieldListener((VisTextField textField, char c) -> {
if (!textField.getText().equals("")) {
attributeVO.value = Float.parseFloat(textField.getText());
}
});
add(visTextField)
.width(50)
.padLeft(5);
}
}
| 1,050 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SpineDrawable.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/SpineDrawable.java | package games.rednblack.editor.plugin.tiled.view;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.utils.BaseDrawable;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.FloatArray;
import com.esotericsoftware.spine.*;
import com.esotericsoftware.spine.attachments.Attachment;
import com.esotericsoftware.spine.attachments.MeshAttachment;
import com.esotericsoftware.spine.attachments.RegionAttachment;
public class SpineDrawable extends BaseDrawable {
private float minX = 0;
private float minY = 0;
private Skeleton skeleton;
private AnimationState animationState;
private SkeletonRenderer skeletonRenderer;
public float width, height;
private FloatArray temp;
public SpineDrawable(Skeleton skeleton, SkeletonRenderer skeletonRenderer) {
temp = new FloatArray();
this.skeletonRenderer = skeletonRenderer;
this.skeleton = skeleton;
AnimationStateData animationStateData = new AnimationStateData(skeleton.getData());
animationState = new AnimationState(animationStateData);
if (skeleton.getData().getDefaultSkin() == null) {
skeleton.setSkin(skeleton.getData().getSkins().get(0));
skeleton.setSlotsToSetupPose();
}
computeBoundBox();
float scaleFactor;
if (this.width > this.height) {
//scale by width
scaleFactor = 1.0f / (this.width / 40);
} else {
scaleFactor = 1.0f / (this.height / 40);
}
skeleton.setScale(scaleFactor, scaleFactor);
}
public Skeleton getSkeleton() {
return skeleton;
}
public AnimationState getAnimationState() {
return animationState;
}
private void computeBoundBox() {
skeleton.updateWorldTransform(Skeleton.Physics.update);
Array<Slot> drawOrder = skeleton.getDrawOrder();
minX = Float.MAX_VALUE;
minY = Float.MAX_VALUE;
float maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE;
for (int i = 0, n = drawOrder.size; i < n; i++) {
Slot slot = drawOrder.get(i);
if (!slot.getBone().isActive()) continue;
int verticesLength = 0;
float[] vertices = null;
Attachment attachment = slot.getAttachment();
if (attachment instanceof RegionAttachment) {
RegionAttachment region = (RegionAttachment)attachment;
verticesLength = 8;
vertices = temp.setSize(8);
region.computeWorldVertices(slot, vertices, 0, 2);
} else if (attachment instanceof MeshAttachment) {
MeshAttachment mesh = (MeshAttachment)attachment;
verticesLength = mesh.getWorldVerticesLength();
vertices = temp.setSize(verticesLength);
mesh.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2);
}
if (vertices != null) {
for (int ii = 0; ii < verticesLength; ii += 2) {
float x = vertices[ii], y = vertices[ii + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
}
width = (maxX - minX);
height = (maxY - minY);
}
@Override
public void draw(Batch batch, float x, float y, float width, float height) {
skeleton.updateWorldTransform(Skeleton.Physics.update);
animationState.update(Gdx.graphics.getDeltaTime());
animationState.apply(skeleton);
skeleton.setPosition(x, y - 20);
skeleton.update(Gdx.graphics.getDeltaTime());
Color color = skeleton.getColor();
float oldAlpha = color.a;
skeleton.getColor().a *= batch.getColor().a;
skeletonRenderer.draw(batch, skeleton);
color.a = oldAlpha;
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
}
}
| 4,176 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
Category.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/Category.java | package games.rednblack.editor.plugin.tiled.view;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisLabel;
import games.rednblack.editor.plugin.tiled.data.AttributeVO;
import games.rednblack.editor.plugin.tiled.data.CategoryVO;
/**
* Created by mariam on 2/5/16.
*/
public class Category extends Table {
private CategoryVO categoryVO;
private Array<AttributeVO> attributes;
private Table attrTable;
public Category(CategoryVO categoryVO) {
this.categoryVO = categoryVO;
attributes = categoryVO.attributes;
// setDebug(true);
VisLabel title = new VisLabel(categoryVO.title);
add(title)
.padTop(2)
.left()
.top();
attrTable = new Table();
add(attrTable)
.padLeft(5);
attributes.forEach(attributeVO -> addAttribute(attributeVO));
}
public void reInitView(Array<AttributeVO> attributes) {
attrTable.clear();
this.attributes = attributes;
attributes.forEach(attributeVO -> addAttribute(attributeVO));
attrTable.pack();
}
private void addAttribute(AttributeVO attributeVO) {
Attribute attr = new Attribute(attributeVO);
attrTable.add(attr)
.top()
.right()
.padBottom(5)
.row();
}
public AttributeVO getAttributeVO(String title) {
for (AttributeVO attributeVO : attributes) {
if (attributeVO.title.equals(title)) {
return attributeVO;
}
}
return new AttributeVO();
}
}
| 1,695 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ImportTileSetDialogMediator.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/dialog/ImportTileSetDialogMediator.java | package games.rednblack.editor.plugin.tiled.view.dialog;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.renderer.data.TexturePackVO;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.plugins.PluginAPI;
import games.rednblack.puremvc.Facade;
import games.rednblack.puremvc.Mediator;
import games.rednblack.puremvc.interfaces.INotification;
import games.rednblack.puremvc.util.Interests;
import java.io.File;
public class ImportTileSetDialogMediator extends Mediator<ImportTileSetDialog> {
private static final String TAG = ImportTileSetDialogMediator.class.getCanonicalName();
public static final String NAME = TAG;
private final PluginAPI pluginAPI;
public ImportTileSetDialogMediator(PluginAPI pluginAPI, Facade facade) {
super(NAME, new ImportTileSetDialog(facade));
this.pluginAPI = pluginAPI;
}
@Override
public void listNotificationInterests(Interests interests) {
interests.add(TiledPlugin.IMPORT_TILESET_PANEL_OPEN,
ImportTileSetDialog.IMPORT_TILESET);
}
@Override
public void handleNotification(INotification notification) {
switch (notification.getName()) {
case TiledPlugin.IMPORT_TILESET_PANEL_OPEN:
viewComponent.show(pluginAPI.getUIStage());
break;
case ImportTileSetDialog.IMPORT_TILESET:
FileHandle tileset = notification.getBody();
importTileset(tileset);
break;
}
}
private void importTileset(FileHandle tileset) {
byte[] image = tileset.readBytes();
Pixmap pixmap = new Pixmap(image, 0, image.length);
String name = tileset.nameWithoutExtension();
int tileW = viewComponent.getTileWidth();
int tileH = viewComponent.getTileHeight();
TexturePackVO texturePackVO = pluginAPI.getCurrentProjectInfoVO().imagesPacks.get(name + "-tile-set");
if (texturePackVO == null) {
texturePackVO = new TexturePackVO();
texturePackVO.name = name + "-tile-set";
pluginAPI.getCurrentProjectInfoVO().imagesPacks.put(texturePackVO.name, texturePackVO);
}
int i = 0;
for (int x = 0; x < pixmap.getWidth(); x += tileW) {
for (int y = 0; y < pixmap.getHeight(); y += tileH) {
int w = x + tileW <= pixmap.getWidth() ? tileW : pixmap.getWidth() - x;
int h = y + tileH <= pixmap.getHeight() ? tileH : pixmap.getHeight() - y;
Pixmap tilePixmap = new Pixmap(w, h, Pixmap.Format.RGBA8888);
tilePixmap.drawPixmap(pixmap, 0, 0, x, y, w, h);
String imagesPath = getCurrentRawImagesPath() + File.separator + name + i + ".png";
FileHandle path = new FileHandle(imagesPath);
PixmapIO.writePNG(path, tilePixmap);
tilePixmap.dispose();
texturePackVO.regions.add(name + i);
i++;
}
}
pixmap.dispose();
viewComponent.close();
facade.sendNotification(MsgAPI.UPDATE_ATLAS_PACK_LIST);
facade.sendNotification(MsgAPI.ACTION_REPACK);
}
public String getCurrentRawImagesPath() {
return pluginAPI.getProjectPath() + File.separator + "assets" + File.separator + "orig" + File.separator + "images";
}
}
| 3,547 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AlternativeAutoTileDialogMediator.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/dialog/AlternativeAutoTileDialogMediator.java | package games.rednblack.editor.plugin.tiled.view.dialog;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.AlternativeAutoTileVO;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.puremvc.Mediator;
import games.rednblack.puremvc.interfaces.INotification;
import games.rednblack.puremvc.util.Interests;
/**
* The mediator for messages for the alternatives.
*
* @author Jan-Thierry Wegener
*/
public class AlternativeAutoTileDialogMediator extends Mediator<AlternativeAutoTileDialog> {
public static final String NAME = AlternativeAutoTileDialogMediator.class.getName();
private TiledPlugin tiledPlugin;
public AlternativeAutoTileDialogMediator(TiledPlugin tiledPlugin) {
super(NAME, new AlternativeAutoTileDialog(tiledPlugin));
this.tiledPlugin = tiledPlugin;
}
@Override
public void listNotificationInterests(Interests interests) {
interests.add(TiledPlugin.ACTION_SETUP_ALTERNATIVES_AUTO_TILE,
TiledPlugin.ACTION_SAVE_ALTERNATIVES_AUTO_TILE,
TiledPlugin.ACTION_RECALC_PERCENT_ALTERNATIVES_AUTO_TILE);
}
@Override
public void handleNotification(INotification notification) {
switch (notification.getName()) {
case TiledPlugin.ACTION_SETUP_ALTERNATIVES_AUTO_TILE:
AutoTileVO autoTileVO = tiledPlugin.dataToSave.getAutoTile(notification.getBody());
viewComponent.setOpeningAutoTileVO(autoTileVO);
viewComponent.initView();
viewComponent.show(tiledPlugin.getAPI().getUIStage());
break;
case TiledPlugin.ACTION_SAVE_ALTERNATIVES_AUTO_TILE:
viewComponent.openingAutoTileVO.alternativeAutoTileList.clear();
AlternativeAutoTileVO alternativeAutoTileVO = new AlternativeAutoTileVO(viewComponent.openingAutoTileVO.regionName, viewComponent.alternativePercentTextFieldArray[0].getText());
viewComponent.openingAutoTileVO.alternativeAutoTileList.add(alternativeAutoTileVO);
for (int i = 0; i < viewComponent.alternativeSelectBoxArray.length; i++) {
String region = viewComponent.alternativeSelectBoxArray[i].getSelected();
Float percent = Float.valueOf(viewComponent.alternativePercentTextFieldArray[i + 1].getText());
viewComponent.openingAutoTileVO.alternativeAutoTileList.add(new AlternativeAutoTileVO(region, percent));
}
tiledPlugin.facade.sendNotification(TiledPlugin.ACTION_RECALC_PERCENT_ALTERNATIVES_AUTO_TILE, viewComponent.openingAutoTileVO.regionName);
break;
case TiledPlugin.ACTION_RECALC_PERCENT_ALTERNATIVES_AUTO_TILE:
String deletedAutoTileRegion = notification.getBody();
if (deletedAutoTileRegion == null) {
for (AutoTileVO at : tiledPlugin.dataToSave.getAutoTiles()) {
recalculatePercent(at);
}
} else {
recalculatePercent(tiledPlugin.dataToSave.getAutoTile(deletedAutoTileRegion));
}
tiledPlugin.saveDataManager.save();
break;
}
}
/**
* Recalculates the probabilities of the alternatives of all or the given auto-tile.
*
* @param at The auto-tile to recalculate, or if <code>null</code> then all auto-tiles.
*/
private void recalculatePercent(AutoTileVO at) {
if (at.alternativeAutoTileList.size() == 0) return;
float total = 0;
for (AlternativeAutoTileVO aat : at.alternativeAutoTileList) {
if (!"".equals(aat.region)) {
total += Math.abs(aat.percent);
}
}
if (total < 0.00001f) {
// kind of 0
at.alternativeAutoTileList.get(0).percent = 1f;
} else {
for (AlternativeAutoTileVO aat : at.alternativeAutoTileList) {
if ("".equals(aat.region)) {
aat.percent = 0f;
} else {
aat.percent = Math.abs(aat.percent) / total;
}
}
}
}
}
| 3,924 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ImportTileSetDialog.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/dialog/ImportTileSetDialog.java | package games.rednblack.editor.plugin.tiled.view.dialog;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.kotcrab.vis.ui.util.Validators;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisTable;
import com.kotcrab.vis.ui.widget.VisTextButton;
import com.kotcrab.vis.ui.widget.VisValidatableTextField;
import com.kotcrab.vis.ui.widget.file.FileChooser;
import games.rednblack.h2d.common.H2DDialog;
import games.rednblack.h2d.common.view.ui.StandardWidgetsFactory;
import games.rednblack.h2d.common.view.ui.widget.InputFileWidget;
import games.rednblack.puremvc.Facade;
public class ImportTileSetDialog extends H2DDialog {
private static final String prefix = "games.rednblack.editor.plugin.tiled.view.dialog.ImportTileSetDialog";
public static final String IMPORT_TILESET = prefix + ".IMPORT_TILESET";
private final VisValidatableTextField width, height;
private final InputFileWidget imagePathField;
private final VisTextButton importButton;
private final Facade facade;
public ImportTileSetDialog(Facade facade) {
super("Import TileSet");
this.facade = facade;
setModal(true);
addCloseButton();
VisTable fileTable = new VisTable();
fileTable.pad(6);
//
fileTable.add(new VisLabel("Tile Set:")).right().padRight(5);
imagePathField = new InputFileWidget(FileChooser.Mode.OPEN, FileChooser.SelectionMode.FILES, false);
imagePathField.setTextFieldWidth(156);
fileTable.add(imagePathField);
getContentTable().add(fileTable);
//
getContentTable().row().padTop(10);
//
Validators.IntegerValidator validator = new Validators.IntegerValidator();
width = StandardWidgetsFactory.createValidableTextField(validator);
height = StandardWidgetsFactory.createValidableTextField(validator);
VisTable sizeTable = new VisTable();
sizeTable.add("Tile Width:").padRight(3);
sizeTable.add(width).width(60);
sizeTable.add("px");
sizeTable.row().padTop(5);
sizeTable.add("Tile Height:").padRight(3);
sizeTable.add(height).width(60);
sizeTable.add("px");
getContentTable().add(sizeTable);
importButton = StandardWidgetsFactory.createTextButton("Import");
getButtonsTable().add(importButton);
pack();
setListeners();
}
public int getTileWidth() {
return Integer.parseInt(width.getText());
}
public int getTileHeight() {
return Integer.parseInt(height.getText());
}
private void setListeners() {
importButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (width.isInputValid() && height.isInputValid() && imagePathField.getValue() != null) {
facade.sendNotification(IMPORT_TILESET, imagePathField.getValue());
}
}
});
}
}
| 3,094 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AlternativeAutoTileDialog.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/dialog/AlternativeAutoTileDialog.java | package games.rednblack.editor.plugin.tiled.view.dialog;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import com.kotcrab.vis.ui.util.Validators.FloatValidator;
import com.kotcrab.vis.ui.widget.VisImageButton;
import com.kotcrab.vis.ui.widget.VisSelectBox;
import com.kotcrab.vis.ui.widget.VisTable;
import com.kotcrab.vis.ui.widget.VisTextButton;
import com.kotcrab.vis.ui.widget.VisValidatableTextField;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.AlternativeAutoTileVO;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.renderer.factory.EntityFactory;
import games.rednblack.h2d.common.UIDraggablePanel;
import games.rednblack.h2d.common.view.ui.StandardWidgetsFactory;
/**
* The dialog that handles the alternatives.
*
* @author Jan-Thierry Wegener
*/
public class AlternativeAutoTileDialog extends UIDraggablePanel {
public AutoTileVO openingAutoTileVO;
private TiledPlugin tiledPlugin;
public VisSelectBox<String>[] alternativeSelectBoxArray;
public VisValidatableTextField[] alternativePercentTextFieldArray;
public AlternativeAutoTileDialog(TiledPlugin tiledPlugin) {
super("Setup alternatives");
this.tiledPlugin = tiledPlugin;
}
/**
* Initiates the view of the dialog.
*/
public void initView() {
clear();
String[] allAutoTileVOArray = new String[tiledPlugin.dataToSave.getAutoTiles().size];
int index = 0;
// add a "none" to the drop down list
allAutoTileVOArray[index++] = "";
for (int i = 0; i < tiledPlugin.dataToSave.getAutoTiles().size; i++) {
AutoTileVO next = tiledPlugin.dataToSave.getAutoTiles().get(i);
if (!openingAutoTileVO.equals(next)) {
allAutoTileVOArray[index++] = next.regionName;
}
}
alternativeSelectBoxArray = new VisSelectBox[allAutoTileVOArray.length - 1];
alternativePercentTextFieldArray = new VisValidatableTextField[allAutoTileVOArray.length + 0];
VisTable table = new VisTable();
table.row().padTop(20);
table.add(getVisImageButton(openingAutoTileVO.regionName)).maxHeight(32);
table.add(StandardWidgetsFactory.createLabel(openingAutoTileVO.regionName, Align.left)).padLeft(5).left();//.width(115);
alternativePercentTextFieldArray[0] = StandardWidgetsFactory.createValidableTextField(new FloatValidator());
alternativePercentTextFieldArray[0].setText(openingAutoTileVO.alternativeAutoTileList.get(0, new AlternativeAutoTileVO()).percent.toString());
table.add(alternativePercentTextFieldArray[0]).padLeft(5).padRight(5).fillX().left();
table.row();
for (int i = 0; i < allAutoTileVOArray.length - 1; i++) {
String region = openingAutoTileVO.alternativeAutoTileList.get(i + 1, new AlternativeAutoTileVO()).region;
VisImageButton imgButton = getVisImageButton(region);
table.add(imgButton).maxHeight(32);
alternativeSelectBoxArray[i] = StandardWidgetsFactory.createSelectBox(String.class);
alternativeSelectBoxArray[i].setItems(allAutoTileVOArray);
alternativeSelectBoxArray[i].setSelected(openingAutoTileVO.alternativeAutoTileList.get(i + 1, new AlternativeAutoTileVO()).region);
alternativeSelectBoxArray[i].addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
updateVisImageButton(imgButton, ((SelectBox<String>) actor).getSelected());
pack();
}
});
table.add(alternativeSelectBoxArray[i]).padLeft(5).left();
alternativePercentTextFieldArray[i + 1] = StandardWidgetsFactory.createValidableTextField(new FloatValidator());
alternativePercentTextFieldArray[i + 1].setText(openingAutoTileVO.alternativeAutoTileList.get(i + 1, new AlternativeAutoTileVO()).percent.toString());
table.add(alternativePercentTextFieldArray[i + 1]).padLeft(5).padRight(5).fillX().left();
table.row().padTop(5).padBottom(5);
}
VisTextButton saveButton = StandardWidgetsFactory.createTextButton("Save");
saveButton.addListener(new ClickListener() {
@Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
super.touchUp(event, x, y, pointer, button);
tiledPlugin.facade.sendNotification(TiledPlugin.ACTION_SAVE_ALTERNATIVES_AUTO_TILE);
hide();
}
});
VisTextButton cancelButton = StandardWidgetsFactory.createTextButton("Cancel");
cancelButton.addListener(new ClickListener() {
@Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
super.touchUp(event, x, y, pointer, button);
hide();
}
});
row();
add(table);
row();
add(saveButton).center().padLeft(5).padRight(5);
add(cancelButton).center().padLeft(5).padRight(5);
row();
pack();
}
/**
* Returns a button with the given region as image.
*
* @param regionName The name of the image.
*
* @return An image button.
*/
private VisImageButton getVisImageButton(String regionName) {
VisImageButton.VisImageButtonStyle imageBoxStyle = new VisImageButton.VisImageButtonStyle();
Drawable tileDrawable = null;
if (!"".equals(regionName)) {
tileDrawable = new TextureRegionDrawable(tiledPlugin.pluginRM.getTextureRegion(regionName, EntityFactory.IMAGE_TYPE));
}
imageBoxStyle.imageUp = tileDrawable;
imageBoxStyle.imageDown = tileDrawable;
imageBoxStyle.imageChecked = tileDrawable;
imageBoxStyle.imageOver = tileDrawable;
VisImageButton ct = new VisImageButton(imageBoxStyle);
return ct;
}
/**
* Updates the given button with the given image.
*
* @param button The button to update.
* @param regionName The name of the new image.
*/
private void updateVisImageButton(VisImageButton button, String regionName) {
VisImageButton.VisImageButtonStyle imageBoxStyle = button.getStyle();
Drawable tileDrawable = null;
if (!"".equals(regionName)) {
tileDrawable = new TextureRegionDrawable(tiledPlugin.pluginRM.getTextureRegion(regionName, EntityFactory.IMAGE_TYPE));
}
imageBoxStyle.imageUp = tileDrawable;
imageBoxStyle.imageDown = tileDrawable;
imageBoxStyle.imageChecked = tileDrawable;
imageBoxStyle.imageOver = tileDrawable;
button.setStyle(imageBoxStyle);
}
/**
* Returns the currently set auto-tile.
*
* @return The currently set auto-tile.
*/
public AutoTileVO getOpeningAutoTileVO() {
return openingAutoTileVO;
}
/**
* Sets the current auto-tile.
*
* @param openingAutoTileVO The new auto-tile.
*/
public void setOpeningAutoTileVO(AutoTileVO openingAutoTileVO) {
this.openingAutoTileVO = openingAutoTileVO;
}
}
| 7,044 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SettingsTab.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/tabs/SettingsTab.java | package games.rednblack.editor.plugin.tiled.view.tabs;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisTextButton;
import games.rednblack.editor.plugin.tiled.TiledPanel;
import games.rednblack.editor.plugin.tiled.data.AttributeVO;
import games.rednblack.editor.plugin.tiled.data.CategoryVO;
import games.rednblack.editor.plugin.tiled.data.ParameterVO;
import games.rednblack.editor.plugin.tiled.view.Category;
/**
* Created by mariam on 2/4/16.
*/
public class SettingsTab extends DefaultTab {
private static final String CLASS_NAME = "com.overlap2d.plugins.tiled.view.tabs.SettingsTab";
public static final String OK_BTN_CLICKED = CLASS_NAME+".OK_BTN_CLICKED";
private ParameterVO currentParameters;
private Category grid;
public SettingsTab(TiledPanel panel, String tabTitle, int tabIndex) {
super(panel, tabTitle, tabIndex);
currentParameters = panel.tiledPlugin.dataToSave.getParameterVO();
}
@Override
public void initView() {
Array<AttributeVO> gridAttributes = new Array<>();
gridAttributes.add(new AttributeVO("Width", currentParameters.gridWidth));
gridAttributes.add(new AttributeVO("Height", currentParameters.gridHeight));
CategoryVO gridVO = new CategoryVO("Grid size: ", gridAttributes);
grid = new Category(gridVO);
content.add(grid)
.expandX()
.colspan(2)
.padTop(10)
.left()
.top()
.row();
panel.tiledPlugin.dataToSave.setParameterVO(currentParameters);
VisTextButton okBtn = new VisTextButton("Save");
content.add(okBtn)
.width(70)
.pad(20)
.colspan(2)
.expandX()
.center()
.bottom()
.row();
okBtn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
currentParameters.gridWidth = grid.getAttributeVO("Width: ").value;
currentParameters.gridHeight = grid.getAttributeVO("Height: ").value;
panel.getFacade().sendNotification(OK_BTN_CLICKED, currentParameters);
}
});
}
public void resetGridCategory() {
Array<AttributeVO> gridAttributes = new Array<>();
gridAttributes.add(new AttributeVO("Width", currentParameters.gridWidth));
gridAttributes.add(new AttributeVO("Height", currentParameters.gridHeight));
grid.reInitView(gridAttributes);
}
}
| 2,774 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AutoGridTilesTab.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/tabs/AutoGridTilesTab.java | package games.rednblack.editor.plugin.tiled.view.tabs;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisTable;
import games.rednblack.editor.plugin.tiled.TiledPanel;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.plugin.tiled.view.tabs.listener.GridTabInputListener;
public class AutoGridTilesTab extends AbstractGridTilesTab<AutoTileVO> {
public AutoGridTilesTab(TiledPanel panel, String tabTitle, int tabIndex) {
super(panel, tabTitle, tabIndex);
}
@Override
protected GridTabInputListener<AutoTileVO> getGridTabInputListener(int index) {
return new GridTabInputListener<AutoTileVO>(this, index, tiledPlugin, (VisTable) pane.getActor(), getTileSelectedNotification(), getTiledOpenDropDownNotification(), savedTiles, tiles);
}
@Override
protected Array<AutoTileVO> initSavedTiles() {
return tiledPlugin.dataToSave.getAutoTiles();
}
@Override
protected String getTileSelectedNotification() {
return TiledPlugin.AUTO_TILE_SELECTED;
}
@Override
protected String getTiledOpenDropDownNotification() {
return TiledPlugin.AUTO_OPEN_DROP_DOWN;
}
@Override
public void selectTile(AutoTileVO tileVO) {
tiledPlugin.setSelectedAutoTileVO(tileVO);
}
@Override
protected void setGridSizeToFirstTileSize(String tileName, int type) {
super.setGridSizeToFirstTileSize(tileName + TiledPlugin.AUTO_TILE_MINI_SUFFIX, type);
}
@Override
protected AutoTileVO getTextureRegionVO(String tileName) {
return new AutoTileVO(tileName);
}
}
| 1,633 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
DefaultTab.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/tabs/DefaultTab.java | package games.rednblack.editor.plugin.tiled.view.tabs;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.kotcrab.vis.ui.widget.VisLabel;
import games.rednblack.editor.plugin.tiled.TiledPanel;
import games.rednblack.h2d.common.view.ui.widget.imagetabbedpane.ImageTab;
/**
* Created by mariam on 10/30/15.
*/
public class DefaultTab extends ImageTab {
protected TiledPanel panel;
protected int tabIndex;
protected Table content = new Table();
protected String tabTitle = "";
public DefaultTab(TiledPanel panel, String tabTitle, int tabIndex) {
super(false, false); //tab is not savable, tab is not closeable by user
this.panel = panel;
this.tabTitle = tabTitle;
this.tabIndex = tabIndex;
}
public void initView() {
content.add(new VisLabel(tabTitle+" example"));
}
@Override
public String getTabTitle () {
return tabTitle;
}
@Override
public String getTabIconStyle() {
return null;
}
@Override
public Table getContentTable () {
return content;
}
public int getTabIndex() {
return tabIndex;
}
}
| 1,161 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AbstractGridTilesTab.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/tabs/AbstractGridTilesTab.java | package games.rednblack.editor.plugin.tiled.view.tabs;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisImageButton;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisScrollPane;
import com.kotcrab.vis.ui.widget.VisTable;
import games.rednblack.editor.plugin.tiled.TiledPanel;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.TextureRegionVO;
import games.rednblack.editor.plugin.tiled.manager.ResourcesManager;
import games.rednblack.editor.plugin.tiled.view.SpineDrawable;
import games.rednblack.editor.plugin.tiled.view.tabs.listener.GridTabInputListener;
import games.rednblack.editor.renderer.factory.EntityFactory;
import games.rednblack.h2d.common.view.ui.StandardWidgetsFactory;
import games.rednblack.h2d.extension.spine.SpineItemType;
public abstract class AbstractGridTilesTab<T extends TextureRegionVO> extends DefaultTab {
public boolean isDrop;
private int tilesCount = 19;
protected Array<VisImageButton> tiles;
protected Array<T> savedTiles;
private int tileIndex;
protected VisScrollPane pane;
private boolean isBottomEdge;
protected TiledPlugin tiledPlugin;
private ResourcesManager resourcesManager;
public AbstractGridTilesTab(TiledPanel panel, String title, int tabIndex) {
super(panel, title, tabIndex);
tiledPlugin = panel.tiledPlugin;
resourcesManager = tiledPlugin.pluginRM;
tiles = new Array<>();
savedTiles = initSavedTiles();
tileIndex = savedTiles.size;
}
protected abstract Array<T> initSavedTiles();
@Override
public void initView() {
if (isDrop = savedTiles.size == 0) {
VisImageButton.VisImageButtonStyle dropBoxStyle = new VisImageButton.VisImageButtonStyle();
dropBoxStyle.up = new TextureRegionDrawable(resourcesManager.getTextureRegion("tiles-drop-here-normal", -1));
dropBoxStyle.imageOver = new TextureRegionDrawable(resourcesManager.getTextureRegion("tiles-drop-here-over", -1));
VisImageButton dropRegion = new VisImageButton(dropBoxStyle);
content.clear();
content.add(dropRegion)
.center()
.padRight(6)
.padBottom(6)
.padTop(10)
.row();
content.add(new VisLabel("Drop an image from resources box"))
.expandX()
.center()
.padBottom(5);
content.pack();
} else {
if (tileIndex > tilesCount) {
tilesCount = tileIndex;
}
initTiles();
}
}
public void addTile(String tileName, int type) {
if (pane != null) isBottomEdge = pane.isBottomEdge();
if (tileIndex == 0) {
setGridSizeToFirstTileSize(tileName, type);
isDrop = false;
panel.reInitTabTable(this);
}
initTiles(tileName, type);
panel.pack();
scrollTiles();
tiles.get(tileIndex).setChecked(true);
tiledPlugin.facade.sendNotification(TiledPlugin.TILE_SELECTED, getTextureRegionVO(tileName));
tileIndex++;
}
public void removeTile() {
if (pane != null) isBottomEdge = pane.isBottomEdge();
tileIndex = --tileIndex < 0 ? 0 : tileIndex;
tilesCount = --tilesCount < 19 ? 19 : tilesCount;
tiles.clear();
initView();
}
public void removeAllTiles() {
if (pane != null) isBottomEdge = pane.isBottomEdge();
tileIndex = 0;
tilesCount = 19;
tiles.clear();
initView();
}
public void scrollTiles() {
if(savedTiles.size + 1 >= tilesCount) {
pane.layout();
pane.setSmoothScrolling(!isBottomEdge);
pane.setScrollY(100);
}
}
protected void setGridSizeToFirstTileSize(String tileName, int type) {
float width = 0;
float height = 0;
if (type == SpineItemType.SPINE_TYPE) {
SpineDrawable spineDrawable = tiledPlugin.pluginRM.getSpineDrawable(tileName);
width = spineDrawable.width;
height = spineDrawable.height;
} else {
TextureRegion r = tiledPlugin.pluginRM.getTextureRegion(tileName, type);
width = r.getRegionWidth();
height = r.getRegionHeight();
}
float gridWidth = width / tiledPlugin.getPixelToWorld();
float gridHeight = height / tiledPlugin.getPixelToWorld();
tiledPlugin.dataToSave.setGrid(gridWidth, gridHeight);
tiledPlugin.facade.sendNotification(TiledPlugin.GRID_CHANGED);
}
private void initTiles(String tileName, int type) {
content.clear();
tiles.clear();
VisTable listTable = new VisTable();
pane = StandardWidgetsFactory.createScrollPane(listTable);
pane.setScrollingDisabled(true, false);
content.add(pane)
.padTop(10);
listTable.top();
if(tileIndex >= tilesCount && !tileName.equals("")) {
tilesCount = tileIndex + 1;
}
for (int i = 0; i < tilesCount + 1; i++) {
VisImageButton ct;
VisImageButton.VisImageButtonStyle imageBoxStyle = new VisImageButton.VisImageButtonStyle();
NinePatchDrawable inactive = new NinePatchDrawable(new NinePatch(resourcesManager.getPluginNinePatch("image-Box-inactive")));
NinePatchDrawable active = new NinePatchDrawable(new NinePatch(resourcesManager.getPluginNinePatch("image-Box-active")));
imageBoxStyle.up = inactive;
imageBoxStyle.down = active;
imageBoxStyle.checked = active;
imageBoxStyle.over = active;
Drawable tileDrawable = null;
if (i < savedTiles.size) {
int t = savedTiles.get(i).getEntityType();
if (t == SpineItemType.SPINE_TYPE) {
tileDrawable = resourcesManager.getSpineDrawable(savedTiles.get(i).getRegionName());
} else {
tileDrawable = new TextureRegionDrawable(resourcesManager.getTextureRegion(savedTiles.get(i).getRegionName(), t));
}
} else if (!tileName.equals("")) {
if (i == tileIndex) {
if (type == SpineItemType.SPINE_TYPE) {
tileDrawable = resourcesManager.getSpineDrawable(tileName);
} else {
tileDrawable = new TextureRegionDrawable(resourcesManager.getTextureRegion(tileName, type));
}
}
}
imageBoxStyle.imageUp = tileDrawable;
imageBoxStyle.imageDown = tileDrawable;
imageBoxStyle.imageChecked = tileDrawable;
imageBoxStyle.imageOver = tileDrawable;
ct = new VisImageButton(imageBoxStyle);
if (i < savedTiles.size) {
ct.setUserObject(savedTiles.get(i).getRegionName());
}
int index = i;
ct.addListener(getGridTabInputListener(index));
listTable.add(ct)
.width(40)
.height(40)
.pad(3);
if((i+1) % 4 == 0) {
listTable.row();
}
tiles.add(ct);
}
content.pack();
}
public void initTiles() {
initTiles("", -1);
}
/**
* Returns the newly initialized input listener for the given tile index.
*
* @param index The index of the tile.
*
* @return The new input listener.
*/
protected abstract GridTabInputListener<T> getGridTabInputListener(int index);
/**
* Returns the notification string to send when selecting a tile.
*
* @return The notification when selecting a tile.
*/
protected abstract String getTileSelectedNotification();
/**
* Returns the notification string to send when opening a drop down.
*
* @return The notification when opening a drop down.
*/
protected abstract String getTiledOpenDropDownNotification();
/**
* Selects the given tile.
*
* @param tileVO The tile to select
*/
public abstract void selectTile(T tileVO);
/**
* Returns the corresponding {@link TextureRegionVO} for the given tile name.
*
* @param tileName The tilename for the texture region.
*
* @return The texture region.
*/
protected abstract T getTextureRegionVO(String tileName);
}
| 8,950 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
GridTilesTab.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/tabs/GridTilesTab.java | package games.rednblack.editor.plugin.tiled.view.tabs;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisTable;
import games.rednblack.editor.plugin.tiled.TiledPanel;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.TileVO;
import games.rednblack.editor.plugin.tiled.view.tabs.listener.GridTabInputListener;
/**
* Created by mariam on 2/11/16.
*/
public class GridTilesTab extends AbstractGridTilesTab<TileVO> {
public GridTilesTab(TiledPanel panel, int tabIndex) {
super(panel, "Tiles", tabIndex);
}
@Override
protected Array<TileVO> initSavedTiles() {
return tiledPlugin.dataToSave.getTiles();
}
@Override
protected GridTabInputListener<TileVO> getGridTabInputListener(int index) {
return new GridTabInputListener<TileVO>(this, index, tiledPlugin, (VisTable) pane.getActor(), getTileSelectedNotification(), getTiledOpenDropDownNotification(), savedTiles, tiles);
}
@Override
protected String getTileSelectedNotification() {
return TiledPlugin.TILE_SELECTED;
}
@Override
protected String getTiledOpenDropDownNotification() {
return TiledPlugin.OPEN_DROP_DOWN;
}
@Override
public void selectTile(TileVO tileVO) {
tiledPlugin.setSelectedTileVO(tileVO);
}
@Override
protected TileVO getTextureRegionVO(String tileName) {
return new TileVO(tileName);
}
}
| 1,437 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
GridTabInputListener.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/view/tabs/listener/GridTabInputListener.java | package games.rednblack.editor.plugin.tiled.view.tabs.listener;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisImageButton;
import com.kotcrab.vis.ui.widget.VisTable;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.TextureRegionVO;
import games.rednblack.editor.plugin.tiled.view.tabs.AbstractGridTilesTab;
public class GridTabInputListener<T extends TextureRegionVO> extends InputListener {
private final int index;
private AbstractGridTilesTab<T> tab;
private String tileSelectedNotification;
private String openDropDownNotification;
private TiledPlugin tiledPlugin;
private VisTable table;
private Array<VisImageButton> tiles;
private boolean isDragging = false;
private Actor draggingSource;
private Array<T> savedTiles;
public GridTabInputListener(AbstractGridTilesTab<T> tab, int index, TiledPlugin tiledPlugin, VisTable table, String tileSelectedNotification, String openDropDownNotification, Array<T> savedTiles, Array<VisImageButton> tiles) {
this.tab = tab;
this.index = index;
this.tiledPlugin = tiledPlugin;
this.tileSelectedNotification = tileSelectedNotification;
this.openDropDownNotification = openDropDownNotification;
this.table = table;
this.savedTiles = savedTiles;
this.tiles = tiles;
}
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if (button == Input.Buttons.LEFT) {
draggingSource = event.getListenerActor();
}
if (index >= savedTiles.size) return true;
for (VisImageButton tile : tiles) {
if (tile.isChecked()) {
tile.setChecked(false);
}
}
return true;
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
super.touchUp(event, x, y, pointer, button);
if (isDragging && button == Input.Buttons.LEFT && draggingSource != null) {
// finished dragging
isDragging = false;
handleDrop(x, y);
} else {
if(button == Input.Buttons.RIGHT && index < savedTiles.size) {
tiledPlugin.facade.sendNotification(openDropDownNotification, savedTiles.get(index).getRegionName());
return;
}
if (index >= savedTiles.size) {
tiles.get(index).setChecked(false);
return;
}
tiledPlugin.facade.sendNotification(tileSelectedNotification, savedTiles.get(index));
}
}
@Override
public void touchDragged (InputEvent event, float x, float y, int pointer) {
isDragging = true;
if (draggingSource != null) {
// draggingSource can be null when dragging with the right mouse button
draggingSource.setColor(new Color(0 / 255f, 0 / 255f, 0f / 255f, 0.5f));
}
}
/**
* Handles the drop of a VisImageButton.
*
* @param x The coordinates relative to the source. Comes from the touchUp event.
* @param y The coordinates relative to the source. Comes from the touchUp event.
*/
private void handleDrop(float x, float y) {
Actor draggingTarget = table.hit(draggingSource.getX() + x, draggingSource.getY() + y, false);
if (draggingTarget instanceof Image) {
for (VisImageButton imgButton : tiles) {
if (imgButton.getImage() == draggingTarget) {
draggingTarget = imgButton;
break;
}
}
}
if (draggingTarget != null) {
String sourceRegionName = String.valueOf(draggingSource.getUserObject());
String targetRegionName = String.valueOf(draggingTarget.getUserObject());
int sourceIndex = -1;
int targetIndex = -1;
for (int i = 0; i < savedTiles.size; i++) {
if (sourceRegionName.equals(savedTiles.get(i).getRegionName())) {
sourceIndex = i;
}
if (targetRegionName.equals(savedTiles.get(i).getRegionName())) {
targetIndex = i;
}
}
// if targetIndex < 0 we dropped at the end
// we already know that we hit another VisImageButton but could not find the name
// thus, an empty button, which are always after the ones with an image
if (targetIndex < 0) {
targetIndex = savedTiles.size - 1;
}
if (sourceIndex >= 0) {
T sourceTileVO = savedTiles.removeIndex(sourceIndex);
savedTiles.insert(targetIndex, sourceTileVO);
tab.initTiles();
// select the dropped button
tiledPlugin.facade.sendNotification(TiledPlugin.TILE_SELECTED, sourceTileVO);
tiles.get(targetIndex).setChecked(true);
}
}
}
}
| 4,595 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SaveDataManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/save/SaveDataManager.java | package games.rednblack.editor.plugin.tiled.save;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import games.rednblack.editor.renderer.utils.HyperJson;
/**
* Created by mariam on 3/24/16.
*/
public class SaveDataManager {
public DataToSave dataToSave;
private Json json;
private FileHandle fileHandle;
public SaveDataManager(String projectPath) {
json = HyperJson.getJson();
fileHandle = Gdx.files.absolute(projectPath + "/tiled_plugin.dt");
load();
}
private void load() {
if (!fileHandle.exists()) {
dataToSave = new DataToSave();
return;
}
String jsonString = fileHandle.readString();
dataToSave = json.fromJson(DataToSave.class, jsonString);
}
public void save() {
String dataString = json.toJson(dataToSave);
fileHandle.writeString(dataString, false);
}
}
| 965 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
DataToSave.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/save/DataToSave.java | package games.rednblack.editor.plugin.tiled.save;
import java.util.stream.StreamSupport;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.plugin.tiled.data.ParameterVO;
import games.rednblack.editor.plugin.tiled.data.TileVO;
/**
* Created by mariam on 3/23/16.
*/
public class DataToSave {
private Array<TileVO> tiles;
private Array<AutoTileVO> autoTiles;
private ParameterVO parameterVO;
public DataToSave() {
tiles = new Array<>();
autoTiles = new Array<>();
parameterVO = new ParameterVO();
}
public void addTile(String tileDrawableName, int type) {
TileVO newTile = new TileVO(tileDrawableName);
newTile.entityType = type;
if (!tiles.contains(newTile, false)) {
tiles.add(newTile);
}
}
public void removeTile(String tileDrawableName) {
tiles.forEach(tile -> {
if (tile.regionName.equals(tileDrawableName)) {
tiles.removeValue(tile, false);
}
});
}
/**
* Removes all tiles.
*/
public void removeAllTiles() {
tiles.clear();
}
public void setTileGridOffset(TileVO tileVO) {
StreamSupport.stream(tiles.spliterator(), false)
.filter(tile -> tile.regionName.equals(tileVO.regionName))
.findFirst()
.ifPresent(t -> t.gridOffset = tileVO.gridOffset);
}
public Vector2 getTileGridOffset(String regionName) {
return StreamSupport.stream(tiles.spliterator(), false)
.filter(tile -> tile.regionName.equals(regionName))
.findFirst()
.get()
.gridOffset;
}
public TileVO getTile(String regionName) {
return StreamSupport.stream(tiles.spliterator(), false)
.filter(tile -> tile.regionName.equals(regionName))
.findFirst()
.get();
}
public Array<TileVO> getTiles() {
return tiles;
}
public boolean containsTile(String regionName) {
return StreamSupport.stream(tiles.spliterator(), false).anyMatch(tile -> tile.regionName.equals(regionName));
}
public void addAutoTile(String autoTileDrawableName, int type) {
AutoTileVO newTile = new AutoTileVO(autoTileDrawableName);
newTile.entityType = type;
if (!autoTiles.contains(newTile, false)) {
autoTiles.add(newTile);
}
}
public AutoTileVO getAutoTile(String regionName) {
return StreamSupport.stream(autoTiles.spliterator(), false)
.filter(tile -> tile.regionName.equals(regionName))
.findFirst()
.get();
}
public void removeAutoTile(String tileDrawableName) {
autoTiles.forEach(tile -> {
if (tile.regionName.equals(tileDrawableName)) {
autoTiles.removeValue(tile, false);
}
});
}
public Array<AutoTileVO> getAutoTiles() {
return autoTiles;
}
public boolean containsAutoTile(String regionName) {
return StreamSupport.stream(autoTiles.spliterator(), false).anyMatch(tile -> regionName.startsWith(tile.regionName));
}
public ParameterVO getParameterVO() {
return parameterVO;
}
public void setParameterVO(ParameterVO parameterVO) {
this.parameterVO = parameterVO;
}
public void setGrid(float gridWidth, float gridHeight) {
parameterVO.gridWidth = gridWidth;
parameterVO.gridHeight = gridHeight;
}
}
| 3,658 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
DrawTileTool.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/DrawTileTool.java | package games.rednblack.editor.plugin.tiled.tools;
import games.rednblack.h2d.extension.spine.SpineItemType;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.kotcrab.vis.ui.util.OsUtils;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.tools.drawStrategy.AutoTileDrawStrategy;
import games.rednblack.editor.plugin.tiled.tools.drawStrategy.IDrawStrategy;
import games.rednblack.editor.plugin.tiled.tools.drawStrategy.ImageDrawStrategy;
import games.rednblack.editor.plugin.tiled.tools.drawStrategy.SpineDrawStrategy;
import games.rednblack.editor.plugin.tiled.tools.drawStrategy.SpriteDrawStrategy;
import games.rednblack.editor.renderer.components.TransformComponent;
import games.rednblack.editor.renderer.factory.EntityFactory;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.command.TransformCommandBuilder;
import games.rednblack.h2d.common.view.tools.Tool;
import games.rednblack.h2d.common.vo.CursorData;
import games.rednblack.puremvc.interfaces.INotification;
/**
* Created by mariam on 3/29/16.
*/
public class DrawTileTool implements Tool {
private static final CursorData CURSOR = new CursorData("tile-cursor", 14, 14);
public static final String NAME = "TILE_ADD_TOOL";
private TiledPlugin tiledPlugin;
private float gridWidth;
private float gridHeight;
private final ImageDrawStrategy imageDrawStrategy;
private final SpriteDrawStrategy spriteDrawStrategy;
private final SpineDrawStrategy spineDrawStrategy;
private final AutoTileDrawStrategy autoTileDrawStrategy;
private IDrawStrategy currentDrawStrategy;
public DrawTileTool(TiledPlugin tiledPlugin) {
this.tiledPlugin = tiledPlugin;
imageDrawStrategy = new ImageDrawStrategy(tiledPlugin);
spriteDrawStrategy = new SpriteDrawStrategy(tiledPlugin);
spineDrawStrategy = new SpineDrawStrategy(tiledPlugin);
autoTileDrawStrategy = new AutoTileDrawStrategy(tiledPlugin);
}
@Override
public void initTool() {
Texture cursorTexture = tiledPlugin.pluginRM.getTexture(CURSOR.region);
tiledPlugin.getAPI().setCursor(CURSOR, new TextureRegion(cursorTexture));
}
@Override
public String getShortcut() {
return OsUtils.getShortcutFor(Input.Keys.CONTROL_LEFT, Input.Keys.B);
}
@Override
public String getTitle() {
return "Draw Tile Tool";
}
@Override
public boolean stageMouseDown(float x, float y) {
initGridThings();
drawTile(x, y);
return true;
}
@Override
public void stageMouseUp(float x, float y) {
tiledPlugin.facade.sendNotification(TiledPlugin.AUTO_FILL_TILES);
}
@Override
public void stageMouseDragged(float x, float y) {
drawTile(x, y);
}
@Override
public void stageMouseDoubleClick(float x, float y) {
}
@Override
public boolean stageMouseScrolled(float amountX, float amountY) {
return false;
}
@Override
public boolean itemMouseDown(int entity, float x, float y) {
initGridThings();
if (entity == -1)
drawTile(x, y);
else
drawOnEntity(entity);
return true;
}
@Override
public void itemMouseUp(int entity, float x, float y) {
tiledPlugin.facade.sendNotification(TiledPlugin.AUTO_FILL_TILES);
}
@Override
public void itemMouseDragged(int entity, float x, float y) {
drawTile(x, y);
}
@Override
public void itemMouseDoubleClick(int entity, float x, float y) {
if (!tiledPlugin.isOnCurrentSelectedLayer(entity)) return;
if (entity != -1 && tiledPlugin.isTile(entity)) {
//rotate
TransformCommandBuilder commandBuilder = new TransformCommandBuilder();
commandBuilder.begin(entity, tiledPlugin.getAPI().getEngine());
TransformComponent transformComponent = ComponentRetriever.get(entity, TransformComponent.class, tiledPlugin.getAPI().getEngine());
if (transformComponent.scaleX > 0 && transformComponent.scaleY > 0) {
commandBuilder.setScale(transformComponent.scaleX * -1f, transformComponent.scaleY);
} else if (transformComponent.scaleX < 0 && transformComponent.scaleY > 0) {
commandBuilder.setScale(transformComponent.scaleX, transformComponent.scaleY * -1f);
} else if (transformComponent.scaleX < 0 && transformComponent.scaleY < 0) {
commandBuilder.setScale(transformComponent.scaleX * -1f, transformComponent.scaleY);
} else if (transformComponent.scaleX > 0 && transformComponent.scaleY < 0) {
commandBuilder.setScale(transformComponent.scaleX, transformComponent.scaleY * -1f);
}
commandBuilder.execute(tiledPlugin.facade);
}
}
@Override
public String getName() {
return NAME;
}
@Override
public void handleNotification(INotification notification) {
}
@Override
public void keyDown(int entity, int keycode) {
if(keycode == Input.Keys.SHIFT_LEFT || keycode == Input.Keys.SHIFT_RIGHT) {
tiledPlugin.getAPI().toolHotSwap(tiledPlugin.deleteTileTool);
tiledPlugin.deleteTileTool.setHotSwapped();
}
}
@Override
public void keyUp(int entity, int keycode) {
}
private void initGridThings() {
gridWidth = tiledPlugin.dataToSave.getParameterVO().gridWidth;
gridHeight = tiledPlugin.dataToSave.getParameterVO().gridHeight;
}
private void chooseDrawStrategy() {
if (tiledPlugin.isAutoGridTilesTabSelected()) {
currentDrawStrategy = autoTileDrawStrategy;
} else {
switch (tiledPlugin.getSelectedTileType()) {
case EntityFactory.IMAGE_TYPE:
currentDrawStrategy = imageDrawStrategy;
break;
case EntityFactory.SPRITE_TYPE:
currentDrawStrategy = spriteDrawStrategy;
break;
case SpineItemType.SPINE_TYPE:
currentDrawStrategy = spineDrawStrategy;
break;
default:
currentDrawStrategy = null;
}
}
}
private void drawTile(float x, float y) {
if (tiledPlugin.getSelectedTileName().equals("")) return;
float newX = MathUtils.floor(x / gridWidth) * gridWidth + tiledPlugin.getSelectedTileGridOffset().x;
float newY = MathUtils.floor(y / gridHeight) * gridHeight + tiledPlugin.getSelectedTileGridOffset().y;
int row = MathUtils.floor(newY / gridHeight);
int column = MathUtils.round(newX / gridWidth);
chooseDrawStrategy();
currentDrawStrategy.drawTile(newX, newY, row, column);
}
private void drawOnEntity(int entity) {
chooseDrawStrategy();
currentDrawStrategy.updateTile(entity);
}
}
| 7,108 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
DeleteTileTool.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/DeleteTileTool.java | package games.rednblack.editor.plugin.tiled.tools;
import java.util.HashSet;
import java.util.Set;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.h2d.common.view.tools.Tool;
import games.rednblack.h2d.common.vo.CursorData;
import games.rednblack.puremvc.interfaces.INotification;
/**
* Created by mariam on 4/5/16.
*/
public class DeleteTileTool implements Tool {
private static final CursorData CURSOR = new CursorData("tile-eraser-cursor", 14, 14);
public static final String NAME = "TILE_DELETE_TOOL";
private TiledPlugin tiledPlugin;
private boolean isHotswapped = false;
public DeleteTileTool(TiledPlugin tiledPlugin) {
this.tiledPlugin = tiledPlugin;
}
@Override
public void initTool() {
Texture cursorTexture = tiledPlugin.pluginRM.getTexture(CURSOR.region);
tiledPlugin.getAPI().setCursor(CURSOR, new TextureRegion(cursorTexture));
}
@Override
public String getShortcut() {
return null;
}
@Override
public String getTitle() {
return "Delete Tile Tool";
}
@Override
public boolean stageMouseDown(float x, float y) {
return true;
}
@Override
public void stageMouseUp(float x, float y) {
tiledPlugin.facade.sendNotification(TiledPlugin.AUTO_FILL_TILES);
}
@Override
public void stageMouseDragged(float x, float y) {
deleteEntityWithCoordinate(x, y);
}
@Override
public void stageMouseDoubleClick(float x, float y) {
}
@Override
public boolean stageMouseScrolled(float amountX, float amountY) {
return false;
}
@Override
public boolean itemMouseDown(int entity, float x, float y) {
deleteEntityWithCoordinate(x, y);
tiledPlugin.facade.sendNotification(TiledPlugin.AUTO_FILL_TILES);
return true;
}
@Override
public void itemMouseUp(int entity, float x, float y) {
tiledPlugin.facade.sendNotification(TiledPlugin.AUTO_FILL_TILES);
}
@Override
public void itemMouseDragged(int entity, float x, float y) {
deleteEntityWithCoordinate(x, y);
}
@Override
public void itemMouseDoubleClick(int entity, float x, float y) {
}
@Override
public String getName() {
return NAME;
}
@Override
public void handleNotification(INotification notification) {
}
@Override
public void keyDown(int entity, int keycode) {
}
@Override
public void keyUp(int entity, int keycode) {
if(isHotswapped) {
if(keycode == Input.Keys.SHIFT_LEFT || keycode == Input.Keys.SHIFT_RIGHT) {
isHotswapped = false;
tiledPlugin.getAPI().toolHotSwapBack();
}
}
}
Set<Integer> items = new HashSet<>();
private void deleteEntity(int entity) {
if (tiledPlugin.isTile(entity) && tiledPlugin.isOnCurrentSelectedLayer(entity)) {
items.clear();
items.add(entity);
tiledPlugin.facade.sendNotification(MsgAPI.ACTION_SET_SELECTION, items);
tiledPlugin.facade.sendNotification(MsgAPI.ACTION_DELETE);
}
}
private void deleteEntityWithCoordinate (float x, float y) {
int entity = tiledPlugin.getPluginEntityWithCoords(x, y);
if (entity != -1) {
deleteEntity(entity);
}
}
public void setHotSwapped() {
isHotswapped = true;
}
}
| 3,639 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
BasicDrawStrategy.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/drawStrategy/BasicDrawStrategy.java | package games.rednblack.editor.plugin.tiled.tools.drawStrategy;
import com.badlogic.gdx.math.Vector2;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.renderer.components.MainItemComponent;
import games.rednblack.editor.renderer.components.TransformComponent;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
public abstract class BasicDrawStrategy implements IDrawStrategy {
protected TiledPlugin tiledPlugin;
protected final Vector2 temp = new Vector2();
public BasicDrawStrategy(TiledPlugin plugin) {
tiledPlugin = plugin;
}
protected void postProcessEntity(int entity, float x, float y, int row, int column) {
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class, tiledPlugin.getAPI().getEngine());
mainItemComponent.tags.add(TiledPlugin.TILE_TAG);
mainItemComponent.setCustomVars(TiledPlugin.ROW, Integer.toString(row));
mainItemComponent.setCustomVars(TiledPlugin.COLUMN, Integer.toString(column));
TransformComponent transformComponent = ComponentRetriever.get(entity, TransformComponent.class, tiledPlugin.getAPI().getEngine());
transformComponent.x = x;
transformComponent.y = y;
}
protected boolean checkValidTile(int entity) {
return tiledPlugin.isOnCurrentSelectedLayer(entity) && tiledPlugin.isTile(entity)
&& ComponentRetriever.get(entity, MainItemComponent.class, tiledPlugin.getAPI().getEngine()).entityType == tiledPlugin.getSelectedTileType();
}
}
| 1,586 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
IDrawStrategy.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/drawStrategy/IDrawStrategy.java | package games.rednblack.editor.plugin.tiled.tools.drawStrategy;
public interface IDrawStrategy {
void drawTile(float x, float y, int row, int column);
void updateTile(int entity);
}
| 191 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SpineDrawStrategy.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/drawStrategy/SpineDrawStrategy.java | package games.rednblack.editor.plugin.tiled.tools.drawStrategy;
import com.esotericsoftware.spine.Skeleton;
import com.esotericsoftware.spine.SkeletonData;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.command.ReplaceSpineCommandBuilder;
import games.rednblack.h2d.common.factory.IFactory;
import games.rednblack.h2d.extension.spine.SpineComponent;
import games.rednblack.h2d.extension.spine.SpineDataObject;
import games.rednblack.h2d.extension.spine.SpineItemType;
public class SpineDrawStrategy extends BasicDrawStrategy {
private final ReplaceSpineCommandBuilder replaceSpineCommandBuilder = new ReplaceSpineCommandBuilder();
public SpineDrawStrategy(TiledPlugin plugin) {
super(plugin);
}
@Override
public void drawTile(float x, float y, int row, int column) {
int underneathTile = tiledPlugin.getPluginEntityWithParams(row, column);
if (underneathTile != -1) {
updateTile(underneathTile);
return;
}
IFactory itemFactory = tiledPlugin.getAPI().getItemFactory();
temp.set(x, y);
if (itemFactory.createSpineAnimation(tiledPlugin.getSelectedTileName(), temp)) {
int imageEntity = itemFactory.getCreatedEntity();
postProcessEntity(imageEntity, x, y, row, column);
}
}
@Override
public void updateTile(int entity) {
if (!checkValidTile(entity)) return;
SpineComponent spineComponent = ComponentRetriever.get(entity, SpineComponent.class, tiledPlugin.getAPI().getEngine());
if (!spineComponent.animationName.equals(tiledPlugin.getSelectedTileName())) {
replaceSpineCommandBuilder.begin(entity);
String animName = tiledPlugin.getSelectedTileName();
replaceSpineCommandBuilder.setAnimationName(animName);
SpineDataObject spineDataObject = (SpineDataObject) tiledPlugin.getAPI().getSceneLoader().getRm().getExternalItemType(SpineItemType.SPINE_TYPE, animName);
replaceSpineCommandBuilder.setSkeletonJson(spineDataObject.skeletonJson);
SkeletonData skeletonData = spineDataObject.skeletonData;
replaceSpineCommandBuilder.setSkeleton(new Skeleton(skeletonData));
replaceSpineCommandBuilder.execute(tiledPlugin.facade);
}
}
}
| 2,414 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AutoTileDrawStrategy.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/drawStrategy/AutoTileDrawStrategy.java | package games.rednblack.editor.plugin.tiled.tools.drawStrategy;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.AutoTileVO;
import games.rednblack.editor.renderer.components.MainItemComponent;
import games.rednblack.editor.renderer.components.TextureRegionComponent;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.command.ReplaceRegionCommandBuilder;
import games.rednblack.h2d.common.factory.IFactory;
public class AutoTileDrawStrategy extends BasicDrawStrategy {
private final ReplaceRegionCommandBuilder replaceRegionCommandBuilder = new ReplaceRegionCommandBuilder();
private String tileToDraw;
public AutoTileDrawStrategy(TiledPlugin plugin) {
super(plugin);
}
@Override
public void drawTile(float x, float y, int row, int column) {
int underneathTile = tiledPlugin.getPluginEntityWithParams(row, column);
if (underneathTile != -1) {
updateTile(underneathTile);
return;
}
IFactory itemFactory = tiledPlugin.getAPI().getItemFactory();
temp.set(x, y);
tileToDraw = selectTileToDraw();
if (itemFactory.createSimpleImage(tileToDraw + TiledPlugin.AUTO_TILE_DRAW_SUFFIX, temp)) {
int imageEntity = itemFactory.getCreatedEntity();
postProcessEntity(imageEntity, x, y, row, column);
}
}
private String selectTileToDraw() {
String retval;
AutoTileVO selectedAutoTileVO = tiledPlugin.getSelectedAutoTileVO();
if (selectedAutoTileVO.alternativeAutoTileList.isEmpty()) {
retval = selectedAutoTileVO.regionName;
} else {
retval = null;
double d = 0d;
double rnd = Math.random();
int i = 0;
while (i < selectedAutoTileVO.alternativeAutoTileList.size() && retval == null) {
d += selectedAutoTileVO.alternativeAutoTileList.get(i).percent;
if (rnd < d) {
retval = selectedAutoTileVO.alternativeAutoTileList.get(i).region;
}
i++;
}
if (retval == null) {
retval = selectedAutoTileVO.alternativeAutoTileList.get(i - 1).region;
}
}
return retval;
}
@Override
public void updateTile(int entity) {
if (!checkValidTile(entity)) return;
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class, tiledPlugin.getAPI().getEngine());
if (tiledPlugin.getSelectedAutoTileName().equals(mainItemComponent.customVariables.get(TiledPlugin.ORIG_AUTO_TILE))) {
// we only allow an update when the auto-tiles is different
// firstly, it does not make any sense to randomly reselect another alternative tile
// secondly, when dragging it constantly reselects between the alternative, making rare tiles even rarer
return;
}
TextureRegionComponent textureRegionComponent = ComponentRetriever.get(entity, TextureRegionComponent.class, tiledPlugin.getAPI().getEngine());
if (textureRegionComponent != null && textureRegionComponent.regionName != null) {
// there is already other tile under this one
String selectedAutoTileName = selectTileToDraw();
String region = selectedAutoTileName + TiledPlugin.AUTO_TILE_DRAW_SUFFIX;
if (!textureRegionComponent.regionName.equals(region)) {
replaceRegionCommandBuilder.begin(entity);
replaceRegionCommandBuilder.setRegion(tiledPlugin.getAPI().getSceneLoader().getRm().getTextureRegion(region));
replaceRegionCommandBuilder.setRegionName(region);
replaceRegionCommandBuilder.execute(tiledPlugin.facade);
mainItemComponent.tags.add(TiledPlugin.AUTO_TILE_TAG);
mainItemComponent.setCustomVars(TiledPlugin.REGION, selectedAutoTileName);
mainItemComponent.setCustomVars(TiledPlugin.ORIG_AUTO_TILE, tiledPlugin.getSelectedAutoTileName());
}
}
}
@Override
protected void postProcessEntity(int entity, float x, float y, int row, int column) {
super.postProcessEntity(entity, x, y, row, column);
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class, tiledPlugin.getAPI().getEngine());
mainItemComponent.tags.add(TiledPlugin.AUTO_TILE_TAG);
mainItemComponent.setCustomVars(TiledPlugin.REGION, tileToDraw);
mainItemComponent.setCustomVars(TiledPlugin.ORIG_AUTO_TILE, tiledPlugin.getSelectedAutoTileName());
}
}
| 4,521 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ImageDrawStrategy.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/drawStrategy/ImageDrawStrategy.java | package games.rednblack.editor.plugin.tiled.tools.drawStrategy;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.renderer.components.MainItemComponent;
import games.rednblack.editor.renderer.components.TextureRegionComponent;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.command.ReplaceRegionCommandBuilder;
import games.rednblack.h2d.common.factory.IFactory;
public class ImageDrawStrategy extends BasicDrawStrategy {
private final ReplaceRegionCommandBuilder replaceRegionCommandBuilder = new ReplaceRegionCommandBuilder();
public ImageDrawStrategy(TiledPlugin plugin) {
super(plugin);
}
@Override
public void drawTile(float x, float y, int row, int column) {
int underneathTile = tiledPlugin.getPluginEntityWithParams(row, column);
if (underneathTile != -1) {
updateTile(underneathTile);
return;
}
IFactory itemFactory = tiledPlugin.getAPI().getItemFactory();
temp.set(x, y);
if (itemFactory.createSimpleImage(tiledPlugin.getSelectedTileName(), temp)) {
int imageEntity = itemFactory.getCreatedEntity();
postProcessEntity(imageEntity, x, y, row, column);
}
}
@Override
public void updateTile(int entity) {
if (!checkValidTile(entity)) return;
TextureRegionComponent textureRegionComponent = ComponentRetriever.get(entity, TextureRegionComponent.class, tiledPlugin.getAPI().getEngine());
if (textureRegionComponent != null && textureRegionComponent.regionName != null) {
// there is already other tile under this one
if (!textureRegionComponent.regionName.equals(tiledPlugin.getSelectedTileName())) {
String region = tiledPlugin.getSelectedTileName();
replaceRegionCommandBuilder.begin(entity);
replaceRegionCommandBuilder.setRegion(tiledPlugin.getAPI().getSceneLoader().getRm().getTextureRegion(region));
replaceRegionCommandBuilder.setRegionName(region);
replaceRegionCommandBuilder.execute(tiledPlugin.facade);
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class, tiledPlugin.getAPI().getEngine());
mainItemComponent.tags.remove(TiledPlugin.AUTO_TILE_TAG);
mainItemComponent.removeCustomVars(TiledPlugin.REGION);
}
}
}
}
| 2,511 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
SpriteDrawStrategy.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/tools/drawStrategy/SpriteDrawStrategy.java | package games.rednblack.editor.plugin.tiled.tools.drawStrategy;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.utils.Array;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.renderer.components.sprite.SpriteAnimationComponent;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.command.ReplaceSpriteAnimationCommandBuilder;
import games.rednblack.h2d.common.factory.IFactory;
public class SpriteDrawStrategy extends BasicDrawStrategy {
ReplaceSpriteAnimationCommandBuilder replaceSpriteAnimationCommandBuilder = new ReplaceSpriteAnimationCommandBuilder();
public SpriteDrawStrategy(TiledPlugin plugin) {
super(plugin);
}
@Override
public void drawTile(float x, float y, int row, int column) {
int underneathTile = tiledPlugin.getPluginEntityWithParams(row, column);
if (underneathTile != -1) {
updateTile(underneathTile);
return;
}
IFactory itemFactory = tiledPlugin.getAPI().getItemFactory();
temp.set(x, y);
if (itemFactory.createSpriteAnimation(tiledPlugin.getSelectedTileName(), temp)) {
int imageEntity = itemFactory.getCreatedEntity();
postProcessEntity(imageEntity, x, y, row, column);
}
}
@Override
public void updateTile(int entity) {
if (!checkValidTile(entity)) return;
SpriteAnimationComponent spriteAnimationComponent = ComponentRetriever.get(entity, SpriteAnimationComponent.class, tiledPlugin.getAPI().getEngine());
if (!spriteAnimationComponent.animationName.equals(tiledPlugin.getSelectedTileName())) {
Array<TextureAtlas.AtlasRegion> regions = getRegions(tiledPlugin.getSelectedTileName());
replaceSpriteAnimationCommandBuilder.begin(entity);
replaceSpriteAnimationCommandBuilder.setAnimationName(tiledPlugin.getSelectedTileName());
replaceSpriteAnimationCommandBuilder.setRegion(regions);
replaceSpriteAnimationCommandBuilder.execute(tiledPlugin.facade);
}
}
private Array<TextureAtlas.AtlasRegion> getRegions(String filter) {
// filtering regions by name
Array<TextureAtlas.AtlasRegion> allRegions = tiledPlugin.getAPI().getSceneLoader().getRm().getSpriteAnimation(filter);
Array<TextureAtlas.AtlasRegion> regions = new Array<>();
for(TextureAtlas.AtlasRegion region: allRegions) {
if(region.name.contains(filter)) {
regions.add(region);
}
}
return regions;
}
}
| 2,643 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
AutoGridTileManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/manager/AutoGridTileManager.java | package games.rednblack.editor.plugin.tiled.manager;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.renderer.components.MainItemComponent;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import games.rednblack.h2d.common.command.ReplaceRegionCommandBuilder;
public class AutoGridTileManager {
private static final int UL = 1;
private static final int U = 2;
private static final int UR = 4;
private static final int R = 8;
private static final int DR = 16;
private static final int D = 32;
private static final int DL = 64;
private static final int L = 128;
private final ReplaceRegionCommandBuilder replaceRegionCommandBuilder = new ReplaceRegionCommandBuilder();
private TiledPlugin tiledPlugin;
public AutoGridTileManager(TiledPlugin tiledPlugin) {
this.tiledPlugin = tiledPlugin;
}
public void autoFill() {
for (int entity : tiledPlugin.getAPI().getProjectEntities()) {
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class, tiledPlugin.getAPI().getEngine());
if (!mainItemComponent.tags.contains(TiledPlugin.AUTO_TILE_TAG)) {
continue;
}
int col = Integer.parseInt(mainItemComponent.customVariables.get(TiledPlugin.COLUMN));
int row = Integer.parseInt(mainItemComponent.customVariables.get(TiledPlugin.ROW));
int c = 0;
int val = 0;
int ul = tiledPlugin.getPluginEntityWithParams(row + 1, col - 1);
if (ul != -1) {
c++;
val += UL;
}
int u = tiledPlugin.getPluginEntityWithParams(row + 1, col);
if (u != -1) {
c++;
val += U;
}
int ur = tiledPlugin.getPluginEntityWithParams(row + 1, col + 1);
if (ur != -1) {
c++;
val += UR;
}
int r = tiledPlugin.getPluginEntityWithParams(row, col + 1);
if (r != -1) {
c++;
val += R;
}
int dr = tiledPlugin.getPluginEntityWithParams(row - 1, col + 1);
if (dr != -1) {
c++;
val += DR;
}
int d = tiledPlugin.getPluginEntityWithParams(row - 1, col);
if (d != -1) {
c++;
val += D;
}
int dl = tiledPlugin.getPluginEntityWithParams(row - 1, col - 1);
if (dl != -1) {
c++;
val += DL;
}
int l = tiledPlugin.getPluginEntityWithParams(row, col - 1);
if (l != -1) {
c++;
val += L;
}
int index = getIndex(c, val);
String region = mainItemComponent.customVariables.get(TiledPlugin.REGION) + index;
replaceRegionCommandBuilder.begin(entity);
replaceRegionCommandBuilder.setRegion(tiledPlugin.getAPI().getSceneLoader().getRm().getTextureRegion(region));
replaceRegionCommandBuilder.setRegionName(region);
replaceRegionCommandBuilder.execute(tiledPlugin.facade);
}
}
/**
* Test whether the tiles in the given direction ({@link #UL} to {@link #L}) are all occupied.
*
* @param tiles The tiles ({@link #UL} to {@link #L}).
* @param val The value for the surroundings.
*
* @return true, if the tiles are all occupied by another tile, false otherwise.
*/
private boolean isOccupied(int val, int ... tiles) {
for (int t : tiles) {
if ((t & val) == 0) {
return false;
}
}
return true;
}
/**
* Test whether the tiles in the given direction ({@link #UL} to {@link #L}) are all empty.
*
* @param tiles The tiles ({@link #UL} to {@link #L}).
* @param val The value for the surroundings.
*
* @return true, if the tiles are all empty, false otherwise.
*/
private boolean isEmpty(int val, int ... tiles) {
for (int t : tiles) {
if ((t & val) > 0) {
return false;
}
}
return true;
}
// 24
private int getIndex(int c, int val) {
switch (c) {
case 8:
return 6;
case 7:
if (isEmpty(val, DR)) {
return 26;
} else if (isEmpty(val, UR)) {
return 27;
} else if (isEmpty(val, DL)) {
return 31;
} else if (isEmpty(val, UL)) {
return 32;
}
case 6:
if (isOccupied(val, L, DL, D, R, U, UL) && isEmpty(val, DR, UR)) {
return 29;
} else if (isOccupied(val, L, U, UR, R, DR, D) && isEmpty(val, UL, DL)) {
return 34;
} else if (isOccupied(val, L, UL, U, UR, R, D) && isEmpty(val, DR, DL)) {
return 41;
} else if (isOccupied(val, L, U, R, DR, D, DL) && isEmpty(val, UR, UL)) {
return 42;
} else if (isOccupied(val, L, UL, U, R, DR, D) && isEmpty(val, DL, UR)) {
return 45;
} else if (isOccupied(val, D, DL, L, U, UR, R) && isEmpty(val, UL, DR)) {
return 46;
}
case 5:
if (isOccupied(val, U, UR, R, DR, D) && isEmpty(val, L)) {
return 1;
} else if (isOccupied(val, R, DR, D, DL, L) && isEmpty(val, U)) {
return 5;
} else if (isOccupied(val, L, UL, U, UR, R) && isEmpty(val, D)) {
return 7;
} else if (isOccupied(val, U, D, DL, L, UL) && isEmpty(val, R)) {
return 11;
} else if (isOccupied(val, L, U, R, DR, D) && isEmpty(val, DL, UL, UR)) {
return 47;
} else if (isOccupied(val, L, U, UR, R, D) && isEmpty(val, UL, DR, DL)) {
return 48;
} else if (isOccupied(val, L, U, R, D, DL) && isEmpty(val, UL, UR, DR)) {
return 52;
} else if (isOccupied(val, L, UL, U, R, D) && isEmpty(val, DL, UR, DR)) {
return 53;
}
case 4:
if (isOccupied(val, U, UR, R, D) && isEmpty(val, DR, L)) {
return 21;
} else if (isOccupied(val, U, R, DR, D) && isEmpty(val, UR, L)) {
return 22;
} else if (isOccupied(val, L, DL, D, R) && isEmpty(val, DR, U)) {
return 25;
} else if (isOccupied(val, L, UL, U, R) && isEmpty(val, UR, D)) {
return 28;
} else if (isOccupied(val, L, D, DR, R) && isEmpty(val, U, DL)) {
return 30;
} else if (isOccupied(val, L, U, UR, R) && isEmpty(val, UL, D)) {
return 33;
} else if (isOccupied(val, L, UL, U, D) && isEmpty(val, R, DL)) {
return 36;
} else if (isOccupied(val, U, D, DL, L) && isEmpty(val, UL, R)) {
return 37;
} else if (isOccupied(val, L, U, R, D) && isEmpty(val, DR, DL, UR, UL)) {
return 44;
}
case 3:
if (isOccupied(val, R, DR, D) && isEmpty(val, L, U)) {
return 0;
} else if (isOccupied(val, U, UR, R) && isEmpty(val, L, D)) {
return 2;
} else if (isOccupied(val, L, DL, D) && isEmpty(val, U, R)) {
return 10;
} else if (isOccupied(val, L, UL, U) && isEmpty(val, R, D)) {
return 12;
} else if (isOccupied(val, U, R, D) && isEmpty(val, L, UR, DR)) {
return 24;
} else if (isOccupied(val, U, D, L) && isEmpty(val, UL, R, DL)) {
return 39;
} else if (isOccupied(val, L, D, R) && isEmpty(val, DL, DR, U)) {
return 40;
} else if (isOccupied(val, L, U, R) && isEmpty(val, UL, UR, D)) {
return 43;
}
case 2:
if (isOccupied(val, L, R) && isEmpty(val, U, D)) {
return 8;
} else if (isOccupied(val, U, D) && isEmpty(val, L, R)) {
return 16;
} else if (isOccupied(val, R, D) && isEmpty(val, DR, U, L)) {
return 20;
} else if (isOccupied(val, U, R) && isEmpty(val, UR, D, L)) {
return 23;
} else if (isOccupied(val, L, U) && isEmpty(val, UL, R, D)) {
return 38;
} else if (isOccupied(val, L, D) && isEmpty(val, DL, U, R)) {
return 35;
}
case 1:
if (isOccupied(val, R) && isEmpty(val, U, D, L)) {
return 3;
} else if (isOccupied(val, L) && isEmpty(val, U, R, D)) {
return 13;
} else if (isOccupied(val, D) && isEmpty(val, L, U, R)) {
return 15;
} else if (isOccupied(val, U) && isEmpty(val, L, D, R)) {
return 17;
}
case 0:
return 18;
}
// default
return 54;
}
}
| 8,246 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ResourcesManager.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/manager/ResourcesManager.java | package games.rednblack.editor.plugin.tiled.manager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.ObjectMap;
import com.esotericsoftware.spine.Skeleton;
import com.esotericsoftware.spine.SkeletonData;
import com.esotericsoftware.spine.SkeletonRenderer;
import com.google.common.io.ByteStreams;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.view.SpineDrawable;
import games.rednblack.editor.renderer.factory.EntityFactory;
import games.rednblack.h2d.extension.spine.SpineDataObject;
import games.rednblack.h2d.extension.spine.SpineItemType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by mariam on 4/21/16.
*/
public class ResourcesManager {
private final String RESOURCES_FILE_NAME = "tiled";
private TiledPlugin tiledPlugin;
private TextureAtlas textureAtlas;
private final SkeletonRenderer skeletonRenderer = new SkeletonRenderer();
private final ObjectMap<String, Texture> textureCache = new ObjectMap<>();
private final ObjectMap<String, SpineDrawable> spineDrawableCache = new ObjectMap<>();
public ResourcesManager(TiledPlugin tiledPlugin) {
this.tiledPlugin = tiledPlugin;
skeletonRenderer.setPremultipliedAlpha(true);
init();
}
private void init() {
FileHandle atlasTempFile = getResourceFileFromJar(RESOURCES_FILE_NAME + ".atlas");
FileHandle pngTempFile = getResourceFileFromJar(RESOURCES_FILE_NAME + ".png");
textureAtlas = new TextureAtlas(atlasTempFile);
atlasTempFile.file().deleteOnExit();
pngTempFile.file().deleteOnExit();
loadTexture("tile-cursor");
loadTexture("tile-eraser-cursor");
}
private void loadTexture(String name) {
FileHandle file = getResourceFileFromJar(name + ".png");
file.file().deleteOnExit();
textureCache.put(name, new Texture(file));
}
private FileHandle getResourceFileFromJar(String fileName) {
File tempFile = new File(tiledPlugin.getAPI().getCacheDir()+ File.separator + fileName);
try {
InputStream in = getClass().getResourceAsStream("/"+fileName);
FileOutputStream out = new FileOutputStream(tempFile);
ByteStreams.copy(in, out);
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return new FileHandle(tempFile);
}
public Texture getTexture(String name) {
return textureCache.get(name);
}
public TextureRegion getTextureRegion(String name, int type) {
TextureRegion region = textureAtlas.findRegion(name); // try to get region from plugin assets
if (region == null) { // take the region from hyperlap assets
switch (type) {
case EntityFactory.IMAGE_TYPE:
region = tiledPlugin.getAPI().getSceneLoader().getRm().getTextureRegion(name);
break;
case EntityFactory.SPRITE_TYPE:
region = tiledPlugin.getAPI().getSceneLoader().getRm().getSpriteAnimation(name).get(0);
break;
}
}
return region;
}
public SpineDrawable getSpineDrawable(String name) {
if (spineDrawableCache.get(name) == null) {
SpineDataObject spineDataObject = (SpineDataObject) tiledPlugin.getAPI().getSceneLoader().getRm().getExternalItemType(SpineItemType.SPINE_TYPE, name);
SkeletonData skeletonData = spineDataObject.skeletonData;
Skeleton skeleton = new Skeleton(skeletonData);
spineDrawableCache.put(name, new SpineDrawable(skeleton, skeletonRenderer));
}
return spineDrawableCache.get(name);
}
public NinePatch getPluginNinePatch(String name) {
TextureAtlas.AtlasRegion region = textureAtlas.findRegion(name);
if(region == null) return null;
int[] splits = region.findValue("split");
return new NinePatch(region, splits[0], splits[1], splits[2], splits[3]);
}
}
| 4,358 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
OffsetPanelMediator.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/offset/OffsetPanelMediator.java | package games.rednblack.editor.plugin.tiled.offset;
import com.badlogic.gdx.math.Vector2;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.puremvc.Mediator;
import games.rednblack.puremvc.interfaces.INotification;
import games.rednblack.puremvc.util.Interests;
/**
* Created by mariam on 5/12/16.
*/
public class OffsetPanelMediator extends Mediator<OffsetPanel> {
private static final String TAG = OffsetPanelMediator.class.getCanonicalName();
public static final String NAME = TAG;
private TiledPlugin tiledPlugin;
public OffsetPanelMediator(TiledPlugin tiledPlugin) {
super(NAME, tiledPlugin.offsetPanel);
this.tiledPlugin = tiledPlugin;
}
@Override
public void listNotificationInterests(Interests interests) {
interests.add(TiledPlugin.ACTION_OPEN_OFFSET_PANEL,
TiledPlugin.TILE_GRID_OFFSET_ADDED,
TiledPlugin.TILE_SELECTED);
}
@Override
public void handleNotification(INotification notification) {
super.handleNotification(notification);
switch (notification.getName()) {
case TiledPlugin.ACTION_OPEN_OFFSET_PANEL:
viewComponent.refreshOffsetValues();
viewComponent.show(tiledPlugin.getAPI().getUIStage());
break;
case TiledPlugin.TILE_GRID_OFFSET_ADDED:
Vector2 offsetValue = notification.getBody();
tiledPlugin.setSelectedTileGridOffset(offsetValue);
tiledPlugin.applySelectedTileGridOffset();
break;
case TiledPlugin.TILE_SELECTED:
if (viewComponent.isOpen) {
viewComponent.refreshOffsetValues();
}
break;
}
}
}
| 1,803 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
OffsetPanel.java | /FileExtraction/Java_unseen/rednblackgames_HyperLap2D/plugin-tiled/src/main/java/games/rednblack/editor/plugin/tiled/offset/OffsetPanel.java | package games.rednblack.editor.plugin.tiled.offset;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.widget.VisTextButton;
import games.rednblack.editor.plugin.tiled.TiledPlugin;
import games.rednblack.editor.plugin.tiled.data.AttributeVO;
import games.rednblack.editor.plugin.tiled.data.CategoryVO;
import games.rednblack.editor.plugin.tiled.view.Category;
import games.rednblack.h2d.common.UIDraggablePanel;
/**
* Created by mariam on 5/12/16.
*/
public class OffsetPanel extends UIDraggablePanel {
private final String TILE_OFFSET_X = "Tile offset x";
private final String TILE_OFFSET_Y = "Tile offset y";
private TiledPlugin tiledPlugin;
private Table mainTable;
private Category offsetCategory;
private AttributeVO offsetAttributeX;
private AttributeVO offsetAttributeY;
public OffsetPanel(TiledPlugin tiledPlugin) {
super("Offset");
this.tiledPlugin = tiledPlugin;
addCloseButton();
mainTable = new Table();
add(mainTable).pad(3);
initView();
}
private void initView() {
offsetAttributeX = new AttributeVO(TILE_OFFSET_X, true);
offsetAttributeY = new AttributeVO(TILE_OFFSET_Y, true);
Array<AttributeVO> attributeVOs = new Array<>();
attributeVOs.add(offsetAttributeX);
attributeVOs.add(offsetAttributeY);
offsetCategory = new Category(new CategoryVO("", attributeVOs));
mainTable.add(offsetCategory)
.pad(7)
.row();
VisTextButton addButton = new VisTextButton("Set");
addButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Vector2 offset = new Vector2(offsetAttributeX.value, offsetAttributeY.value);
tiledPlugin.facade.sendNotification(TiledPlugin.TILE_GRID_OFFSET_ADDED, offset);
super.clicked(event, x, y);
}
});
mainTable.add(addButton);
}
public void refreshOffsetValues() {
offsetAttributeX = new AttributeVO(TILE_OFFSET_X, tiledPlugin.getSelectedTileGridOffset().x, true);
offsetAttributeY = new AttributeVO(TILE_OFFSET_Y, tiledPlugin.getSelectedTileGridOffset().y, true);
Array<AttributeVO> attributeVOs = new Array<>();
attributeVOs.add(offsetAttributeX);
attributeVOs.add(offsetAttributeY);
offsetCategory.reInitView(attributeVOs);
}
}
| 2,691 | Java | .java | rednblackgames/HyperLap2D | 348 | 63 | 14 | 2020-07-17T14:25:00Z | 2024-05-08T21:35:58Z |
ConversionTest.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/test/java/com/glencoesoftware/raw2ometiff/test/ConversionTest.java | /**
* Copyright (c) 2020 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.raw2ometiff.test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.bc.zarr.ZarrArray;
import com.bc.zarr.ZarrGroup;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glencoesoftware.bioformats2raw.Converter;
import com.glencoesoftware.pyramid.CompressionType;
import com.glencoesoftware.pyramid.PyramidFromDirectoryWriter;
import loci.common.DataTools;
import loci.common.services.ServiceFactory;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.ImageReader;
import loci.formats.ome.OMEXMLMetadata;
import loci.formats.services.OMEXMLService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.TiffParser;
import picocli.CommandLine;
import picocli.CommandLine.ExecutionException;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class ConversionTest {
Path input;
Path output;
Path outputOmeTiff;
Converter converter;
PyramidFromDirectoryWriter writer;
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
/**
* Run the bioformats2raw main method and check for success or failure.
*
* @param additionalArgs CLI arguments as needed beyond "input output"
*/
void assertBioFormats2Raw(String...additionalArgs) throws IOException {
List<String> args = new ArrayList<String>();
for (String arg : additionalArgs) {
args.add(arg);
}
args.add(input.toString());
output = tmp.newFolder().toPath().resolve("test");
args.add(output.toString());
try {
converter = new Converter();
CommandLine.call(converter, args.toArray(new String[]{}));
Assert.assertTrue(Files.exists(output.resolve(".zattrs")));
Assert.assertTrue(Files.exists(
output.resolve("OME").resolve("METADATA.ome.xml")));
}
catch (RuntimeException rt) {
throw rt;
}
catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Run the PyramidFromDirectoryWriter main method and check for success or
* failure.
*
* @param additionalArgs CLI arguments as needed beyond "input output"
*/
void assertTool(String...additionalArgs) throws IOException {
assertTool(0, 0, additionalArgs);
}
/**
* Run the PyramidFromDirectoryWriter main method and check for success or
* failure.
*
* @param seriesCount number of series to expect, if splitting
* @param fileCount number of files to expect, if splitting
* @param additionalArgs CLI arguments as needed beyond "input output"
*/
void assertTool(int seriesCount, int fileCount, String...additionalArgs)
throws IOException
{
List<String> args = new ArrayList<String>();
for (String arg : additionalArgs) {
args.add(arg);
}
args.add(output.toString());
outputOmeTiff = output.resolve("output.ome.tiff");
args.add(outputOmeTiff.toString());
try {
writer = new PyramidFromDirectoryWriter();
CommandLine.call(writer, args.toArray(new String[]{}));
if (fileCount == 0) {
Assert.assertTrue(Files.exists(outputOmeTiff));
}
else if (seriesCount == fileCount) {
String prefix = output.resolve("output").toString();
for (int i=0; i<fileCount; i++) {
Assert.assertTrue(Files.exists(
Paths.get(prefix + "_s" + i + ".ome.tiff")));
}
Assert.assertFalse(Files.exists(
Paths.get(prefix + "_s" +
fileCount + ".ome.tiff")));
}
else {
String prefix = output.resolve("output").toString();
for (int i=0; i<seriesCount; i++) {
Assert.assertTrue(Files.exists(
Paths.get(prefix + "_s" + i + "_z0_c0_t0.ome.tiff")));
}
Assert.assertFalse(Files.exists(Paths.get(prefix + "_s0.ome.tiff")));
}
}
catch (RuntimeException rt) {
throw rt;
}
catch (Throwable t) {
throw new RuntimeException(t);
}
}
static Path fake(String...args) {
Assert.assertTrue(args.length %2 == 0);
Map<String, String> options = new HashMap<String, String>();
for (int i = 0; i < args.length; i += 2) {
options.put(args[i], args[i+1]);
}
return fake(options);
}
static Path fake(Map<String, String> options) {
return fake(options, null);
}
/**
* Create a Bio-Formats fake INI file to use for testing.
* @param options map of the options to assign as part of the fake filename
* from the allowed keys
* @param series map of the integer series index and options map (same format
* as <code>options</code> to add to the fake INI content
* @see https://docs.openmicroscopy.org/bio-formats/6.4.0/developers/
* generating-test-images.html#key-value-pairs
* @return path to the fake INI file that has been created
*/
static Path fake(Map<String, String> options,
Map<Integer, Map<String, String>> series)
{
return fake(options, series, null);
}
static Path fake(Map<String, String> options,
Map<Integer, Map<String, String>> series,
Map<String, String> originalMetadata)
{
StringBuilder sb = new StringBuilder();
sb.append("image");
if (options != null) {
for (Map.Entry<String, String> kv : options.entrySet()) {
sb.append("&");
sb.append(kv.getKey());
sb.append("=");
sb.append(kv.getValue());
}
}
sb.append("&");
try {
List<String> lines = new ArrayList<String>();
if (originalMetadata != null) {
lines.add("[GlobalMetadata]");
for (String key : originalMetadata.keySet()) {
lines.add(String.format("%s=%s", key, originalMetadata.get(key)));
}
}
if (series != null) {
for (int s : series.keySet()) {
Map<String, String> seriesOptions = series.get(s);
lines.add(String.format("[series_%d]", s));
for (String key : seriesOptions.keySet()) {
lines.add(String.format("%s=%s", key, seriesOptions.get(key)));
}
}
}
Path ini = Files.createTempFile(sb.toString(), ".fake.ini");
File iniAsFile = ini.toFile();
String iniPath = iniAsFile.getAbsolutePath();
String fakePath = iniPath.substring(0, iniPath.length() - 4);
Path fake = Paths.get(fakePath);
File fakeAsFile = fake.toFile();
Files.write(fake, new byte[]{});
Files.write(ini, lines);
iniAsFile.deleteOnExit();
fakeAsFile.deleteOnExit();
return ini;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Compare each pixel in each plane in each series of the input fake
* and output OME-TIFF files. Sub-resolutions are not checked.
*/
void iteratePixels() throws Exception {
try (ImageReader outputReader = new ImageReader()) {
outputReader.setFlattenedResolutions(false);
outputReader.setId(outputOmeTiff.toString());
iteratePixels(outputReader);
}
}
/**
* Compare each pixel in each plane in each series of the input fake
* and output OME-TIFF files. Sub-resolutions are not checked.
*
* @param outputReader initialized reader for converted OME-TIFF
*/
void iteratePixels(ImageReader outputReader) throws Exception {
try (ImageReader inputReader = new ImageReader()) {
inputReader.setId(input.toString());
for (int series=0; series<inputReader.getSeriesCount(); series++) {
inputReader.setSeries(series);
outputReader.setSeries(series);
Assert.assertEquals(
inputReader.getImageCount(), outputReader.getImageCount());
Assert.assertEquals(inputReader.getSizeC(), outputReader.getSizeC());
for (int plane=0; plane<inputReader.getImageCount(); plane++) {
Object inputPlane = getPlane(inputReader, plane);
Object outputPlane = getPlane(outputReader, plane);
int inputLength = Array.getLength(inputPlane);
int outputLength = Array.getLength(outputPlane);
Assert.assertEquals(inputLength, outputLength);
for (int px=0; px<inputLength; px++) {
Assert.assertEquals(
Array.get(inputPlane, px), Array.get(outputPlane, px));
}
}
}
}
}
/**
* Get the specified plane as a primitive array.
*
* @param reader initialized reader with correct series set
* @param planeIndex plane to read
* @return primitive array of pixels
*/
Object getPlane(ImageReader reader, int planeIndex) throws Exception {
byte[] rawPlane = reader.openBytes(planeIndex);
int pixelType = reader.getPixelType();
return DataTools.makeDataArray(rawPlane,
FormatTools.getBytesPerPixel(pixelType),
FormatTools.isFloatingPoint(pixelType),
reader.isLittleEndian());
}
private void assertDefaults() throws Exception {
ZarrArray series0 = ZarrGroup.open(output.resolve("0")).openArray("0");
// no getter for DimensionSeparator in ZarrArray
// check that the correct separator was used by checking
// that the expected first chunk file exists
Assert.assertTrue(output.resolve("0/0/0/0/0/0/0").toFile().exists());
// Also ensure we're using the latest .zarray metadata
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(
output.resolve("0/0/.zarray").toFile());
Assert.assertEquals("/", root.path("dimension_separator").asText());
try (ImageReader reader = new ImageReader()) {
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(2, reader.getResolutionCount());
}
iteratePixels();
}
/**
* Test defaults.
*/
@Test
public void testDefaults() throws Exception {
input = fake();
assertBioFormats2Raw();
assertTool();
assertDefaults();
}
/**
* Test symlink as the root.
*/
@Test
public void testSymlinkAsRoot() throws Exception {
Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
input = fake();
assertBioFormats2Raw();
Path notASymlink = output.resolveSibling(output.getFileName() + ".old");
Files.move(output, notASymlink);
Files.createSymbolicLink(output, notASymlink);
assertTool();
assertDefaults();
}
/**
* Test series count check.
*/
@Test
public void testSeriesCountCheck() throws Exception {
input = fake();
assertBioFormats2Raw();
Files.delete(output.resolve("0").resolve(".zgroup"));
try {
assertTool();
}
catch (ExecutionException e) {
// First cause is RuntimeException wrapping the checked FormatException
Assert.assertEquals(
FormatException.class, e.getCause().getCause().getClass());
}
}
/**
* Test South and East edge padding.
*/
@Test
public void testSouthEastEdgePadding() throws Exception {
input = fake();
assertBioFormats2Raw("-w", "240", "-h", "240");
assertTool("--compression", "raw");
try (ImageReader reader = new ImageReader()) {
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(2, reader.getResolutionCount());
Assert.assertEquals(240, reader.getOptimalTileWidth());
Assert.assertEquals(240, reader.getOptimalTileHeight());
ByteBuffer plane = ByteBuffer.wrap(reader.openBytes(0));
Assert.assertEquals(512 * 512, plane.capacity());
int offset = 0;
for (int y = 0; y < reader.getSizeY(); y++) {
offset = (y * 512) + 511;
Assert.assertEquals(255, Byte.toUnsignedInt(plane.get(offset)));
}
}
try (TiffParser tiffParser = new TiffParser(outputOmeTiff.toString())) {
IFDList mainIFDs = tiffParser.getMainIFDs();
Assert.assertEquals(1, mainIFDs.size());
int tileSize = 240 * 240;
Assert.assertArrayEquals(new long[] {
tileSize, tileSize, tileSize, // Row 1
tileSize, tileSize, tileSize, // Row 2
tileSize, tileSize, tileSize // Row 3
}, mainIFDs.get(0).getStripByteCounts());
}
iteratePixels();
}
/**
* Test edge padding uint16.
*/
@Test
public void testEdgePaddingUint16() throws Exception {
input = fake("pixelType", "uint16");
assertBioFormats2Raw("-w", "240", "-h", "240");
assertTool("--compression", "raw");
try (ImageReader reader = new ImageReader()) {
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(2, reader.getResolutionCount());
Assert.assertEquals(240, reader.getOptimalTileWidth());
Assert.assertEquals(240, reader.getOptimalTileHeight());
ShortBuffer plane = ByteBuffer.wrap(reader.openBytes(0)).asShortBuffer();
Assert.assertEquals(512 * 512, plane.capacity());
int offset = 0;
for (int y = 0; y < reader.getSizeY(); y++) {
offset = (y * 512) + 511;
Assert.assertEquals(511, Short.toUnsignedInt(plane.get(offset)));
}
}
try (TiffParser tiffParser = new TiffParser(outputOmeTiff.toString())) {
IFDList mainIFDs = tiffParser.getMainIFDs();
Assert.assertEquals(1, mainIFDs.size());
int tileSize = 240 * 240 * 2;
Assert.assertArrayEquals(new long[] {
tileSize, tileSize, tileSize, // Row 1
tileSize, tileSize, tileSize, // Row 2
tileSize, tileSize, tileSize // Row 3
}, mainIFDs.get(0).getStripByteCounts());
}
iteratePixels();
}
/**
* Test 17x19 tile size with uint16 data.
*/
@Test
public void testOddTileSize() throws Exception {
input = fake("pixelType", "uint16");
assertBioFormats2Raw("-w", "17", "-h", "19");
assertTool("--compression", "raw");
iteratePixels();
try (TiffParser parser = new TiffParser(outputOmeTiff.toString())) {
IFDList mainIFDs = parser.getMainIFDs();
Assert.assertEquals(1, mainIFDs.size());
int tileSize = 32 * 32 * 2;
long[] tileByteCounts = mainIFDs.get(0).getStripByteCounts();
Assert.assertEquals(256, tileByteCounts.length);
for (long count : tileByteCounts) {
Assert.assertEquals(tileSize, count);
}
}
}
/**
* Test 128x128 tile size with 497x498 image.
*/
@Test
public void testOddImageSize() throws Exception {
input = fake("sizeX", "497", "sizeY", "498", "pixelType", "uint16");
assertBioFormats2Raw("-w", "128", "-h", "128");
assertTool();
iteratePixels();
}
/**
* Test RGB with multiple timepoints.
*/
@Test
public void testRGBMultiT() throws Exception {
input = fake("sizeC", "3", "sizeT", "5", "rgb", "3");
assertBioFormats2Raw();
assertTool("--rgb");
iteratePixels();
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(
3, metadata.getPixelsSizeC(0).getNumberValue());
Assert.assertEquals(1, metadata.getChannelCount(0));
Assert.assertEquals(
3, metadata.getChannelSamplesPerPixel(0, 0).getNumberValue());
Assert.assertNull(metadata.getChannelColor(0, 0));
Assert.assertNull(metadata.getChannelEmissionWavelength(0, 0));
Assert.assertNull(metadata.getChannelExcitationWavelength(0, 0));
Assert.assertNull(metadata.getChannelName(0, 0));
}
checkRGBIFDs();
}
/**
* Test RGB with multiple channels.
*/
@Test
public void testRGBMultiC() throws Exception {
input = fake("sizeC", "12", "rgb", "3");
assertBioFormats2Raw();
assertTool("--rgb");
iteratePixels();
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(
12, metadata.getPixelsSizeC(0).getNumberValue());
Assert.assertEquals(4, metadata.getChannelCount(0));
Assert.assertEquals(
3, metadata.getChannelSamplesPerPixel(0, 0).getNumberValue());
Assert.assertNull(metadata.getChannelColor(0, 0));
Assert.assertNull(metadata.getChannelEmissionWavelength(0, 0));
Assert.assertNull(metadata.getChannelExcitationWavelength(0, 0));
Assert.assertNull(metadata.getChannelName(0, 0));
Assert.assertEquals(
3, metadata.getChannelSamplesPerPixel(0, 1).getNumberValue());
Assert.assertNull(metadata.getChannelColor(0, 1));
Assert.assertNull(metadata.getChannelEmissionWavelength(0, 1));
Assert.assertNull(metadata.getChannelExcitationWavelength(0, 1));
Assert.assertNull(metadata.getChannelName(0, 1));
Assert.assertEquals(
3, metadata.getChannelSamplesPerPixel(0, 2).getNumberValue());
Assert.assertNull(metadata.getChannelColor(0, 2));
Assert.assertNull(metadata.getChannelEmissionWavelength(0, 2));
Assert.assertNull(metadata.getChannelExcitationWavelength(0, 2));
Assert.assertNull(metadata.getChannelName(0, 2));
Assert.assertEquals(
3, metadata.getChannelSamplesPerPixel(0, 3).getNumberValue());
Assert.assertNull(metadata.getChannelColor(0, 3));
Assert.assertNull(metadata.getChannelEmissionWavelength(0, 3));
Assert.assertNull(metadata.getChannelExcitationWavelength(0, 3));
Assert.assertNull(metadata.getChannelName(0, 3));
}
checkRGBIFDs();
}
/**
* Test RGB with channel metadata.
*/
@Test
public void testRGBChannelMetadata() throws Exception {
Map<String, String> options = new HashMap<String, String>();
options.put("sizeC", "3");
options.put("rgb", "3");
options.put("color_0", "16711935");
Map<Integer, Map<String, String>> series =
new HashMap<Integer, Map<String, String>>();
Map<String, String> series0 = new HashMap<String, String>();
series0.put("ChannelName_0", "FITC");
series.put(0, series0);
input = fake(options, series);
assertBioFormats2Raw();
assertTool("--rgb");
iteratePixels();
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(
3, metadata.getPixelsSizeC(0).getNumberValue());
Assert.assertEquals(1, metadata.getChannelCount(0));
Assert.assertEquals(
3, metadata.getChannelSamplesPerPixel(0, 0).getNumberValue());
Assert.assertNull(metadata.getChannelColor(0, 0));
Assert.assertNull(metadata.getChannelEmissionWavelength(0, 0));
Assert.assertNull(metadata.getChannelExcitationWavelength(0, 0));
Assert.assertNull(metadata.getChannelName(0, 0));
}
checkRGBIFDs();
}
/**
* Test TIFF metadata.
*/
@Test
public void testMetadata() throws Exception {
input = fake("physicalSizeX", "0.5", "physicalSizeY", "0.6");
assertBioFormats2Raw();
assertTool();
try (TiffParser parser = new TiffParser(outputOmeTiff.toString())) {
IFDList mainIFDs = parser.getMainIFDs();
Assert.assertEquals(1, mainIFDs.size());
IFD ifd = mainIFDs.get(0);
Assert.assertEquals(ifd.getXResolution(), 0.5, 0.0001);
Assert.assertEquals(ifd.getYResolution(), 0.6, 0.0001);
}
}
/**
* Test small plate.
*/
@Test
public void testPlate() throws Exception {
input =
fake("plateRows", "2", "plateCols", "3", "fields", "4", "sizeC", "3");
assertBioFormats2Raw();
assertTool();
iteratePixels();
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(24, reader.getSeriesCount());
Assert.assertEquals(24, metadata.getImageCount());
Assert.assertEquals(1, metadata.getPlateCount());
}
}
/**
* Test single image no HCS.
*/
@Test
public void testSingleImageNoHCS() throws Exception {
input =
fake("plateRows", "2", "plateCols", "3", "fields", "4", "sizeC", "3");
assertBioFormats2Raw("--series", "0", "--no-hcs");
assertTool();
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(1, reader.getSeriesCount());
Assert.assertEquals(1, metadata.getImageCount());
Assert.assertEquals(0, metadata.getPlateCount());
}
}
/**
* Test splitting series into separate files.
*/
@Test
public void testSplitFiles() throws Exception {
input =
fake("plateRows", "2", "plateCols", "3", "fields", "4", "sizeC", "3");
assertBioFormats2Raw();
assertTool(24, 24, "--split");
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
// --split should always produce a companion OME-XML file
// with BinaryOnly OME-TIFFs
reader.setId(output.resolve("output").toString() + ".companion.ome");
Assert.assertEquals(reader.getUsedFiles().length, 25);
Assert.assertEquals(reader.getSeriesCount(), 24);
Assert.assertEquals(1, metadata.getPlateCount());
Assert.assertEquals(24, metadata.getImageCount());
iteratePixels(reader);
}
}
/**
* Test splitting planes into separate files.
*/
@Test
public void testSplitPlanes() throws Exception {
input =
fake("plateRows", "2", "plateCols", "3", "fields", "4", "sizeC", "3");
assertBioFormats2Raw();
assertTool(24, 72, "--split-planes");
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
// --split-planes should always produce a companion OME-XML file
// with BinaryOnly OME-TIFFs
reader.setId(output.resolve("output").toString() + ".companion.ome");
Assert.assertEquals(reader.getUsedFiles().length, 73);
Assert.assertEquals(reader.getSeriesCount(), 24);
Assert.assertEquals(1, metadata.getPlateCount());
Assert.assertEquals(24, metadata.getImageCount());
iteratePixels(reader);
}
}
/**
* Test what happens when the split-by-series and split-by-plane
* options are used together.
*/
@Test
public void testBothSplitOptions() throws Exception {
input =
fake("plateRows", "2", "plateCols", "3", "fields", "4", "sizeC", "3");
assertBioFormats2Raw();
// expect --split-planes to take precedence
assertTool(24, 72, "--split", "--split-planes");
try (ImageReader reader = new ImageReader()) {
ServiceFactory sf = new ServiceFactory();
OMEXMLService xmlService = sf.getInstance(OMEXMLService.class);
OMEXMLMetadata metadata = xmlService.createOMEXMLMetadata();
reader.setMetadataStore(metadata);
reader.setFlattenedResolutions(false);
// --split-planes should always produce a companion OME-XML file
// with BinaryOnly OME-TIFFs
reader.setId(output.resolve("output").toString() + ".companion.ome");
Assert.assertEquals(reader.getUsedFiles().length, 73);
Assert.assertEquals(reader.getSeriesCount(), 24);
Assert.assertEquals(1, metadata.getPlateCount());
Assert.assertEquals(24, metadata.getImageCount());
iteratePixels(reader);
}
}
/**
* Test RGB with multiple channels using API instead of command line.
*/
@Test
public void testOptionsAPI() throws Exception {
input = fake("sizeC", "12", "rgb", "3");
assertBioFormats2Raw();
outputOmeTiff = output.resolve("output.ome.tiff");
PyramidFromDirectoryWriter apiConverter = new PyramidFromDirectoryWriter();
CommandLine cmd = new CommandLine(apiConverter);
cmd.parseArgs();
apiConverter.setInputPath(output.toString());
apiConverter.setOutputPath(outputOmeTiff.toString());
apiConverter.setCompression(CompressionType.UNCOMPRESSED);
apiConverter.setRGB(true);
apiConverter.call();
iteratePixels();
checkRGBIFDs();
}
/**
* Test resetting options to their default values.
*/
@Test
public void testResetAPI() throws Exception {
input = fake("sizeC", "12", "rgb", "3");
assertBioFormats2Raw();
outputOmeTiff = output.resolve("output.ome.tiff");
// make sure default options are set
PyramidFromDirectoryWriter apiConverter = new PyramidFromDirectoryWriter();
CommandLine cmd = new CommandLine(apiConverter);
cmd.parseArgs();
Assert.assertEquals(apiConverter.getInputPath(), null);
Assert.assertEquals(apiConverter.getOutputPath(), null);
Assert.assertEquals(apiConverter.getCompression(), CompressionType.LZW);
Assert.assertEquals(apiConverter.getRGB(), false);
Assert.assertEquals(apiConverter.getLegacyTIFF(), false);
Assert.assertEquals(apiConverter.getSplitTIFFs(), false);
// override default options, as though to start a conversion
apiConverter.setInputPath(output.toString());
apiConverter.setOutputPath(outputOmeTiff.toString());
apiConverter.setCompression(CompressionType.UNCOMPRESSED);
apiConverter.setRGB(true);
// change our minds and reset the options to defaults again
cmd.parseArgs();
Assert.assertEquals(apiConverter.getInputPath(), null);
Assert.assertEquals(apiConverter.getOutputPath(), null);
Assert.assertEquals(apiConverter.getCompression(), CompressionType.LZW);
Assert.assertEquals(apiConverter.getRGB(), false);
Assert.assertEquals(apiConverter.getLegacyTIFF(), false);
Assert.assertEquals(apiConverter.getSplitTIFFs(), false);
// update options, make sure they were set, and actually convert
apiConverter.setInputPath(output.toString());
apiConverter.setOutputPath(outputOmeTiff.toString());
apiConverter.setCompression(CompressionType.UNCOMPRESSED);
apiConverter.setRGB(true);
Assert.assertEquals(apiConverter.getInputPath(), output.toString());
Assert.assertEquals(apiConverter.getOutputPath(), outputOmeTiff.toString());
Assert.assertEquals(apiConverter.getCompression(),
CompressionType.UNCOMPRESSED);
Assert.assertEquals(apiConverter.getRGB(), true);
apiConverter.call();
iteratePixels();
}
/**
* Test "--quality" command line option.
*/
@Test
public void testCompressionQuality() throws Exception {
input = fake("sizeC", "3", "rgb", "3");
assertBioFormats2Raw();
assertTool("--compression", "JPEG-2000", "--quality", "0.25", "--rgb");
try (ImageReader reader = new ImageReader()) {
reader.setFlattenedResolutions(false);
reader.setId(outputOmeTiff.toString());
Assert.assertEquals(1, reader.getSeriesCount());
Assert.assertEquals(3, reader.getRGBChannelCount());
}
checkRGBIFDs();
}
/**
* Test "--version" with no other arguments.
* Does not test the version values, just makes sure that an exception
* is not thrown.
*/
@Test
public void testVersionOnly() throws Exception {
CommandLine.call(
new PyramidFromDirectoryWriter(), new String[] {"--version"});
}
private void checkRGBIFDs() throws FormatException, IOException {
try (TiffParser parser = new TiffParser(outputOmeTiff.toString())) {
IFDList mainIFDs = parser.getMainIFDs();
for (IFD ifd : mainIFDs) {
Assert.assertEquals(1, ifd.getPlanarConfiguration());
Assert.assertEquals(3, ifd.getSamplesPerPixel());
IFDList subresolutions = parser.getSubIFDs(ifd);
for (IFD subres : subresolutions) {
Assert.assertEquals(1, subres.getPlanarConfiguration());
Assert.assertEquals(3, ifd.getSamplesPerPixel());
}
}
}
}
}
| 29,834 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
PyramidSeries.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/PyramidSeries.java | /**
* Copyright (c) 2019-2020 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.ome.OMEPyramidStore;
import loci.formats.tiff.IFDList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bc.zarr.ZarrArray;
import com.bc.zarr.ZarrGroup;
public class PyramidSeries {
private static final Logger LOG =
LoggerFactory.getLogger(PyramidSeries.class);
/** Path to series. */
String path;
List<String> uuid = new ArrayList<String>();
int index = -1;
IFDList[] ifds;
/** FormatTools pixel type. */
Integer pixelType;
/** Number of resolutions. */
int numberOfResolutions;
boolean littleEndian = false;
int planeCount = 1;
int z = 1;
int c = 1;
int t = 1;
String dimensionOrder;
int[] dimensionLengths = new int[3];
boolean rgb = false;
/** Description of each resolution in the pyramid. */
List<ResolutionDescriptor> resolutions;
/**
* Calculate image width and height for each resolution.
* Uses the first tile in the resolution to find the tile size.
*
* @param reader reader used to get dataset attributes
* @param metadata additional OME-XML metadata
*/
public void describePyramid(ZarrGroup reader, OMEPyramidStore metadata)
throws FormatException, IOException
{
LOG.info("Number of resolution levels: {}", numberOfResolutions);
resolutions = new ArrayList<ResolutionDescriptor>();
for (int resolution = 0; resolution < numberOfResolutions; resolution++) {
ResolutionDescriptor descriptor = new ResolutionDescriptor();
descriptor.resolutionNumber = resolution;
descriptor.path = path + "/" + resolution;
ZarrArray array = reader.openArray(descriptor.path);
int[] dimensions = array.getShape();
int[] blockSizes = array.getChunks();
descriptor.sizeX = dimensions[dimensions.length - 1];
descriptor.sizeY = dimensions[dimensions.length - 2];
descriptor.tileSizeX = blockSizes[blockSizes.length - 1];
descriptor.tileSizeY = blockSizes[blockSizes.length - 2];
if (descriptor.tileSizeX % 16 != 0) {
LOG.debug("Tile width ({}) not a multiple of 16; correcting",
descriptor.tileSizeX);
descriptor.tileSizeX += (16 - (descriptor.tileSizeX % 16));
}
if (descriptor.tileSizeY % 16 != 0) {
LOG.debug("Tile height ({}) not a multiple of 16; correcting",
descriptor.tileSizeY);
descriptor.tileSizeY += (16 - (descriptor.tileSizeY % 16));
}
descriptor.numberOfTilesX =
getTileCount(descriptor.sizeX, descriptor.tileSizeX);
descriptor.numberOfTilesY =
getTileCount(descriptor.sizeY, descriptor.tileSizeY);
if (resolution == 0) {
// If we have image metadata available sanity check the dimensions
// against those in the underlying pyramid
if (metadata.getImageCount() > 0) {
int sizeX =
metadata.getPixelsSizeX(index).getNumberValue().intValue();
int sizeY =
metadata.getPixelsSizeY(index).getNumberValue().intValue();
if (descriptor.sizeX != sizeX) {
throw new FormatException(String.format(
"Resolution %d dimension mismatch! metadata=%d pyramid=%d",
resolution, descriptor.sizeX, sizeX));
}
if (descriptor.sizeY != sizeY) {
throw new FormatException(String.format(
"Resolution %d dimension mismatch! metadata=%d pyramid=%d",
resolution, descriptor.sizeY, sizeY));
}
}
if (dimensions.length != 5) {
throw new FormatException(String.format(
"Expected 5 dimensions in series %d, found %d",
index, dimensions.length));
}
for (int i=0; i<dimensions.length-2; i++) {
if (dimensions[i] != dimensionLengths[2 - i]) {
throw new FormatException(
"Dimension order mismatch in series " + index);
}
}
}
resolutions.add(descriptor);
}
}
/**
* Convenience method that delegates to FormatTools to calculate
* the Z, C, and T index for a given plane index.
*
* @param plane index
* @return array of Z, C, and T indexes
*/
public int[] getZCTCoords(int plane) {
int effectiveC = rgb ? c / 3 : c;
return FormatTools.getZCTCoords(
dimensionOrder, z, effectiveC, t, planeCount, plane);
}
/**
* Calculate the number of tiles for a dimension based upon the tile size.
*
* @param size the number of pixels in the dimension (e.g. image width)
* @param tileSize the number of pixels in the tile along the same dimension
* @return the number of tiles
*/
private int getTileCount(long size, long tileSize) {
return (int) Math.ceil((double) size / tileSize);
}
}
| 5,246 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
PyramidFromDirectoryWriter.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/PyramidFromDirectoryWriter.java | /**
* Copyright (c) 2019-2020 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import ch.qos.logback.classic.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import loci.common.Constants;
import loci.common.DataTools;
import loci.common.RandomAccessOutputStream;
import loci.common.Region;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.codec.CodecOptions;
import loci.formats.ome.OMEPyramidStore;
import loci.formats.services.OMEXMLService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffConstants;
import loci.formats.tiff.TiffRational;
import loci.formats.tiff.TiffSaver;
import ome.units.UNITS;
import ome.units.quantity.Length;
import ome.xml.meta.OMEXMLMetadataRoot;
import ome.xml.model.Channel;
import ome.xml.model.FilterSet;
import ome.xml.model.Pixels;
import ome.xml.model.enums.DimensionOrder;
import ome.xml.model.enums.EnumerationException;
import ome.xml.model.enums.PixelType;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
import org.json.JSONObject;
import org.perf4j.StopWatch;
import org.perf4j.slf4j.Slf4JStopWatch;
import com.bc.zarr.DataType;
import com.bc.zarr.ZarrArray;
import com.bc.zarr.ZarrGroup;
import com.glencoesoftware.bioformats2raw.IProgressListener;
import com.glencoesoftware.bioformats2raw.NoOpProgressListener;
import com.glencoesoftware.bioformats2raw.ProgressBarListener;
import ucar.ma2.InvalidRangeException;
import picocli.CommandLine;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
/**
* Writes a pyramid OME-TIFF file or Bio-Formats 5.9.x "Faas" TIFF file.
* Image tiles are read from files within a specific folder structure:
*
* root_folder/resolution_index/x_coordinate/y_coordinate.tiff
*
* root_folder/resolution_index/x_coordinate/y_coordinate/c-z-t.tiff
*
* The resulting OME-TIFF file can be read using Bio-Formats 6.x,
* for example with this command:
*
* $ showinf -noflat pyramid.ome.tiff -nopix
*
* which should show the expected number of resolutions with the
* expected image dimensions.
*
* Missing tiles are supported, but every resolution and X coordinate
* must have at least one valid tile file.
* Any missing tiles are filled in with pixel values of 0 (black).
*/
public class PyramidFromDirectoryWriter implements Callable<Void> {
private static final long FIRST_IFD_OFFSET = 8;
/** Name of JSON metadata file. */
private static final String METADATA_FILE = "METADATA.json";
/** Name of OME-XML metadata file. */
private static final String OMEXML_FILE = "METADATA.ome.xml";
private static final Logger LOG =
LoggerFactory.getLogger(PyramidFromDirectoryWriter.class);
/** Path to each output file. */
private List<Path> seriesPaths;
private BlockingQueue<Runnable> tileQueue;
private ExecutorService executor;
private IProgressListener progressListener;
/** Where to write? */
Path outputFilePath;
Path inputDirectory;
private volatile String logLevel;
private volatile boolean progressBars = false;
boolean printVersion = false;
boolean help = false;
CompressionType compression;
CodecOptions compressionOptions;
boolean legacy = false;
int maxWorkers;
boolean rgb = false;
private List<PyramidSeries> series = new ArrayList<PyramidSeries>();
private Map<String, TiffSaver> tiffSavers = new HashMap<String, TiffSaver>();
boolean splitBySeries = false;
boolean splitByPlane = false;
private ZarrGroup reader = null;
/** Writer metadata. */
OMEPyramidStore metadata;
OMEPyramidStore binaryOnly;
private Map<String, Object> plateData = null;
/**
* Construct a writer for performing the pyramid conversion.
*/
public PyramidFromDirectoryWriter() {
}
/**
* Where to write?
*
* @param output path to output TIFF
*/
@Parameters(
index = "1",
arity = "1",
description = "Relative path to the output OME-TIFF file",
defaultValue = Option.NULL_VALUE
)
public void setOutputPath(String output) {
// could be expanded to allow other output locations
if (output != null) {
outputFilePath = Paths.get(output);
}
else {
outputFilePath = null;
}
}
/**
* Where to read?
*
* @param input path to input Zarr directory
*/
@Parameters(
index = "0",
arity = "1",
description = "Directory containing pixel data to convert",
defaultValue = Option.NULL_VALUE
)
public void setInputPath(String input) {
// could be expanded to allow other input locations
if (input != null) {
inputDirectory = Paths.get(input);
}
else {
inputDirectory = null;
}
}
/**
* Set the slf4j logging level. Defaults to "WARN".
*
* @param level logging level
*/
@Option(
names = {"--log-level", "--debug"},
arity = "0..1",
description = "Change logging level; valid values are " +
"OFF, ERROR, WARN, INFO, DEBUG, TRACE and ALL. " +
"(default: ${DEFAULT-VALUE})",
defaultValue = "WARN",
fallbackValue = "DEBUG"
)
public void setLogLevel(String level) {
logLevel = level;
}
/**
* Configure whether or not progress bars are shown during conversion.
* Progress bars are turned off by default.
*
* @param useProgressBars whether or not to show progress bars
*/
@Option(
names = {"-p", "--progress"},
description = "Print progress bars during conversion",
defaultValue = "false"
)
public void setProgressBars(boolean useProgressBars) {
progressBars = useProgressBars;
}
/**
* Configure whether to print version information and exit
* without converting.
*
* @param versionOnly whether or not to print version information and exit
*/
@Option(
names = "--version",
description = "Print version information and exit",
help = true,
defaultValue = "false"
)
public void setPrintVersionOnly(boolean versionOnly) {
printVersion = versionOnly;
}
/**
* Configure whether to print help and exit without converting.
*
* @param helpOnly whether or not to print help and exit
*/
@Option(
names = "--help",
description = "Print usage information and exit",
usageHelp = true,
defaultValue = "false"
)
public void setHelp(boolean helpOnly) {
help = helpOnly;
}
/**
* Set the compression type for the output OME-TIFF. Defaults to LZW.
* Valid types are defined in the CompressionType enum.
*
* @param compressionType compression type
*/
@Option(
names = "--compression",
description = "Compression type for output OME-TIFF file " +
"(${COMPLETION-CANDIDATES}; default: ${DEFAULT-VALUE})",
converter = CompressionTypeConverter.class,
defaultValue = "LZW"
)
public void setCompression(CompressionType compressionType) {
compression = compressionType;
}
/**
* Set the compression options.
*
* When using the command line "--quality" option, the quality value will be
* wrapped in a CodecOptions. The interpretation of the quality value
* depends upon the selected compression type.
*
* This value currently only applies to "JPEG-2000 Lossy" compression,
* and corresponds to the encoded bitrate in bits per pixel.
* The quality is a floating point number and must be greater than 0.
* A larger number implies less data loss but also larger file size.
* By default, the quality is set to the largest positive finite double value.
* This is equivalent to lossless compression; to see truly lossy compression,
* the quality should be set to less than the bit depth of the input image.
*
* Options other than quality may be specified in this object, but their
* interpretation will also depend upon the compression type selected.
* Options that conflict with the input data (e.g. bits per pixel)
* will be ignored.
*
* @param options compression options
*/
@Option(
names = "--quality",
converter = CompressionQualityConverter.class,
description = "Compression quality",
defaultValue = Option.NULL_VALUE
)
public void setCompressionOptions(CodecOptions options) {
compressionOptions = options;
}
/**
* Configure whether to write a pyramid OME-TIFF compatible with
* Bio-Formats 6.x (the default), or a legacy pyramid TIFF compatible
* with Bio-Formats 5.9.x.
*
* @param legacyTIFF true if a legacy pyramid TIFF should be written
*/
@Option(
names = "--legacy",
description = "Write a Bio-Formats 5.9.x pyramid instead of OME-TIFF",
defaultValue = "false"
)
public void setLegacyTIFF(boolean legacyTIFF) {
legacy = legacyTIFF;
}
/**
* Configure whether to write one OME-TIFF per OME Image/Zarr group.
*
* @param split true if output should be split into one OME-TIFF per Image
*/
@Option(
names = "--split",
description =
"Split output into one OME-TIFF file per OME Image/Zarr group",
defaultValue = "false"
)
public void setSplitTIFFs(boolean split) {
splitBySeries = split;
}
/**
* Configure whether to write one OME-TIFF per plane.
*
* @param split true if output should be split into one OME-TIFF per plane
*/
@Option(
names = "--split-planes",
description =
"Split output into one OME-TIFF file per plane"
)
public void setSplitSinglePlaneTIFFs(boolean split) {
splitByPlane = split;
}
/**
* Set the maximum number of workers to use for converting tiles.
* Defaults to 4 or the number of detected CPUs, whichever is smaller.
*
* @param workers maximum worker count
*/
@Option(
names = "--max_workers",
description = "Maximum number of workers (default: ${DEFAULT-VALUE})",
defaultValue = "4"
)
public void setMaxWorkers(int workers) {
int availableProcessors = Runtime.getRuntime().availableProcessors();
int prevWorkers = getMaxWorkers();
if (workers > availableProcessors) {
maxWorkers = availableProcessors;
}
else if (workers > 0 && workers != maxWorkers) {
maxWorkers = workers;
}
if (prevWorkers != maxWorkers) {
tileQueue = new LimitedQueue<Runnable>(maxWorkers);
}
}
/**
* Write an RGB TIFF, if the input data contains a multiple of 3 channels
* If RGB TIFFs are written, any channel metadata (names, wavelengths, etc.)
* in the input data will be lost.
*
* @param isRGB true if an RGB TIFF should be written
*/
@Option(
names = "--rgb",
description = "Attempt to write channels as RGB; " +
"channel count must be a multiple of 3",
defaultValue = "false"
)
public void setRGB(boolean isRGB) {
rgb = isRGB;
}
/**
* @return path to output data
*/
public String getOutputPath() {
if (outputFilePath == null) {
return null;
}
return outputFilePath.toString();
}
/**
* @return path to input data
*/
public String getInputPath() {
if (inputDirectory == null) {
return null;
}
return inputDirectory.toString();
}
/**
* @return slf4j logging level
*/
public String getLogLevel() {
return logLevel;
}
/**
* @return true if progress bars are displayed
*/
public boolean getProgressBars() {
return progressBars;
}
// path and UUID for companion OME-XML file
// only used with the --split option
private String companionPath = null;
private String companionUUID = null;
/**
* @return true if only version info is displayed
*/
public boolean getPrintVersionOnly() {
return printVersion;
}
/**
* @return true if only usage info is displayed
*/
public boolean getHelp() {
return help;
}
/**
* @return compression type
*/
public CompressionType getCompression() {
return compression;
}
/**
* @return compression options
*/
public CodecOptions getCompressionOptions() {
return compressionOptions;
}
/**
* @return true if a legacy pyramid TIFF will be written
* instead of pyramid OME-TIFF
*/
public boolean getLegacyTIFF() {
return legacy;
}
/**
* @return true if output will be split into one OME-TIFF per image
*/
public boolean getSplitTIFFs() {
return splitBySeries;
}
/**
* @return true if output will be split into one OME-TIFF per plane
*/
public boolean getSplitSinglePlaneTIFFs() {
return splitByPlane;
}
/**
* @return maximum number of worker threads
*/
public int getMaxWorkers() {
return maxWorkers;
}
/**
* @return true if an RGB TIFF should be written
*/
public boolean getRGB() {
return rgb;
}
/**
* Convert a pyramid based upon the provided command line arguments.
* @param args command line arguments
*/
public static void main(String[] args) {
CommandLine.call(new PyramidFromDirectoryWriter(), args);
}
/**
* Set a listener for tile processing events.
* Intended to be used to show a status bar.
*
* @param listener a progress event listener
*/
public void setProgressListener(IProgressListener listener) {
progressListener = listener;
}
/**
* Get the current listener for tile processing events.
* If no listener was set, a no-op listener is returned.
*
* @return the current progress listener
*/
public IProgressListener getProgressListener() {
if (progressListener == null) {
setProgressListener(new NoOpProgressListener());
}
return progressListener;
}
@Override
public Void call() throws Exception {
setupLogger();
if (help) {
return null;
}
if (printVersion) {
printVersion();
return null;
}
if (progressBars) {
setProgressListener(new ProgressBarListener(logLevel));
}
if (inputDirectory == null) {
throw new IllegalArgumentException("Input directory not specified");
}
if (outputFilePath == null) {
throw new IllegalArgumentException("Output path not specified");
}
// Resolve symlinks
inputDirectory = inputDirectory.toRealPath();
// we could support this case later, just keeping it simple for now
if ((splitBySeries || splitByPlane) && legacy) {
throw new IllegalArgumentException(
"--split and --split-planes not supported with --legacy");
}
try {
StopWatch t0 = new Slf4JStopWatch("initialize");
try {
initialize();
}
finally {
t0.stop();
}
t0 = new Slf4JStopWatch("convertToPyramid");
try {
convertToPyramid();
}
finally {
t0.stop();
}
}
catch (FormatException|IOException e) {
throw new RuntimeException(e);
}
return null;
}
//* Initialization */
/**
* Get the JSON metadata file, which may or may not exist.
*
* @return Path representing the expected JSON metadata file
*/
private Path getMetadataFile() {
return inputDirectory.resolve(METADATA_FILE);
}
/**
* Get the OME-XML metadata file, which may or may not exist.
*
* @return Path representing the expected OME-XML metadata file
*/
private Path getOMEXMLFile() {
return getZarr().resolve("OME").resolve(OMEXML_FILE);
}
/**
* Get the root Zarr directory.
*
* @return Path representing the root Zarr directory
*/
private Path getZarr() {
return inputDirectory;
}
/**
* Provide tile from the input folder.
*
* @param s current series
* @param resolution the pyramid level, indexed from 0 (largest)
* @param no the plane index
* @param x the tile X index, from 0 to numberOfTilesX
* @param y the tile Y index, from 0 to numberOfTilesY
* @param region specifies the width and height to read;
if null, the whole tile is read
* @return byte array containing the pixels for the tile
*/
private byte[] getInputTileBytes(PyramidSeries s, int resolution,
int no, int x, int y, Region region)
throws FormatException, IOException
{
int[] pos = FormatTools.rasterToPosition(s.dimensionLengths, no);
getProgressListener().notifyChunkStart(no, x, y, pos[0]);
ResolutionDescriptor descriptor = s.resolutions.get(resolution);
int realWidth = descriptor.tileSizeX;
int realHeight = descriptor.tileSizeY;
if (region != null) {
realWidth = region.width;
realHeight = region.height;
}
int[] gridPosition = new int[] {pos[2], pos[1], pos[0],
y * descriptor.tileSizeY, x * descriptor.tileSizeX};
int[] shape = new int[] {1, 1, 1, realHeight, realWidth};
ZarrArray block = reader.openArray(descriptor.path);
if (block == null) {
throw new FormatException("Could not find block = " + descriptor.path +
", position = [" + pos[0] + ", " + pos[1] + ", " + pos[2] + "]");
}
byte[] tile = null;
try {
Object bytes = block.read(shape, gridPosition);
if (bytes instanceof byte[]) {
tile = (byte[]) bytes;
}
else if (bytes instanceof short[]) {
tile = DataTools.shortsToBytes((short[]) bytes, s.littleEndian);
}
else if (bytes instanceof int[]) {
tile = DataTools.intsToBytes((int[]) bytes, s.littleEndian);
}
else if (bytes instanceof long[]) {
tile = DataTools.longsToBytes((long[]) bytes, s.littleEndian);
}
else if (bytes instanceof float[]) {
tile = DataTools.floatsToBytes((float[]) bytes, s.littleEndian);
}
else if (bytes instanceof double[]) {
tile = DataTools.doublesToBytes((double[]) bytes, s.littleEndian);
}
}
catch (InvalidRangeException e) {
throw new IOException("Could not read from " + descriptor.path, e);
}
return tile;
}
/**
* Translate Zarr attributes to the current metadata store.
*/
private void populateMetadata() throws IOException {
if (plateData != null) {
List<Map<String, Object>> acquisitions =
(List<Map<String, Object>>) plateData.get("acquisitions");
List<Map<String, Object>> columns =
(List<Map<String, Object>>) plateData.get("columns");
List<Map<String, Object>> rows =
(List<Map<String, Object>>) plateData.get("rows");
List<Map<String, Object>> wells =
(List<Map<String, Object>>) plateData.get("wells");
Map<String, Integer> rowLookup = new HashMap<String, Integer>();
Map<String, Integer> colLookup = new HashMap<String, Integer>();
for (int i=0; i<rows.size(); i++) {
rowLookup.put(rows.get(i).get("name").toString(), i);
}
for (int i=0; i<columns.size(); i++) {
Object name = columns.get(i).get("name");
colLookup.put(getString(name), i);
}
metadata.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
metadata.setPlateName((String) plateData.get("name"), 0);
metadata.setPlateRows(new PositiveInteger(rows.size()), 0);
metadata.setPlateColumns(new PositiveInteger(columns.size()), 0);
Map<String, Integer> acqLookup = new HashMap<String, Integer>();
List<Integer> wsCounter = new ArrayList<Integer>();
for (int i=0; i<acquisitions.size(); i++) {
String acqID = MetadataTools.createLSID("PlateAcquisition", 0, i);
metadata.setPlateAcquisitionID(acqID, 0, i);
String plateAcqName = acquisitions.get(i).get("id").toString();
metadata.setPlateAcquisitionName(plateAcqName, 0, i);
wsCounter.add(0);
acqLookup.put(plateAcqName, i);
}
int wsIndex = 0;
for (int i=0; i<wells.size(); i++) {
String well = (String) wells.get(i).get("path");
Integer rowIndex = (Integer) wells.get(i).get("row_index");
Integer colIndex = (Integer) wells.get(i).get("column_index");
String[] path = well.split("/");
if (rowIndex == null) {
LOG.warn("Well {} row_index missing; attempting to calculate", i);
rowIndex = rowLookup.get(path[path.length - 2]);
}
if (colIndex == null) {
LOG.warn("Well {} column_index missing; attempting to calculate", i);
colIndex = colLookup.get(path[path.length - 1]);
}
metadata.setWellID(MetadataTools.createLSID("Well", 0, i), 0, i);
metadata.setWellColumn(new NonNegativeInteger(colIndex), 0, i);
metadata.setWellRow(new NonNegativeInteger(rowIndex), 0, i);
ZarrGroup wellGroup = getZarrGroup(well);
Map<String, Object> wellAttr =
(Map<String, Object>) wellGroup.getAttributes().get("well");
List<Map<String, Object>> images =
(List<Map<String, Object>>) wellAttr.get("images");
for (int img=0; img<images.size(); img++) {
String wsID = MetadataTools.createLSID("WellSample", 0, i, img);
metadata.setWellSampleID(wsID, 0, i, img);
metadata.setWellSampleIndex(
new NonNegativeInteger(wsIndex), 0, i, img);
String imageID = MetadataTools.createLSID("Image", wsIndex);
metadata.setWellSampleImageRef(imageID, 0, i, img);
int acquisition =
acqLookup.get(images.get(img).get("acquisition").toString());
int acqIndex = wsCounter.get(acquisition);
metadata.setPlateAcquisitionWellSampleRef(
wsID, 0, acquisition, acqIndex);
wsCounter.set(acquisition, acqIndex + 1);
metadata.setImageID(imageID, wsIndex);
metadata.setPixelsID(
MetadataTools.createLSID("Pixels", wsIndex), wsIndex);
String imgName = (String) images.get(img).get("path");
String imgPath = well + "/" + imgName;
metadata.setImageName(imgName, wsIndex);
ZarrGroup imgGroup = getZarrGroup(imgPath);
ZarrArray imgArray = imgGroup.openArray("0");
int[] dims = imgArray.getShape();
String order = "XYZCT";
int cIndex = order.length() - order.indexOf("C") - 1;
int zIndex = order.length() - order.indexOf("Z") - 1;
int tIndex = order.length() - order.indexOf("T") - 1;
int c = dims[cIndex];
PixelType type = getPixelType(imgArray.getDataType());
boolean bigEndian = imgArray.getByteOrder() == ByteOrder.BIG_ENDIAN;
metadata.setPixelsBigEndian(bigEndian, wsIndex);
metadata.setPixelsType(type, wsIndex);
metadata.setPixelsSizeX(
new PositiveInteger(dims[dims.length - 1]), wsIndex);
metadata.setPixelsSizeY(
new PositiveInteger(dims[dims.length - 2]), wsIndex);
metadata.setPixelsSizeZ(new PositiveInteger(dims[zIndex]), wsIndex);
metadata.setPixelsSizeC(new PositiveInteger(c), wsIndex);
metadata.setPixelsSizeT(new PositiveInteger(dims[tIndex]), wsIndex);
try {
metadata.setPixelsDimensionOrder(
DimensionOrder.fromString(order), wsIndex);
}
catch (EnumerationException e) {
LOG.warn("Could not save dimension order", e);
}
for (int ch=0; ch<c; ch++) {
metadata.setChannelID(
MetadataTools.createLSID("Channel", wsIndex, ch), wsIndex, ch);
metadata.setChannelSamplesPerPixel(
new PositiveInteger(1), wsIndex, ch);
}
wsIndex++;
}
}
}
}
private PixelType getPixelType(DataType type) {
switch (type) {
case i1:
return PixelType.INT8;
case u1:
return PixelType.UINT8;
case i2:
return PixelType.INT16;
case u2:
return PixelType.UINT16;
case i4:
return PixelType.INT32;
case u4:
return PixelType.UINT32;
case f4:
return PixelType.FLOAT;
case f8:
return PixelType.DOUBLE;
default:
throw new IllegalArgumentException("Unsupported pixel type: " + type);
}
}
private ZarrGroup getZarrGroup(String path) throws IOException {
return ZarrGroup.open(inputDirectory.resolve(path).toString());
}
private int getSubgroupCount(String path) throws IOException {
return getZarrGroup(path).getGroupKeys().size();
}
/**
* Calculate the number of series.
*
* @return number of series
*/
private int getSeriesCount() throws IOException {
Set<String> groupKeys = reader.getGroupKeys();
groupKeys.remove("OME");
int groupKeyCount = groupKeys.size();
LOG.debug("getSeriesCount:");
LOG.debug(" plateData = {}", plateData);
LOG.debug(" group key count = {}", groupKeyCount);
if (plateData != null) {
int count = 0;
List<Map<String, Object>> wells =
(List<Map<String, Object>>) plateData.get("wells");
for (Map<String, Object> well : wells) {
count += getSubgroupCount((String) well.get("path"));
}
LOG.debug(" returning plate-based series count = {}", count);
return count;
}
return groupKeyCount;
}
/**
* Calculate the number of resolutions for the given series based upon
* the number of directories in the base input directory.
*
* @param s current series
*/
private void findNumberOfResolutions(PyramidSeries s) throws IOException {
if (plateData != null) {
List<Map<String, Object>> wells =
(List<Map<String, Object>>) plateData.get("wells");
int index = 0;
for (Map<String, Object> well : wells) {
int fields = getSubgroupCount((String) well.get("path"));
if (index + fields > s.index) {
s.path = well.get("path") + "/" + (s.index - index);
break;
}
index += fields;
}
}
else {
s.path = String.valueOf(s.index);
}
ZarrGroup seriesGroup = getZarrGroup(s.path);
if (seriesGroup == null) {
throw new IOException("Expected series " + s.index + " not found");
}
// use multiscales metadata if it exists, to distinguish between
// resolutions and labels
// if no multiscales metadata (older dataset?), assume no labels
// and just use the path listing length
Map<String, Object> seriesAttributes = seriesGroup.getAttributes();
List<Map<String, Object>> multiscales =
(List<Map<String, Object>>) seriesAttributes.get("multiscales");
if (multiscales != null && multiscales.size() > 0) {
List<Map<String, Object>> datasets =
(List<Map<String, Object>>) multiscales.get(0).get("datasets");
if (datasets != null) {
s.numberOfResolutions = datasets.size();
}
}
if (s.numberOfResolutions == 0) {
s.numberOfResolutions = seriesGroup.getArrayKeys().size();
}
}
/**
* Set up the TIFF writer with all necessary metadata.
* After this method is called, image data can be written.
*/
public void initialize()
throws FormatException, IOException, DependencyException
{
createReader();
if (reader == null) {
throw new FormatException("Could not create a reader");
}
Map<String, Object> attributes = reader.getAttributes();
Integer layoutVersion = (Integer) attributes.get("bioformats2raw.layout");
if (layoutVersion == null) {
LOG.warn("Layout version not recorded; may be unsupported");
}
else if (layoutVersion != 3) {
throw new FormatException("Unsupported version: " + layoutVersion);
}
plateData = (Map<String, Object>) attributes.get("plate");
LOG.info("Creating tiled pyramid file {}", this.outputFilePath);
OMEXMLService service = getService();
if (service != null) {
Path omexml = getOMEXMLFile();
String xml = null;
if (omexml != null && Files.exists(omexml)) {
xml = DataTools.readFile(omexml.toString());
}
try {
if (xml != null) {
metadata = (OMEPyramidStore) service.createOMEXMLMetadata(xml);
OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) metadata.getRoot();
for (int image = 0; image<root.sizeOfImageList(); image++) {
Pixels pixels = root.getImage(image).getPixels();
pixels.setMetadataOnly(null);
while (pixels.sizeOfTiffDataList() > 0) {
pixels.removeTiffData(pixels.getTiffData(0));
}
}
}
else {
metadata = (OMEPyramidStore) service.createOMEXMLMetadata();
populateMetadata();
}
}
catch (ServiceException e) {
throw new FormatException("Could not parse OME-XML", e);
}
}
int seriesCount = getSeriesCount();
if (seriesCount < 1) {
throw new FormatException("Found no images to convert. Corrupt input?");
}
if (seriesCount > 1 && legacy) {
LOG.warn("Omitting {} series due to legacy output", seriesCount - 1);
seriesCount = 1;
}
int totalPlanes = 0;
seriesPaths = new ArrayList<Path>(seriesCount);
for (int seriesIndex=0; seriesIndex<seriesCount; seriesIndex++) {
PyramidSeries s = new PyramidSeries();
s.index = seriesIndex;
findNumberOfResolutions(s);
s.z = metadata.getPixelsSizeZ(seriesIndex).getNumberValue().intValue();
s.c = metadata.getPixelsSizeC(seriesIndex).getNumberValue().intValue();
s.t = metadata.getPixelsSizeT(seriesIndex).getNumberValue().intValue();
s.dimensionOrder =
metadata.getPixelsDimensionOrder(seriesIndex).toString();
s.planeCount = s.z * s.t;
// Zarr format allows both little and big endian order
s.littleEndian = !metadata.getPixelsBigEndian(seriesIndex);
s.pixelType = FormatTools.pixelTypeFromString(
metadata.getPixelsType(seriesIndex).getValue());
if (seriesIndex > 0 && s.littleEndian != series.get(0).littleEndian) {
// always warn on endian mismatches
// mismatch is only fatal if pixel type is neither INT8 nor UINT8
String msg = String.format("Endian mismatch in series {} (expected {}",
seriesIndex, series.get(0).littleEndian);
if (FormatTools.getBytesPerPixel(s.pixelType) > 1) {
throw new FormatException(msg);
}
LOG.warn(msg);
}
s.dimensionLengths[s.dimensionOrder.indexOf("Z") - 2] = s.z;
s.dimensionLengths[s.dimensionOrder.indexOf("T") - 2] = s.t;
s.dimensionLengths[s.dimensionOrder.indexOf("C") - 2] = s.c;
int rgbChannels = 1;
int effectiveChannels = s.c;
// --rgb flag only respected if the number of channels in the source data
// is a multiple of 3
// this assumes that channels should be grouped by 3s (not 2s or 4s)
// into RGB planes
// this could be made configurable later?
s.rgb = rgb && (s.c % 3 == 0);
if (s.rgb) {
rgbChannels = 3;
effectiveChannels = s.c / rgbChannels;
LOG.debug("Merging {} original channels into {} RGB channels",
s.c, effectiveChannels);
OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) metadata.getRoot();
Pixels pixels = root.getImage(seriesIndex).getPixels();
for (int index=pixels.sizeOfChannelList()-1; index>0; index--) {
if (index % rgbChannels == 0) {
continue;
}
Channel ch = pixels.getChannel(index);
pixels.removeChannel(ch);
}
for (int index=0; index<pixels.sizeOfChannelList(); index++) {
Channel channel = pixels.getChannel(index);
channel.setSamplesPerPixel(new PositiveInteger(rgbChannels));
if (channel.getColor() != null) {
LOG.warn("Removing channel color");
channel.setColor(null);
}
if (channel.getEmissionWavelength() != null) {
LOG.warn("Removing channel emission wavelength");
channel.setEmissionWavelength(null);
}
if (channel.getExcitationWavelength() != null) {
LOG.warn("Removing channel excitation wavelength");
channel.setEmissionWavelength(null);
}
if (channel.getLightPath() != null) {
LOG.warn("Removing channel light path");
channel.setLightPath(null);
}
if (channel.getLightSourceSettings() != null) {
LOG.warn("Removing channel light source settings");
channel.setLightSourceSettings(null);
}
FilterSet filterSet = channel.getLinkedFilterSet();
if (filterSet != null) {
LOG.warn("Removing channel filter set");
channel.unlinkFilterSet(filterSet);
}
if (channel.getName() != null) {
LOG.warn("Removing channel name");
channel.setName(null);
}
}
// RGB data needs to have XYC* dimension order
if (!s.dimensionOrder.startsWith("XYC")) {
if (s.dimensionOrder.indexOf("Z") < s.dimensionOrder.indexOf("T")) {
s.dimensionOrder = "XYCZT";
}
else {
s.dimensionOrder = "XYCTZ";
}
}
}
else if (rgb) {
LOG.warn(
"Ignoring --rgb flag; channel count {} is not a multiple of 3", s.c);
}
s.planeCount *= effectiveChannels;
s.describePyramid(reader, metadata);
metadata.setTiffDataIFD(new NonNegativeInteger(totalPlanes), s.index, 0);
for (ResolutionDescriptor descriptor : s.resolutions) {
LOG.info("Adding metadata for resolution: {}",
descriptor.resolutionNumber);
if (descriptor.resolutionNumber == 0) {
MetadataTools.populateMetadata(
this.metadata, seriesIndex, null, s.littleEndian, s.dimensionOrder,
FormatTools.getPixelTypeString(s.pixelType),
descriptor.sizeX, descriptor.sizeY, s.z, s.c, s.t,
rgbChannels);
}
else {
if (legacy) {
MetadataTools.populateMetadata(this.metadata,
descriptor.resolutionNumber, null, s.littleEndian,
s.dimensionOrder, FormatTools.getPixelTypeString(s.pixelType),
descriptor.sizeX, descriptor.sizeY,
s.z, s.c, s.t, rgbChannels);
}
else {
metadata.setResolutionSizeX(new PositiveInteger(
descriptor.sizeX), seriesIndex, descriptor.resolutionNumber);
metadata.setResolutionSizeY(new PositiveInteger(
descriptor.sizeY), seriesIndex, descriptor.resolutionNumber);
}
}
}
series.add(s);
totalPlanes += s.planeCount;
if (splitBySeries && !splitByPlane) {
String basePath = getOutputPathPrefix();
// append the series index and file extension
basePath += "_s";
seriesPaths.add(Paths.get(basePath + s.index + ".ome.tiff"));
// generate one UUID per file
s.uuid.add("urn:uuid:" + UUID.randomUUID().toString());
}
else if (splitByPlane) {
String basePath = getOutputPathPrefix();
// append the series index and file extension
basePath += "_s";
basePath += s.index;
basePath += "_z";
for (int t=0; t<s.t; t++) {
for (int c=0; c<effectiveChannels; c++) {
for (int z=0; z<s.z; z++) {
seriesPaths.add(
Paths.get(basePath + z + "_c" + c + "_t" + t + ".ome.tiff"));
// generate one UUID per file
s.uuid.add("urn:uuid:" + UUID.randomUUID().toString());
}
}
}
}
else {
seriesPaths.add(outputFilePath);
// use the same UUID everywhere since we're only writing one file
if (seriesIndex == 0) {
s.uuid.add("urn:uuid:" + UUID.randomUUID().toString());
}
else {
s.uuid.add(series.get(0).uuid.get(0));
}
}
}
populateTiffData();
populateOriginalMetadata(service);
if (splitBySeries || splitByPlane) {
// splitting into separate OME-TIFFs results in a companion OME-XML file
// the OME-TIFFs then use the BinaryOnly element to reference the OME-XML
// for large plates in particular, this is useful as it reduces the
// OME-TIFF file size
companionPath = getOutputPathPrefix() + ".companion.ome";
companionUUID = "urn:uuid:" + UUID.randomUUID().toString();
try {
metadata.setUUID(companionUUID);
String omexml = service.getOMEXML(metadata);
Files.write(Paths.get(companionPath),
omexml.getBytes(Constants.ENCODING));
}
catch (ServiceException e) {
throw new FormatException("Could not get OME-XML", e);
}
}
for (Path p : seriesPaths) {
writeTIFFHeader(p.toString());
}
}
/**
* Remove the [.ome].tif[f] suffix from the output file path, if present.
*
* @return output file path without OME-TIFF extension
*/
private String getOutputPathPrefix() {
String basePath = outputFilePath.toString();
if (basePath.toLowerCase().endsWith(".tif") ||
basePath.toLowerCase().endsWith(".tiff"))
{
basePath = basePath.substring(0, basePath.lastIndexOf("."));
if (basePath.toLowerCase().endsWith(".ome")) {
basePath = basePath.substring(0, basePath.lastIndexOf("."));
}
}
return basePath;
}
private void writeTIFFHeader(String output) throws IOException {
try (RandomAccessOutputStream out = new RandomAccessOutputStream(output)) {
try (TiffSaver w = createTiffSaver(out, output)) {
w.writeHeader();
}
}
tiffSavers.remove(output);
}
private TiffSaver createTiffSaver(RandomAccessOutputStream out, String file) {
if (tiffSavers.containsKey(file)) {
return tiffSavers.get(file);
}
TiffSaver w = new TiffSaver(out, file);
w.setBigTiff(true);
// assumes all series have same endian setting
// series with opposite endianness are logged above
w.setLittleEndian(series.get(0).littleEndian);
tiffSavers.put(file, w);
return w;
}
private String getPathName(PyramidSeries s, int plane) {
if (splitByPlane) {
int index = 0;
for (int i=0; i<series.size(); i++) {
if (!series.get(i).equals(s)) {
index += series.get(i).uuid.size();
}
else {
break;
}
}
return seriesPaths.get(index + plane).toString();
}
return seriesPaths.get(s.index).toString();
}
//* Conversion */
/**
* Writes all image data to the initialized TIFF writer.
*/
public void convertToPyramid()
throws FormatException, IOException,
InterruptedException, DependencyException
{
long tileCount = 0;
int[] seriesTileCount = new int[series.size()];
for (int s=0; s<series.size(); s++) {
PyramidSeries ps = series.get(s);
seriesTileCount[s] = 0;
for (int resolution=0; resolution<ps.numberOfResolutions; resolution++) {
ResolutionDescriptor descriptor = ps.resolutions.get(resolution);
int resTiles = descriptor.numberOfTilesY * descriptor.numberOfTilesX;
seriesTileCount[s] += resTiles * ps.planeCount;
}
tileCount += seriesTileCount[s];
}
getProgressListener().notifyStart(series.size(), tileCount);
for (int s=0; s<series.size(); s++) {
convertPyramid(series.get(s), seriesTileCount[s]);
}
StopWatch t0 = new Slf4JStopWatch("writeIFDs");
writeIFDs();
t0.stop();
binaryOnly = null;
}
private void convertPyramid(PyramidSeries s, int totalTileCount)
throws FormatException, IOException,
InterruptedException, DependencyException
{
getProgressListener().notifySeriesStart(
s.index, s.numberOfResolutions, totalTileCount);
// convert every resolution in the pyramid
s.ifds = new IFDList[s.numberOfResolutions];
for (int resolution=0; resolution<s.numberOfResolutions; resolution++) {
s.ifds[resolution] = new IFDList();
for (int plane=0; plane<s.planeCount; plane++) {
IFD ifd = makeIFD(s, resolution, plane);
s.ifds[resolution].add(ifd);
}
}
int rgbChannels = s.rgb ? 3 : 1;
int bytesPerPixel = FormatTools.getBytesPerPixel(s.pixelType);
for (int resolution=0; resolution<s.numberOfResolutions; resolution++) {
executor = new ThreadPoolExecutor(
maxWorkers, maxWorkers, 0L, TimeUnit.MILLISECONDS, tileQueue);
try {
LOG.info("Converting resolution #{}", resolution);
ResolutionDescriptor descriptor = s.resolutions.get(resolution);
int tileCount = descriptor.numberOfTilesY * descriptor.numberOfTilesX;
int resTileCount = tileCount * s.planeCount;
getProgressListener().notifyResolutionStart(resolution, resTileCount);
int plane = 0;
for (int t=0; t<s.t; t++) {
for (int c=0; c<(s.c / rgbChannels); c++) {
for (int z=0; z<s.z; z++, plane++) {
int tileIndex = 0;
// if the resolution has already been calculated,
// just read each tile from disk and store in the OME-TIFF
for (int y=0; y<descriptor.numberOfTilesY; y++) {
for (int x=0; x<descriptor.numberOfTilesX; x++, tileIndex++) {
Region region = new Region(
x * descriptor.tileSizeX,
y * descriptor.tileSizeY, 0, 0);
region.width = (int) Math.min(
descriptor.tileSizeX, descriptor.sizeX - region.x);
region.height = (int) Math.min(
descriptor.tileSizeY, descriptor.sizeY - region.y);
if (region.width <= 0 || region.height <= 0) {
continue;
}
StopWatch t0 = new Slf4JStopWatch("getInputTileBytes");
byte[] packedTileBytes = null;
try {
for (int ch=0; ch<rgbChannels; ch++) {
// assumes TCZYX order consistent with bioformats2raw
int planeIndex = FormatTools.positionToRaster(
s.dimensionLengths,
new int[] {z, c * rgbChannels + ch, t});
byte[] componentBytes = getInputTileBytes(
s, resolution, planeIndex, x, y, region);
if (rgbChannels == 1) {
packedTileBytes = componentBytes;
}
else {
if (ch == 0) {
packedTileBytes =
new byte[componentBytes.length * rgbChannels];
}
// unpack componentBytes into packedTileBytes
int pixels = componentBytes.length / bytesPerPixel;
for (int pixel=0; pixel<pixels; pixel++) {
int srcIndex = pixel * bytesPerPixel;
int destIndex =
bytesPerPixel * (pixel * rgbChannels + ch);
for (int b=0; b<bytesPerPixel; b++) {
packedTileBytes[destIndex + b] =
componentBytes[srcIndex + b];
}
}
}
}
}
finally {
t0.stop();
}
final int currentIndex = tileIndex;
final int currentPlane = plane;
final int currentResolution = resolution;
final int xx = x;
final int yy = y;
final byte[] tileBytes = packedTileBytes;
executor.execute(() -> {
Slf4JStopWatch t1 = new Slf4JStopWatch("writeTile");
try {
if (tileBytes != null) {
if (region.width == descriptor.tileSizeX &&
region.height == descriptor.tileSizeY)
{
writeTile(s, currentPlane, tileBytes,
currentIndex, currentResolution, xx, yy);
}
else {
// padded tile, use descriptor X and Y tile size
int tileX = descriptor.tileSizeX;
int tileY = descriptor.tileSizeY;
int pixelWidth = bytesPerPixel * rgbChannels;
byte[] realTile =
new byte[tileX * tileY * pixelWidth];
int totalRows = region.height;
int inRowLen = region.width * pixelWidth;
int outRowLen = tileX * pixelWidth;
for (int row=0; row<totalRows; row++) {
System.arraycopy(tileBytes, row * inRowLen,
realTile, row * outRowLen, inRowLen);
}
writeTile(s, currentPlane, realTile,
currentIndex, currentResolution, xx, yy);
}
}
}
catch (FormatException|IOException e) {
LOG.error(
"Failed to write tile in series {} resolution {}",
s.index, currentResolution, e);
}
finally {
t1.stop();
}
});
}
}
}
}
}
}
finally {
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
getProgressListener().notifyResolutionEnd(resolution);
}
}
getProgressListener().notifySeriesEnd(s.index);
}
private void writeIFDs() throws FormatException, IOException {
StopWatch t0 = new Slf4JStopWatch("subifds");
Map<String, Long> firstIFDOffsets = new HashMap<String, Long>();
// write sub-IFDs for every series first
long[][][] subs = new long[series.size()][][];
for (PyramidSeries s : series) {
StopWatch t1 = new Slf4JStopWatch("subifd-" + s.index);
String path = getPathName(s, 0);
try (RandomAccessOutputStream out = new RandomAccessOutputStream(path)) {
out.order(s.littleEndian);
out.seek(out.length());
if (!firstIFDOffsets.containsKey(path)) {
firstIFDOffsets.put(path, out.getFilePointer());
}
if (legacy) {
for (int res=0; res<s.numberOfResolutions; res++) {
for (int plane=0; plane<s.planeCount; plane++) {
boolean last = (res == s.numberOfResolutions - 1) &&
(plane == s.planeCount - 1);
writeIFD(out, s, res, plane, !last);
}
}
out.seek(FIRST_IFD_OFFSET);
out.writeLong(firstIFDOffsets.get(path));
}
else {
subs[s.index] = new long[s.planeCount][s.numberOfResolutions - 1];
for (int plane=0; plane<s.planeCount; plane++) {
if (splitByPlane) {
String planePath = getPathName(s, plane);
try (RandomAccessOutputStream p =
new RandomAccessOutputStream(planePath))
{
p.order(s.littleEndian);
p.seek(p.length());
for (int r=1; r<s.numberOfResolutions; r++) {
subs[s.index][plane][r - 1] = p.getFilePointer();
writeIFD(p, s, r, plane, r < s.numberOfResolutions - 1);
}
}
tiffSavers.remove(planePath);
}
else {
for (int r=1; r<s.numberOfResolutions; r++) {
subs[s.index][plane][r - 1] = out.getFilePointer();
writeIFD(out, s, r, plane, r < s.numberOfResolutions - 1);
}
}
}
}
}
tiffSavers.remove(path);
t1.stop();
}
t0.stop();
t0 = new Slf4JStopWatch("fullResolutionIFDs");
// now write the full resolution IFD for each series
if (!legacy) {
firstIFDOffsets.clear();
for (PyramidSeries s : series) {
StopWatch t1 = new Slf4JStopWatch("fullResolution-" + s.index);
String path = getPathName(s, 0);
try (RandomAccessOutputStream out =
new RandomAccessOutputStream(path))
{
out.order(s.littleEndian);
out.seek(out.length());
if (!firstIFDOffsets.containsKey(path)) {
firstIFDOffsets.put(path, out.getFilePointer());
}
for (int plane=0; plane<s.planeCount; plane++) {
s.ifds[0].get(plane).put(IFD.SUB_IFD, subs[s.index][plane]);
// if splitting by plane, the first IFD is also the last in the file
if (!splitByPlane) {
boolean overwrite = plane < s.planeCount - 1;
if (!splitBySeries) {
overwrite = overwrite || s.index < series.size() - 1;
}
writeIFD(out, s, 0, plane, overwrite);
}
else {
String planePath = getPathName(s, plane);
try (RandomAccessOutputStream p =
new RandomAccessOutputStream(planePath))
{
p.order(s.littleEndian);
long offset = p.length();
p.seek(offset);
writeIFD(p, s, 0, plane, false);
p.seek(FIRST_IFD_OFFSET);
p.writeLong(offset);
}
tiffSavers.remove(planePath);
}
}
if (!splitByPlane) {
out.seek(FIRST_IFD_OFFSET);
out.writeLong(firstIFDOffsets.get(path));
}
}
tiffSavers.remove(path);
t1.stop();
}
}
t0.stop();
}
/**
* Overwrite an IFD offset at the given pointer.
* The output stream should be positioned to the new IFD offset
* before this method is called.
*
* @param outStream open output file stream
* @param offsetPointer pointer to the IFD offset that will be overwritten
* @throws IOException
*/
private void overwriteNextOffset(
RandomAccessOutputStream outStream, long offsetPointer) throws IOException
{
long fp = outStream.getFilePointer();
outStream.seek(offsetPointer);
outStream.writeLong(fp);
outStream.seek(fp);
}
/**
* Get the size in bytes of the given IFD.
* This size includes the IFD header and tags that would be written,
* but does not include the size of any non-inlined tag values.
* This is mainly used to calculate the file pointer at which to write
* the offset to the next IFD.
*
* @param ifd the IFD for which to calculate a size
* @return the number of bytes in the IFD
*/
private int getIFDSize(IFD ifd) {
// subtract LITTLE_ENDIAN from the key count
return 8 + TiffConstants.BIG_TIFF_BYTES_PER_ENTRY * (ifd.size() - 1);
}
/**
* Create an IFD for the given plane in the given resolution.
* All relevant tags are filled in; sub-IFD and tile data are
* filled with placeholders.
*
* @param s current series
* @param resolution the resolution index for the new IFD
* @param plane the plane index for the new IFD
* @return an IFD that is ready to be filled with tile data
*/
private IFD makeIFD(PyramidSeries s, int resolution, int plane)
throws FormatException, DependencyException
{
IFD ifd = new IFD();
ifd.put(IFD.LITTLE_ENDIAN, s.littleEndian);
ResolutionDescriptor descriptor = s.resolutions.get(resolution);
ifd.put(IFD.IMAGE_WIDTH, (long) descriptor.sizeX);
ifd.put(IFD.IMAGE_LENGTH, (long) descriptor.sizeY);
ifd.put(IFD.TILE_WIDTH, descriptor.tileSizeX);
ifd.put(IFD.TILE_LENGTH, descriptor.tileSizeY);
ifd.put(IFD.COMPRESSION, compression.getTIFFCompression().getCode());
ifd.put(IFD.PLANAR_CONFIGURATION, 1);
int sampleFormat = 1;
if (FormatTools.isFloatingPoint(s.pixelType)) {
sampleFormat = 3;
}
else if (FormatTools.isSigned(s.pixelType)) {
sampleFormat = 2;
}
ifd.put(IFD.SAMPLE_FORMAT, sampleFormat);
int[] bps = new int[s.rgb ? 3 : 1];
Arrays.fill(bps, FormatTools.getBytesPerPixel(s.pixelType) * 8);
ifd.put(IFD.BITS_PER_SAMPLE, bps);
ifd.put(IFD.PHOTOMETRIC_INTERPRETATION,
s.rgb ? PhotoInterp.RGB.getCode() : PhotoInterp.BLACK_IS_ZERO.getCode());
ifd.put(IFD.SAMPLES_PER_PIXEL, bps.length);
if (legacy) {
ifd.put(IFD.SOFTWARE, "Faas-raw2ometiff");
}
else {
ifd.put(IFD.SOFTWARE, FormatTools.CREATOR);
if (resolution == 0) {
ifd.put(IFD.SUB_IFD, (long) 0);
}
else {
ifd.put(IFD.NEW_SUBFILE_TYPE, 1);
}
}
// only write the OME-XML to the first full-resolution IFD
if (resolution == 0 && (plane == 0 || splitByPlane)) {
if (splitBySeries || splitByPlane) {
// if each series is in a separate OME-TIFF, store BinaryOnly OME-XML
// that references the companion OME-XML file
String omexml = getBinaryOnlyOMEXML(s, plane);
ifd.put(IFD.IMAGE_DESCRIPTION, omexml);
}
else if (s.index == 0) {
// if everything is in one OME-TIFF file, store the complete OME-XML
try {
metadata.setUUID(s.uuid.get(0));
OMEXMLService service = getService();
String omexml = service.getOMEXML(metadata);
ifd.put(IFD.IMAGE_DESCRIPTION, omexml);
}
catch (ServiceException e) {
throw new FormatException("Could not get OME-XML", e);
}
}
}
int tileCount = descriptor.numberOfTilesX * descriptor.numberOfTilesY;
ifd.put(IFD.TILE_BYTE_COUNTS, new long[tileCount]);
ifd.put(IFD.TILE_OFFSETS, new long[tileCount]);
ifd.put(IFD.RESOLUTION_UNIT, 3);
ifd.put(IFD.X_RESOLUTION,
getPhysicalSize(metadata.getPixelsPhysicalSizeX(s.index)));
ifd.put(IFD.Y_RESOLUTION,
getPhysicalSize(metadata.getPixelsPhysicalSizeY(s.index)));
return ifd;
}
private TiffRational getPhysicalSize(Length size) {
if (size == null || size.value(UNITS.MICROMETER) == null) {
return new TiffRational(0, 1000);
}
Double physicalSize = size.value(UNITS.MICROMETER).doubleValue();
if (physicalSize.doubleValue() != 0) {
physicalSize = 1d / physicalSize;
}
return new TiffRational((long) (physicalSize * 1000 * 10000), 1000);
}
/**
* Write a single tile to the writer's current resolution.
*
* @param s current series
* @param imageNumber the plane number in the resolution
* @param buffer the array containing the tile's pixel data
* @param tileIndex index of the tile to be written in XY space
* @param resolution resolution index of the tile
* @param x tile index along X
* @param y tile index along Y
*/
private void writeTile(PyramidSeries s,
Integer imageNumber, byte[] buffer, int tileIndex, int resolution,
int x, int y)
throws FormatException, IOException
{
LOG.debug("Writing series: {}, image: {}, tileIndex: {}",
s.index, imageNumber, tileIndex);
IFD ifd = s.ifds[resolution].get(imageNumber);
TiffCompression tiffCompression = compression.getTIFFCompression();
CodecOptions options =
tiffCompression.getCompressionCodecOptions(ifd, compressionOptions);
// buffer has been padded to full tile width before calling writeTile
// but is not necessarily full tile height (if in the bottom row)
int bpp = FormatTools.getBytesPerPixel(s.pixelType);
options.width = (int) ifd.getTileWidth();
options.channels = s.rgb ? 3 : 1;
options.height = buffer.length / (options.width * bpp * options.channels);
options.bitsPerSample = bpp * 8;
byte[] realTile = tiffCompression.compress(buffer, options);
writeToDisk(s, realTile, tileIndex, resolution, imageNumber);
int z = s.getZCTCoords(imageNumber)[0];
getProgressListener().notifyChunkEnd(imageNumber, x, y, z);
}
/**
* Write a pre-compressed buffer corresponding to the
* given IFD and tile index.
*
* @param s current series
* @param realTile array of compressed bytes representing the tile
* @param tileIndex index into the array of tile offsets
* @param resolution resolution index of the tile
* @param imageNumber image index of the tile
*/
private synchronized void writeToDisk(
PyramidSeries s,
byte[] realTile, int tileIndex,
int resolution, int imageNumber)
throws FormatException, IOException
{
IFD ifd = s.ifds[resolution].get(imageNumber);
// do not use ifd.getStripByteCounts() or ifd.getStripOffsets() here
// as both can return values other than what is in the IFD
long[] offsets = ifd.getIFDLongArray(IFD.TILE_OFFSETS);
long[] byteCounts = ifd.getIFDLongArray(IFD.TILE_BYTE_COUNTS);
byteCounts[tileIndex] = (long) realTile.length;
String file = getPathName(s, imageNumber);
try (RandomAccessOutputStream out = new RandomAccessOutputStream(file)) {
out.seek(out.length());
offsets[tileIndex] = out.getFilePointer();
LOG.debug(" writing {} compressed bytes to {} at {}",
realTile.length, file, out.getFilePointer());
out.write(realTile);
}
ifd.put(IFD.TILE_OFFSETS, offsets);
ifd.put(IFD.TILE_BYTE_COUNTS, byteCounts);
}
/**
* Create an OMEXMLService for manipulating OME-XML metadata.
*
* @return OMEXMLService instance, or null if the service is not available
*/
private OMEXMLService getService() throws DependencyException {
ServiceFactory factory = new ServiceFactory();
return factory.getInstance(OMEXMLService.class);
}
/**
* Write the IFD for the given resolution and plane.
*
* @param outStream open output file stream
* @param s current series
* @param resolution the resolution index
* @param plane the plane index
* @param overwrite true unless this is the last IFD in the list
*/
private void writeIFD(
RandomAccessOutputStream outStream,
PyramidSeries s, int resolution, int plane, boolean overwrite)
throws FormatException, IOException
{
TiffSaver writer = createTiffSaver(outStream, getPathName(s, plane));
int ifdSize = getIFDSize(s.ifds[resolution].get(plane));
long offsetPointer = outStream.getFilePointer() + ifdSize;
writer.writeIFD(s.ifds[resolution].get(plane), 0);
if (overwrite) {
overwriteNextOffset(outStream, offsetPointer);
}
}
/**
* Create a reader for the chosen input directory.
* If the input directory contains a Zarr group, a Zarr reader is used.
* If an appropriate reader cannot be found, the reader will remain null.
*/
private void createReader() throws IOException {
Path zarr = getZarr();
LOG.debug("attempting to open {}", zarr);
if (Files.exists(zarr)) {
LOG.debug(" zarr directory exists");
reader = ZarrGroup.open(zarr.toString());
}
}
/**
* Set up the root logger, turning on debug logging if appropriate.
*/
private void setupLogger() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger)
LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.toLevel(logLevel));
}
/**
* Print versions for raw2ometiff and associated Bio-Formats dependency.
*/
private void printVersion() {
String version = Optional.ofNullable(
this.getClass().getPackage().getImplementationVersion()
).orElse("development");
System.out.println("Version = " + version);
System.out.println("Bio-Formats version = " + FormatTools.VERSION);
}
private void populateTiffData() {
for (PyramidSeries s : series) {
for (int tiffData=0; tiffData<s.uuid.size(); tiffData++) {
String path = getPathName(s, tiffData);
metadata.setUUIDFileName(
Paths.get(path).getFileName().toString(), s.index, tiffData);
metadata.setUUIDValue(s.uuid.get(tiffData), s.index, tiffData);
if (splitByPlane) {
int[] zct = s.getZCTCoords(tiffData);
metadata.setTiffDataFirstZ(
new NonNegativeInteger(zct[0]), s.index, tiffData);
metadata.setTiffDataFirstC(
new NonNegativeInteger(zct[1]), s.index, tiffData);
metadata.setTiffDataFirstT(
new NonNegativeInteger(zct[2]), s.index, tiffData);
metadata.setTiffDataPlaneCount(
new NonNegativeInteger(1), s.index, tiffData);
}
else {
metadata.setTiffDataPlaneCount(
new NonNegativeInteger(s.planeCount), s.index, tiffData);
}
if (splitBySeries || splitByPlane) {
metadata.setTiffDataIFD(new NonNegativeInteger(0), s.index, tiffData);
}
}
}
}
/**
* Get a BinaryOnly OME-XML string for the given OME-TIFF path.
* When datasets are split across multiple OME-TIFF files,
* a companion OME-XML file is used which requires each OME-TIFF
* to have BinaryOnly OME-XML that references the companion OME-XML file.
*
* @param s pyramid series for UUID retrieval
* @param plane plane index for UUID retrieval
* @return corresponding BinaryOnly OME-XML string
*/
private String getBinaryOnlyOMEXML(PyramidSeries s, int plane) {
try {
OMEXMLService service = getService();
if (binaryOnly == null) {
binaryOnly = (OMEPyramidStore) service.createOMEXMLMetadata();
Path companion = Paths.get(companionPath);
binaryOnly.setBinaryOnlyMetadataFile(
companion.getName(companion.getNameCount() - 1).toString());
binaryOnly.setBinaryOnlyUUID(companionUUID);
}
binaryOnly.setUUID(s.uuid.get(plane));
return service.getOMEXML(binaryOnly);
}
catch (DependencyException | ServiceException e) {
LOG.warn("Could not create OME-XML for " + getPathName(s, plane), e);
}
return null;
}
/**
* Use the given service to create original metadata annotations
* based upon the dataset's JSON metadata file (if present).
*
* @param service to use for creating original metadata annotations
* @throws IOException
*/
private void populateOriginalMetadata(OMEXMLService service)
throws IOException
{
Path metadataFile = getMetadataFile();
Hashtable<String, Object> originalMeta = new Hashtable<String, Object>();
if (metadataFile != null && Files.exists(metadataFile)) {
String jsonMetadata = DataTools.readFile(metadataFile.toString());
JSONObject json = new JSONObject(jsonMetadata);
parseJSONValues(json, originalMeta, "");
service.populateOriginalMetadata(metadata, originalMeta);
}
}
/**
* Translate JSON objects to a set of key/value pairs.
*
* @param root JSON object
* @param originalMeta hashtable to store key/value pairs
* @param prefix key prefix, used to preserve JSON hierarchy
*/
private void parseJSONValues(JSONObject root,
Hashtable<String, Object> originalMeta, String prefix)
{
for (String key : root.keySet()) {
Object value = root.get(key);
if (value instanceof JSONObject) {
parseJSONValues(
(JSONObject) value, originalMeta,
prefix.isEmpty() ? key : prefix + " | " + key);
}
else {
originalMeta.put(prefix.isEmpty() ? key : prefix + " | " + key,
value.toString());
}
}
}
private String getString(Object attr) {
if (attr == null) {
return null;
}
if (attr instanceof Double) {
return String.valueOf(((Double) attr).intValue());
}
return attr.toString();
}
}
| 65,081 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
ResolutionDescriptor.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/ResolutionDescriptor.java | /**
* Copyright (c) 2019-2020 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
public class ResolutionDescriptor {
/** Path to resolution. */
String path;
/** Resolution index (0 = the original image). */
Integer resolutionNumber;
/** Image width at this resolution. */
Integer sizeX;
/** Image height at this resolution. */
Integer sizeY;
/** Tile width at this resolution. */
Integer tileSizeX;
/** Tile height at this resolution. */
Integer tileSizeY;
/** Number of tiles along X axis. */
Integer numberOfTilesX;
/** Number of tiles along Y axis. */
Integer numberOfTilesY;
}
| 885 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
CompressionQualityConverter.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/CompressionQualityConverter.java | /**
* Copyright (c) 2023 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
import loci.formats.codec.CodecOptions;
import loci.formats.codec.JPEG2000CodecOptions;
import picocli.CommandLine.ITypeConverter;
/**
* Convert a string to a CodecOptions.
*/
public class CompressionQualityConverter
implements ITypeConverter<CodecOptions>
{
@Override
public CodecOptions convert(String value) throws Exception {
// JPEG2000CodecOptions used here as it's the only way to pass
// a quality value through to the JPEG-2000 codecs
// this could be changed later if/when we support options on other codecs
CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.quality = Double.parseDouble(value);
return options;
}
}
| 1,026 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
CompressionTypeConverter.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/CompressionTypeConverter.java | /**
* Copyright (c) 2023 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
import picocli.CommandLine.ITypeConverter;
/**
* Convert a string to a CompressionType.
*/
public class CompressionTypeConverter
implements ITypeConverter<CompressionType>
{
@Override
public CompressionType convert(String value) throws Exception {
return CompressionType.lookup(value);
}
}
| 647 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
LimitedQueue.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/LimitedQueue.java | /**
* Copyright (c) 2019 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
import java.util.concurrent.LinkedBlockingQueue;
/**
* A limited queue which blocks when <code>offer(...)</code> is attempted.
* @see https://stackoverflow.com/questions/4521983/
* @param <E> the type of elements in this queue
*/
public class LimitedQueue<E> extends LinkedBlockingQueue<E> {
/**
* Construct a new queue with the given maximum size.
*
* @param maxSize the maximum number of items in the queue
*/
public LimitedQueue(int maxSize) {
super(maxSize);
}
@Override
public boolean offer(E e) {
// turn offer() and add() into a blocking calls (unless interrupted)
try {
put(e);
return true;
}
catch(InterruptedException ie) {
Thread.currentThread().interrupt();
}
return false;
}
}
| 1,152 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
CompressionType.java | /FileExtraction/Java_unseen/glencoesoftware_raw2ometiff/src/main/java/com/glencoesoftware/pyramid/CompressionType.java | /**
* Copyright (c) 2019-2020 Glencoe Software, Inc. All rights reserved.
*
* This software is distributed under the terms described by the LICENSE.txt
* file you can find at the root of the distribution bundle. If the file is
* missing please request a copy by contacting [email protected]
*/
package com.glencoesoftware.pyramid;
import java.util.EnumSet;
import loci.formats.out.TiffWriter;
import loci.formats.tiff.TiffCompression;
/**
* List of valid compression types for the output OME-TIFF file.
*/
public enum CompressionType {
UNCOMPRESSED(
TiffWriter.COMPRESSION_UNCOMPRESSED, TiffCompression.UNCOMPRESSED),
LZW(TiffWriter.COMPRESSION_LZW, TiffCompression.LZW),
JPEG(TiffWriter.COMPRESSION_JPEG, TiffCompression.JPEG),
JPEG_2000(TiffWriter.COMPRESSION_J2K, TiffCompression.JPEG_2000),
JPEG_2000_LOSSY(
TiffWriter.COMPRESSION_J2K_LOSSY, TiffCompression.JPEG_2000_LOSSY);
private String compressionName;
private TiffCompression compressionType;
/**
* Construct a list of valid compression types.
*
* @param name compression name (used in command line arguments)
* @param type corresponding TIFF compression
*/
private CompressionType(String name, TiffCompression type) {
compressionName = name;
compressionType = type;
}
/**
* Find the compression corresponding to the given name.
* If there is no matching name, return the uncompressed type.
*
* @param compressionName desired compression name
* @return corresponding CompressionType, or UNCOMPRESSED if no match
*/
public static CompressionType lookup(String compressionName) {
for (CompressionType t : EnumSet.allOf(CompressionType.class)) {
if (t.getName().equals(compressionName)) {
return t;
}
}
return UNCOMPRESSED;
}
/**
* @return name of this compression type
*/
public String getName() {
return compressionName;
}
/**
* @return TiffCompression for this compression type
*/
public TiffCompression getTIFFCompression() {
return compressionType;
}
}
| 2,078 | Java | .java | glencoesoftware/raw2ometiff | 44 | 20 | 3 | 2019-10-09T14:50:58Z | 2024-04-23T08:39:21Z |
BitArrayTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/harenet/BitArrayTest.java | package test.harenet;
import static org.junit.Assert.*;
import org.junit.Test;
import harenet.BitArray;
public class BitArrayTest {
/**
* Purpose: Check BitArray's data having size 0
* Input: input 0 to constructor
* Expected:
* BitArray's data length == 0
*/
@Test
public void testConstructorZero() {
BitArray bitArray = new BitArray(0);
assertEquals(bitArray.getData().length,0);
}
/**
* Purpose: Check BitArray' data having negative size
* Input: input -1 to constructor
* Expected:
* NegativeArraySizeException occurs
*/
@Test(expected=NegativeArraySizeException.class)
public void testConstructorNegative() throws Exception {
BitArray bitArray = new BitArray(-1);
}
/**
* birArray is size 0 Array ===> it's wrong!!!
*/
/**
* Purpose: Check BitArray' data having size 1
* Input: input 1 to constructor
* Expected:
* BitArray's data length == 1
*/
@Test
public void testConstructorPositive1() {
BitArray bitArray = new BitArray(1);
assertEquals(bitArray.getData().length,1);
}
/**
* Purpose: Check BitArray's data having word size(8)
* Input: input 8 to constructor
* Expected:
* BitArray's data length == 1
*/
@Test
public void testConstructorPositive8() {
BitArray bitArray = new BitArray(8);
assertEquals(bitArray.getData().length,1);
}
/**
* Purpose: Check BitArray's data having size over 8(word size)
* Input: input 9 to constructor
* Expected:
* BitArray's data length == 2
*/
@Test
public void testConstructorPositive9() {
BitArray bitArray = new BitArray(9);
assertEquals(bitArray.getData().length,2);
}
/**
* Purpose: Check BitArray's data having int max size
* Input: input to constructor
* Expected:
* Integer.MAX_VALUE = 2147483647
* 2147483647/8 + 1 = 268435456
* BitArray's data length == 268435456
*/
@Test
public void testConstructorPositiveMax() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
assertEquals(bitArray.getData().length,268435456);
}
/**
* Purpose: Test setBit for 0.
* Input: setBit => 0
* Expected:
* data[0] == 0b1 == 1
*/
@Test
public void testSetBitZero() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(0);
assertEquals(bitArray.getData()[0],1);
}
/**
* Purpose: Test setBit for Positive(1).
* Input: setBit => 1
* Expected:
* data[0] == 0b10 == 2
*/
@Test
public void testSetBit1() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(1);
assertEquals(bitArray.getData()[0],2);
}
/**
* Purpose: Test setBit for Positive(2).
* Input: setBit => 2
* Expected:
* data[0] == 0b100 == 4
*/
@Test
public void testSetBit2() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(2);
assertEquals(bitArray.getData()[0],4);
}
/**
* Purpose: Test setBit for Positive(3).
* Input: setBit => 3
* Expected:
* data[0] == 0b1000 == 8
*/
@Test
public void testSetBit3() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(3);
assertEquals(bitArray.getData()[0],8);
}
/**
* Purpose: Test setBit for Positive(4).
* Input: setBit => 4
* Expected:
* data[0] == 0b10000 == 16
*/
@Test
public void testSetBit4() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(4);
assertEquals(bitArray.getData()[0],16);
}
/**
* Purpose: Test setBit for Positive(5).
* Input: setBit => 5
* Expected:
* data[0] == 0b100000 == 32
*/
@Test
public void testSetBit5() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(5);
assertEquals(bitArray.getData()[0],32);
}
/**
* Purpose: Test setBit for Positive(6).
* Input: setBit => 6
* Expected:
* data[0] == 0b100 0000 == 64
*/
@Test
public void testSetBit6() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(6);
assertEquals(bitArray.getData()[0],64);
}
/**
* Purpose: Test setBit for Positive(7).
* Input: setBit => 7
* Expected:
* data[0] == 0b1000 0000 == -128 (because data[0] is byte.)
*/
@Test
public void testSetBit7() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(7);
assertEquals(bitArray.getData()[0],-128);
}
/**
* Purpose: Test setBit for Positive(8).
* Input: setBit => 8
* Expected:
* data[1] == 0b1 == 1
* data[0] == 0b00000000 == 0
*/
@Test
public void testSetBit8() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(8);
assertEquals(bitArray.getData()[1],1);
assertEquals(bitArray.getData()[0],0);
}
/**
* Purpose: Test setBit for Zero in true branch.
* Input: setBit => (0,true)
* Expected:
* data[0] == 0b1 == 1
*/
@Test
public void testSetBitTrueZero() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(0,true);
assertEquals(bitArray.getData()[0],1);
}
/**
* Purpose: Test setBit for Positive(1) in true branch.
* Input: setBit => (1,true)
* Expected:
* data[0] == 0b10 == 2
*/
@Test
public void testSetBitTrue1() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(1);
assertEquals(bitArray.getData()[0],2);
}
/**
* Purpose: Test setBit for Positive(2) in true branch.
* Input: setBit => (2,true)
* Expected:
* data[0] == 0b100 == 4
*/
@Test
public void testSetBitTrue2() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(2);
assertEquals(bitArray.getData()[0],4);
}
/**
* Purpose: Test setBit for Positive(3) in true branch.
* Input: setBit => (3,true)
* Expected:
* data[0] == 0b1000 == 8
*/
@Test
public void testSetBitTrue3() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(3);
assertEquals(bitArray.getData()[0],8);
}
/**
* Purpose: Test setBit for Positive(4) in true branch.
* Input: setBit => (4,true)
* Expected:
* data[0] == 0b10000 == 16
*/
@Test
public void testSetBitTrue4() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(4);
assertEquals(bitArray.getData()[0],16);
}
/**
* Purpose: Test setBit for Positive(5) in true branch.
* Input: setBit => (5,true)
* Expected:
* data[0] == 0b100000 == 32
*/
@Test
public void testSetBitTrue5() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(5);
assertEquals(bitArray.getData()[0],32);
}
/**
* Purpose: Test setBit for Positive(6) in true branch.
* Input: setBit => (6,true)
* Expected:
* data[0] == 0b100 0000 == 64
*/
@Test
public void testSetBitTrue6() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(6);
assertEquals(bitArray.getData()[0],64);
}
/**
* Purpose: Test setBit for Positive(7) in true branch.
* Input: setBit => (7,true)
* Expected:
* data[0] == 0b1000 0000 == -128 (because data[0] is byte.)
*/
@Test
public void testSetBitTrue7() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(7);
assertEquals(bitArray.getData()[0],-128);
}
/**
* Purpose: Test setBit for Positive(8) in true branch.
* Input: setBit => (8,true)
* Expected:
* data[1] == 0b1 == 1
* data[0] == 0b00000000 == 0
*/
@Test
public void testSetBitTrue8() {
BitArray bitArray = new BitArray(Integer.MAX_VALUE);
bitArray.setBit(8);
assertEquals(bitArray.getData()[1],1);
assertEquals(bitArray.getData()[0],0);
}
/**
* Purpose: Test setBit for Zero in false branch.
* Input: setBit => (0,false)
* Expected:
* data[0] == 0b1111 1110 => -0b0000 0010 == -2
*/
@Test
public void testSetBitFalseZero() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(0,false);
assertEquals(bitArray.getData()[0],-2);
}
/**
* Purpose: Test setBit for Positive(1) in false branch.
* Input: setBit => (1,false)
* Expected:
* data[0] == 0b1111 1101 => -0b0000 0011 == -3
*/
@Test
public void testSetBitFalse1() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(1,false);
assertEquals(bitArray.getData()[0],-3);
}
/**
* Purpose: Test setBit for Positive(2) in false branch.
* Input: setBit => (2,false)
* Expected:
* data[0] == 0b1111 1011 => -0b0000 0101 == -5
*/
@Test
public void testSetBitFalse2() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(2,false);
assertEquals(bitArray.getData()[0],-5);
}
/**
* Purpose: Test setBit for Positive(3) in false branch.
* Input: setBit => (3,false)
* Expected:
* data[0] == 0b1111 0111 => -0b0000 1001 == -9
*/
@Test
public void testSetBitFalse3() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(3,false);
assertEquals(bitArray.getData()[0],-9);
}
/**
* Purpose: Test setBit for Positive(4) in false branch.
* Input: setBit => (4,false)
* Expected:
* data[0] == 0b1110 1111 => -0b0001 0001 == -17
*/
@Test
public void testSetBitFalse4() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(4,false);
assertEquals(bitArray.getData()[0],-17);
}
/**
* Purpose: Test setBit for Positive(5) in false branch.
* Input: setBit => (5,false)
* Expected:
* data[0] == 0b1101 1111 => -0b0010 0001 == -33
*/
@Test
public void testSetBitFalse5() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(5,false);
assertEquals(bitArray.getData()[0],-33);
}
/**
* Purpose: Test setBit for Positive(6) in false branch.
* Input: setBit => (6,true)
* Expected:
* data[0] == 0b1011 1111 => -0b0100 0001 == -65
*/
@Test
public void testSetBitFalse6() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(6,false);
assertEquals(bitArray.getData()[0],-65);
}
/**
* Purpose: Test setBit for Positive(7) in false branch.
* Input: setBit => (7,false)
* Expected:
* data[0] == 0b0111 1111 => 127
*/
@Test
public void testSetBitFalse7() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
//data[0] = 0b1111 1111
bitArray.setBit(7,false);
assertEquals(bitArray.getData()[0],127);
}
/**
* Purpose: Test setBit for Positive(8) in false branch.
* Input: setBit => (8,false)
* Expected:
* data[1] == 0b0000 0000 == 0
* data[0] == 0b1111 1111 => -0b0000 0001 == -1
*/
@Test
public void testSetBitFalse8() {
BitArray bitArray = new BitArray(9);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
bitArray.setBit(8);
//data[1] = 0b0000 0001
//data[0] = 0b1111 1111
bitArray.setBit(8,false);
assertEquals(bitArray.getData()[1],0);
assertEquals(bitArray.getData()[0],-1);
}
/**
* Purpose: Test clear for 1 byte.
* Input: data[0] => 0b1010 0101
* Expected:
* data[0] == 0b0000 0000
*/
@Test
public void testClear1() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0);
bitArray.setBit(2);
bitArray.setBit(5);
bitArray.setBit(7);
//data[0] == 0b1010 0101
bitArray.clear();
assertEquals(bitArray.getData()[0],0);
}
/**
* Purpose: Test clear for 2 byte.
* Input: data[1] => 0b1010 0101 data[0] => 0b1111 1111
* Expected:
* data[1] == 0b0000 0000
* data[0] == 0b0000 0000
*/
@Test
public void testClear2() {
BitArray bitArray = new BitArray(9);
bitArray.setBit(0);
bitArray.setBit(1);
bitArray.setBit(2);
bitArray.setBit(3);
bitArray.setBit(4);
bitArray.setBit(5);
bitArray.setBit(6);
bitArray.setBit(7);
bitArray.setBit(8);
bitArray.setBit(10);
bitArray.setBit(13);
bitArray.setBit(15);
//data[1] == 0b1010 0101
//data[0] == 0b1111 1111
bitArray.clear();
assertEquals(bitArray.getData()[1],0);
assertEquals(bitArray.getData()[0],0);
}
/**
* Purpose: Test setAll in case all bits are 0.
* Input: data[0] => 0b0000 0000
* Expected:
* data[0] == 0b1111 1111 => -0b0000 0001 == -1
*/
@Test
public void testSetAllZero() {
BitArray bitArray = new BitArray(8);
//data[0] == 0b0000 0000
bitArray.setAll();
assertEquals(bitArray.getData()[0],-1);
}
/**
* Purpose: Test setAll for 1 byte.
* Input: data[0] => 0b1010 0101
* Expected:
* data[0] == 0b1111 1111 => -0b0000 0001 == -1
*/
@Test
public void testSetAll1() {
BitArray bitArray = new BitArray(9);
bitArray.setBit(0);
bitArray.setBit(2);
bitArray.setBit(5);
bitArray.setBit(7);
//data[0] == 0b1010 0101
bitArray.setAll();
assertEquals(bitArray.getData()[0],-1);
}
/**
* Purpose: Test setAll for 2 byte.
* Input: data[1] => 0b1010 0101 data[0] => 0b0000 0000
* Expected:
* data[1] == 0b1111 1111 => -0b0000 0001 == -1
* data[0] == 0b1111 1111 => -0b0000 0001 == -1
*/
@Test
public void testSetAll2() {
BitArray bitArray = new BitArray(9);
bitArray.setBit(8);
bitArray.setBit(10);
bitArray.setBit(13);
bitArray.setBit(15);
//data[1] == 1010 0101
//data[0] == 0b0000 0000
bitArray.setAll();
assertEquals(bitArray.getData()[1],-1);
assertEquals(bitArray.getData()[0],-1);
}
/**
* Purpose: Test whether getBit returns false for bit 0.
* Input: getBit => 0
* Expected:
* data[0] == 0b1111 1110
* 0 != 0 => false
*/
@Test
public void testGetBitZero0() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
//data[0] == 0b1111 1110
assertEquals(bitArray.getBit(0),false);
}
/**
* Purpose: Test whether getBit returns false for bit 1.
* Input: getBit => 1
* Expected:
* data[0] == 0b1111 1101
* 0 != 0 => false
*/
@Test
public void testGetBitZero1() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,false);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
//data[0] == 0b1111 1101
assertEquals(bitArray.getBit(1),false);
}
/**
* Purpose: Test whether getBit returns false for bit 2.
* Input: getBit => 2
* Expected:
* data[0] == 0b1111 1011
* 0 != 0 => false
*/
@Test
public void testGetBitZero2() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,false);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
//data[0] == 0b1111 1011
assertEquals(bitArray.getBit(2),false);
}
/**
* Purpose: Test whether getBit returns false for bit 3.
* Input: getBit => 3
* Expected:
* data[0] == 0b1111 0111
* 0 != 0 => false
*/
@Test
public void testGetBitZero3() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,false);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
//data[0] == 0b1111 0111
assertEquals(bitArray.getBit(3),false);
}
/**
* Purpose: Test whether getBit returns false for bit 4.
* Input: getBit => 4
* Expected:
* data[0] == 0b1110 1111
* 0 != 0 => false
*/
@Test
public void testGetBitZero4() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,false);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
//data[0] == 0b1110 1111
assertEquals(bitArray.getBit(4),false);
}
/**
* Purpose: Test whether getBit returns false for bit 5.
* Input: getBit => 5
* Expected:
* data[0] == 0b1101 1111
* 0 != 0 => false
*/
@Test
public void testGetBitZero5() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,false);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
//data[0] == 0b1101 1111
assertEquals(bitArray.getBit(5),false);
}
/**
* Purpose: Test whether getBit returns false for bit 6.
* Input: getBit => 6
* Expected:
* data[0] == 0b1011 1111
* 0 != 0 => false
*/
@Test
public void testGetBitZero6() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,false);
bitArray.setBit(7,true);
//data[0] == 0b0000 0000
assertEquals(bitArray.getBit(6),false);
}
/**
* Purpose: Test whether getBit returns false for bit 7.
* Input: getBit => 7
* Expected:
* data[0] == 0b0111 1111
* 0 != 0 => false
*/
@Test
public void testGetBitZero7() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,false);
//data[0] == 0b0000 0000
assertEquals(bitArray.getBit(7),false);
}
/**
* Purpose: Test whether getBit returns false for bit 8.
* Input: getBit => 8
* Expected:
* data[1] == 0b0000 0000
* data[0] == 0b1111 1111
* 0 != 0 => false
*/
@Test
public void testGetBitZero8() {
BitArray bitArray = new BitArray(9);
bitArray.setBit(0,true);
bitArray.setBit(1,true);
bitArray.setBit(2,true);
bitArray.setBit(3,true);
bitArray.setBit(4,true);
bitArray.setBit(5,true);
bitArray.setBit(6,true);
bitArray.setBit(7,true);
bitArray.setBit(8,false);
//data[1] == 0b0000 0000
//data[0] == 0b1111 1111
assertEquals(bitArray.getBit(8),false);
}
/**
* Purpose: Test whether getBit returns true for bit 0.
* Input: getBit => 0
* Expected:
* data[0] == 0b0000 0001
* 1 != 0 => true
*/
@Test
public void testGetBitOne0() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,true);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
//data[0] == 0b0000 0001
assertEquals(bitArray.getBit(0),true);
}
/**
* Purpose: Test whether getBit returns true for bit 1.
* Input: getBit => 1
* Expected:
* data[0] == 0b0000 0010
* 1 != 0 => true
*/
@Test
public void testGetBitOne1() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,true);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
//data[0] == 0b0000 0010
assertEquals(bitArray.getBit(1),true);
}
/**
* Purpose: Test whether getBit returns true for bit 2.
* Input: getBit => 2
* Expected:
* data[0] == 0b0000 0100
* 1 != 0 => true
*/
@Test
public void testGetBitOne2() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,true);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
//data[0] == 0b0000 0100
assertEquals(bitArray.getBit(2),true);
}
/**
* Purpose: Test whether getBit returns true for bit 3.
* Input: getBit => 3
* Expected:
* data[0] == 0b0000 1000
* 1 != 0 => true
*/
@Test
public void testGetBitOne3() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,true);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
//data[0] == 0b0000 1000
assertEquals(bitArray.getBit(3),true);
}
/**
* Purpose: Test whether getBit returns true for bit 4.
* Input: getBit => 4
* Expected:
* data[0] == 0b0001 0000
* 1 != 0 => true
*/
@Test
public void testGetBitOne4() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,true);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
//data[0] == 0b0001 0000
assertEquals(bitArray.getBit(4),true);
}
/**
* Purpose: Test whether getBit returns true for bit 5.
* Input: getBit => 5
* Expected:
* data[0] == 0b0010 0000
* 1 != 0 => true
*/
@Test
public void testGetBitOne5() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,true);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
//data[0] == 0b0010 0000
assertEquals(bitArray.getBit(5),true);
}
/**
* Purpose: Test whether getBit returns true for bit 6.
* Input: getBit => 6
* Expected:
* data[0] == 0b0001 0000
* 1 != 0 => true
*/
@Test
public void testGetBitOne6() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,true);
bitArray.setBit(7,false);
//data[0] == 0b0100 0000
assertEquals(bitArray.getBit(6),true);
}
/**
* Purpose: Test whether getBit returns true for bit 6.
* Input: getBit => 6
* Expected:
* data[0] == 0b1000 0000
* 1 != 0 => true
*/
@Test
public void testGetBitOne7() {
BitArray bitArray = new BitArray(8);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,true);
//data[0] == 0b1000 0000
assertEquals(bitArray.getBit(7),true);
}
/**
* Purpose: Test whether getBit returns true for bit 8.
* Input: getBit => 8
* Expected:
* data[1] == 0b0000 0001
* data[0] == 0b0000 0000
* 1 != 0 => true
*/
@Test
public void testGetBitOne8() {
BitArray bitArray = new BitArray(9);
bitArray.setBit(0,false);
bitArray.setBit(1,false);
bitArray.setBit(2,false);
bitArray.setBit(3,false);
bitArray.setBit(4,false);
bitArray.setBit(5,false);
bitArray.setBit(6,false);
bitArray.setBit(7,false);
bitArray.setBit(8,true);
//data[1] == 0b0000 0001
//data[0] == 0b0000 0000
assertEquals(bitArray.getBit(8),true);
}
}
| 29,829 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ByteBufferIOBufferTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/harenet/ByteBufferIOBufferTest.java | /*
* see license.txt
*/
package test.harenet;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import org.junit.Test;
import harenet.ByteBufferIOBuffer;
import harenet.IOBuffer;
import harenet.Protocol;
import harenet.messages.ConnectionAcceptedMessage;
import harenet.messages.ConnectionRequestMessage;
import harenet.messages.NetMessage;
import harenet.messages.NetMessageFactory;
/**
* @author Tony
*
*/
public class ByteBufferIOBufferTest {
@Test
public void test() {
IOBuffer writeBuffer = IOBuffer.Factory.allocate(1500);
Protocol writeProtocol = new Protocol(-1, 1500);
Protocol readProtocol = new Protocol(-1, 1500);
IOBuffer readBuffer = IOBuffer.Factory.allocate(1500);
int attempts = 3;
while(attempts --> 0) {
writeProtocol.reset();
writeBuffer.position(writeProtocol.size());
writeProtocol.setPeerId((byte)10);
writeProtocol.setAckHistory(0xff);
writeProtocol.setAcknowledge(4*attempts);
writeProtocol.setNumberOfMessages( (byte)attempts);
writeProtocol.setSendSequence(12);
writeProtocol.writeTo(writeBuffer);
writeBuffer.putInt(attempts);
writeBuffer.putByte( (byte) 5);
writeBuffer.putByteBits( (byte)12, 6);
writeBuffer.putInt(attempts);
//writeBuffer.flip();
//~~~~~~~~~ sent packet
ByteBuffer out = writeBuffer.sendSync().asByteBuffer();
out.flip();
// send buffer to socket
//~~~~~~~~~
//~~~~~~~~~ receive packet
ByteBuffer in = readBuffer.clear().asByteBuffer();
in.clear();
// read buffer from socket
in.put(out.array(), 0, out.limit());
in.flip();
readBuffer.receiveSync();
///~~~~~~~~~~~~
readProtocol.reset();
readProtocol.readFrom(readBuffer, new NetMessageFactory() {
@Override
public NetMessage readNetMessage(IOBuffer buffer) {
return null;
}
});
assertEquals(writeProtocol.getPeerId(), readProtocol.getPeerId());
assertEquals(writeProtocol.getAckHistory(), readProtocol.getAckHistory());
assertEquals(writeProtocol.getAcknowledge(), readProtocol.getAcknowledge());
assertEquals(writeProtocol.getNumberOfMessages(), readProtocol.getNumberOfMessages());
assertEquals(writeProtocol.getSendSequence(), readProtocol.getSendSequence());
assertEquals(attempts, readBuffer.getInt());
assertEquals( (byte) 5, readBuffer.getByte());
assertEquals( (byte) 12, readBuffer.getByteBits(6));
assertEquals(attempts, readBuffer.getInt());
}
}
@Test
public void testShort() {
IOBuffer writeBuffer = IOBuffer.Factory.allocate(1500);
writeBuffer.putIntBits( 8189, 13);
writeBuffer.flip();
int value = writeBuffer.getIntBits(13);// & (short)0b111111111111;
assertEquals(8189, value);
}
@Test
public void testLong() {
IOBuffer writeBuffer = IOBuffer.Factory.allocate(1500);
long value = 0xf123a4234ac5af21L;
writeBuffer.putLong(value);
writeBuffer.flip();
long outputValue = writeBuffer.getLong();
assertEquals(value, outputValue);
}
@Test
public void testDouble() {
IOBuffer writeBuffer = IOBuffer.Factory.allocate(1500);
double value = 0xf123a4234ac5af21L;
writeBuffer.putDouble(value);
writeBuffer.flip();
double outputValue = writeBuffer.getDouble();
System.out.println("output: " + Double.toHexString(outputValue));
System.out.println("given: " + Double.toHexString(value));
assertEquals(value, outputValue, 0.001D);
}
}
| 4,117 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.