Moved isLoaded to BaseResource. Loading and unloading will still be overridden if necessary. Added some subclass/super safe load and unload functions.

This commit is contained in:
2025-10-01 00:06:46 +02:00
parent d432887860
commit d661e0d4b5
2 changed files with 20 additions and 21 deletions

View File

@@ -16,33 +16,38 @@ public abstract class BaseResource {
return this.isLoaded; return this.isLoaded;
} }
public void load() throws FileNotFoundException{ public void load() throws FileNotFoundException {
this.loadRawData();
isLoaded = true;
}
private void loadRawData() throws FileNotFoundException{
try { try {
this.rawData = Files.readAllBytes(file.toPath()); this.rawData = Files.readAllBytes(file.toPath());
isLoaded = true;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public void unload() { public void unload(){
this.unloadRawData();
isLoaded = false;
}
private void unloadRawData() {
this.rawData = null; this.rawData = null;
this.isLoaded = false;
} }
public File getFile() { public File getFile() {
return this.file; return this.file;
} }
public InputStream getInputStream() { public InputStream getInputStream() throws FileNotFoundException {
if (!isLoaded){ if (!isLoaded){
try { // Manually load the data, makes sure it doesn't call subclass load()
this.load(); loadRawData();
} catch (FileNotFoundException e) { isLoaded = true;
throw new RuntimeException(e);
}
} }
return new BufferedInputStream(new ByteArrayInputStream(this.rawData)); return new BufferedInputStream(new ByteArrayInputStream(this.rawData));
} }
} }

View File

@@ -6,7 +6,6 @@ import java.io.FileNotFoundException;
public class ImageAsset extends BaseResource implements LoadableResource { public class ImageAsset extends BaseResource implements LoadableResource {
private Image image; private Image image;
private boolean isLoaded = false;
public ImageAsset(final File file) throws FileNotFoundException { public ImageAsset(final File file) throws FileNotFoundException {
super(file); super(file);
@@ -14,25 +13,20 @@ public class ImageAsset extends BaseResource implements LoadableResource {
@Override @Override
public void load() throws FileNotFoundException { public void load() throws FileNotFoundException {
if (!this.isLoaded) { if (!this.isLoaded()) {
super.load(); // Make sure that base class (byte[]) is loaded
this.image = new Image(this.getInputStream()); this.image = new Image(this.getInputStream());
this.isLoaded = true;
} }
} }
@Override @Override
public void unload() { public void unload() {
this.image = null; this.image = null;
this.isLoaded = false; super.unload();
}
@Override
public boolean isLoaded() {
return this.isLoaded;
} }
public Image getImage() { public Image getImage() {
if (!this.isLoaded) try { if (!this.isLoaded()) try {
load(); load();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);