Skip to content

Commit

Permalink
Merge pull request #42 from Leg0shii/astart-pathfinding-optimization
Browse files Browse the repository at this point in the history
add InfoWindow + bugfix for end block detection
  • Loading branch information
Leg0shii authored Dec 20, 2024
2 parents 0036475 + d760169 commit 0a2a9b8
Show file tree
Hide file tree
Showing 7 changed files with 222 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public InputTick getNextTick() {
}

private float generateFacing() {
float facing = 0;
float facing = 0.0F;
if (random.nextDouble() < fChangeProb) {
facing = new Random().nextFloat(361) - 180;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
public class Bruteforcer implements Runnable {

private static final Logger logger = LogManager.getLogger(Bruteforcer.class.getName());
@Getter private final UUID uuid = UUID.randomUUID();

@Getter private HashMap<Vec3, List<InputTick>> ticksMap = new HashMap<>();
@Getter private List<InputTick> currentFastestSolution = new ArrayList<>();
Expand All @@ -33,10 +34,11 @@ public class Bruteforcer implements Runnable {
@Getter private boolean isActive;
private long startTime;

private int longestElement;
@Getter private int tickGeneration;
@Getter private int longestElement;
@Getter @Setter private int iterationCount;
@Setter private int lowestBound;
@Setter private int highestBound;
@Getter @Setter private int lowestBound;
@Getter @Setter private int highestBound;

private final MultiThreadBruteforcer instance;
private Parkour parkour;
Expand All @@ -50,7 +52,7 @@ public Bruteforcer(Parkour parkour, MultiThreadBruteforcer multiThreadBruteforce

@Override
public void run() {
logger.debug("Started bruteforcer instance. " + this);
logger.debug("Started bruteforcer instance. {}", this);
this.parkour = parkour.clone();
this.clearBruteforce();
this.findPath();
Expand All @@ -60,6 +62,10 @@ protected synchronized void syncMap(ConcurrentHashMap<Vec3, List<InputTick>> map
this.ticksMap = new HashMap<>(map);
}

protected synchronized void syncCFS(List<InputTick> solution) {
setCurrentFastestSolution(solution);
}

protected void cancelBruteforce() {
if (isActive) {
isActive = false;
Expand Down Expand Up @@ -87,6 +93,7 @@ private void findPath() {
inputTicks = new ArrayList<>(nthEntry);
startIndex = inputTicks.size();
}
this.tickGeneration = startIndex;

for (int j = 0; j < bruteforceOptions.getTicksPerTrial(); j++) {
inputTicks.add(inputGenerator.getNextTick());
Expand All @@ -99,7 +106,7 @@ private void findPath() {
}
}
} catch (Exception e) {
logger.error("An error occurred in findPath: " + e.getMessage(), e);
logger.error("An error occurred in findPath: {}", e.getMessage(), e);
} finally {
this.isActive = false;
}
Expand Down Expand Up @@ -146,16 +153,15 @@ private void saveInputs(List<Vec3> boundaries, List<InputTick> inputTicks, int s
}
}

Vec3 possibleLBPos = roundedVec.copy();
possibleLBPos.y--;
ABlock possibleLB = parkour.getBlockManager().getBlock(possibleLBPos);
List<Vec3> endBlockBounds = new ArrayList<>();
endBlockBounds.add(endBlock.getVec3());

if (!(possibleLB instanceof Air) && possibleLB.getVec3().equals(endBlock.getVec3())) {
if (isInsideBoundaries(endBlockBounds, unRoundedVec)) {
List<InputTick> shrinkList = new ArrayList<>(inputTicks.subList(0, count));
if ((currentFastestSolution.isEmpty() || shrinkList.size() < currentFastestSolution.size())) {
instance.mergeFastestSolution(shrinkList);
logger.debug("New Solution with " + currentFastestSolution.size() + " ticks. Found in: "
+ ((System.currentTimeMillis() - startTime)) + "ms");
// instance.mergeFastestSolution(shrinkList);
this.currentFastestSolution = new ArrayList<>(shrinkList);
logger.debug("New Solution with {} ticks. Found in: {}ms", currentFastestSolution.size(), System.currentTimeMillis() - startTime);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package de.legoshi.parkourcalculator.ai.bruteforcer;

import de.legoshi.parkourcalculator.Application;
import de.legoshi.parkourcalculator.gui.debug.menu.InfoWindow;
import de.legoshi.parkourcalculator.simulation.Parkour;
import de.legoshi.parkourcalculator.ai.AStarPathfinder;
import de.legoshi.parkourcalculator.ai.BruteforceOptions;
Expand Down Expand Up @@ -36,6 +37,9 @@ public class MultiThreadBruteforcer {
private final InputTickGUI inputTickGUI;
private final InputTickManager inputTickManager;

private final InfoWindow infoWindow;
private long started;

private final List<Bruteforcer> bruteforcers;
private final List<BruteforceOptions> bruteforceOptions;
private final List<InputGenerator> inputGenerators;
Expand All @@ -61,6 +65,7 @@ public MultiThreadBruteforcer(Application application, List<Vec3> boundaries) {
this.bruteforceOptions = new ArrayList<>();
this.inputGenerators = new ArrayList<>();
this.boundaries = boundaries;
this.infoWindow = new InfoWindow();

this.aStarPathfinder = new AStarPathfinder(application.getParkour(), application.getMinecraftGUI());
this.aStarPathfinder.setColorize(true);
Expand All @@ -85,20 +90,25 @@ public void calculateBoundaries(Vec3 start, Vec3 end) {
this.boundaries.addAll(aStarPathfinder.calculateBoundaries(start, end));
}

public void cancelBruteforce() {
private void shutdown() {
bruteforcers.forEach(Bruteforcer::cancelBruteforce);
endRun();
if (bfService != null) bfService.shutdown();
if (scheduler != null) scheduler.shutdown();
if (mainService != null) mainService.shutdown();
if (infoWindow != null) infoWindow.updateStatus("Ended");
}

public void endRun() {
syncAllToMain();
shutdown();
showResult();
}

public void clearAll() {
if (mainService != null && !mainService.isShutdown()) {
mainService.shutdownNow();
}
if (scheduler != null && !scheduler.isShutdown()) {
scheduler.shutdownNow();
}
if (bfService != null && !bfService.isShutdown()) {
bfService.shutdownNow();
shutdown();
if (infoWindow != null) {
infoWindow.close();
infoWindow.getBruteforcerMap().clear();
}

this.lowestBound = 0;
Expand All @@ -117,6 +127,13 @@ public void start() {
scheduler = Executors.newSingleThreadScheduledExecutor();
bfService = Executors.newCachedThreadPool();

started = System.currentTimeMillis();

infoWindow.setBFOptions(bruteforceOptions.get(0));
infoWindow.show();
infoWindow.clearWindow();
infoWindow.updateStatus("Running");

mainService.submit(() -> {
try {
buildBruteforcer();
Expand All @@ -127,6 +144,7 @@ public void start() {
for (Bruteforcer bruteforcer : bruteforcers) {
bruteforcer.setBoundaries(boundaries);
bfService.submit(bruteforcer);
infoWindow.addBruteforcer(bruteforcer.getUuid().toString());
}

scheduler.scheduleAtFixedRate(() -> {
Expand All @@ -148,6 +166,7 @@ public void start() {

scheduler.scheduleAtFixedRate(this::syncAllToMain, SYNC_INTERVAL, SYNC_INTERVAL, TimeUnit.SECONDS);
scheduler.scheduleAtFixedRate(this::showUpdate, SHOW_INTERVAL, SHOW_INTERVAL, TimeUnit.MILLISECONDS);
scheduler.scheduleAtFixedRate(this::updateInfoWindow, 1, 1, TimeUnit.SECONDS);
});
}

Expand Down Expand Up @@ -193,6 +212,8 @@ private void showUpdate() {

private void showResult() {
logger.debug("Setting current fastest solution: {}", currentFastestSolution.size());
if (currentFastestSolution.isEmpty()) return;

Platform.runLater(() -> {
inputTickGUI.clearAllTicks();
inputTickManager.setInputTicks(currentFastestSolution);
Expand All @@ -215,7 +236,38 @@ private void syncAllToMain() {
currentFastestSolution = new ArrayList<>(bruteforcer.getCurrentFastestSolution());
}
}

bruteforcers.forEach(bf -> bf.syncMap(ticksMap));
bruteforcers.forEach(bf -> bf.syncCFS(currentFastestSolution));
}

private void updateInfoWindow() {
infoWindow.updateTimePassed("" + (System.currentTimeMillis() - started) / 1000);
infoWindow.updateGlobalBest("" + currentFastestSolution.size());

long nextSync = SYNC_INTERVAL - (((System.currentTimeMillis() - started) / 1000) % SYNC_INTERVAL);
infoWindow.updateNextSync("" + (nextSync - 1));

for (Bruteforcer bf : bruteforcers) {
long nextIntervall = TICK_INTERVAL - (((System.currentTimeMillis() - started) / 1000) % TICK_INTERVAL);
int lower, upper;
lower = 0;
if (bruteforceOptions.get(0).isWindowed()) {
lower = bf.getLowestBound();
upper = bf.getHighestBound();
} else {
lower = Math.max(lower, bf.getLongestElement() - bruteforceOptions.get(0).getRecTicks());
upper = bf.getLongestElement();
}

infoWindow.updateBruteforcer(
bf.getUuid().toString(),
"" + bf.getTickGeneration(),
lower + " - " + upper,
"" + (nextIntervall - 1),
"" + bf.getCurrentFastestSolution().size()
);
}
}

private boolean setIterationCount() {
Expand Down Expand Up @@ -258,16 +310,6 @@ private void calculateTickBounds() {
}
}

private void endRun() {
syncAllToMain();

bfService.shutdown();
scheduler.shutdownNow();
mainService.shutdownNow();

showResult();
}

private boolean isAllDone() {
for (Bruteforcer bruteforcer : bruteforcers) {
if (bruteforcer.isActive()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ private void createTextFieldComponents() {
this.intervallOfLastShownField = addUIPair("Show Path:", new TextField("100"), 0, 1, 10);

this.recTicksField = addUIPair("Recursive:", new TextField("100"), 2, 3, 2);
this.recTicksField.setDisable(true);

this.syncField = addUIPair("Sync (s):", new TextField("5"), 2, 3, 3);
this.instancesField = addUIPair("Instance:", new TextField("5"), 2, 3, 4);
this.overlapField = addUIPair("Overlap (t):", new TextField("20"), 2, 3, 9);
Expand All @@ -128,7 +130,7 @@ private void createButtonComponents() {
this.removePathButton = addButton(new Button("Remove Path"), 2, 16, 2);

this.bruteforceButton = addButton(new Button("Bruteforce"), 0, 17, 1);
this.cancelButton = addButton(new Button("Cancel"), 1, 17, 1);
this.cancelButton = addButton(new Button("Stop"), 1, 17, 1);
this.resetAllButton = addButton(new Button("Reset ALL"), 2, 17, 2);
}

Expand Down Expand Up @@ -267,7 +269,7 @@ private void onStartBlockClick() {
}

private void cancelBruteforce() {
multiThreadBruteforcer.cancelBruteforce();
multiThreadBruteforcer.endRun();
}

private <T extends Node> T addUIPair(String labelName, T node, int column1, int column2, int row) {
Expand Down
Loading

0 comments on commit 0a2a9b8

Please sign in to comment.