Created
July 27, 2021 23:37
-
-
Save tstone/fee1f58caf9258937bd7eefc7e27802a to your computer and use it in GitHub Desktop.
Timer for VM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.collidermodular.util; | |
public class Timer { | |
private final double samplesPerMs; | |
private final Runnable runnable; | |
private double duration; | |
private double sampleCounter; | |
private double targetSampleCount; | |
private boolean active; | |
private boolean loop = false; | |
public Timer(double duration, double samplesPerMs, Runnable runnable) { | |
this.runnable = runnable; | |
this.samplesPerMs = samplesPerMs; | |
this.setDuration(duration); | |
this.reset(); | |
} | |
public double getDuration() { return this.duration; } | |
public double getDurationRemaining() { | |
if (this.active) { | |
double samplesRem = targetSampleCount - sampleCounter; | |
return samplesRem / samplesPerMs; | |
} else { | |
return 0.0; | |
} | |
} | |
public boolean isActive() { return this.active; } | |
public void setDuration(double duration) { | |
this.duration = duration; | |
this.targetSampleCount = samplesPerMs * duration; | |
} | |
public void trigger() { | |
this.reset(); | |
this.active = true; | |
} | |
public void startLoop() { | |
this.runnable.run(); | |
this.loop = true; | |
this.trigger(); | |
} | |
public void stopLoop() { | |
this.loop = false; | |
this.reset(); | |
} | |
public void reset() { | |
this.sampleCounter = 0; | |
this.active = false; | |
} | |
public void processSample() { | |
if (this.active) { | |
this.sampleCounter += 1; | |
if (sampleCounter >= targetSampleCount) { | |
this.runnable.run(); | |
if (this.loop) { | |
// carry over remainder for more accurate timing between samples | |
this.sampleCounter = this.sampleCounter - targetSampleCount; | |
} else { | |
this.reset(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment