Automatic code cleanup

This commit is contained in:
Andrea Cavalli 2018-05-12 21:18:29 +02:00
parent d379f8a318
commit 5d585a9ad6
91 changed files with 1257 additions and 1277 deletions

View File

@ -31,7 +31,8 @@ import java.nio.file.ProviderNotFoundException;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
/** /**
* A simple library class which helps with loading dynamic libraries stored in the * A simple library class which helps with loading dynamic libraries stored in
* the
* JAR archive. These libraries usualy contain implementation of some methods in * JAR archive. These libraries usualy contain implementation of some methods in
* native code (using JNI - Java Native Interface). * native code (using JNI - Java Native Interface).
* *
@ -40,106 +41,112 @@ import java.nio.file.StandardCopyOption;
* *
*/ */
public class NativeUtils { public class NativeUtils {
/**
* The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}.
*/
private static final int MIN_PREFIX_LENGTH = 3;
/** /**
* Temporary directory which will contain the DLLs. * The minimum length a prefix for a file has to have according to
*/ * {@link File#createTempFile(String, String)}}.
private static File temporaryDir; */
private static final int MIN_PREFIX_LENGTH = 3;
/** /**
* Private constructor - this class will never be instanced * Temporary directory which will contain the DLLs.
*/ */
private NativeUtils() { private static File temporaryDir;
}
/** /**
* Loads library from current JAR archive * Private constructor - this class will never be instanced
* */
* The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after private NativeUtils() {}
* exiting.
* Method uses String as filename because the pathname is "abstract", not system-dependent.
*
* @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
* @throws IOException If temporary file creation or read/write operation fails
* @throws IllegalArgumentException If source file (param path) does not exist
* @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters
* (restriction of {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException If the file could not be found inside the JAR.
*/
public static void loadLibraryFromJar(String path) throws IOException {
if (!path.startsWith("/")) {
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
}
// Obtain filename from path
String[] parts = path.split("/");
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
// Check if the filename is okay
if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
}
// Prepare temporary file
if (temporaryDir == null) {
temporaryDir = createTempDirectory("nativeutils");
temporaryDir.deleteOnExit();
}
File temp = new File(temporaryDir, filename); /**
* Loads library from current JAR archive
*
* The file from JAR is copied into system temporary directory and then
* loaded. The temporary file is deleted after
* exiting.
* Method uses String as filename because the pathname is "abstract", not
* system-dependent.
*
* @param path
* The path of file inside JAR as absolute path (beginning with
* '/'), e.g. /package/File.ext
* @throws IOException
* If temporary file creation or read/write operation fails
* @throws IllegalArgumentException
* If source file (param path) does not exist
* @throws IllegalArgumentException
* If the path is not absolute or if the filename is shorter
* than three characters
* (restriction of
* {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException
* If the file could not be found inside the JAR.
*/
public static void loadLibraryFromJar(String path) throws IOException {
try (InputStream is = NativeUtils.class.getResourceAsStream(path)) { if (!path.startsWith("/")) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING); throw new IllegalArgumentException("The path has to be absolute (start with '/').");
} catch (IOException e) { }
temp.delete();
throw e;
} catch (NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}
try { // Obtain filename from path
System.load(temp.getAbsolutePath()); final String[] parts = path.split("/");
} finally { final String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
if (isPosixCompliant()) {
// Assume POSIX compliant file system, can be deleted after loading
temp.delete();
} else {
// Assume non-POSIX, and don't delete until last file descriptor closed
temp.deleteOnExit();
}
}
}
private static boolean isPosixCompliant() { // Check if the filename is okay
try { if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
if (FileSystems.getDefault() throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
.supportedFileAttributeViews() }
.contains("posix")) {
return true; // Prepare temporary file
} if (temporaryDir == null) {
return false; temporaryDir = createTempDirectory("nativeutils");
} catch (FileSystemNotFoundException temporaryDir.deleteOnExit();
| ProviderNotFoundException }
| SecurityException e) {
return false; final File temp = new File(temporaryDir, filename);
}
} try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
private static File createTempDirectory(String prefix) throws IOException } catch (final IOException e) {
{ temp.delete();
String tempDir = System.getProperty("java.io.tmpdir"); throw e;
File generatedDir = new File(tempDir, prefix + System.nanoTime()); } catch (final NullPointerException e) {
temp.delete();
if (!generatedDir.mkdir()) throw new FileNotFoundException("File " + path + " was not found inside JAR.");
throw new IOException("Failed to create temp directory " + generatedDir.getName()); }
return generatedDir; try {
} System.load(temp.getAbsolutePath());
} finally {
if (isPosixCompliant()) {
// Assume POSIX compliant file system, can be deleted after loading
temp.delete();
} else {
// Assume non-POSIX, and don't delete until last file descriptor closed
temp.deleteOnExit();
}
}
}
private static boolean isPosixCompliant() {
try {
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
return true;
}
return false;
} catch (FileSystemNotFoundException | ProviderNotFoundException | SecurityException e) {
return false;
}
}
private static File createTempDirectory(String prefix) throws IOException {
final String tempDir = System.getProperty("java.io.tmpdir");
final File generatedDir = new File(tempDir, prefix + System.nanoTime());
if (!generatedDir.mkdir()) {
throw new IOException("Failed to create temp directory " + generatedDir.getName());
}
return generatedDir;
}
} }

View File

@ -1,12 +1,5 @@
package org.warp.picalculator; package org.warp.picalculator;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.warp.picalculator.device.Keyboard; import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.PIHardwareDisplay; import org.warp.picalculator.device.PIHardwareDisplay;
import org.warp.picalculator.gui.CalculatorHUD; import org.warp.picalculator.gui.CalculatorHUD;
@ -23,6 +16,7 @@ import com.pi4j.wiringpi.Gpio;
public class Main { public class Main {
public static Main instance; public static Main instance;
public static String[] args; public static String[] args;
public Main(String[] args) throws InterruptedException, Error { public Main(String[] args) throws InterruptedException, Error {
this(new LoadingScreen(), new PIHardwareDisplay(), new CalculatorHUD(), args); this(new LoadingScreen(), new PIHardwareDisplay(), new CalculatorHUD(), args);
} }
@ -52,7 +46,7 @@ public class Main {
boolean isRaspi = false; boolean isRaspi = false;
try { try {
isRaspi = com.pi4j.system.SystemInfo.getBoardType() != BoardType.UNKNOWN; isRaspi = com.pi4j.system.SystemInfo.getBoardType() != BoardType.UNKNOWN;
} catch (Exception e) {} } catch (final Exception e) {}
if (Utils.isRunningOnRaspberry() && !Utils.isInArray("-noraspi", args) && isRaspi) { if (Utils.isRunningOnRaspberry() && !Utils.isInArray("-noraspi", args) && isRaspi) {
Gpio.wiringPiSetupPhys(); Gpio.wiringPiSetupPhys();
Gpio.pinMode(12, Gpio.PWM_OUTPUT); Gpio.pinMode(12, Gpio.PWM_OUTPUT);
@ -61,7 +55,7 @@ public class Main {
StaticVars.debugOn = true; StaticVars.debugOn = true;
} }
Utils.debugThirdScreen = StaticVars.debugOn & false; Utils.debugThirdScreen = StaticVars.debugOn & false;
for (String arg : args) { for (final String arg : args) {
if (arg.contains("2x")) { if (arg.contains("2x")) {
StaticVars.debugWindow2x = true; StaticVars.debugWindow2x = true;
} }

View File

@ -1,13 +1,12 @@
package org.warp.picalculator; package org.warp.picalculator;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
public class MmapByteBuffer { public class MmapByteBuffer {
private int fd; private final int fd;
private int address; private final int address;
private int length; private final int length;
private ByteBuffer buffer; private final ByteBuffer buffer;
public MmapByteBuffer(int fd, int address, int length, ByteBuffer buffer) { public MmapByteBuffer(int fd, int address, int length, ByteBuffer buffer) {
this.fd = fd; this.fd = fd;
@ -19,15 +18,15 @@ public class MmapByteBuffer {
public int getFd() { public int getFd() {
return fd; return fd;
} }
public int getAddress() { public int getAddress() {
return address; return address;
} }
public int getLength() { public int getLength() {
return length; return length;
} }
public ByteBuffer getBuffer() { public ByteBuffer getBuffer() {
return buffer; return buffer;
} }

View File

@ -10,13 +10,13 @@ public class ScriptUtils {
} }
public static LinkedList<BigInteger> mcm(LinkedList<BigInteger> factors1, LinkedList<BigInteger> factors2) { public static LinkedList<BigInteger> mcm(LinkedList<BigInteger> factors1, LinkedList<BigInteger> factors2) {
LinkedList<BigInteger> mcm = new LinkedList<>(); final LinkedList<BigInteger> mcm = new LinkedList<>();
Iterator<BigInteger> i1 = factors1.iterator(); final Iterator<BigInteger> i1 = factors1.iterator();
while(i1.hasNext()) { while (i1.hasNext()) {
BigInteger int1 = i1.next(); final BigInteger int1 = i1.next();
Iterator<BigInteger> i2 = factors2.iterator(); final Iterator<BigInteger> i2 = factors2.iterator();
while(i2.hasNext()) { while (i2.hasNext()) {
BigInteger int2 = i2.next(); final BigInteger int2 = i2.next();
if (int1.equals(int2)) { if (int1.equals(int2)) {
i1.remove(); i1.remove();
i2.remove(); i2.remove();

View File

@ -14,9 +14,9 @@ public class StaticVars {
public static boolean debugWindow2x = false; public static boolean debugWindow2x = false;
public static Class<?> classLoader; public static Class<?> classLoader;
public static float windowZoom = 2; public static float windowZoom = 2;
private StaticVars() { private StaticVars() {
} }
public static float getCurrentZoomValue() { public static float getCurrentZoomValue() {

View File

@ -115,7 +115,7 @@ public class TestGPU {
break; break;
} }
return false; return false;
} catch (Exception ex) { } catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return false; return false;

View File

@ -2,12 +2,11 @@ package org.warp.picalculator;
import org.warp.picalculator.MmapByteBuffer; import org.warp.picalculator.MmapByteBuffer;
public class TestJNI { public class TestJNI {
public TestJNI() { public TestJNI() {
} }
static { static {
System.load("/boot/libpicalc.so"); System.load("/boot/libpicalc.so");
} }
@ -19,7 +18,7 @@ public class TestJNI {
public MmapByteBuffer retrieveBuffer() { public MmapByteBuffer retrieveBuffer() {
return getDisplayBuffer(); return getDisplayBuffer();
} }
public void deleteBuffer() { public void deleteBuffer() {
disposeDisplayBuffer(); disposeDisplayBuffer();
} }

View File

@ -77,46 +77,29 @@ public class Utils {
public static boolean msDosMode; public static boolean msDosMode;
public static boolean debugCache; public static boolean debugCache;
public static boolean newtMode = true; public static boolean newtMode = true;
public static final class AdvancedOutputStream extends StringWriter { public static final class AdvancedOutputStream extends StringWriter {
private void print(PrintStream stream, String str) { private void print(PrintStream stream, String str) {
stream.print(fixString(str)); stream.print(fixString(str));
} }
private void println(PrintStream stream, String str) { private void println(PrintStream stream, String str) {
stream.println(fixString(str)); stream.println(fixString(str));
} }
private void println(PrintStream stream) { private void println(PrintStream stream) {
stream.println(); stream.println();
} }
private String fixString(String str) { private String fixString(String str) {
return str return str.replace("" + MathematicalSymbols.NTH_ROOT, "root").replace("" + MathematicalSymbols.SQUARE_ROOT, "sqrt").replace("" + MathematicalSymbols.POWER, "powerOf").replace("" + MathematicalSymbols.POWER_OF_TWO, "powerOfTwo").replace("" + MathematicalSymbols.SINE, "sine").replace("" + MathematicalSymbols.COSINE, "cosine").replace("" + MathematicalSymbols.TANGENT, "tangent").replace("" + MathematicalSymbols.ARC_SINE, "asin").replace("" + MathematicalSymbols.ARC_COSINE, "acos").replace("" + MathematicalSymbols.ARC_TANGENT, "atan").replace("" + MathematicalSymbols.UNDEFINED, "undefined").replace("" + MathematicalSymbols.PI, "PI").replace("" + MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER").replace("" + MathematicalSymbols.X, "X").replace("" + MathematicalSymbols.Y, "Y");
.replace(""+MathematicalSymbols.NTH_ROOT, "root")
.replace(""+MathematicalSymbols.SQUARE_ROOT, "sqrt")
.replace(""+MathematicalSymbols.POWER, "powerOf")
.replace(""+MathematicalSymbols.POWER_OF_TWO, "powerOfTwo")
.replace(""+MathematicalSymbols.SINE, "sine")
.replace(""+MathematicalSymbols.COSINE, "cosine")
.replace(""+MathematicalSymbols.TANGENT, "tangent")
.replace(""+MathematicalSymbols.ARC_SINE, "asin")
.replace(""+MathematicalSymbols.ARC_COSINE, "acos")
.replace(""+MathematicalSymbols.ARC_TANGENT, "atan")
.replace(""+MathematicalSymbols.UNDEFINED, "undefined")
.replace(""+MathematicalSymbols.PI, "PI")
.replace(""+MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER")
.replace(""+MathematicalSymbols.X, "X")
.replace(""+MathematicalSymbols.Y, "Y")
;
} }
public void println(String str) { public void println(String str) {
println(0, str); println(0, str);
} }
public void println(int level) { public void println(int level) {
if (StaticVars.outputLevel >= level) { if (StaticVars.outputLevel >= level) {
@ -133,9 +116,9 @@ public class Utils {
if (StaticVars.outputLevel >= level) { if (StaticVars.outputLevel >= level) {
final String time = getTimeString(); final String time = getTimeString();
if (StaticVars.outputLevel == 0) { if (StaticVars.outputLevel == 0) {
println(System.out, "[" + time + "]"+str); println(System.out, "[" + time + "]" + str);
} else { } else {
println(System.out, "[" + time + "]"+str); println(System.out, "[" + time + "]" + str);
} }
} }
} }
@ -179,7 +162,7 @@ public class Utils {
} }
} }
} }
private String getTimeString() { private String getTimeString() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); return LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
} }
@ -809,29 +792,29 @@ public class Utils {
} }
public static <T> ObjectArrayList<T> newArrayList(T o) { public static <T> ObjectArrayList<T> newArrayList(T o) {
ObjectArrayList<T> t = new ObjectArrayList<T>(); final ObjectArrayList<T> t = new ObjectArrayList<>();
t.add(o); t.add(o);
return t; return t;
} }
public static Path getResource(String string) throws IOException, URISyntaxException { public static Path getResource(String string) throws IOException, URISyntaxException {
URL res = Main.instance.getClass().getResource(string); final URL res = Main.instance.getClass().getResource(string);
boolean isResource = res != null; final boolean isResource = res != null;
if (isResource) { if (isResource) {
try { try {
final URI uri = res.toURI(); final URI uri = res.toURI();
if (res.getProtocol().equalsIgnoreCase("jar")) { if (res.getProtocol().equalsIgnoreCase("jar")) {
try { try {
FileSystems.newFileSystem(uri, Collections.emptyMap()); FileSystems.newFileSystem(uri, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException e) { } catch (final FileSystemAlreadyExistsException e) {
FileSystems.getFileSystem(uri); FileSystems.getFileSystem(uri);
} }
Path myFolderPath = Paths.get(uri); final Path myFolderPath = Paths.get(uri);
return myFolderPath; return myFolderPath;
} else { } else {
return Paths.get(uri); return Paths.get(uri);
} }
} catch (java.lang.IllegalArgumentException e) { } catch (final java.lang.IllegalArgumentException e) {
throw e; throw e;
} }
} else { } else {
@ -842,81 +825,81 @@ public class Utils {
public static InputStream getResourceStreamSafe(String string) throws IOException, URISyntaxException { public static InputStream getResourceStreamSafe(String string) throws IOException, URISyntaxException {
try { try {
return getResourceStream(string); return getResourceStream(string);
} catch (Exception ex) { } catch (final Exception ex) {
return null; return null;
} }
} }
public static InputStream getResourceStream(String string) throws IOException, URISyntaxException { public static InputStream getResourceStream(String string) throws IOException, URISyntaxException {
URL res = Main.instance.getClass().getResource(string); final URL res = Main.instance.getClass().getResource(string);
boolean isResource = res != null; final boolean isResource = res != null;
if (isResource) { if (isResource) {
try { try {
final URI uri = res.toURI(); final URI uri = res.toURI();
if (res.getProtocol().equalsIgnoreCase("jar")) { if (res.getProtocol().equalsIgnoreCase("jar")) {
try { try {
FileSystems.newFileSystem(uri, Collections.emptyMap()); FileSystems.newFileSystem(uri, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException e) { } catch (final FileSystemAlreadyExistsException e) {
FileSystems.getFileSystem(uri); FileSystems.getFileSystem(uri);
} }
Path myFolderPath = Paths.get(uri); final Path myFolderPath = Paths.get(uri);
return Files.newInputStream(myFolderPath); return Files.newInputStream(myFolderPath);
} else { } else {
return Files.newInputStream(Paths.get(uri)); return Files.newInputStream(Paths.get(uri));
} }
} catch (java.lang.IllegalArgumentException e) { } catch (final java.lang.IllegalArgumentException e) {
throw e; throw e;
} }
} else { } else {
return Files.newInputStream(Paths.get(string.substring(1))); return Files.newInputStream(Paths.get(string.substring(1)));
} }
} }
public static String read(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
}
public static void zip(String targetPath, String destinationFilePath, String password) {
try {
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(password.length()>0){ public static String read(InputStream input) throws IOException {
parameters.setEncryptFiles(true); try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); return buffer.lines().collect(Collectors.joining("\n"));
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); }
parameters.setPassword(password); }
}
ZipFile zipFile = new ZipFile(destinationFilePath); public static void zip(String targetPath, String destinationFilePath, String password) {
try {
final ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
File targetFile = new File(targetPath); if (password.length() > 0) {
if(targetFile.isFile()){ parameters.setEncryptFiles(true);
zipFile.addFile(targetFile, parameters); parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
}else if(targetFile.isDirectory()){ parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipFile.addFolder(targetFile, parameters); parameters.setPassword(password);
} }
} catch (Exception e) { final ZipFile zipFile = new ZipFile(destinationFilePath);
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
} catch (Exception e) { final File targetFile = new File(targetPath);
e.printStackTrace(); if (targetFile.isFile()) {
} zipFile.addFile(targetFile, parameters);
} } else if (targetFile.isDirectory()) {
zipFile.addFolder(targetFile, parameters);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
final ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
} catch (final Exception e) {
e.printStackTrace();
}
}
public static Path getJarDirectory() { public static Path getJarDirectory() {
return Paths.get("").toAbsolutePath(); return Paths.get("").toAbsolutePath();

View File

@ -24,7 +24,7 @@ public class CacheFile {
} while (Files.exists(Paths.get(path))); } while (Files.exists(Paths.get(path)));
try { try {
Files.createTempFile(StaticVars.calculatorNameLOWER, ""); Files.createTempFile(StaticVars.calculatorNameLOWER, "");
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -33,7 +33,7 @@ public class CacheFile {
if (lastOOS == null) { if (lastOOS == null) {
try { try {
return new ObjectOutputStream(new FileOutputStream(path)); return new ObjectOutputStream(new FileOutputStream(path));
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
return lastOOS; return lastOOS;
} }
@ -46,7 +46,7 @@ public class CacheFile {
if (lastOIS == null) { if (lastOIS == null) {
try { try {
return new ObjectInputStream(new FileInputStream(path)); return new ObjectInputStream(new FileInputStream(path));
} catch (IOException e) { } catch (final IOException e) {
return lastOIS; return lastOIS;
} }
} else { } else {
@ -72,7 +72,7 @@ public class CacheFile {
lastFIS.close(); lastFIS.close();
lastFIS = null; lastFIS = null;
} }
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -81,7 +81,7 @@ public class CacheFile {
closeStreams(); closeStreams();
try { try {
Files.deleteIfExists(Paths.get(path)); Files.deleteIfExists(Paths.get(path));
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@ -1,12 +1,5 @@
package org.warp.picalculator.device; package org.warp.picalculator.device;
public enum Key { public enum Key {
POWEROFF, debug_DEG, debug_RAD, debug_GRA, SHIFT, ALPHA, NONE, HISTORY_BACK, POWEROFF, debug_DEG, debug_RAD, debug_GRA, SHIFT, ALPHA, NONE, HISTORY_BACK, HISTORY_FORWARD, SURD_MODE, DRG_CYCLE, LETTER_X, LETTER_Y, LETTER_Z, STEP, SIMPLIFY, BRIGHTNESS_CYCLE, BRIGHTNESS_CYCLE_REVERSE, DOT, NUM0, NUM1, NUM2, NUM3, NUM4, NUM5, NUM6, NUM7, NUM8, NUM9, PARENTHESIS_OPEN, PARENTHESIS_CLOSE, PLUS, MINUS, PLUS_MINUS, MULTIPLY, DIVIDE, EQUAL, DELETE, RESET, LEFT, RIGHT, UP, DOWN, OK, debug1, debug2, debug3, debug4, debug5, SQRT, ROOT, POWER_OF_2, POWER_OF_x, SINE, COSINE, TANGENT, ARCSINE, ARCCOSINE, ARCTANGENT, PI, SETTINGS, F1, F2, F3, F4, BACK, ZOOM_MODE, LOGARITHM, EULER_NUMBER
HISTORY_FORWARD, SURD_MODE, DRG_CYCLE, LETTER_X, LETTER_Y, LETTER_Z, STEP,
SIMPLIFY, BRIGHTNESS_CYCLE, BRIGHTNESS_CYCLE_REVERSE, DOT, NUM0, NUM1, NUM2,
NUM3, NUM4, NUM5, NUM6, NUM7, NUM8, NUM9, PARENTHESIS_OPEN, PARENTHESIS_CLOSE,
PLUS, MINUS, PLUS_MINUS, MULTIPLY, DIVIDE, EQUAL, DELETE, RESET, LEFT, RIGHT,
UP, DOWN, OK, debug1, debug2, debug3, debug4, debug5, SQRT, ROOT, POWER_OF_2,
POWER_OF_x, SINE, COSINE, TANGENT, ARCSINE, ARCCOSINE, ARCTANGENT, PI, SETTINGS,
F1, F2, F3, F4, BACK, ZOOM_MODE, LOGARITHM, EULER_NUMBER
} }

View File

@ -523,89 +523,80 @@ public class Keyboard {
} }
static final Key[][][] keyMap = /* [ROW, COLUMN, (0:normal 1:shift 2:alpha)] */ static final Key[][][] keyMap = /* [ROW, COLUMN, (0:normal 1:shift 2:alpha)] */
{ { { /* ROW 0 */
{ /* ROW 0 */ { Key.SHIFT, Key.SHIFT, Key.SHIFT }, /* 0,0 */
{Key.SHIFT, Key.SHIFT, Key.SHIFT}, /* 0,0 */ { Key.ALPHA, Key.ALPHA, Key.ALPHA }, /* 0,1 */
{Key.ALPHA, Key.ALPHA, Key.ALPHA}, /* 0,1 */ { Key.NONE, Key.NONE, Key.NONE }, /* 0,2 */
{Key.NONE, Key.NONE, Key.NONE}, /* 0,2 */ { Key.NONE, Key.NONE, Key.NONE }, /* 0,3 */
{Key.NONE, Key.NONE, Key.NONE}, /* 0,3 */ { Key.NONE, Key.NONE, Key.NONE }, /* 0,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 0,4 */ { Key.SETTINGS, Key.NONE, Key.NONE }, /* 0,5 */
{Key.SETTINGS, Key.NONE, Key.NONE}, /* 0,5 */ { Key.BRIGHTNESS_CYCLE, Key.BRIGHTNESS_CYCLE_REVERSE, Key.ZOOM_MODE }, /* 0,6 */
{Key.BRIGHTNESS_CYCLE, Key.BRIGHTNESS_CYCLE_REVERSE, Key.ZOOM_MODE}, /* 0,6 */ { Key.SIMPLIFY, Key.STEP, Key.NONE } /* 0,7 */
{Key.SIMPLIFY, Key.STEP, Key.NONE} /* 0,7 */ }, { /* ROW 1 */
}, { Key.F4, Key.F4, Key.F4 }, /* 1,0 */
{ /* ROW 1 */ { Key.NONE, Key.NONE, Key.NONE }, /* 1,1 */
{Key.F4, Key.F4, Key.F4}, /* 1,0 */ { Key.LEFT, Key.NONE, Key.NONE }, /* 1,2 */
{Key.NONE, Key.NONE, Key.NONE}, /* 1,1 */ { Key.OK, Key.NONE, Key.NONE }, /* 1,3 */
{Key.LEFT, Key.NONE, Key.NONE}, /* 1,2 */ { Key.RIGHT, Key.NONE, Key.NONE }, /* 1,4 */
{Key.OK, Key.NONE, Key.NONE}, /* 1,3 */ { Key.HISTORY_BACK, Key.NONE, Key.NONE }, /* 1,5 */
{Key.RIGHT, Key.NONE, Key.NONE}, /* 1,4 */ { Key.HISTORY_FORWARD, Key.NONE, Key.NONE }, /* 1,6 */
{Key.HISTORY_BACK, Key.NONE, Key.NONE}, /* 1,5 */ { Key.NONE, Key.PI, Key.DRG_CYCLE } /* 1,7 */
{Key.HISTORY_FORWARD, Key.NONE, Key.NONE}, /* 1,6 */ }, { /* ROW 2 */
{Key.NONE, Key.PI, Key.DRG_CYCLE} /* 1,7 */ { Key.F3, Key.F4, Key.F4 }, /* 2,0 */
}, { Key.SQRT, Key.ROOT, Key.NONE }, /* 2,1 */
{ /* ROW 2 */ { Key.NONE, Key.NONE, Key.NONE }, /* 2,2 */
{Key.F3, Key.F4, Key.F4}, /* 2,0 */ { Key.DOWN, Key.NONE, Key.NONE }, /* 2,3 */
{Key.SQRT, Key.ROOT, Key.NONE}, /* 2,1 */ { Key.BACK, Key.NONE, Key.NONE }, /* 2,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 2,2 */ { Key.HISTORY_BACK, Key.NONE, Key.NONE }, /* 2,5 */
{Key.DOWN, Key.NONE, Key.NONE}, /* 2,3 */ { Key.HISTORY_FORWARD, Key.NONE, Key.NONE }, /* 2,6 */
{Key.BACK, Key.NONE, Key.NONE}, /* 2,4 */ { Key.NONE, Key.NONE, Key.LETTER_Z } /* 2,7 */
{Key.HISTORY_BACK, Key.NONE, Key.NONE}, /* 2,5 */ }, { /* ROW 3 */
{Key.HISTORY_FORWARD, Key.NONE, Key.NONE}, /* 2,6 */ { Key.F2, Key.F2, Key.F2 }, /* 3,0 */
{Key.NONE, Key.NONE, Key.LETTER_Z} /* 2,7 */ { Key.NONE, Key.NONE, Key.NONE }, /* 3,1 */
}, { Key.POWER_OF_x, Key.NONE, Key.NONE }, /* 3,2 */
{ /* ROW 3 */ { Key.POWER_OF_2, Key.NONE, Key.NONE }, /* 3,3 */
{Key.F2, Key.F2, Key.F2}, /* 3,0 */ { Key.NONE, Key.NONE, Key.NONE }, /* 3,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,1 */ { Key.NONE, Key.NONE, Key.NONE }, /* 3,5 */
{Key.POWER_OF_x, Key.NONE, Key.NONE}, /* 3,2 */ { Key.NONE, Key.NONE, Key.NONE }, /* 3,6 */
{Key.POWER_OF_2, Key.NONE, Key.NONE}, /* 3,3 */ { Key.DOT, Key.NONE, Key.LETTER_Y } /* 3,7 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,4 */ }, { /* ROW 4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,5 */ { Key.F1, Key.F1, Key.F1 }, /* 4,0 */
{Key.NONE, Key.NONE, Key.NONE}, /* 3,6 */ { Key.NONE, Key.NONE, Key.NONE }, /* 4,1 */
{Key.DOT, Key.NONE, Key.LETTER_Y} /* 3,7 */ { Key.PARENTHESIS_OPEN, Key.NONE, Key.NONE }, /* 4,2 */
}, { Key.PARENTHESIS_CLOSE, Key.NONE, Key.NONE }, /* 4,3 */
{ /* ROW 4 */ { Key.NONE, Key.NONE, Key.NONE }, /* 4,4 */
{Key.F1, Key.F1, Key.F1}, /* 4,0 */ { Key.SURD_MODE, Key.NONE, Key.NONE }, /* 4,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 4,1 */ { Key.NONE, Key.NONE, Key.NONE }, /* 4,6 */
{Key.PARENTHESIS_OPEN, Key.NONE, Key.NONE}, /* 4,2 */ { Key.NUM0, Key.NONE, Key.LETTER_X } /* 4,7 */
{Key.PARENTHESIS_CLOSE, Key.NONE, Key.NONE}, /* 4,3 */ }, { /* ROW 5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 4,4 */ { Key.NUM7, Key.NONE, Key.NONE }, /* 5,0 */
{Key.SURD_MODE, Key.NONE, Key.NONE}, /* 4,5 */ { Key.NUM8, Key.NONE, Key.NONE }, /* 5,1 */
{Key.NONE, Key.NONE, Key.NONE}, /* 4,6 */ { Key.NUM9, Key.NONE, Key.NONE }, /* 5,2 */
{Key.NUM0, Key.NONE, Key.LETTER_X} /* 4,7 */ { Key.DELETE, Key.NONE, Key.NONE }, /* 5,3 */
}, { Key.RESET, Key.NONE, Key.NONE }, /* 5,4 */
{ /* ROW 5 */ { Key.NONE, Key.NONE, Key.NONE }, /* 5,5 */
{Key.NUM7, Key.NONE, Key.NONE}, /* 5,0 */ { Key.NONE, Key.NONE, Key.NONE }, /* 5,6 */
{Key.NUM8, Key.NONE, Key.NONE}, /* 5,1 */ { Key.NONE, Key.NONE, Key.NONE } /* 5,7 */
{Key.NUM9, Key.NONE, Key.NONE}, /* 5,2 */ }, { /* ROW 6 */
{Key.DELETE, Key.NONE, Key.NONE}, /* 5,3 */ { Key.NUM4, Key.NONE, Key.NONE }, /* 6,0 */
{Key.RESET, Key.NONE, Key.NONE}, /* 5,4 */ { Key.NUM5, Key.NONE, Key.NONE }, /* 6,1 */
{Key.NONE, Key.NONE, Key.NONE}, /* 5,5 */ { Key.NUM6, Key.NONE, Key.NONE }, /* 6,2 */
{Key.NONE, Key.NONE, Key.NONE}, /* 5,6 */ { Key.MULTIPLY, Key.NONE, Key.NONE }, /* 6,3 */
{Key.NONE, Key.NONE, Key.NONE} /* 5,7 */ { Key.DIVIDE, Key.NONE, Key.NONE }, /* 6,4 */
}, { Key.NONE, Key.NONE, Key.NONE }, /* 6,5 */
{ /* ROW 6 */ { Key.NONE, Key.NONE, Key.NONE }, /* 6,6 */
{Key.NUM4, Key.NONE, Key.NONE}, /* 6,0 */ { Key.NONE, Key.NONE, Key.NONE } /* 6,7 */
{Key.NUM5, Key.NONE, Key.NONE}, /* 6,1 */ }, { /* ROW 7 */
{Key.NUM6, Key.NONE, Key.NONE}, /* 6,2 */ { Key.NUM1, Key.NONE, Key.NONE }, /* 7,0 */
{Key.MULTIPLY, Key.NONE, Key.NONE}, /* 6,3 */ { Key.NUM2, Key.NONE, Key.NONE }, /* 7,1 */
{Key.DIVIDE, Key.NONE, Key.NONE}, /* 6,4 */ { Key.NUM3, Key.NONE, Key.NONE }, /* 7,2 */
{Key.NONE, Key.NONE, Key.NONE}, /* 6,5 */ { Key.PLUS, Key.PLUS_MINUS, Key.NONE }, /* 7,3 */
{Key.NONE, Key.NONE, Key.NONE}, /* 6,6 */ { Key.MINUS, Key.NONE, Key.NONE }, /* 7,4 */
{Key.NONE, Key.NONE, Key.NONE} /* 6,7 */ { Key.NONE, Key.NONE, Key.NONE }, /* 7,5 */
}, { Key.NONE, Key.NONE, Key.NONE }, /* 7,6 */
{ /* ROW 7 */ { Key.NONE, Key.NONE, Key.NONE } /* 7,7 */
{Key.NUM1, Key.NONE, Key.NONE}, /* 7,0 */ } };
{Key.NUM2, Key.NONE, Key.NONE}, /* 7,1 */
{Key.NUM3, Key.NONE, Key.NONE}, /* 7,2 */
{Key.PLUS, Key.PLUS_MINUS, Key.NONE}, /* 7,3 */
{Key.MINUS, Key.NONE, Key.NONE}, /* 7,4 */
{Key.NONE, Key.NONE, Key.NONE}, /* 7,5 */
{Key.NONE, Key.NONE, Key.NONE}, /* 7,6 */
{Key.NONE, Key.NONE, Key.NONE} /* 7,7 */
}
};
static synchronized void keyPressedRaw(int row, int col) { static synchronized void keyPressedRaw(int row, int col) {
// KeyboardDebugScreen.keyX = row; // KeyboardDebugScreen.keyX = row;
// KeyboardDebugScreen.keyY = col; // KeyboardDebugScreen.keyY = col;
@ -614,7 +605,7 @@ public class Keyboard {
keyPressed(k); keyPressed(k);
} else { } else {
if (false) { if (false) {
} else { } else {
keyPressed(Key.NONE); keyPressed(Key.NONE);
} }

View File

@ -1,15 +1,15 @@
package org.warp.picalculator.extra.mario; package org.warp.picalculator.extra.mario;
public class MarioBlock { public class MarioBlock {
private int x, y; private final int x, y;
private byte id; private final byte id;
public MarioBlock(int x, int y, byte b) { public MarioBlock(int x, int y, byte b) {
this.x = x; this.x = x;
this.y = y; this.y = y;
id = b; id = b;
} }
public boolean isSolid() { public boolean isSolid() {
return MarioBlock.isSolid(id); return MarioBlock.isSolid(id);
} }
@ -17,11 +17,11 @@ public class MarioBlock {
public byte getID() { public byte getID() {
return id; return id;
} }
public int getX() { public int getX() {
return x; return x;
} }
public int getY() { public int getY() {
return y; return y;
} }

View File

@ -10,13 +10,13 @@ public class MarioEntity {
public boolean collisionLeft; public boolean collisionLeft;
public boolean collisionRight; public boolean collisionRight;
public boolean subjectToGravity; public boolean subjectToGravity;
public MarioEntity(double x, double y, double forceX, double forceY, boolean onGround, boolean subjectToGravity) { public MarioEntity(double x, double y, double forceX, double forceY, boolean onGround, boolean subjectToGravity) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.forceX = forceX; this.forceX = forceX;
this.forceY = forceY; this.forceY = forceY;
this.collisionDown = onGround; collisionDown = onGround;
this.subjectToGravity = subjectToGravity; this.subjectToGravity = subjectToGravity;
} }
@ -28,55 +28,55 @@ public class MarioEntity {
public void setPosition(double x, double y, boolean onGround) { public void setPosition(double x, double y, boolean onGround) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.collisionDown = onGround; collisionDown = onGround;
} }
public double getX() { public double getX() {
return x; return x;
} }
public double getY() { public double getY() {
return y; return y;
} }
public boolean isOnGround() { public boolean isOnGround() {
return collisionDown; return collisionDown;
} }
public void setOnGround(boolean onGround) { public void setOnGround(boolean onGround) {
this.collisionDown = onGround; collisionDown = onGround;
} }
public void gameTick(double dt) { public void gameTick(double dt) {
this.x = computeFutureDX(dt); x = computeFutureDX(dt);
this.y = computeFutureDY(dt); y = computeFutureDY(dt);
this.forceX = computeFutureForceDX(dt); forceX = computeFutureForceDX(dt);
this.forceY = computeFutureForceDY(dt); forceY = computeFutureForceDY(dt);
} }
public double computeFutureDX(double dt) { public double computeFutureDX(double dt) {
return (x + dt * forceX) - this.x; return (x + dt * forceX) - x;
} }
public double computeFutureDY(double dt) { public double computeFutureDY(double dt) {
double forceY = this.forceY; final double forceY = this.forceY;
double y = this.y; double y = this.y;
if (!collisionDown) { if (!collisionDown) {
y += dt * forceY; y += dt * forceY;
} }
return y - this.y; return y - this.y;
} }
public double computeFutureForceDX(double dt) { public double computeFutureForceDX(double dt) {
double forceX = this.forceX; double forceX = this.forceX;
forceX *= 0.75; forceX *= 0.75;
return forceX - this.forceX; return forceX - this.forceX;
} }
public double computeFutureForceDY(double dt) { public double computeFutureForceDY(double dt) {
double forceY = this.forceY; double forceY = this.forceY;
if (subjectToGravity && !this.collisionDown) { if (subjectToGravity && !collisionDown) {
forceY -= dt * 1569.6/16f; forceY -= dt * 1569.6 / 16f;
} else { } else {
forceY *= 0.75; forceY *= 0.75;
} }

File diff suppressed because one or more lines are too long

View File

@ -2,13 +2,13 @@ package org.warp.picalculator.extra.mario;
public class MarioWorld { public class MarioWorld {
private int[] spawnPoint; private final int[] spawnPoint;
private int width; private final int width;
private int height; private final int height;
private byte[][] data; private final byte[][] data;
private MarioEvent[] events; private final MarioEvent[] events;
private MarioEntity[] entities; private final MarioEntity[] entities;
/** /**
* @param width * @param width
* @param height * @param height
@ -26,10 +26,14 @@ public class MarioWorld {
} }
public byte getBlockIdAt(int x, int y) { public byte getBlockIdAt(int x, int y) {
int idy = (height - 1 - y); final int idy = (height - 1 - y);
if (idy < 0 || idy >= data.length) return 0b0; if (idy < 0 || idy >= data.length) {
int idx = x; return 0b0;
if (idx < 0 || idx >= data[0].length) return 0b0; }
final int idx = x;
if (idx < 0 || idx >= data[0].length) {
return 0b0;
}
return data[idy][idx]; return data[idy][idx];
} }
@ -46,7 +50,7 @@ public class MarioWorld {
} }
public void reset() { public void reset() {
} }
public double getSpawnPointX() { public double getSpawnPointX() {

View File

@ -1,8 +1,8 @@
package org.warp.picalculator.extra.mario; package org.warp.picalculator.extra.mario;
public class PlayerEntity extends MarioEntity { public class PlayerEntity extends MarioEntity {
private int life; private final int life;
public float walkAnimation = 0; public float walkAnimation = 0;
public float jumptime = 0; public float jumptime = 0;
public boolean walking = false; public boolean walking = false;
@ -12,19 +12,19 @@ public class PlayerEntity extends MarioEntity {
public int[] marioSkinPos = new int[] { 0, 0 }; public int[] marioSkinPos = new int[] { 0, 0 };
private double controllerDX; private double controllerDX;
private double controllerDY; private double controllerDY;
public PlayerEntity(double x, double y, int life) { public PlayerEntity(double x, double y, int life) {
super(x, y, 0, 0, true, true); super(x, y, 0, 0, true, true);
this.life = life; this.life = life;
} }
@Override @Override
public void gameTick(double dt) { public void gameTick(double dt) {
walkAnimation += dt; walkAnimation += dt;
this.x += computeFutureDX(dt); x += computeFutureDX(dt);
this.y += computeFutureDY(dt); y += computeFutureDY(dt);
this.forceX += computeFutureForceDX(dt); forceX += computeFutureForceDX(dt);
this.forceY += computeFutureForceDY(dt); forceY += computeFutureForceDY(dt);
if (controllerDX == 0) { if (controllerDX == 0) {
walking = false; walking = false;
walkAnimation = 0; walkAnimation = 0;
@ -47,8 +47,7 @@ public class PlayerEntity extends MarioEntity {
if (jumptime <= 0.5f && !jumping && collisionDown) { if (jumptime <= 0.5f && !jumping && collisionDown) {
jumping = true; jumping = true;
collisionDown = false; collisionDown = false;
} else if (jumptime <= 0.5f) { } else if (jumptime <= 0.5f) {} else {
} else {
jumping = false; jumping = false;
} }
} else { } else {
@ -81,34 +80,36 @@ public class PlayerEntity extends MarioEntity {
marioSkinPos[1] = 1; marioSkinPos[1] = 1;
} }
} }
@Override
public double computeFutureDX(double dt) { public double computeFutureDX(double dt) {
return super.computeFutureDX(dt); return super.computeFutureDX(dt);
} }
public double computeFuturedDY(double dt) { public double computeFuturedDY(double dt) {
return super.computeFutureDY(dt); return super.computeFutureDY(dt);
} }
@Override
public double computeFutureForceDX(double dt) { public double computeFutureForceDX(double dt) {
double forceX = this.forceX; double forceX = this.forceX;
if (controllerDX == 0) { if (controllerDX == 0) {} else {
} else {
if (controllerDX > 0) { //RIGHT if (controllerDX > 0) { //RIGHT
if (forceX < 500f/16f) { if (forceX < 500f / 16f) {
forceX += dt * 500f/16f; forceX += dt * 500f / 16f;
} }
} }
if (controllerDX < 0) { //LEFT if (controllerDX < 0) { //LEFT
if (forceX > -500f/16f) { if (forceX > -500f / 16f) {
forceX -= dt * 500f/16f; forceX -= dt * 500f / 16f;
} }
} }
} }
return (forceX + super.computeFutureForceDX(dt)) - this.forceX; return (forceX + super.computeFutureForceDX(dt)) - this.forceX;
} }
@Override
public double computeFutureForceDY(double dt) { public double computeFutureForceDY(double dt) {
float jumptime = this.jumptime; float jumptime = this.jumptime;
double forceY = this.forceY; double forceY = this.forceY;
@ -118,9 +119,9 @@ public class PlayerEntity extends MarioEntity {
} }
jumptime += dt; jumptime += dt;
if (jumptime <= 0.5f && !jumping && collisionDown) { if (jumptime <= 0.5f && !jumping && collisionDown) {
forceY = dt * (4 * 1569.6f)/16f; forceY = dt * (4 * 1569.6f) / 16f;
} else if (jumptime <= 0.5f) { } else if (jumptime <= 0.5f) {
forceY = dt * (4 * 1569.6f)/16f; forceY = dt * (4 * 1569.6f) / 16f;
} }
} }
return (forceY + super.computeFutureForceDY(dt)) - this.forceY; return (forceY + super.computeFutureForceDY(dt)) - this.forceY;
@ -128,9 +129,9 @@ public class PlayerEntity extends MarioEntity {
public void move(float dt, double dX, double dY) { public void move(float dt, double dX, double dY) {
walkAnimation += dt; walkAnimation += dt;
this.controllerDX = dX; controllerDX = dX;
this.controllerDY = dY; controllerDY = dY;
} }
} }

View File

@ -12,37 +12,37 @@ public class CalculatorHUD extends HUD {
@Override @Override
public void created() throws InterruptedException { public void created() throws InterruptedException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void initialized() throws InterruptedException { public void initialized() throws InterruptedException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void render() { public void render() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void renderTopmostBackground() { public void renderTopmostBackground() {
Renderer renderer = d.renderer; final Renderer renderer = d.renderer;
GraphicEngine engine = d.engine; final GraphicEngine engine = d.engine;
Skin guiSkin = d.guiSkin; final Skin guiSkin = d.guiSkin;
renderer.glColor(0xFFc5c2af); renderer.glColor(0xFFc5c2af);
renderer.glFillColor(0, 0, engine.getWidth(), 20); renderer.glFillColor(0, 0, engine.getWidth(), 20);
} }
@Override @Override
public void renderTopmost() { public void renderTopmost() {
Renderer renderer = d.renderer; final Renderer renderer = d.renderer;
GraphicEngine engine = d.engine; final GraphicEngine engine = d.engine;
Skin guiSkin = d.guiSkin; final Skin guiSkin = d.guiSkin;
//DRAW TOP //DRAW TOP
renderer.glColor3i(0, 0, 0); renderer.glColor3i(0, 0, 0);
renderer.glDrawLine(0, 20, engine.getWidth() - 1, 20); renderer.glDrawLine(0, 20, engine.getWidth() - 1, 20);
@ -107,10 +107,9 @@ public class CalculatorHUD extends HUD {
} }
padding += 18; padding += 18;
//DRAW BOTTOM //DRAW BOTTOM
this.d.renderer.glDrawStringLeft(2, 90, this.d.displayDebugString); d.renderer.glDrawStringLeft(2, 90, d.displayDebugString);
Utils.getFont(true, false).use(DisplayManager.INSTANCE.engine); Utils.getFont(true, false).use(DisplayManager.INSTANCE.engine);
DisplayManager.INSTANCE.renderer.glColor4i(255, 0, 0, 40); DisplayManager.INSTANCE.renderer.glColor4i(255, 0, 0, 40);
@ -126,13 +125,13 @@ public class CalculatorHUD extends HUD {
@Override @Override
public void beforeRender(float dt) { public void beforeRender(float dt) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void renderBackground() { public void renderBackground() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -41,7 +41,7 @@ public final class DisplayManager implements RenderingLoop {
public final int[] glyphsHeight; public final int[] glyphsHeight;
private Screen screen; private Screen screen;
private HUD hud; private final HUD hud;
public Semaphore screenChange = new Semaphore(0); public Semaphore screenChange = new Semaphore(0);
public String displayDebugString; public String displayDebugString;
public ObjectArrayList<GUIErrorMessage> errorMessages; public ObjectArrayList<GUIErrorMessage> errorMessages;
@ -50,31 +50,33 @@ public final class DisplayManager implements RenderingLoop {
INSTANCE = this; INSTANCE = this;
engine = chooseGraphicEngine(); engine = chooseGraphicEngine();
supportsPauses = engine.doesRefreshPauses(); supportsPauses = engine.doesRefreshPauses();
this.monitor = monitor; this.monitor = monitor;
this.hud = hud; this.hud = hud;
monitor.initialize(); monitor.initialize();
glyphsHeight = new int[] { 9, 6, 12, 9 }; glyphsHeight = new int[] { 9, 6, 12, 9 };
displayDebugString = ""; displayDebugString = "";
errorMessages = new ObjectArrayList<>(); errorMessages = new ObjectArrayList<>();
try { try {
hud.d = this; hud.d = this;
hud.create(); hud.create();
if (!hud.initialized) hud.initialize(); if (!hud.initialized) {
hud.initialize();
}
} catch (final Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
System.exit(0); System.exit(0);
} }
setScreen(screen); setScreen(screen);
try { try {
engine.create(); engine.create();
renderer = engine.getRenderer(); renderer = engine.getRenderer();
engine.setTitle(title); engine.setTitle(title);
loop(); loop();
} catch (Exception ex) { } catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
monitor.shutdown(); monitor.shutdown();
@ -154,7 +156,7 @@ public final class DisplayManager implements RenderingLoop {
if (screen.initialized == false) { if (screen.initialized == false) {
if (screen.canBeInHistory) { if (screen.canBeInHistory) {
if (DisplayManager.INSTANCE.currentSession > 0) { if (DisplayManager.INSTANCE.currentSession > 0) {
int sl = DisplayManager.INSTANCE.sessions.length + 5; //TODO: I don't know why if i don't add +5 or more some items disappear final int sl = DisplayManager.INSTANCE.sessions.length + 5; //TODO: I don't know why if i don't add +5 or more some items disappear
DisplayManager.INSTANCE.sessions = Arrays.copyOfRange(DisplayManager.INSTANCE.sessions, DisplayManager.INSTANCE.currentSession, sl); DisplayManager.INSTANCE.sessions = Arrays.copyOfRange(DisplayManager.INSTANCE.sessions, DisplayManager.INSTANCE.currentSession, sl);
} }
DisplayManager.INSTANCE.currentSession = 0; DisplayManager.INSTANCE.currentSession = 0;
@ -293,8 +295,8 @@ public final class DisplayManager implements RenderingLoop {
private void draw_init() { private void draw_init() {
if (engine.supportsFontRegistering()) { if (engine.supportsFontRegistering()) {
List<BinaryFont> fontsIterator = engine.getRegisteredFonts(); final List<BinaryFont> fontsIterator = engine.getRegisteredFonts();
for (BinaryFont f : fontsIterator) { for (final BinaryFont f : fontsIterator) {
if (!f.isInitialized()) { if (!f.isInitialized()) {
f.initialize(engine); f.initialize(engine);
} }
@ -307,7 +309,7 @@ public final class DisplayManager implements RenderingLoop {
renderer.glColor3i(255, 255, 255); renderer.glColor3i(255, 255, 255);
if (error != null) { if (error != null) {
BinaryFont fnt = Utils.getFont(false, false); final BinaryFont fnt = Utils.getFont(false, false);
if (fnt != null && fnt != engine.getRenderer().getCurrentFont()) { if (fnt != null && fnt != engine.getRenderer().getCurrentFont()) {
fnt.use(engine); fnt.use(engine);
} }

View File

@ -2,9 +2,14 @@ package org.warp.picalculator.gui;
public interface GraphicalInterface { public interface GraphicalInterface {
public void create() throws InterruptedException; public void create() throws InterruptedException;
public void initialize() throws InterruptedException; public void initialize() throws InterruptedException;
public void render(); public void render();
public void renderTopmost(); public void renderTopmost();
public void beforeRender(float dt); public void beforeRender(float dt);
public boolean mustBeRefreshed(); public boolean mustBeRefreshed();
} }

View File

@ -22,18 +22,18 @@ public abstract class HUD implements GraphicalInterface {
created(); created();
} }
} }
public abstract void created() throws InterruptedException; public abstract void created() throws InterruptedException;
public abstract void initialized() throws InterruptedException; public abstract void initialized() throws InterruptedException;
public abstract void renderBackground(); public abstract void renderBackground();
@Override @Override
public abstract void render(); public abstract void render();
public abstract void renderTopmostBackground(); public abstract void renderTopmostBackground();
@Override @Override
public abstract void renderTopmost(); public abstract void renderTopmost();
@ -44,5 +44,5 @@ public abstract class HUD implements GraphicalInterface {
public boolean mustBeRefreshed() { public boolean mustBeRefreshed() {
return true; return true;
} }
} }

View File

@ -2,6 +2,8 @@ package org.warp.picalculator.gui;
public interface HardwareDisplay { public interface HardwareDisplay {
public void initialize(); public void initialize();
public void shutdown(); public void shutdown();
public void setBrightness(double value); public void setBrightness(double value);
} }

View File

@ -5,8 +5,8 @@ public class Caret {
private int pos; private int pos;
private int remaining; private int remaining;
private CaretState state; private CaretState state;
private int[] lastSize; private final int[] lastSize;
private int[] lastLocation; private final int[] lastLocation;
public Caret(CaretState state, int pos) { public Caret(CaretState state, int pos) {
this(state, pos, new int[] { 0, 0 }, new int[] { 2, 5 }); this(state, pos, new int[] { 0, 0 }, new int[] { 2, 5 });

View File

@ -30,8 +30,8 @@ public abstract class ExtraMenu<T extends Block> implements Serializable, Keyboa
public abstract void close(); public abstract void close();
public boolean beforeRender(float delta, Caret caret) { public boolean beforeRender(float delta, Caret caret) {
int[] l = caret.getLastLocation(); final int[] l = caret.getLastLocation();
int[] cs = caret.getLastSize(); final int[] cs = caret.getLastSize();
location[0] = l[0] - block.getWidth() / 2 - width / 2; location[0] = l[0] - block.getWidth() / 2 - width / 2;
location[1] = l[1] + cs[1]; location[1] = l[1] + cs[1];
return false; return false;

View File

@ -11,9 +11,9 @@ public class InputContext {
public BlockVariable variableTypeDirtyID = null; public BlockVariable variableTypeDirtyID = null;
public InputContext() { public InputContext() {
this.variableTypes = new HashMap<>(); variableTypes = new HashMap<>();
this.variableTypes.put(MathematicalSymbols.PI, V_TYPE.CONSTANT); variableTypes.put(MathematicalSymbols.PI, V_TYPE.CONSTANT);
this.variableTypes.put(MathematicalSymbols.EULER_NUMBER, V_TYPE.CONSTANT); variableTypes.put(MathematicalSymbols.EULER_NUMBER, V_TYPE.CONSTANT);
} }
public InputContext(HashMap<Character, V_TYPE> variableTypes) { public InputContext(HashMap<Character, V_TYPE> variableTypes) {

View File

@ -72,7 +72,7 @@ public class BlockContainer implements GraphicalElement {
addBlockUnsafe(position, b); addBlockUnsafe(position, b);
recomputeDimensions(); recomputeDimensions();
} }
public void addBlockUnsafe(int position, Block b) { public void addBlockUnsafe(int position, Block b) {
if (b.isSmall() != small) { if (b.isSmall() != small) {
b.setSmall(small); b.setSmall(small);
@ -111,7 +111,7 @@ public class BlockContainer implements GraphicalElement {
} }
public BlockReference<?> getBlockAt(int i) { public BlockReference<?> getBlockAt(int i) {
Block b = content.get(i); final Block b = content.get(i);
return new BlockReference<>(b, i, this); return new BlockReference<>(b, i, this);
} }
@ -336,11 +336,11 @@ public class BlockContainer implements GraphicalElement {
public void setSmall(boolean small) { public void setSmall(boolean small) {
this.small = small; this.small = small;
if (this.autoMinimums) { if (autoMinimums) {
this.minWidth = BlockContainer.getDefaultCharWidth(small); minWidth = BlockContainer.getDefaultCharWidth(small);
this.minHeight = BlockContainer.getDefaultCharHeight(small); minHeight = BlockContainer.getDefaultCharHeight(small);
} }
for (Block b : this.content) { for (final Block b : content) {
b.setSmall(small); b.setSmall(small);
} }
recomputeDimensions(); recomputeDimensions();
@ -365,13 +365,14 @@ public class BlockContainer implements GraphicalElement {
} }
public Function toFunction(MathContext context) throws Error { public Function toFunction(MathContext context) throws Error {
ObjectArrayList<Block> blocks = getContent(); final ObjectArrayList<Block> blocks = getContent();
final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>(); final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>();
for (final Block block : blocks) { for (final Block block : blocks) {
final Feature blockFeature = block.toFeature(context); final Feature blockFeature = block.toFeature(context);
if (blockFeature == null) if (blockFeature == null) {
throw new Error(Errors.NOT_IMPLEMENTED, "The block " + block.getClass().getSimpleName() + " isn't a known Block"); throw new Error(Errors.NOT_IMPLEMENTED, "The block " + block.getClass().getSimpleName() + " isn't a known Block");
}
blockFeatures.add(blockFeature); blockFeatures.add(blockFeature);
} }

View File

@ -21,6 +21,6 @@ public class BlockExponentialNotation extends BlockPower {
super.recomputeDimensions(); super.recomputeDimensions();
bw = (int) (BlockContainer.getDefaultCharWidth(small) * 1.5); bw = (int) (BlockContainer.getDefaultCharWidth(small) * 1.5);
bh = BlockContainer.getDefaultCharHeight(small); bh = BlockContainer.getDefaultCharHeight(small);
this.width += bw; width += bw;
} }
} }

View File

@ -58,7 +58,7 @@ public class BlockLogarithm extends Block {
r.glDrawCharLeft(x + width - chw, y + toph, '╮'); r.glDrawCharLeft(x + width - chw, y + toph, '╮');
r.glDrawCharLeft(x + width - chw, y + toph + nmbh - chh, '╯'); r.glDrawCharLeft(x + width - chw, y + toph + nmbh - chh, '╯');
r.glColor(BlockContainer.getDefaultColor()); r.glColor(BlockContainer.getDefaultColor());
containerBase.draw(ge, r, x + prw, y + line + chh/2 - bl, caret); containerBase.draw(ge, r, x + prw, y + line + chh / 2 - bl, caret);
r.glColor(BlockContainer.getDefaultColor()); r.glColor(BlockContainer.getDefaultColor());
containerNumber.draw(ge, r, x + bw + prw + chw, y + toph, caret); containerNumber.draw(ge, r, x + bw + prw + chw, y + toph, caret);
} }
@ -111,7 +111,7 @@ public class BlockLogarithm extends Block {
schh = BlockContainer.getDefaultCharHeight(true); schh = BlockContainer.getDefaultCharHeight(true);
width = prw + bw + chw + containerNumber.getWidth() + chw + 3; width = prw + bw + chw + containerNumber.getWidth() + chw + 3;
nmbh = containerNumber.getHeight(); nmbh = containerNumber.getHeight();
int nl = containerNumber.getLine(); final int nl = containerNumber.getLine();
if (bl > nmbh) { if (bl > nmbh) {
toph = bl - nmbh; toph = bl - nmbh;
line = toph + nl; line = toph + nl;

View File

@ -27,13 +27,13 @@ public abstract class BlockParenthesisAbstract extends Block {
public BlockParenthesisAbstract() { public BlockParenthesisAbstract() {
containerNumber = new BlockContainer(false); containerNumber = new BlockContainer(false);
this.prefix = null; prefix = null;
recomputeDimensions(); recomputeDimensions();
} }
public BlockParenthesisAbstract(ObjectArrayList<Block> blocks) { public BlockParenthesisAbstract(ObjectArrayList<Block> blocks) {
containerNumber = new BlockContainer(false, blocks); containerNumber = new BlockContainer(false, blocks);
this.prefix = null; prefix = null;
recomputeDimensions(); recomputeDimensions();
} }

View File

@ -4,13 +4,13 @@ public class BlockReference<T extends Block> {
private final T block; private final T block;
private final BlockContainer container; private final BlockContainer container;
private final int blockPosition; private final int blockPosition;
public BlockReference(T block, int blockPosition, BlockContainer container) { public BlockReference(T block, int blockPosition, BlockContainer container) {
this.block = block; this.block = block;
this.blockPosition = blockPosition; this.blockPosition = blockPosition;
this.container = container; this.container = container;
} }
public T get() { public T get() {
return block; return block;
} }
@ -22,19 +22,19 @@ public class BlockReference<T extends Block> {
public int getIndex() { public int getIndex() {
return blockPosition; return blockPosition;
} }
public BlockReference<?> getNextBlock() { public BlockReference<?> getNextBlock() {
return getBlockAtSafe(this.blockPosition + 1); return getBlockAtSafe(this.blockPosition + 1);
} }
public boolean hasNextBlock() { public boolean hasNextBlock() {
return isInsideBounds(this.blockPosition + 1); return isInsideBounds(this.blockPosition + 1);
} }
public BlockReference<?> getPreviousBlock() { public BlockReference<?> getPreviousBlock() {
return getBlockAtSafe(this.blockPosition - 1); return getBlockAtSafe(this.blockPosition - 1);
} }
public boolean hasPreviousBlock() { public boolean hasPreviousBlock() {
return isInsideBounds(this.blockPosition - 1); return isInsideBounds(this.blockPosition - 1);
} }
@ -45,10 +45,9 @@ public class BlockReference<T extends Block> {
} }
return null; return null;
} }
private boolean isInsideBounds(int i) { private boolean isInsideBounds(int i) {
return i < container.getSize() && i >= 0; return i < container.getSize() && i >= 0;
} }
} }

View File

@ -16,7 +16,7 @@ import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class BlockVariable extends Block { public class BlockVariable extends Block {
private InputContext ic; private final InputContext ic;
private final char ch; private final char ch;
private final VariableMenu menu; private final VariableMenu menu;
private V_TYPE type; private V_TYPE type;
@ -32,11 +32,11 @@ public class BlockVariable extends Block {
public BlockVariable(InputContext ic, char ch, boolean typeLocked) { public BlockVariable(InputContext ic, char ch, boolean typeLocked) {
this.ic = ic; this.ic = ic;
this.ch = ch; this.ch = ch;
this.type = V_TYPE.VARIABLE; type = V_TYPE.VARIABLE;
this.color = 0xFF304ffe; color = 0xFF304ffe;
this.typeDirtyID = this; typeDirtyID = this;
this.typeLocked = typeLocked; this.typeLocked = typeLocked;
this.menu = typeLocked ? null : new VariableMenu(this); menu = typeLocked ? null : new VariableMenu(this);
retrieveValue(); retrieveValue();
recomputeDimensions(); recomputeDimensions();
} }
@ -205,7 +205,7 @@ public class BlockVariable extends Block {
if (mustRefreshMenu) { if (mustRefreshMenu) {
mustRefreshMenu = false; mustRefreshMenu = false;
text = block.type.toString(); text = block.type.toString();
BinaryFont f = BlockContainer.getDefaultFont(true); final BinaryFont f = BlockContainer.getDefaultFont(true);
width = 7 + f.getStringWidth(text) + 7; width = 7 + f.getStringWidth(text) + 7;
height = 2 + f.getCharacterHeight() + 2; height = 2 + f.getCharacterHeight() + 2;
@ -227,7 +227,7 @@ public class BlockVariable extends Block {
if (popupY < 0) { if (popupY < 0) {
popupY = 0; popupY = 0;
} }
int[] screenSize = ge.getSize(); final int[] screenSize = ge.getSize();
if (popupX + width >= screenSize[0]) { if (popupX + width >= screenSize[0]) {
popupX = screenSize[0] - width - 1; popupX = screenSize[0] - width - 1;
} }

View File

@ -96,7 +96,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S
public BlockReference<?> getSelectedBlock() { public BlockReference<?> getSelectedBlock() {
caret.resetRemaining(); caret.resetRemaining();
BlockReference<?> selectedBlock = root.getBlock(caret); final BlockReference<?> selectedBlock = root.getBlock(caret);
return selectedBlock; return selectedBlock;
} }
@ -230,7 +230,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S
public void toggleExtra() { public void toggleExtra() {
if (extra == null) { if (extra == null) {
BlockReference<?> selectedBlock = getSelectedBlock(); final BlockReference<?> selectedBlock = getSelectedBlock();
if (selectedBlock != null) { if (selectedBlock != null) {
extra = selectedBlock.get().getExtraMenu(); extra = selectedBlock.get().getExtraMenu();
extra.open(); extra.open();

View File

@ -79,7 +79,7 @@ public class NormalInputContainer extends InputContainer {
case MathematicalSymbols.EULER_NUMBER: case MathematicalSymbols.EULER_NUMBER:
return new BlockVariable(inputContext, c, true); return new BlockVariable(inputContext, c, true);
default: default:
for (char v : MathematicalSymbols.variables) { for (final char v : MathematicalSymbols.variables) {
if (c == v) { if (c == v) {
return new BlockVariable(inputContext, c); return new BlockVariable(inputContext, c);
} }
@ -93,18 +93,20 @@ public class NormalInputContainer extends InputContainer {
super.typeChar(c); super.typeChar(c);
switch (c) { switch (c) {
case MathematicalSymbols.PARENTHESIS_CLOSE: case MathematicalSymbols.PARENTHESIS_CLOSE:
this.moveRight(); moveRight();
case MathematicalSymbols.DIVISION: case MathematicalSymbols.DIVISION:
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final
BlockReference<BlockDivision> ref = (BlockReference<BlockDivision>) this.getSelectedBlock(); BlockReference<BlockDivision> ref = (BlockReference<BlockDivision>) getSelectedBlock();
BlockContainer parentContainer = ref.getContainer(); final BlockContainer parentContainer = ref.getContainer();
BlockReference<?> currentBlock = ref; BlockReference<?> currentBlock = ref;
boolean groupedBefore = false; boolean groupedBefore = false;
int before = 0; int before = 0;
while (true) { while (true) {
currentBlock = currentBlock.getPreviousBlock(); currentBlock = currentBlock.getPreviousBlock();
if (currentBlock == null) break; if (currentBlock == null) {
Block b = currentBlock.get(); break;
}
final Block b = currentBlock.get();
if (b instanceof BlockNumericChar || b instanceof BlockVariable) { if (b instanceof BlockNumericChar || b instanceof BlockVariable) {
if (!groupedBefore) { if (!groupedBefore) {
groupedBefore = true; groupedBefore = true;
@ -115,21 +117,21 @@ public class NormalInputContainer extends InputContainer {
} }
} }
if (groupedBefore) { if (groupedBefore) {
this.moveLeft(); moveLeft();
for (int i = 0; i < before; i++) { for (int i = 0; i < before; i++) {
BlockReference<?> b = this.getSelectedBlock(); final BlockReference<?> b = getSelectedBlock();
this.del(); del();
this.moveRight(); moveRight();
this.typeBlock(b.get()); typeBlock(b.get());
this.moveLeft(); moveLeft();
this.moveLeft(); moveLeft();
} }
for (int i = 0; i < before + 1; i++) { for (int i = 0; i < before + 1; i++) {
this.moveRight(); moveRight();
} }
this.moveRight();// Move to the divisor moveRight();// Move to the divisor
} }
} }
} }
} }

View File

@ -35,8 +35,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
public void setContentAsSingleGroup(ObjectArrayList<Block> blocks) { public void setContentAsSingleGroup(ObjectArrayList<Block> blocks) {
roots.clear(); roots.clear();
BlockContainer bcnt = new BlockContainer(); final BlockContainer bcnt = new BlockContainer();
for (Block block : blocks) { for (final Block block : blocks) {
bcnt.appendBlockUnsafe(block); bcnt.appendBlockUnsafe(block);
} }
roots.add(bcnt); roots.add(bcnt);
@ -45,9 +45,9 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
public void setContentAsMultipleGroups(ObjectArrayList<ObjectArrayList<Block>> roots) { public void setContentAsMultipleGroups(ObjectArrayList<ObjectArrayList<Block>> roots) {
this.roots.clear(); this.roots.clear();
for (ObjectArrayList<Block> blocks : roots) { for (final ObjectArrayList<Block> blocks : roots) {
BlockContainer bcnt = new BlockContainer(); final BlockContainer bcnt = new BlockContainer();
for (Block block : blocks) { for (final Block block : blocks) {
bcnt.appendBlockUnsafe(block); bcnt.appendBlockUnsafe(block);
} }
this.roots.add(bcnt); this.roots.add(bcnt);
@ -56,18 +56,18 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
} }
public void setContentAsMultipleElements(ObjectArrayList<Block> elems) { public void setContentAsMultipleElements(ObjectArrayList<Block> elems) {
this.roots.clear(); roots.clear();
for (Block block : elems) { for (final Block block : elems) {
BlockContainer bcnt = new BlockContainer(); final BlockContainer bcnt = new BlockContainer();
bcnt.appendBlockUnsafe(block); bcnt.appendBlockUnsafe(block);
this.roots.add(bcnt); roots.add(bcnt);
} }
recomputeDimensions(); recomputeDimensions();
} }
@Override @Override
public void recomputeDimensions() { public void recomputeDimensions() {
for (BlockContainer root : roots) { for (final BlockContainer root : roots) {
root.recomputeDimensions(); root.recomputeDimensions();
} }
} }
@ -75,10 +75,11 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
@Override @Override
public int getWidth() { public int getWidth() {
int maxw = 0; int maxw = 0;
for (BlockContainer root : roots) { for (final BlockContainer root : roots) {
int w = root.getWidth(); final int w = root.getWidth();
if (w > maxw) if (w > maxw) {
maxw = w; maxw = w;
}
} }
return maxw; return maxw;
} }
@ -86,7 +87,7 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
@Override @Override
public int getHeight() { public int getHeight() {
int h = 0; int h = 0;
for (BlockContainer root : roots) { for (final BlockContainer root : roots) {
h += root.getHeight() + 2; h += root.getHeight() + 2;
} }
if (h > 0) { if (h > 0) {
@ -123,7 +124,7 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
*/ */
public void draw(GraphicEngine ge, Renderer r, int x, int y) { public void draw(GraphicEngine ge, Renderer r, int x, int y) {
int offset = 0; int offset = 0;
for (BlockContainer root : roots) { for (final BlockContainer root : roots) {
root.draw(ge, r, x, y + offset, caret); root.draw(ge, r, x, y + offset, caret);
offset += root.getHeight() + 2; offset += root.getHeight() + 2;
} }
@ -136,8 +137,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout,
} }
public boolean isContentEmpty() { public boolean isContentEmpty() {
for (BlockContainer root : roots) { for (final BlockContainer root : roots) {
ObjectArrayList<Block> cnt = root.getContent(); final ObjectArrayList<Block> cnt = root.getContent();
if (cnt != null && !cnt.isEmpty()) { if (cnt != null && !cnt.isEmpty()) {
return false; return false;
} }

View File

@ -36,7 +36,7 @@ public interface GraphicEngine {
public Renderer getRenderer(); public Renderer getRenderer();
public BinaryFont loadFont(String fontName) throws IOException; public BinaryFont loadFont(String fontName) throws IOException;
public BinaryFont loadFont(String path, String fontName) throws IOException; public BinaryFont loadFont(String path, String fontName) throws IOException;
public Skin loadSkin(String file) throws IOException; public Skin loadSkin(String file) throws IOException;

View File

@ -11,8 +11,8 @@ public interface Skin {
public boolean isInitialized(); public boolean isInitialized();
public void use(GraphicEngine d); public void use(GraphicEngine d);
public int getSkinWidth(); public int getSkinWidth();
public int getSkinHeight(); public int getSkinHeight();
} }

View File

@ -55,16 +55,21 @@ public class CPUEngine implements GraphicEngine {
setDisplayMode(StaticVars.screenSize[0], StaticVars.screenSize[1]); setDisplayMode(StaticVars.screenSize[0], StaticVars.screenSize[1]);
INSTANCE.setVisible(true); INSTANCE.setVisible(true);
initialized = true; initialized = true;
if (onInitialized != null) if (onInitialized != null) {
onInitialized.run(); onInitialized.run();
}
} }
@Override @Override
public boolean wasResized() { public boolean wasResized() {
if (INSTANCE.wasResized) { if (INSTANCE.wasResized) {
r.size = new int[] { INSTANCE.getWidth(), INSTANCE.getHeight() }; r.size = new int[] { INSTANCE.getWidth(), INSTANCE.getHeight() };
if (r.size[0] <= 0) r.size[0] = 1; if (r.size[0] <= 0) {
if (r.size[1] <= 0) r.size[1] = 1; r.size[0] = 1;
}
if (r.size[1] <= 0) {
r.size[1] = 1;
}
CPURenderer.canvas2d = new int[r.size[0] * r.size[1]]; CPURenderer.canvas2d = new int[r.size[0] * r.size[1]];
g = new BufferedImage(r.size[0], r.size[1], BufferedImage.TYPE_INT_ARGB); g = new BufferedImage(r.size[0], r.size[1], BufferedImage.TYPE_INT_ARGB);
INSTANCE.wasResized = false; INSTANCE.wasResized = false;
@ -180,13 +185,14 @@ public class CPUEngine implements GraphicEngine {
public void waitForExit() { public void waitForExit() {
try { try {
exitSemaphore.acquire(); exitSemaphore.acquire();
} catch (InterruptedException e) {} } catch (final InterruptedException e) {}
} }
@Override @Override
public boolean isSupported() { public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "cpu") if (Utils.forceEngine != null && Utils.forceEngine != "cpu") {
return false; return false;
}
return (Utils.headlessOverride || GraphicsEnvironment.isHeadless()) == false; return (Utils.headlessOverride || GraphicsEnvironment.isHeadless()) == false;
} }

View File

@ -38,11 +38,11 @@ public class CPUFont implements BinaryFont {
isResource = true; isResource = true;
load("/font_" + fontName + ".rft", onlyRaw); load("/font_" + fontName + ".rft", onlyRaw);
} }
public CPUFont(String path, String fontName) throws IOException { public CPUFont(String path, String fontName) throws IOException {
this(path, fontName, false); this(path, fontName, false);
} }
CPUFont(String path, String fontName, boolean onlyRaw) throws IOException { CPUFont(String path, String fontName, boolean onlyRaw) throws IOException {
isResource = false; isResource = false;
load(path + "/font_" + fontName + ".rft", onlyRaw); load(path + "/font_" + fontName + ".rft", onlyRaw);
@ -60,7 +60,7 @@ public class CPUFont implements BinaryFont {
public void load(String path) throws IOException { public void load(String path) throws IOException {
load(path, false); load(path, false);
} }
private void load(String path, boolean onlyRaw) throws IOException { private void load(String path, boolean onlyRaw) throws IOException {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "Loading font " + path); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "Loading font " + path);
loadFont(path); loadFont(path);
@ -167,38 +167,38 @@ public class CPUFont implements BinaryFont {
} }
private void findIntervals() { private void findIntervals() {
final LinkedList<int[]> intervals = new LinkedList<int[]>(); final LinkedList<int[]> intervals = new LinkedList<>();
int beginIndex = -1; int beginIndex = -1;
int endIndex = 0; int endIndex = 0;
int intervalSize = 0; int intervalSize = 0;
int holeSize = 0; final int holeSize = 0;
for (int i = 0; i < rawchars.length; i++) { for (int i = 0; i < rawchars.length; i++) {
if (rawchars[i] != null) { if (rawchars[i] != null) {
beginIndex = i; beginIndex = i;
int firstNull = 0; int firstNull = 0;
while(i+firstNull < rawchars.length && rawchars[i+firstNull] != null) { while (i + firstNull < rawchars.length && rawchars[i + firstNull] != null) {
firstNull++; firstNull++;
} }
endIndex = beginIndex + firstNull - 1; endIndex = beginIndex + firstNull - 1;
i = endIndex; i = endIndex;
if (endIndex >= 0) { if (endIndex >= 0) {
intervalSize = endIndex - beginIndex + 1; intervalSize = endIndex - beginIndex + 1;
intervals.add(new int[] {beginIndex, endIndex, intervalSize}); intervals.add(new int[] { beginIndex, endIndex, intervalSize });
intervalsTotalSize += intervalSize; intervalsTotalSize += intervalSize;
} }
beginIndex = -1; beginIndex = -1;
} }
} }
int lastIndex = 0; int lastIndex = 0;
boolean[][] newrawchars = new boolean[intervalsTotalSize][]; final boolean[][] newrawchars = new boolean[intervalsTotalSize][];
for (int[] interval: intervals) { for (final int[] interval : intervals) {
if (rawchars.length - (interval[0]) - interval[2] < 0) { if (rawchars.length - (interval[0]) - interval[2] < 0) {
System.err.println(interval[0] + "-" + interval[1] + "(" + interval[2] + ")"); System.err.println(interval[0] + "-" + interval[1] + "(" + interval[2] + ")");
System.err.println(rawchars.length - (interval[0]) - interval[2]); System.err.println(rawchars.length - (interval[0]) - interval[2]);
throw new ArrayIndexOutOfBoundsException(); throw new ArrayIndexOutOfBoundsException();
} }
if (newrawchars.length - (lastIndex-1) - interval[2] < 0) { if (newrawchars.length - (lastIndex - 1) - interval[2] < 0) {
System.err.println(newrawchars.length - (lastIndex-1) - interval[2]); System.err.println(newrawchars.length - (lastIndex - 1) - interval[2]);
throw new ArrayIndexOutOfBoundsException(); throw new ArrayIndexOutOfBoundsException();
} }
System.arraycopy(rawchars, interval[0], newrawchars, lastIndex, interval[2]); System.arraycopy(rawchars, interval[0], newrawchars, lastIndex, interval[2]);
@ -208,7 +208,7 @@ public class CPUFont implements BinaryFont {
final int intervalsSize = intervals.size(); final int intervalsSize = intervals.size();
this.intervals = new int[intervalsSize * 3]; this.intervals = new int[intervalsSize * 3];
for (int i = 0; i < intervalsSize; i++) { for (int i = 0; i < intervalsSize; i++) {
int[] interval = intervals.get(i); final int[] interval = intervals.get(i);
this.intervals[i * 3 + 0] = interval[0]; this.intervals[i * 3 + 0] = interval[0];
this.intervals[i * 3 + 1] = interval[1]; this.intervals[i * 3 + 1] = interval[1];
this.intervals[i * 3 + 2] = interval[2]; this.intervals[i * 3 + 2] = interval[2];
@ -232,41 +232,41 @@ public class CPUFont implements BinaryFont {
final int[] indexes = new int[l]; final int[] indexes = new int[l];
final char[] chars = txt.toCharArray(); final char[] chars = txt.toCharArray();
for (int i = 0; i < l; i++) { for (int i = 0; i < l; i++) {
int originalIndex = (chars[i] & 0xFFFF) - minBound; final int originalIndex = (chars[i] & 0xFFFF) - minBound;
indexes[i] = compressIndex(originalIndex); indexes[i] = compressIndex(originalIndex);
} }
return indexes; return indexes;
} }
public int getCharIndex(char c) { public int getCharIndex(char c) {
int originalIndex = c & 0xFFFF; final int originalIndex = c & 0xFFFF;
return compressIndex(originalIndex); return compressIndex(originalIndex);
} }
private int compressIndex(int originalIndex) { private int compressIndex(int originalIndex) {
int compressedIndex = 0; int compressedIndex = 0;
for (int i = 0; i < intervals.length; i+=3) { for (int i = 0; i < intervals.length; i += 3) {
if (intervals[i] > originalIndex) { if (intervals[i] > originalIndex) {
break; break;
} else if (originalIndex <= intervals[i+1]) { } else if (originalIndex <= intervals[i + 1]) {
compressedIndex+=(originalIndex-intervals[i]); compressedIndex += (originalIndex - intervals[i]);
break; break;
} else { } else {
compressedIndex+=intervals[i+2]; compressedIndex += intervals[i + 2];
} }
} }
return compressedIndex; return compressedIndex;
} }
private int decompressIndex(int compressedIndex) { private int decompressIndex(int compressedIndex) {
int originalIndex = 0; final int originalIndex = 0;
int i = 0; int i = 0;
for (int intvl = 0; intvl < intervals.length; intvl+=3) { for (int intvl = 0; intvl < intervals.length; intvl += 3) {
i+=intervals[intvl+2]; i += intervals[intvl + 2];
if (i == compressedIndex) { if (i == compressedIndex) {
return intervals[intvl+1]; return intervals[intvl + 1];
} else if (i > compressedIndex) { } else if (i > compressedIndex) {
return intervals[intvl+1] - (i - compressedIndex); return intervals[intvl + 1] - (i - compressedIndex);
} }
} }
return originalIndex; return originalIndex;

View File

@ -48,8 +48,10 @@ public class CPURenderer implements Renderer {
public void glClear(int screenWidth, int screenHeight) { public void glClear(int screenWidth, int screenHeight) {
for (int x = 0; x < screenWidth; x++) { for (int x = 0; x < screenWidth; x++) {
for (int y = 0; y < screenHeight; y++) { for (int y = 0; y < screenHeight; y++) {
int index = x + y * size[0]; final int index = x + y * size[0];
if (index >= 0 && index < canvas2d.length) canvas2d[index] = clearcolor; if (index >= 0 && index < canvas2d.length) {
canvas2d[index] = clearcolor;
}
} }
} }
} }
@ -57,10 +59,10 @@ public class CPURenderer implements Renderer {
private void glDrawSkin(int x0, int y0, int x1, int y1, int s0, int t0, int s1, int t1, boolean transparent) { private void glDrawSkin(int x0, int y0, int x1, int y1, int s0, int t0, int s1, int t1, boolean transparent) {
x0 += StaticVars.screenPos[0]; x0 += StaticVars.screenPos[0];
y0 += StaticVars.screenPos[1]; y0 += StaticVars.screenPos[1];
double incrementX = Math.abs((double)(x1-x0)/(double)(s1-s0)); final double incrementX = Math.abs((double) (x1 - x0) / (double) (s1 - s0));
double incrementY = Math.abs((double)(y1-y0)/(double)(t1-t0)); final double incrementY = Math.abs((double) (y1 - y0) / (double) (t1 - t0));
boolean flippedX = (x1-x0)/(s1-s0) < 0; final boolean flippedX = (x1 - x0) / (s1 - s0) < 0;
boolean flippedY = (y1-y0)/(t1-t0) < 0; final boolean flippedY = (y1 - y0) / (t1 - t0) < 0;
int oldColor; int oldColor;
int newColor; int newColor;
final int onex = s0 <= s1 ? 1 : -1; final int onex = s0 <= s1 ? 1 : -1;
@ -106,25 +108,25 @@ public class CPURenderer implements Renderer {
} }
y0 = 0; y0 = 0;
} }
for (double pixelX = 0; pixelX < x1-x0; pixelX++) { for (double pixelX = 0; pixelX < x1 - x0; pixelX++) {
for (double pixelY = 0; pixelY < y1-y0; pixelY++) { for (double pixelY = 0; pixelY < y1 - y0; pixelY++) {
final int index = (int) (x0+pixelX + (y0+pixelY) * size[0]); final int index = (int) (x0 + pixelX + (y0 + pixelY) * size[0]);
if (index >= 0 && index < canvas2d.length && pixelX < size[0]) { if (index >= 0 && index < canvas2d.length && pixelX < size[0]) {
int texx = (int) (pixelX / incrementX); final int texx = (int) (pixelX / incrementX);
int texy = (int) (pixelY / incrementY); final int texy = (int) (pixelY / incrementY);
int expX = 0; int expX = 0;
int expY = 0; int expY = 0;
if (incrementX < 1) { if (incrementX < 1) {
expX = (int) Math.round(1d/incrementX/2d); expX = (int) Math.round(1d / incrementX / 2d);
} }
if (incrementY < 1) { if (incrementY < 1) {
expY = (int) Math.round(1d/incrementY/2d); expY = (int) Math.round(1d / incrementY / 2d);
} }
int[] newColors = new int[(1+expX*2)*(1+expY*2)]; final int[] newColors = new int[(1 + expX * 2) * (1 + expY * 2)];
for (int expXi = -expX; expXi <= expX; expXi++) { for (int expXi = -expX; expXi <= expX; expXi++) {
for (int expYi = -expY; expYi <= expY; expYi++) { for (int expYi = -expY; expYi <= expY; expYi++) {
int skinIndex = (int) (s0 + (texx*(flippedX ? -1d : 1d)+(flippedX ? -(s0 - s1)-1 : 0)+expXi) + (t0 + (texy*(flippedY ? -1d : 1d)+(flippedY ? -(t0 - t1)-1 : 0)+expYi)) * currentSkin.skinSize[0]); final int skinIndex = (int) (s0 + (texx * (flippedX ? -1d : 1d) + (flippedX ? -(s0 - s1) - 1 : 0) + expXi) + (t0 + (texy * (flippedY ? -1d : 1d) + (flippedY ? -(t0 - t1) - 1 : 0) + expYi)) * currentSkin.skinSize[0]);
int idx = (expXi+expX)+(expYi+expY)*(1+expY*2); final int idx = (expXi + expX) + (expYi + expY) * (1 + expY * 2);
if (idx >= 0 && idx < newColors.length) { if (idx >= 0 && idx < newColors.length) {
newColors[idx] = getSkinColorAt(currentSkin.skinData, skinIndex); newColors[idx] = getSkinColorAt(currentSkin.skinData, skinIndex);
} }
@ -135,12 +137,12 @@ public class CPURenderer implements Renderer {
oldColor = canvas2d[index]; oldColor = canvas2d[index];
final float a2 = (newColor >> 24 & 0xFF) / 255f; final float a2 = (newColor >> 24 & 0xFF) / 255f;
final float a1 = 1f - a2; final float a1 = 1f - a2;
int r = (int) ((oldColor >> 16 & 0xFF) * a1 + (newColor >> 16 & 0xFF) * a2); final int r = (int) ((oldColor >> 16 & 0xFF) * a1 + (newColor >> 16 & 0xFF) * a2);
int g = (int) ((oldColor >> 8 & 0xFF) * a1 + (newColor >> 8 & 0xFF) * a2); final int g = (int) ((oldColor >> 8 & 0xFF) * a1 + (newColor >> 8 & 0xFF) * a2);
int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2); final int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2);
newColor = 0xFF000000 | r << 16 | g << 8 | b; newColor = 0xFF000000 | r << 16 | g << 8 | b;
} }
canvas2d[index] = stackColors(canvas2d[index], newColor); canvas2d[index] = stackColors(canvas2d[index], newColor);
} }
} }
@ -152,14 +154,13 @@ public class CPURenderer implements Renderer {
int r = 0; int r = 0;
int g = 0; int g = 0;
int b = 0; int b = 0;
for (int i = 0; i < newColors.length; i++) { for (final int newColor : newColors) {
int newColor = newColors[i];
a += newColor >> 24 & 0xFF; a += newColor >> 24 & 0xFF;
r += newColor >> 16 & 0xFF; r += newColor >> 16 & 0xFF;
g += newColor >> 8 & 0xFF; g += newColor >> 8 & 0xFF;
b += newColor & 0xFF; b += newColor & 0xFF;
} }
return (a/newColors.length) << 24 | (r/newColors.length) << 16 | (g/newColors.length) << 8 | (b/newColors.length); return (a / newColors.length) << 24 | (r / newColors.length) << 16 | (g / newColors.length) << 8 | (b / newColors.length);
} }
private int stackColors(int... color) { private int stackColors(int... color) {
@ -167,25 +168,24 @@ public class CPURenderer implements Renderer {
double r = 0; double r = 0;
double g = 0; double g = 0;
double b = 0; double b = 0;
for (int i = 0; i < color.length; i++) { for (final int newColor : color) {
int newColor = color[i]; final double alpha = (newColor >> 24 & 0xFF) / 255d;
double alpha = (newColor >> 24 & 0xFF) / 255d; a = a * (1d - alpha) + (newColor >> 24 & 0xFF) * alpha;
a = a * (1d-alpha) + (newColor >> 24 & 0xFF) * alpha; r = r * (1d - alpha) + (newColor >> 16 & 0xFF) * alpha;
r = r * (1d-alpha) + (newColor >> 16 & 0xFF) * alpha; g = g * (1d - alpha) + (newColor >> 8 & 0xFF) * alpha;
g = g * (1d-alpha) + (newColor >> 8 & 0xFF) * alpha; b = b * (1d - alpha) + (newColor & 0xFF) * alpha;
b = b * (1d-alpha) + (newColor & 0xFF) * alpha;
} }
return ((int)a) << 24 | ((int)r) << 16 | ((int)g) << 8 | ((int)b); return ((int) a) << 24 | ((int) r) << 16 | ((int) g) << 8 | ((int) b);
} }
private int getSkinColorAt(int[] skinData, int skinIndex) { private int getSkinColorAt(int[] skinData, int skinIndex) {
int newColor = 0; int newColor = 0;
if (skinIndex >= 0 && skinIndex < skinData.length) { if (skinIndex >= 0 && skinIndex < skinData.length) {
newColor = skinData[skinIndex]; newColor = skinData[skinIndex];
final int a = (int) ((double)(newColor >> 24 & 0xFF) * ((double)(color >> 24 & 0xFF)/(double)0xFF)); final int a = (int) ((newColor >> 24 & 0xFF) * ((double) (color >> 24 & 0xFF) / (double) 0xFF));
int r = (int) ((double)(newColor >> 16 & 0xFF) * ((double)(color >> 16 & 0xFF)/(double)0xFF)); final int r = (int) ((newColor >> 16 & 0xFF) * ((double) (color >> 16 & 0xFF) / (double) 0xFF));
int g = (int) ((double)(newColor >> 8 & 0xFF) * ((double)(color >> 8 & 0xFF)/(double)0xFF)); final int g = (int) ((newColor >> 8 & 0xFF) * ((double) (color >> 8 & 0xFF) / (double) 0xFF));
int b = (int) ((double)(newColor & 0xFF) * ((double)(color & 0xFF)/(double)0xFF)); final int b = (int) ((newColor & 0xFF) * ((double) (color & 0xFF) / (double) 0xFF));
newColor = a << 24 | r << 16 | g << 8 | b; newColor = a << 24 | r << 16 | g << 8 | b;
} }
return newColor; return newColor;
@ -270,9 +270,10 @@ public class CPURenderer implements Renderer {
final int sizeW = size[0]; final int sizeW = size[0];
for (int px = x0; px < x1; px++) { for (int px = x0; px < x1; px++) {
for (int py = y0; py < y1; py++) { for (int py = y0; py < y1; py++) {
int idx = (px) + (py) * sizeW; final int idx = (px) + (py) * sizeW;
if (px < sizeW && idx >= 0 && idx < canvas2d.length) if (px < sizeW && idx >= 0 && idx < canvas2d.length) {
canvas2d[idx] = stackColors(canvas2d[idx], color); canvas2d[idx] = stackColors(canvas2d[idx], color);
}
} }
} }
} }
@ -307,7 +308,7 @@ public class CPURenderer implements Renderer {
final int bit = dx + dy * currentFont.charW; final int bit = dx + dy * currentFont.charW;
currentInt = (int) (Math.floor(bit) / (CPUFont.intBits)); currentInt = (int) (Math.floor(bit) / (CPUFont.intBits));
currentIntBitPosition = bit - (currentInt * CPUFont.intBits); currentIntBitPosition = bit - (currentInt * CPUFont.intBits);
int charIdx = charIndex * currentFont.charIntCount + currentInt; final int charIdx = charIndex * currentFont.charIntCount + currentInt;
if (charIdx >= 0 && charIdx < currentFont.chars32.length) { if (charIdx >= 0 && charIdx < currentFont.chars32.length) {
bitData = (currentFont.chars32[charIdx] >> currentIntBitPosition) & 1; bitData = (currentFont.chars32[charIdx] >> currentIntBitPosition) & 1;
screenPos = ix + cpos + dx + (iy + dy) * screenSize[0]; screenPos = ix + cpos + dx + (iy + dy) * screenSize[0];

View File

@ -25,7 +25,7 @@ public class CPUSkin implements Skin {
final BufferedImage img = ImageIO.read(isResource ? this.getClass().getResource("/" + file) : new File(file).toURI().toURL()); final BufferedImage img = ImageIO.read(isResource ? this.getClass().getResource("/" + file) : new File(file).toURI().toURL());
if (img == null) { if (img == null) {
skinData = new int[0]; skinData = new int[0];
skinSize = new int[] {0,0}; skinSize = new int[] { 0, 0 };
} else { } else {
skinData = getMatrixOfImage(img); skinData = getMatrixOfImage(img);
skinSize = new int[] { img.getWidth(), img.getHeight() }; skinSize = new int[] { img.getWidth(), img.getHeight() };

View File

@ -39,7 +39,9 @@ public class SwingWindow extends JFrame {
// Transparent 16 x 16 pixel cursor image. // Transparent 16 x 16 pixel cursor image.
final BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); final BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
if (StaticVars.debugOn & StaticVars.debugWindow2x) mult = 2; if (StaticVars.debugOn & StaticVars.debugWindow2x) {
mult = 2;
}
if (StaticVars.debugOn) { if (StaticVars.debugOn) {
if (Utils.debugThirdScreen) { if (Utils.debugThirdScreen) {
this.setLocation(2880, 900); this.setLocation(2880, 900);
@ -100,10 +102,10 @@ public class SwingWindow extends JFrame {
@Override @Override
public void setSize(int width, int height) { public void setSize(int width, int height) {
c.setSize(new Dimension(width*mult, height*mult)); c.setSize(new Dimension(width * mult, height * mult));
c.setPreferredSize(new Dimension(width*mult, height*mult)); c.setPreferredSize(new Dimension(width * mult, height * mult));
super.getContentPane().setSize(new Dimension(width*mult, height*mult)); super.getContentPane().setSize(new Dimension(width * mult, height * mult));
super.getContentPane().setPreferredSize(new Dimension(width*mult, height*mult)); super.getContentPane().setPreferredSize(new Dimension(width * mult, height * mult));
super.pack(); super.pack();
} }
@ -114,12 +116,12 @@ public class SwingWindow extends JFrame {
@Override @Override
public int getWidth() { public int getWidth() {
return c.getWidth()/mult; return c.getWidth() / mult;
} }
@Override @Override
public int getHeight() { public int getHeight() {
return c.getHeight()/mult; return c.getHeight() / mult;
} }
public void setRenderingLoop(RenderingLoop renderingLoop) { public void setRenderingLoop(RenderingLoop renderingLoop) {
@ -127,12 +129,12 @@ public class SwingWindow extends JFrame {
} }
public void centerWindow() { public void centerWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); final Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - super.getWidth()) / 2); final int x = (int) ((dimension.getWidth() - super.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - super.getHeight()) / 2); final int y = (int) ((dimension.getHeight() - super.getHeight()) / 2);
super.setLocation(x, y); super.setLocation(x, y);
} }
// private static ObjectArrayList<Double> mediaValori = new ObjectArrayList<Double>(); // private static ObjectArrayList<Double> mediaValori = new ObjectArrayList<Double>();
public class CustomCanvas extends JPanel { public class CustomCanvas extends JPanel {
@ -151,8 +153,8 @@ public class SwingWindow extends JFrame {
final int[] a = ((DataBufferInt) display.g.getRaster().getDataBuffer()).getData(); final int[] a = ((DataBufferInt) display.g.getRaster().getDataBuffer()).getData();
// System.arraycopy(canvas2d, 0, a, 0, canvas2d.length); // System.arraycopy(canvas2d, 0, a, 0, canvas2d.length);
CPURenderer.canvas2d = a; CPURenderer.canvas2d = a;
g.clearRect(0, 0, display.r.size[0]*mult, display.r.size[1]*mult); g.clearRect(0, 0, display.r.size[0] * mult, display.r.size[1] * mult);
g.drawImage(display.g, 0, 0, display.r.size[0]*mult, display.r.size[1]*mult, null); g.drawImage(display.g, 0, 0, display.r.size[0] * mult, display.r.size[1] * mult, null);
// long time2 = System.nanoTime(); // long time2 = System.nanoTime();
// double timeDelta = ((double)(time2-time1))/1000000000d; // double timeDelta = ((double)(time2-time1))/1000000000d;
// double mediaAttuale = timeDelta; // double mediaAttuale = timeDelta;

View File

@ -1,11 +1,9 @@
package org.warp.picalculator.gui.graphicengine.framebuffer; package org.warp.picalculator.gui.graphicengine.framebuffer;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer; import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import org.warp.picalculator.MmapByteBuffer; import org.warp.picalculator.MmapByteBuffer;
@ -26,8 +24,8 @@ public class FBEngine implements GraphicEngine {
private static final int FB_DISPLAY_BPP = 32; private static final int FB_DISPLAY_BPP = 32;
private static final int WIDTH = 480; private static final int WIDTH = 480;
private static final int HEIGHT = 320; private static final int HEIGHT = 320;
private static final int[] SIZE = new int[] {WIDTH, HEIGHT}; private static final int[] SIZE = new int[] { WIDTH, HEIGHT };
private TestJNI jni = new TestJNI(); private final TestJNI jni = new TestJNI();
public FBRenderer r; public FBRenderer r;
private MappedByteBuffer fb; private MappedByteBuffer fb;
MmapByteBuffer realFb; MmapByteBuffer realFb;
@ -35,8 +33,7 @@ public class FBEngine implements GraphicEngine {
public volatile boolean initialized = false; public volatile boolean initialized = false;
public Semaphore exitSemaphore = new Semaphore(0); public Semaphore exitSemaphore = new Semaphore(0);
private boolean resizedTrigger = false; private boolean resizedTrigger = false;
@Override @Override
public int[] getSize() { public int[] getSize() {
return SIZE; return SIZE;
@ -48,16 +45,13 @@ public class FBEngine implements GraphicEngine {
} }
@Override @Override
public void setTitle(String title) { public void setTitle(String title) {}
}
@Override @Override
public void setResizable(boolean r) { public void setResizable(boolean r) {}
}
@Override @Override
public void setDisplayMode(int ww, int wh) { public void setDisplayMode(int ww, int wh) {}
}
@Override @Override
public void create(Runnable onInitialized) { public void create(Runnable onInitialized) {
@ -65,12 +59,13 @@ public class FBEngine implements GraphicEngine {
realFb = jni.retrieveBuffer(); realFb = jni.retrieveBuffer();
final long fbLen = realFb.getLength(); final long fbLen = realFb.getLength();
fb = (MappedByteBuffer) ByteBuffer.allocateDirect((int) fbLen); fb = (MappedByteBuffer) ByteBuffer.allocateDirect((int) fbLen);
r = new FBRenderer(this, fb); r = new FBRenderer(this, fb);
initialized = true; initialized = true;
if (onInitialized != null) if (onInitialized != null) {
onInitialized.run(); onInitialized.run();
}
} }
@Override @Override
@ -97,7 +92,7 @@ public class FBEngine implements GraphicEngine {
public void destroy() { public void destroy() {
try { try {
fbFileRW.close(); fbFileRW.close();
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -132,7 +127,7 @@ public class FBEngine implements GraphicEngine {
} }
private int _________________TMP = 0; private int _________________TMP = 0;
@Override @Override
public void repaint() { public void repaint() {
if (_________________TMP % 100 == 0) { if (_________________TMP % 100 == 0) {
@ -142,10 +137,10 @@ public class FBEngine implements GraphicEngine {
_________________TMP++; _________________TMP++;
realFb.getBuffer().clear(); realFb.getBuffer().clear();
realFb.getBuffer().put(fb); realFb.getBuffer().put(fb);
for (int i = 0; i < fb.capacity()/2; i++) { for (int i = 0; i < fb.capacity() / 2; i++) {
realFb.getBuffer().put(i, (byte) (_________________TMP < 50 ? 0xFF : 0xF0)); realFb.getBuffer().put(i, (byte) (_________________TMP < 50 ? 0xFF : 0xF0));
} }
for (int i = fb.capacity()/2; i < fb.capacity(); i++) { for (int i = fb.capacity() / 2; i < fb.capacity(); i++) {
realFb.getBuffer().put(i, (byte) (0x18)); realFb.getBuffer().put(i, (byte) (0x18));
} }
} }
@ -174,13 +169,14 @@ public class FBEngine implements GraphicEngine {
public void waitForExit() { public void waitForExit() {
try { try {
exitSemaphore.acquire(); exitSemaphore.acquire();
} catch (InterruptedException e) {} } catch (final InterruptedException e) {}
} }
@Override @Override
public boolean isSupported() { public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "fb") if (Utils.forceEngine != null && Utils.forceEngine != "fb") {
return false; return false;
}
if (Utils.headlessOverride) { if (Utils.headlessOverride) {
return false; return false;
} }
@ -203,5 +199,5 @@ public class FBEngine implements GraphicEngine {
public boolean doesRefreshPauses() { public boolean doesRefreshPauses() {
return true; return true;
} }
} }

View File

@ -7,49 +7,48 @@ import org.warp.picalculator.gui.graphicengine.Renderer;
public class FBRenderer implements Renderer { public class FBRenderer implements Renderer {
public FBRenderer(FBEngine fbEngine, MappedByteBuffer fb) { public FBRenderer(FBEngine fbEngine, MappedByteBuffer fb) {}
}
@Override @Override
public void glColor3i(int r, int gg, int b) { public void glColor3i(int r, int gg, int b) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glColor(int c) { public void glColor(int c) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glColor4i(int red, int green, int blue, int alpha) { public void glColor4i(int red, int green, int blue, int alpha) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glColor3f(float red, float green, float blue) { public void glColor3f(float red, float green, float blue) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glColor4f(float red, float green, float blue, float alpha) { public void glColor4f(float red, float green, float blue, float alpha) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glClearColor4i(int red, int green, int blue, int alpha) { public void glClearColor4i(int red, int green, int blue, int alpha) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glClearColor4f(float red, float green, float blue, float alpha) { public void glClearColor4f(float red, float green, float blue, float alpha) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
@ -61,74 +60,74 @@ public class FBRenderer implements Renderer {
@Override @Override
public void glClearColor(int c) { public void glClearColor(int c) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glClear(int screenWidth, int screenHeight) { public void glClear(int screenWidth, int screenHeight) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawLine(float x0, float y0, float x1, float y1) { public void glDrawLine(float x0, float y0, float x1, float y1) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight) { float uvHeight) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glFillColor(float x, float y, float width, float height) { public void glFillColor(float x, float y, float width, float height) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawCharLeft(int x, int y, char ch) { public void glDrawCharLeft(int x, int y, char ch) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawCharCenter(int x, int y, char ch) { public void glDrawCharCenter(int x, int y, char ch) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawCharRight(int x, int y, char ch) { public void glDrawCharRight(int x, int y, char ch) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawStringLeft(float x, float y, String text) { public void glDrawStringLeft(float x, float y, String text) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawStringCenter(float x, float y, String text) { public void glDrawStringCenter(float x, float y, String text) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glDrawStringRight(float x, float y, String text) { public void glDrawStringRight(float x, float y, String text) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void glClearSkin() { public void glClearSkin() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override

View File

@ -15,7 +15,6 @@ import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.RenderingLoop; import org.warp.picalculator.gui.graphicengine.RenderingLoop;
import org.warp.picalculator.gui.graphicengine.Skin; import org.warp.picalculator.gui.graphicengine.Skin;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.Texture;
@ -26,10 +25,10 @@ public class GPUEngine implements GraphicEngine {
private NEWTWindow wnd; private NEWTWindow wnd;
private RenderingLoop d; private RenderingLoop d;
private GPURenderer r; private GPURenderer r;
private Map<String, GPUFont> fontCache = new HashMap<String, GPUFont>(); private final Map<String, GPUFont> fontCache = new HashMap<>();
int[] size = new int[] { StaticVars.screenSize[0], StaticVars.screenSize[1] }; int[] size = new int[] { StaticVars.screenSize[0], StaticVars.screenSize[1] };
private final CopyOnWriteArrayList<BinaryFont> registeredFonts = new CopyOnWriteArrayList<BinaryFont>(); private final CopyOnWriteArrayList<BinaryFont> registeredFonts = new CopyOnWriteArrayList<>();
private Semaphore exitSemaphore = new Semaphore(0); private final Semaphore exitSemaphore = new Semaphore(0);
protected LinkedList<Texture> registeredTextures; protected LinkedList<Texture> registeredTextures;
protected LinkedList<Texture> unregisteredTextures; protected LinkedList<Texture> unregisteredTextures;
@ -127,24 +126,24 @@ public class GPUEngine implements GraphicEngine {
@Override @Override
public BinaryFont loadFont(String name) throws IOException { public BinaryFont loadFont(String name) throws IOException {
for (Entry<String, GPUFont> entry : fontCache.entrySet()) { for (final Entry<String, GPUFont> entry : fontCache.entrySet()) {
if (entry.getKey().equals(name)) { if (entry.getKey().equals(name)) {
return entry.getValue(); return entry.getValue();
} }
} }
GPUFont font = new GPUFont(this, name); final GPUFont font = new GPUFont(this, name);
fontCache.put(name, font); fontCache.put(name, font);
return font; return font;
} }
@Override @Override
public BinaryFont loadFont(String path, String name) throws IOException { public BinaryFont loadFont(String path, String name) throws IOException {
for (Entry<String, GPUFont> entry : fontCache.entrySet()) { for (final Entry<String, GPUFont> entry : fontCache.entrySet()) {
if (entry.getKey().equals(name)) { if (entry.getKey().equals(name)) {
return entry.getValue(); return entry.getValue();
} }
} }
GPUFont font = new GPUFont(this, path, name); final GPUFont font = new GPUFont(this, path, name);
fontCache.put(name, font); fontCache.put(name, font);
return font; return font;
} }
@ -158,22 +157,24 @@ public class GPUEngine implements GraphicEngine {
public void waitForExit() { public void waitForExit() {
try { try {
exitSemaphore.acquire(); exitSemaphore.acquire();
} catch (InterruptedException e) {} } catch (final InterruptedException e) {}
} }
@Override @Override
public boolean isSupported() { public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "gpu") if (Utils.forceEngine != null && Utils.forceEngine != "gpu") {
return false; return false;
if (Utils.headlessOverride) }
if (Utils.headlessOverride) {
return false; return false;
}
boolean available = false; boolean available = false;
boolean errored = false; boolean errored = false;
try { try {
available = GLProfile.isAvailable(GLProfile.GL2ES2); available = GLProfile.isAvailable(GLProfile.GL2ES2);
} catch (Exception ex) { } catch (final Exception ex) {
errored = true; errored = true;
System.err.println("OpenGL Error: "+ex.getMessage()); System.err.println("OpenGL Error: " + ex.getMessage());
} }
if (!available && !errored) { if (!available && !errored) {
System.err.println(GLProfile.glAvailabilityToString()); System.err.println(GLProfile.glAvailabilityToString());

View File

@ -4,8 +4,6 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.LinkedList;
import org.warp.picalculator.Utils; import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.graphicengine.BinaryFont; import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
@ -45,7 +43,7 @@ public class GPUFont implements BinaryFont {
load(path, name); load(path, name);
((GPUEngine) g).registerFont(this); ((GPUEngine) g).registerFont(this);
} }
@Override @Override
public void load(String name) throws IOException { public void load(String name) throws IOException {
load(null, name); load(null, name);
@ -75,79 +73,79 @@ public class GPUFont implements BinaryFont {
public int[] getCharIndexes(String txt) { public int[] getCharIndexes(String txt) {
final int[] indexes = new int[txt.length()]; final int[] indexes = new int[txt.length()];
int i = 0; int i = 0;
for (char c : txt.toCharArray()) { for (final char c : txt.toCharArray()) {
indexes[i] = compressIndex((c & 0xFFFF) - minCharIndex); indexes[i] = compressIndex((c & 0xFFFF) - minCharIndex);
i++; i++;
} }
return indexes; return indexes;
} }
public int getCharIndex(char c) { public int getCharIndex(char c) {
int originalIndex = c & 0xFFFF; final int originalIndex = c & 0xFFFF;
return compressIndex(originalIndex); return compressIndex(originalIndex);
} }
private int compressIndex(int originalIndex) { private int compressIndex(int originalIndex) {
int compressedIndex = 0; int compressedIndex = 0;
for (int i = 0; i < intervals.length; i+=3) { for (int i = 0; i < intervals.length; i += 3) {
if (intervals[i] > originalIndex) { if (intervals[i] > originalIndex) {
break; break;
} else if (originalIndex <= intervals[i+1]) { } else if (originalIndex <= intervals[i + 1]) {
compressedIndex+=(originalIndex-intervals[i]); compressedIndex += (originalIndex - intervals[i]);
break; break;
} else { } else {
compressedIndex+=intervals[i+2]; compressedIndex += intervals[i + 2];
} }
} }
return compressedIndex; return compressedIndex;
} }
private int decompressIndex(int compressedIndex) { private int decompressIndex(int compressedIndex) {
int originalIndex = 0; final int originalIndex = 0;
int i = 0; int i = 0;
for (int intvl = 0; i < intervals.length; i+=3) { for (final int intvl = 0; i < intervals.length; i += 3) {
i+=intervals[intvl+2]; i += intervals[intvl + 2];
if (i >= compressedIndex) { if (i >= compressedIndex) {
return intervals[intvl+1] - (i - compressedIndex); return intervals[intvl + 1] - (i - compressedIndex);
} }
} }
return originalIndex; return originalIndex;
} }
private void pregenTexture(boolean[][] chars) throws IOException { private void pregenTexture(boolean[][] chars) throws IOException {
final int totalChars = this.intervalsTotalSize; final int totalChars = intervalsTotalSize;
int w = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charW))); int w = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charW)));
int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH))); int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH)));
int maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1; int maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1;
int maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1; int maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1;
if (w > h) { if (w > h) {
System.out.println("w > h"); System.out.println("w > h");
h = powerOf2((int) (Math.ceil((((double)totalChars)/((double)(maxIndexW))) * charH))); h = powerOf2((int) (Math.ceil((((double) totalChars) / ((double) (maxIndexW))) * charH)));
maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1; maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1;
} else { } else {
System.out.println("w <= h"); System.out.println("w <= h");
w = powerOf2((int) (Math.ceil((((double)totalChars)/((double)(maxIndexH))) * charW))); w = powerOf2((int) (Math.ceil((((double) totalChars) / ((double) (maxIndexH))) * charW)));
maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1; maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1;
} }
// final int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH))); // final int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH)));
System.out.println(((int)Math.ceil(Math.sqrt(totalChars) * charW)) + " * " + ((int)Math.ceil(Math.sqrt(totalChars) * charH)) + " --> " + w + " * " + h); System.out.println(((int) Math.ceil(Math.sqrt(totalChars) * charW)) + " * " + ((int) Math.ceil(Math.sqrt(totalChars) * charH)) + " --> " + w + " * " + h);
File f = Files.createTempFile("texture-font-", ".png").toFile(); final File f = Files.createTempFile("texture-font-", ".png").toFile();
f.deleteOnExit(); f.deleteOnExit();
final FileOutputStream outputStream = new FileOutputStream(f); final FileOutputStream outputStream = new FileOutputStream(f);
final ImageInfo imi = new ImageInfo(w, h, 8, true); // 8 bits per channel, alpha final ImageInfo imi = new ImageInfo(w, h, 8, true); // 8 bits per channel, alpha
// open image for writing to a output stream // open image for writing to a output stream
final PngWriter png = new PngWriter(outputStream, imi); final PngWriter png = new PngWriter(outputStream, imi);
for (int y = 0; y < png.imgInfo.rows; y++) { for (int y = 0; y < png.imgInfo.rows; y++) {
ImageLineInt iline = new ImageLineInt(imi); final ImageLineInt iline = new ImageLineInt(imi);
int[] xValues = new int[imi.cols]; final int[] xValues = new int[imi.cols];
for (int indexX = 0; indexX <= maxIndexW; indexX++) {// this line will be written to all rows for (int indexX = 0; indexX <= maxIndexW; indexX++) {// this line will be written to all rows
final int charY = (y % charH); final int charY = (y % charH);
final int indexY = (y - charY)/charH; final int indexY = (y - charY) / charH;
final int i = indexY * (maxIndexW+1) + indexX - this.minCharIndex; final int i = indexY * (maxIndexW + 1) + indexX - minCharIndex;
boolean[] currentChar; boolean[] currentChar;
if (i < totalChars && (currentChar=chars[i]) != null) { if (i < totalChars && (currentChar = chars[i]) != null) {
for (int charX = 0; charX < charW; charX++) { for (int charX = 0; charX < charW; charX++) {
if (i >= 0 & i < totalChars && currentChar != null && currentChar[charX + charY * charW]) { if (i >= 0 & i < totalChars && currentChar != null && currentChar[charX + charY * charW]) {
xValues[indexX * charW + charX] = 0xFFFFFFFF; xValues[indexX * charW + charX] = 0xFFFFFFFF;
@ -165,7 +163,7 @@ public class GPUFont implements BinaryFont {
chars = null; chars = null;
png.end(); png.end();
Utils.gc(); Utils.gc();
try { try {
memoryWidth = w; memoryWidth = w;
memoryHeight = h; memoryHeight = h;
@ -175,7 +173,7 @@ public class GPUFont implements BinaryFont {
outputStream.flush(); outputStream.flush();
outputStream.close(); outputStream.close();
Utils.gc(); Utils.gc();
this.tmpFont = f; tmpFont = f;
} catch (GLException | IOException e) { } catch (GLException | IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -191,7 +189,7 @@ public class GPUFont implements BinaryFont {
} }
private int powerOf2(int i) { private int powerOf2(int i) {
return i >1 ? Integer.highestOneBit(i-1)<<1 : 1; return i > 1 ? Integer.highestOneBit(i - 1) << 1 : 1;
} }
@Override @Override
@ -238,11 +236,11 @@ public class GPUFont implements BinaryFont {
@Override @Override
public int getSkinWidth() { public int getSkinWidth() {
return this.memoryWidth; return memoryWidth;
} }
@Override @Override
public int getSkinHeight() { public int getSkinHeight() {
return this.memoryHeight; return memoryHeight;
} }
} }

View File

@ -6,7 +6,6 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.Buffer; import java.nio.Buffer;
import java.nio.FloatBuffer; import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.file.Files; import java.nio.file.Files;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
@ -28,10 +27,8 @@ public class GPURenderer implements Renderer {
public static GL2ES1 gl; public static GL2ES1 gl;
private static final int ELEMENTS_MAX_COUNT_PER_BUFFER = StaticVars.enableVBO ? 128 : 1; private static final int ELEMENTS_MAX_COUNT_PER_BUFFER = StaticVars.enableVBO ? 128 : 1;
private static final int ELEMENT_VERTICES_COUNT = 6, private static final int ELEMENT_VERTICES_COUNT = 6, vertSize = 3, texSize = 2, colSize = 4, vertBuffer = 0,
vertSize = 3, texSize = 2, colSize = 4, texBuffer = 1, colBuffer = 2, vertMax = vertSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER,
vertBuffer = 0, texBuffer = 1, colBuffer = 2,
vertMax = vertSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER,
texMax = texSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER, texMax = texSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER,
colMax = colSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER; colMax = colSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER;
@ -256,19 +253,19 @@ public class GPURenderer implements Renderer {
} else { } else {
f = new File(file); f = new File(file);
} }
int imgW = img.getWidth(); final int imgW = img.getWidth();
int imgH = img.getHeight(); final int imgH = img.getHeight();
img = null; img = null;
Utils.gc(); Utils.gc();
return new OpenedTextureData(imgW, imgH, f, isResource); return new OpenedTextureData(imgW, imgH, f, isResource);
} }
public static class OpenedTextureData { public static class OpenedTextureData {
public final int w; public final int w;
public final int h; public final int h;
public final File f; public final File f;
public final boolean deleteOnExit; public final boolean deleteOnExit;
/** /**
* @param w * @param w
* @param h * @param h
@ -281,16 +278,18 @@ public class GPURenderer implements Renderer {
this.f = f; this.f = f;
this.deleteOnExit = deleteOnExit; this.deleteOnExit = deleteOnExit;
} }
} }
static Texture importTexture(File f, boolean deleteOnExit) throws GLException, IOException { static Texture importTexture(File f, boolean deleteOnExit) throws GLException, IOException {
final Texture tex = TextureIO.newTexture(f, false); final Texture tex = TextureIO.newTexture(f, false);
if (deleteOnExit && f.exists()) { if (deleteOnExit && f.exists()) {
try { try {
if (StaticVars.debugOn) throw new IOException("Delete on exit!"); if (StaticVars.debugOn) {
throw new IOException("Delete on exit!");
}
f.delete(); f.delete();
}catch (Exception ex) { } catch (final Exception ex) {
f.deleteOnExit(); f.deleteOnExit();
} }
} }
@ -328,7 +327,7 @@ public class GPURenderer implements Renderer {
} }
} }
} }
private void changeTexture() { private void changeTexture() {
precTexEnabled = currentTexEnabled; precTexEnabled = currentTexEnabled;
precTex = currentTex; precTex = currentTex;
@ -340,7 +339,7 @@ public class GPURenderer implements Renderer {
} }
firstBufferTexDataCall = true; firstBufferTexDataCall = true;
} }
public void startDrawSegment(boolean continuation) { public void startDrawSegment(boolean continuation) {
if (!continuation || cycleEnded) { if (!continuation || cycleEnded) {
fbElements = 0; fbElements = 0;
@ -371,52 +370,37 @@ public class GPURenderer implements Renderer {
boolean firstBufferDataCall = true; boolean firstBufferDataCall = true;
boolean firstBufferTexDataCall = true; boolean firstBufferTexDataCall = true;
public void endDrawSegment() { public void endDrawSegment() {
fbVertices.flip(); fbVertices.flip();
fbTextures.flip(); fbTextures.flip();
fbColors.flip(); fbColors.flip();
// gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, fbVertices); // gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, fbVertices);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[vertBuffer]); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[vertBuffer]);
if (firstBufferTexDataCall) { if (firstBufferTexDataCall) {
gl.glBufferData( gl.glBufferData(GL.GL_ARRAY_BUFFER, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices, GL.GL_STATIC_DRAW);
GL.GL_ARRAY_BUFFER, fbVertices.limit() * Buffers.SIZEOF_FLOAT,
fbVertices,
GL2ES1.GL_STATIC_DRAW);
} else { } else {
gl.glBufferSubData( gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices);
GL.GL_ARRAY_BUFFER, 0, fbVertices.limit() * Buffers.SIZEOF_FLOAT,
fbVertices);
} }
gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, 0l); gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, 0l);
// gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, fbTextures); // gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, fbTextures);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[texBuffer]); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[texBuffer]);
if (firstBufferTexDataCall) { if (firstBufferTexDataCall) {
gl.glBufferData( gl.glBufferData(GL.GL_ARRAY_BUFFER, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures, GL.GL_STATIC_DRAW);
GL.GL_ARRAY_BUFFER, fbTextures.limit() * Buffers.SIZEOF_FLOAT,
fbTextures,
GL2ES1.GL_STATIC_DRAW);
} else { } else {
gl.glBufferSubData( gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures);
GL.GL_ARRAY_BUFFER, 0, fbTextures.limit() * Buffers.SIZEOF_FLOAT,
fbTextures);
} }
gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, 0l); gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, 0l);
// gl.glColorPointer(colSize, GL.GL_FLOAT, 0, fbColors); // gl.glColorPointer(colSize, GL.GL_FLOAT, 0, fbColors);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[colBuffer]); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[colBuffer]);
if (firstBufferTexDataCall) { if (firstBufferTexDataCall) {
gl.glBufferData( gl.glBufferData(GL.GL_ARRAY_BUFFER, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors, GL.GL_STATIC_DRAW);
GL.GL_ARRAY_BUFFER, fbColors.limit() * Buffers.SIZEOF_FLOAT,
fbColors,
GL2ES1.GL_STATIC_DRAW);
} else { } else {
gl.glBufferSubData( gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors);
GL.GL_ARRAY_BUFFER, 0, fbColors.limit() * Buffers.SIZEOF_FLOAT,
fbColors);
} }
gl.glColorPointer(colSize, GL.GL_FLOAT, 0, 0l); gl.glColorPointer(colSize, GL.GL_FLOAT, 0, 0l);
fbVertices.limit(vertMax); fbVertices.limit(vertMax);
fbTextures.limit(texMax); fbTextures.limit(texMax);
fbColors.limit(colMax); fbColors.limit(colMax);

View File

@ -8,7 +8,6 @@ import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Skin; import org.warp.picalculator.gui.graphicengine.Skin;
import org.warp.picalculator.gui.graphicengine.gpu.GPURenderer.OpenedTextureData; import org.warp.picalculator.gui.graphicengine.gpu.GPURenderer.OpenedTextureData;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2ES1; import com.jogamp.opengl.GL2ES1;
import com.jogamp.opengl.GLException; import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.Texture;
@ -22,14 +21,14 @@ public class GPUSkin implements Skin {
private String texturePath; private String texturePath;
private boolean initialized = false; private boolean initialized = false;
private boolean isResource; private boolean isResource;
GPUSkin(GraphicEngine d, String file) throws IOException { GPUSkin(GraphicEngine d, String file) throws IOException {
load(file); load(file);
} }
@Override @Override
public void load(String file) throws IOException { public void load(String file) throws IOException {
boolean isResource = !Files.exists(Paths.get(file)); final boolean isResource = !Files.exists(Paths.get(file));
if (isResource && (this.getClass().getClassLoader().getResource(file)) == null) { if (isResource && (this.getClass().getClassLoader().getResource(file)) == null) {
throw new IOException("File '" + file + "' not found!"); throw new IOException("File '" + file + "' not found!");
} }
@ -45,7 +44,7 @@ public class GPUSkin implements Skin {
t = GPURenderer.importTexture(i.f, i.deleteOnExit); t = GPURenderer.importTexture(i.f, i.deleteOnExit);
w = i.w; w = i.w;
h = i.h; h = i.h;
((GPUEngine)d).registerTexture(t); ((GPUEngine) d).registerTexture(t);
initialized = true; initialized = true;
} catch (GLException | IOException e) { } catch (GLException | IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -28,10 +28,6 @@
package org.warp.picalculator.gui.graphicengine.gpu; package org.warp.picalculator.gui.graphicengine.gpu;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.warp.picalculator.StaticVars; import org.warp.picalculator.StaticVars;
import org.warp.picalculator.device.Key; import org.warp.picalculator.device.Key;
import org.warp.picalculator.device.Keyboard; import org.warp.picalculator.device.Keyboard;
@ -72,7 +68,7 @@ class NEWTWindow implements GLEventListener {
public NEWTWindow(GPUEngine disp) { public NEWTWindow(GPUEngine disp) {
this.disp = disp; this.disp = disp;
renderer = disp.getRenderer(); renderer = disp.getRenderer();
realWindowSize = new int[] {1,1}; realWindowSize = new int[] { 1, 1 };
} }
public GLWindow window; public GLWindow window;
@ -300,7 +296,7 @@ class NEWTWindow implements GLEventListener {
//Vsync //Vsync
gl.setSwapInterval(2); gl.setSwapInterval(2);
} }
//Textures //Textures
gl.glEnable(GL.GL_TEXTURE_2D); gl.glEnable(GL.GL_TEXTURE_2D);
@ -341,24 +337,24 @@ class NEWTWindow implements GLEventListener {
} }
private void onZoomChanged(GL2ES1 gl, boolean sizeChanged) { private void onZoomChanged(GL2ES1 gl, boolean sizeChanged) {
float precWindowZoom = windowZoom; final float precWindowZoom = windowZoom;
windowZoom = StaticVars.getCurrentZoomValue(); windowZoom = StaticVars.getCurrentZoomValue();
if (((precWindowZoom % ((int)precWindowZoom)) != 0f) != ((windowZoom % ((int)windowZoom)) != 0f)) { if (((precWindowZoom % ((int) precWindowZoom)) != 0f) != ((windowZoom % ((int) windowZoom)) != 0f)) {
boolean linear = (windowZoom % ((int)windowZoom)) != 0f; final boolean linear = (windowZoom % ((int) windowZoom)) != 0f;
for(Texture t : disp.registeredTextures) { for (final Texture t : disp.registeredTextures) {
t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, linear ? GL.GL_LINEAR : GL.GL_NEAREST); t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, linear ? GL.GL_LINEAR : GL.GL_NEAREST);
t.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); t.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
} }
} }
final int width = realWindowSize[0]; final int width = realWindowSize[0];
final int height = realWindowSize[1]; final int height = realWindowSize[1];
disp.size[0] = (int) (realWindowSize[0] / windowZoom); disp.size[0] = (int) (realWindowSize[0] / windowZoom);
disp.size[1] = (int) (realWindowSize[1] / windowZoom); disp.size[1] = (int) (realWindowSize[1] / windowZoom);
gl.glViewport(0, 0, width, height); gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
@ -369,28 +365,28 @@ class NEWTWindow implements GLEventListener {
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
gl.glLoadIdentity(); gl.glLoadIdentity();
} }
@Override @Override
public void display(GLAutoDrawable glad) { public void display(GLAutoDrawable glad) {
final GL2ES1 gl = glad.getGL().getGL2ES1(); final GL2ES1 gl = glad.getGL().getGL2ES1();
GPURenderer.gl = gl; GPURenderer.gl = gl;
if (windowZoom != StaticVars.getCurrentZoomValue()) { if (windowZoom != StaticVars.getCurrentZoomValue()) {
onZoomChanged(gl, false); onZoomChanged(gl, false);
} }
Boolean linear = null; Boolean linear = null;
while(!disp.unregisteredTextures.isEmpty()) { while (!disp.unregisteredTextures.isEmpty()) {
if (linear == null) { if (linear == null) {
linear = (windowZoom % ((int)windowZoom)) != 0f; linear = (windowZoom % ((int) windowZoom)) != 0f;
} }
Texture t = disp.unregisteredTextures.pop(); final Texture t = disp.unregisteredTextures.pop();
t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
t.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); t.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
disp.registeredTextures.addLast(t); disp.registeredTextures.addLast(t);
} }
gl.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY); gl.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY); gl.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY); gl.glEnableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);

View File

@ -14,7 +14,7 @@ import org.warp.picalculator.gui.graphicengine.RenderingLoop;
public class Headless24bitEngine implements org.warp.picalculator.gui.graphicengine.GraphicEngine { public class Headless24bitEngine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
private Headless24bitRenderer r = new Headless24bitRenderer(); private final Headless24bitRenderer r = new Headless24bitRenderer();
private boolean stopped = true; private boolean stopped = true;
private RenderingLoop renderLoop; private RenderingLoop renderLoop;
public static final int C_MUL_X = 4;//8; public static final int C_MUL_X = 4;//8;
@ -67,7 +67,7 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
if (Utils.isWindows() && !Utils.msDosMode) { if (Utils.isWindows() && !Utils.msDosMode) {
win = true; win = true;
WindowsSupport.setConsoleMode(0x0200); WindowsSupport.setConsoleMode(0x0200);
Thread t = new Thread(() -> { final Thread t = new Thread(() -> {
int ch = -1; int ch = -1;
while (true) { while (true) {
if (precKey != null) { if (precKey != null) {
@ -132,8 +132,9 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
t.start(); t.start();
} }
stopped = false; stopped = false;
if (onInitialized != null) if (onInitialized != null) {
onInitialized.run(); onInitialized.run();
}
} }
@Override @Override
@ -158,7 +159,7 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
@Override @Override
public void start(RenderingLoop d) { public void start(RenderingLoop d) {
this.renderLoop = d; renderLoop = d;
final Thread th = new Thread(() -> { final Thread th = new Thread(() -> {
try { try {
double extratime = 0; double extratime = 0;
@ -215,10 +216,10 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
} }
} }
int[] newpix = new int[3]; int[] newpix = new int[3];
for (int i = 0; i < pixs.length; i++) { for (final int[] pix : pixs) {
newpix[0] += pixs[i][0]; newpix[0] += pix[0];
newpix[1] += pixs[i][1]; newpix[1] += pix[1];
newpix[2] += pixs[i][2]; newpix[2] += pix[2];
} }
newpix[0] /= pixs.length; newpix[0] /= pixs.length;
newpix[1] /= pixs.length; newpix[1] /= pixs.length;
@ -233,10 +234,10 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
} }
} }
newpix = new int[3]; newpix = new int[3];
for (int i = 0; i < pixs.length; i++) { for (final int[] pix : pixs) {
newpix[0] += pixs[i][0]; newpix[0] += pix[0];
newpix[1] += pixs[i][1]; newpix[1] += pix[1];
newpix[2] += pixs[i][2]; newpix[2] += pix[2];
} }
newpix[0] /= pixs.length; newpix[0] /= pixs.length;
newpix[1] /= pixs.length; newpix[1] /= pixs.length;
@ -318,8 +319,9 @@ public class Headless24bitEngine implements org.warp.picalculator.gui.graphiceng
@Override @Override
public boolean isSupported() { public boolean isSupported() {
if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-24bit")) if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-24bit")) {
return false; return false;
}
return true; return true;
} }

View File

@ -82,11 +82,11 @@ public class Headless24bitRenderer implements Renderer {
@Override @Override
public void glDrawLine(float x1, float y1, float x2, float y2) { public void glDrawLine(float x1, float y1, float x2, float y2) {
int dx = (int) Math.abs(x2 - x1); final int dx = (int) Math.abs(x2 - x1);
int dy = (int) Math.abs(y2 - y1); final int dy = (int) Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1; final int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1; final int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy; int err = dx - dy;
@ -101,7 +101,7 @@ public class Headless24bitRenderer implements Renderer {
break; break;
} }
int e2 = 2 * err; final int e2 = 2 * err;
if (e2 > -dy) { if (e2 > -dy) {
err = err - dy; err = err - dy;
@ -185,7 +185,7 @@ public class Headless24bitRenderer implements Renderer {
final int cx = (int) x; final int cx = (int) x;
final int cy = (int) y; final int cy = (int) y;
int i = 0; int i = 0;
for (char c : text.toCharArray()) { for (final char c : text.toCharArray()) {
if (cx + i >= size[0] || cy >= size[1]) { if (cx + i >= size[0] || cy >= size[1]) {
break; break;
} }
@ -200,7 +200,7 @@ public class Headless24bitRenderer implements Renderer {
final int cx = ((int) x) - (text.length() / 2) * Headless24bitEngine.C_MUL_X; final int cx = ((int) x) - (text.length() / 2) * Headless24bitEngine.C_MUL_X;
final int cy = ((int) y); final int cy = ((int) y);
int i = 0; int i = 0;
for (char c : text.toCharArray()) { for (final char c : text.toCharArray()) {
if (cx + i >= size[0] || cy >= size[1]) { if (cx + i >= size[0] || cy >= size[1]) {
break; break;
} }

View File

@ -31,12 +31,12 @@ public class Headless24bitSkin implements Skin {
final int[][] pixels = new int[width * height][]; final int[][] pixels = new int[width * height][];
for (int i = 0; i < width; i++) { for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) { for (int j = 0; j < height; j++) {
int rgb = bufferedImage.getRGB(i, j); final int rgb = bufferedImage.getRGB(i, j);
int r = (rgb >> 16) & 0xFF; final int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF; final int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF; final int b = rgb & 0xFF;
boolean transparent = ((rgb >> 24) & 0xFF) <= 128; final boolean transparent = ((rgb >> 24) & 0xFF) <= 128;
int[] curCol = Headless24bitRenderer.rgbToIntArray(r, g, b); final int[] curCol = Headless24bitRenderer.rgbToIntArray(r, g, b);
pixels[i + j * width] = new int[] { curCol[0], curCol[1], curCol[2], transparent ? 1 : 0 }; pixels[i + j * width] = new int[] { curCol[0], curCol[1], curCol[2], transparent ? 1 : 0 };
} }
} }

View File

@ -15,7 +15,7 @@ import org.warp.picalculator.gui.graphicengine.headless24bit.Headless24bitRender
public class Headless256Engine implements org.warp.picalculator.gui.graphicengine.GraphicEngine { public class Headless256Engine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
private Headless256Renderer r = new Headless256Renderer(); private final Headless256Renderer r = new Headless256Renderer();
private boolean stopped = true; private boolean stopped = true;
private RenderingLoop renderLoop; private RenderingLoop renderLoop;
public static final int C_MUL_X = 4;//8; public static final int C_MUL_X = 4;//8;
@ -66,7 +66,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
if (Utils.isWindows() && !Utils.msDosMode) { if (Utils.isWindows() && !Utils.msDosMode) {
win = true; win = true;
WindowsSupport.setConsoleMode(0x0200); WindowsSupport.setConsoleMode(0x0200);
Thread t = new Thread(() -> { final Thread t = new Thread(() -> {
int ch = -1; int ch = -1;
while (true) { while (true) {
if (precKey != null) { if (precKey != null) {
@ -131,8 +131,9 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
t.start(); t.start();
} }
stopped = false; stopped = false;
if (onInitialized != null) if (onInitialized != null) {
onInitialized.run(); onInitialized.run();
}
} }
@Override @Override
@ -157,7 +158,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
@Override @Override
public void start(RenderingLoop d) { public void start(RenderingLoop d) {
this.renderLoop = d; renderLoop = d;
final Thread th = new Thread(() -> { final Thread th = new Thread(() -> {
try { try {
double extratime = 0; double extratime = 0;
@ -207,7 +208,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
curBgColor = r.bgColorMatrix[x + y * C_WIDTH]; curBgColor = r.bgColorMatrix[x + y * C_WIDTH];
curFgColor = r.fgColorMatrix[x + y * C_WIDTH]; curFgColor = r.fgColorMatrix[x + y * C_WIDTH];
if (precBgColor != curBgColor) { if (precBgColor != curBgColor) {
String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiBgColorPrefix + curBgColor + Headless256Renderer.ansiColorSuffix; final String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiBgColorPrefix + curBgColor + Headless256Renderer.ansiColorSuffix;
if (win) { if (win) {
WindowsSupport.writeConsole(str); WindowsSupport.writeConsole(str);
} else { } else {
@ -215,7 +216,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
} }
} }
if (precFgColor != curFgColor) { if (precFgColor != curFgColor) {
String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiFgColorPrefix + curFgColor + Headless256Renderer.ansiColorSuffix; final String str = Headless256Renderer.ANSI_PREFIX + Headless256Renderer.ansiFgColorPrefix + curFgColor + Headless256Renderer.ansiColorSuffix;
if (win) { if (win) {
WindowsSupport.writeConsole(str); WindowsSupport.writeConsole(str);
} else { } else {
@ -223,7 +224,7 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
} }
} }
String stri = r.charmatrix[x + y * C_WIDTH] + ""; final String stri = r.charmatrix[x + y * C_WIDTH] + "";
if (win) { if (win) {
WindowsSupport.writeConsole(stri); WindowsSupport.writeConsole(stri);
} else { } else {
@ -275,8 +276,9 @@ public class Headless256Engine implements org.warp.picalculator.gui.graphicengin
@Override @Override
public boolean isSupported() { public boolean isSupported() {
if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-256")) if (Utils.msDosMode || (Utils.forceEngine != null && Utils.forceEngine != "console-256")) {
return false; return false;
}
return true; return true;
} }

View File

@ -41,20 +41,20 @@ public class Headless256Renderer implements Renderer {
public static int rgbToX256(int r_U, int g_U, int b_U) { public static int rgbToX256(int r_U, int g_U, int b_U) {
// Calculate the nearest 0-based color index at 16 .. 231 // Calculate the nearest 0-based color index at 16 .. 231
int ir = v2ci(r_U), ig = v2ci(g_U), ib = v2ci(b_U); // 0..5 each final int ir = v2ci(r_U), ig = v2ci(g_U), ib = v2ci(b_U); // 0..5 each
/* 0..215, lazy evaluation */ /* 0..215, lazy evaluation */
// Calculate the nearest 0-based gray index at 232 .. 255 // Calculate the nearest 0-based gray index at 232 .. 255
int average = (r_U + g_U + b_U) / 3; final int average = (r_U + g_U + b_U) / 3;
int grayIndex = average > 238 ? 23 : (average - 3) / 10; // 0..23 final int grayIndex = average > 238 ? 23 : (average - 3) / 10; // 0..23
int cr = i2cv[ir], cg = i2cv[ig], cb = i2cv[ib]; // r/g/b, 0..255 each final int cr = i2cv[ir], cg = i2cv[ig], cb = i2cv[ib]; // r/g/b, 0..255 each
int gv = 8 + 10 * grayIndex; // same value for r/g/b, 0..255 final int gv = 8 + 10 * grayIndex; // same value for r/g/b, 0..255
// Return the one which is nearer to the original input rgb value // Return the one which is nearer to the original input rgb value
int colorErr = distSquare(cr, cg, cb, r_U, g_U, b_U); final int colorErr = distSquare(cr, cg, cb, r_U, g_U, b_U);
int grayErr = distSquare(gv, gv, gv, r_U, g_U, b_U); final int grayErr = distSquare(gv, gv, gv, r_U, g_U, b_U);
return colorErr <= grayErr ? 16 + colorIndex(ir, ig, ib) : 232 + grayIndex; return colorErr <= grayErr ? 16 + colorIndex(ir, ig, ib) : 232 + grayIndex;
} }
@ -115,11 +115,11 @@ public class Headless256Renderer implements Renderer {
y1 /= Headless256Engine.C_MUL_Y; y1 /= Headless256Engine.C_MUL_Y;
y2 /= Headless256Engine.C_MUL_Y; y2 /= Headless256Engine.C_MUL_Y;
int dx = (int) Math.abs(x2 - x1); final int dx = (int) Math.abs(x2 - x1);
int dy = (int) Math.abs(y2 - y1); final int dy = (int) Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1; final int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1; final int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy; int err = dx - dy;
@ -134,7 +134,7 @@ public class Headless256Renderer implements Renderer {
break; break;
} }
int e2 = 2 * err; final int e2 = 2 * err;
if (e2 > -dy) { if (e2 > -dy) {
err = err - dy; err = err - dy;
@ -217,7 +217,7 @@ public class Headless256Renderer implements Renderer {
final int cx = ((int) x) / Headless256Engine.C_MUL_X; final int cx = ((int) x) / Headless256Engine.C_MUL_X;
final int cy = ((int) y) / Headless256Engine.C_MUL_Y; final int cy = ((int) y) / Headless256Engine.C_MUL_Y;
int i = 0; int i = 0;
for (char c : text.toCharArray()) { for (final char c : text.toCharArray()) {
if (cx + i >= Headless256Engine.C_WIDTH || cy >= Headless256Engine.C_HEIGHT) { if (cx + i >= Headless256Engine.C_WIDTH || cy >= Headless256Engine.C_HEIGHT) {
break; break;
} }
@ -232,7 +232,7 @@ public class Headless256Renderer implements Renderer {
final int cx = ((int) x) / Headless256Engine.C_MUL_X - text.length() / 2; final int cx = ((int) x) / Headless256Engine.C_MUL_X - text.length() / 2;
final int cy = ((int) y) / Headless256Engine.C_MUL_Y; final int cy = ((int) y) / Headless256Engine.C_MUL_Y;
int i = 0; int i = 0;
for (char c : text.toCharArray()) { for (final char c : text.toCharArray()) {
if (cx + i >= Headless256Engine.C_WIDTH || cy >= Headless256Engine.C_HEIGHT) { if (cx + i >= Headless256Engine.C_WIDTH || cy >= Headless256Engine.C_HEIGHT) {
break; break;
} }

View File

@ -28,9 +28,9 @@ public class Headless256Skin implements Skin {
public static int[] getMatrixOfImage(BufferedImage bufferedImage) { public static int[] getMatrixOfImage(BufferedImage bufferedImage) {
BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB); BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform(); final AffineTransform at = new AffineTransform();
at.scale(1f / (Headless256Engine.C_MUL_X), 1f / (Headless256Engine.C_MUL_Y)); at.scale(1f / (Headless256Engine.C_MUL_X), 1f / (Headless256Engine.C_MUL_Y));
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(bufferedImage, after); after = scaleOp.filter(bufferedImage, after);
final int width = after.getWidth(null); final int width = after.getWidth(null);
@ -38,11 +38,11 @@ public class Headless256Skin implements Skin {
final int[] pixels = new int[width * height]; final int[] pixels = new int[width * height];
for (int i = 0; i < width; i++) { for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) { for (int j = 0; j < height; j++) {
int rgb = after.getRGB(i, j); final int rgb = after.getRGB(i, j);
int r = (rgb >> 16) & 0xFF; final int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF; final int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF; final int b = rgb & 0xFF;
boolean transparent = ((rgb >> 24) & 0xFF) <= 128; final boolean transparent = ((rgb >> 24) & 0xFF) <= 128;
pixels[i + j * width] = Headless256Renderer.rgbToX256(r, g, b) | (transparent ? Headless256Renderer.TRANSPARENT : 0); pixels[i + j * width] = Headless256Renderer.rgbToX256(r, g, b) | (transparent ? Headless256Renderer.TRANSPARENT : 0);
} }
} }

View File

@ -15,7 +15,7 @@ import org.warp.picalculator.gui.graphicengine.headless24bit.Headless24bitRender
public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.GraphicEngine { public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
private Headless8Renderer r = new Headless8Renderer(); private final Headless8Renderer r = new Headless8Renderer();
private boolean stopped = true; private boolean stopped = true;
private RenderingLoop renderLoop; private RenderingLoop renderLoop;
public static final int C_MUL_X = 4;//8; public static final int C_MUL_X = 4;//8;
@ -66,7 +66,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
if (Utils.isWindows() && !Utils.msDosMode) { if (Utils.isWindows() && !Utils.msDosMode) {
win = true; win = true;
WindowsSupport.setConsoleMode(0x0200); WindowsSupport.setConsoleMode(0x0200);
Thread t = new Thread(() -> { final Thread t = new Thread(() -> {
int ch = -1; int ch = -1;
while (true) { while (true) {
if (precKey != null) { if (precKey != null) {
@ -131,8 +131,9 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
t.start(); t.start();
} }
stopped = false; stopped = false;
if (onInitialized != null) if (onInitialized != null) {
onInitialized.run(); onInitialized.run();
}
} }
@Override @Override
@ -157,7 +158,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
@Override @Override
public void start(RenderingLoop d) { public void start(RenderingLoop d) {
this.renderLoop = d; renderLoop = d;
final Thread th = new Thread(() -> { final Thread th = new Thread(() -> {
try { try {
double extratime = 0; double extratime = 0;
@ -207,7 +208,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
curBgColor = (r.colorMatrix[x + y * C_WIDTH] & 0xF0) >> 4; curBgColor = (r.colorMatrix[x + y * C_WIDTH] & 0xF0) >> 4;
curFgColor = r.colorMatrix[x + y * C_WIDTH] & 0x0F; curFgColor = r.colorMatrix[x + y * C_WIDTH] & 0x0F;
if (precBgColor != curBgColor) { if (precBgColor != curBgColor) {
String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiBgColorPrefix + Headless8Renderer.colorANSI[curBgColor] + Headless8Renderer.ansiColorSuffix; final String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiBgColorPrefix + Headless8Renderer.colorANSI[curBgColor] + Headless8Renderer.ansiColorSuffix;
if (win) { if (win) {
WindowsSupport.writeConsole(str); WindowsSupport.writeConsole(str);
} else { } else {
@ -215,7 +216,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
} }
} }
if (precFgColor != curFgColor) { if (precFgColor != curFgColor) {
String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiFgColorPrefix + Headless8Renderer.colorANSI[curFgColor] + Headless8Renderer.ansiColorSuffix; final String str = Headless8Renderer.ANSI_PREFIX + Headless8Renderer.ansiFgColorPrefix + Headless8Renderer.colorANSI[curFgColor] + Headless8Renderer.ansiColorSuffix;
if (win) { if (win) {
WindowsSupport.writeConsole(str); WindowsSupport.writeConsole(str);
} else { } else {
@ -223,7 +224,7 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
} }
} }
String stri = r.charmatrix[x + y * C_WIDTH] + ""; final String stri = r.charmatrix[x + y * C_WIDTH] + "";
if (win) { if (win) {
WindowsSupport.writeConsole(stri); WindowsSupport.writeConsole(stri);
} else { } else {
@ -275,8 +276,9 @@ public class Headless8Engine implements org.warp.picalculator.gui.graphicengine.
@Override @Override
public boolean isSupported() { public boolean isSupported() {
if (Utils.forceEngine != null && Utils.forceEngine != "console-8") if (Utils.forceEngine != null && Utils.forceEngine != "console-8") {
return false; return false;
}
return true; return true;
} }

View File

@ -22,9 +22,14 @@ public class Headless8Renderer implements Renderer {
public static final char FILL = Utils.msDosMode ? 0xDB : '█'; public static final char FILL = Utils.msDosMode ? 0xDB : '█';
private int hexColor(int red, int green, int blue) { private int hexColor(int red, int green, int blue) {
int r1 = red, r2, g1 = green, g2, b1 = blue, b2; final int r1 = red;
int r2;
final int g1 = green;
int g2;
final int b1 = blue;
int b2;
float[] match = new float[16]; final float[] match = new float[16];
// COLOR // COLOR
r2 = 0; r2 = 0;
@ -124,7 +129,7 @@ public class Headless8Renderer implements Renderer {
int minIndex = 0; int minIndex = 0;
for (int i = 1; i < match.length; i++) { for (int i = 1; i < match.length; i++) {
float newnumber = match[i]; final float newnumber = match[i];
if ((newnumber < match[minIndex])) { if ((newnumber < match[minIndex])) {
minIndex = i; minIndex = i;
} }
@ -231,11 +236,11 @@ public class Headless8Renderer implements Renderer {
y1 /= Headless8Engine.C_MUL_Y; y1 /= Headless8Engine.C_MUL_Y;
y2 /= Headless8Engine.C_MUL_Y; y2 /= Headless8Engine.C_MUL_Y;
int dx = (int) Math.abs(x2 - x1); final int dx = (int) Math.abs(x2 - x1);
int dy = (int) Math.abs(y2 - y1); final int dy = (int) Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1; final int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1; final int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy; int err = dx - dy;
@ -243,7 +248,7 @@ public class Headless8Renderer implements Renderer {
if (((int) x1) >= Headless8Engine.C_WIDTH || ((int) y1) >= Headless8Engine.C_HEIGHT || ((int) x2) >= Headless8Engine.C_WIDTH || ((int) y2) >= Headless8Engine.C_HEIGHT) { if (((int) x1) >= Headless8Engine.C_WIDTH || ((int) y1) >= Headless8Engine.C_HEIGHT || ((int) x2) >= Headless8Engine.C_WIDTH || ((int) y2) >= Headless8Engine.C_HEIGHT) {
break; break;
} }
int precBG = colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] & 0xF0; final int precBG = colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] = precBG | curColor; colorMatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] = precBG | curColor;
charmatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] = FILL; charmatrix[((int) x1) + ((int) y1) * Headless8Engine.C_WIDTH] = FILL;
@ -251,7 +256,7 @@ public class Headless8Renderer implements Renderer {
break; break;
} }
int e2 = 2 * err; final int e2 = 2 * err;
if (e2 > -dy) { if (e2 > -dy) {
err = err - dy; err = err - dy;
@ -300,7 +305,7 @@ public class Headless8Renderer implements Renderer {
final int sizeW = Headless8Engine.C_WIDTH; final int sizeW = Headless8Engine.C_WIDTH;
for (int px = ix; px < x1; px++) { for (int px = ix; px < x1; px++) {
for (int py = iy; py < y1; py++) { for (int py = iy; py < y1; py++) {
int precBG = colorMatrix[(px) + (py) * sizeW] & 0xF0; final int precBG = colorMatrix[(px) + (py) * sizeW] & 0xF0;
colorMatrix[(px) + (py) * sizeW] = precBG | color; colorMatrix[(px) + (py) * sizeW] = precBG | color;
charmatrix[(px) + (py) * sizeW] = character; charmatrix[(px) + (py) * sizeW] = character;
} }
@ -315,7 +320,7 @@ public class Headless8Renderer implements Renderer {
return; return;
} }
charmatrix[cx + cy * Headless8Engine.C_WIDTH] = ch; charmatrix[cx + cy * Headless8Engine.C_WIDTH] = ch;
int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0; final int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + cy * Headless8Engine.C_WIDTH] = precBG | curColor; colorMatrix[cx + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
} }
@ -332,7 +337,7 @@ public class Headless8Renderer implements Renderer {
return; return;
} }
charmatrix[cx + cy * Headless8Engine.C_WIDTH] = ch; charmatrix[cx + cy * Headless8Engine.C_WIDTH] = ch;
int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0; final int precBG = colorMatrix[cx + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + cy * Headless8Engine.C_WIDTH] = precBG | curColor; colorMatrix[cx + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
} }
@ -341,12 +346,12 @@ public class Headless8Renderer implements Renderer {
final int cx = ((int) x) / Headless8Engine.C_MUL_X; final int cx = ((int) x) / Headless8Engine.C_MUL_X;
final int cy = ((int) y) / Headless8Engine.C_MUL_Y; final int cy = ((int) y) / Headless8Engine.C_MUL_Y;
int i = 0; int i = 0;
for (char c : text.toCharArray()) { for (final char c : text.toCharArray()) {
if (cx + i >= Headless8Engine.C_WIDTH || cy >= Headless8Engine.C_HEIGHT) { if (cx + i >= Headless8Engine.C_WIDTH || cy >= Headless8Engine.C_HEIGHT) {
break; break;
} }
charmatrix[cx + i + cy * Headless8Engine.C_WIDTH] = c; charmatrix[cx + i + cy * Headless8Engine.C_WIDTH] = c;
int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0; final int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] = precBG | curColor; colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
i++; i++;
} }
@ -357,12 +362,12 @@ public class Headless8Renderer implements Renderer {
final int cx = ((int) x) / Headless8Engine.C_MUL_X - text.length() / 2; final int cx = ((int) x) / Headless8Engine.C_MUL_X - text.length() / 2;
final int cy = ((int) y) / Headless8Engine.C_MUL_Y; final int cy = ((int) y) / Headless8Engine.C_MUL_Y;
int i = 0; int i = 0;
for (char c : text.toCharArray()) { for (final char c : text.toCharArray()) {
if (cx + i >= Headless8Engine.C_WIDTH || cy >= Headless8Engine.C_HEIGHT) { if (cx + i >= Headless8Engine.C_WIDTH || cy >= Headless8Engine.C_HEIGHT) {
break; break;
} }
charmatrix[cx + i + cy * Headless8Engine.C_WIDTH] = c; charmatrix[cx + i + cy * Headless8Engine.C_WIDTH] = c;
int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0; final int precBG = colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] = precBG | curColor; colorMatrix[cx + i + cy * Headless8Engine.C_WIDTH] = precBG | curColor;
i++; i++;
} }
@ -438,7 +443,7 @@ public class Headless8Renderer implements Renderer {
final int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2); final int b = (int) ((oldColor & 0xFF) * a1 + (newColor & 0xFF) * a2);
newColor = 0xFF000000 | r << 16 | g << 8 | b; newColor = 0xFF000000 | r << 16 | g << 8 | b;
} }
int bgColor = colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] & 0xF0; final int bgColor = colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] & 0xF0;
colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] = bgColor | hexColor(newColor >> 16 & 0xFF, newColor >> 8 & 0xFF, newColor & 0xFF); colorMatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] = bgColor | hexColor(newColor >> 16 & 0xFF, newColor >> 8 & 0xFF, newColor & 0xFF);
charmatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] = FILL; charmatrix[pixelX + pixelY * Headless8Engine.C_WIDTH] = FILL;
} }

View File

@ -28,9 +28,9 @@ public class Headless8Skin implements Skin {
public static int[] getMatrixOfImage(BufferedImage bufferedImage) { public static int[] getMatrixOfImage(BufferedImage bufferedImage) {
BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB); BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform(); final AffineTransform at = new AffineTransform();
at.scale(1f / (Headless8Engine.C_MUL_X), 1f / (Headless8Engine.C_MUL_Y)); at.scale(1f / (Headless8Engine.C_MUL_X), 1f / (Headless8Engine.C_MUL_Y));
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(bufferedImage, after); after = scaleOp.filter(bufferedImage, after);
final int width = after.getWidth(null); final int width = after.getWidth(null);

View File

@ -17,7 +17,7 @@ public class NoGuiEngine implements GraphicEngine {
@Override @Override
public int[] getSize() { public int[] getSize() {
return new int[] {2, 2}; return new int[] { 2, 2 };
} }
@Override @Override
@ -26,23 +26,20 @@ public class NoGuiEngine implements GraphicEngine {
} }
@Override @Override
public void setTitle(String title) { public void setTitle(String title) {}
}
@Override @Override
public void setResizable(boolean r) { public void setResizable(boolean r) {}
}
@Override @Override
public void setDisplayMode(int ww, int wh) { public void setDisplayMode(int ww, int wh) {}
}
@Override @Override
public void create(Runnable onInitialized) { public void create(Runnable onInitialized) {
initialized = true; initialized = true;
if (onInitialized != null) if (onInitialized != null) {
onInitialized.run(); onInitialized.run();
}
} }
@Override @Override
@ -67,12 +64,10 @@ public class NoGuiEngine implements GraphicEngine {
} }
@Override @Override
public void start(RenderingLoop d) { public void start(RenderingLoop d) {}
}
@Override @Override
public void repaint() { public void repaint() {}
}
@Override @Override
public Renderer getRenderer() { public Renderer getRenderer() {
@ -81,83 +76,65 @@ public class NoGuiEngine implements GraphicEngine {
public int glGetClearColor() { public int glGetClearColor() {
return 0; return 0;
} }
@Override @Override
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight) { float uvHeight) {}
}
@Override @Override
public void glFillColor(float x, float y, float width, float height) { public void glFillColor(float x, float y, float width, float height) {}
}
@Override @Override
public void glDrawStringRight(float x, float y, String text) { public void glDrawStringRight(float x, float y, String text) {}
}
@Override @Override
public void glDrawStringLeft(float x, float y, String text) { public void glDrawStringLeft(float x, float y, String text) {}
}
@Override @Override
public void glDrawStringCenter(float x, float y, String text) { public void glDrawStringCenter(float x, float y, String text) {}
}
@Override @Override
public void glDrawLine(float x0, float y0, float x1, float y1) { public void glDrawLine(float x0, float y0, float x1, float y1) {}
}
@Override @Override
public void glDrawCharRight(int x, int y, char ch) { public void glDrawCharRight(int x, int y, char ch) {}
}
@Override @Override
public void glDrawCharLeft(int x, int y, char ch) { public void glDrawCharLeft(int x, int y, char ch) {}
}
@Override @Override
public void glDrawCharCenter(int x, int y, char ch) { public void glDrawCharCenter(int x, int y, char ch) {}
}
@Override @Override
public void glColor4i(int red, int green, int blue, int alpha) { public void glColor4i(int red, int green, int blue, int alpha) {}
}
@Override @Override
public void glColor4f(float red, float green, float blue, float alpha) { public void glColor4f(float red, float green, float blue, float alpha) {}
}
@Override @Override
public void glColor3i(int r, int gg, int b) { public void glColor3i(int r, int gg, int b) {}
}
@Override @Override
public void glColor3f(float red, float green, float blue) { public void glColor3f(float red, float green, float blue) {}
}
@Override @Override
public void glColor(int c) { public void glColor(int c) {}
}
@Override @Override
public void glClearSkin() { public void glClearSkin() {}
}
@Override @Override
public void glClearColor4i(int red, int green, int blue, int alpha) { public void glClearColor4i(int red, int green, int blue, int alpha) {}
}
@Override @Override
public void glClearColor4f(float red, float green, float blue, float alpha) { public void glClearColor4f(float red, float green, float blue, float alpha) {}
}
@Override @Override
public void glClearColor(int c) { public void glClearColor(int c) {}
}
@Override @Override
public void glClear(int screenWidth, int screenHeight) { public void glClear(int screenWidth, int screenHeight) {}
}
@Override @Override
public BinaryFont getCurrentFont() { public BinaryFont getCurrentFont() {
return null; return null;
@ -169,32 +146,29 @@ public class NoGuiEngine implements GraphicEngine {
public BinaryFont loadFont(String fontName) throws IOException { public BinaryFont loadFont(String fontName) throws IOException {
return new BinaryFont() { return new BinaryFont() {
@Override @Override
public void use(GraphicEngine d) { public void use(GraphicEngine d) {}
}
@Override @Override
public void load(String file) throws IOException { public void load(String file) throws IOException {}
}
@Override @Override
public boolean isInitialized() { public boolean isInitialized() {
return true; return true;
} }
@Override @Override
public void initialize(GraphicEngine d) { public void initialize(GraphicEngine d) {}
}
@Override @Override
public int getStringWidth(String text) { public int getStringWidth(String text) {
return 1; return 1;
} }
@Override @Override
public int getCharacterWidth() { public int getCharacterWidth() {
return 1; return 1;
} }
@Override @Override
public int getCharacterHeight() { public int getCharacterHeight() {
return 1; return 1;
@ -218,32 +192,29 @@ public class NoGuiEngine implements GraphicEngine {
public BinaryFont loadFont(String path, String fontName) throws IOException { public BinaryFont loadFont(String path, String fontName) throws IOException {
return new BinaryFont() { return new BinaryFont() {
@Override @Override
public void use(GraphicEngine d) { public void use(GraphicEngine d) {}
}
@Override @Override
public void load(String file) throws IOException { public void load(String file) throws IOException {}
}
@Override @Override
public boolean isInitialized() { public boolean isInitialized() {
return true; return true;
} }
@Override @Override
public void initialize(GraphicEngine d) { public void initialize(GraphicEngine d) {}
}
@Override @Override
public int getStringWidth(String text) { public int getStringWidth(String text) {
return 1; return 1;
} }
@Override @Override
public int getCharacterWidth() { public int getCharacterWidth() {
return 1; return 1;
} }
@Override @Override
public int getCharacterHeight() { public int getCharacterHeight() {
return 1; return 1;
@ -267,21 +238,18 @@ public class NoGuiEngine implements GraphicEngine {
public Skin loadSkin(String file) throws IOException { public Skin loadSkin(String file) throws IOException {
return new Skin() { return new Skin() {
@Override @Override
public void use(GraphicEngine d) { public void use(GraphicEngine d) {}
}
@Override @Override
public void load(String file) throws IOException { public void load(String file) throws IOException {}
}
@Override @Override
public boolean isInitialized() { public boolean isInitialized() {
return true; return true;
} }
@Override @Override
public void initialize(GraphicEngine d) { public void initialize(GraphicEngine d) {}
}
@Override @Override
public int getSkinWidth() { public int getSkinWidth() {
@ -301,7 +269,7 @@ public class NoGuiEngine implements GraphicEngine {
public void waitForExit() { public void waitForExit() {
try { try {
exitSemaphore.acquire(); exitSemaphore.acquire();
} catch (InterruptedException e) {} } catch (final InterruptedException e) {}
} }
@Override @Override

View File

@ -14,7 +14,7 @@ import org.warp.picalculator.gui.graphicengine.Skin;
public class MarioScreen extends Screen { public class MarioScreen extends Screen {
private MarioGame g; private MarioGame g;
private static Skin skin; private static Skin skin;
private static Skin groundskin; private static Skin groundskin;
private static BinaryFont gpuTest2; private static BinaryFont gpuTest2;
@ -23,8 +23,8 @@ public class MarioScreen extends Screen {
private static Skin gpuTest3; private static Skin gpuTest3;
private int gpuTestNum = 0; private int gpuTestNum = 0;
private float gpuTestElapsed = 0; private float gpuTestElapsed = 0;
private int gpuTestMax = 21; private final int gpuTestMax = 21;
private String[] gpuCharTest1 = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "ò"}; private final String[] gpuCharTest1 = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "ò" };
private int gpuCharTest1Num = 0; private int gpuCharTest1Num = 0;
private float gpuCharTestt1Elapsed = 0; private float gpuCharTestt1Elapsed = 0;
private boolean errored; private boolean errored;
@ -45,29 +45,34 @@ public class MarioScreen extends Screen {
@Override @Override
public void initialized() { public void initialized() {
try { try {
if (skin == null) if (skin == null) {
skin = DisplayManager.INSTANCE.engine.loadSkin("marioskin.png"); skin = DisplayManager.INSTANCE.engine.loadSkin("marioskin.png");
if (groundskin == null) }
if (groundskin == null) {
groundskin = DisplayManager.INSTANCE.engine.loadSkin("marioground.png"); groundskin = DisplayManager.INSTANCE.engine.loadSkin("marioground.png");
if (gpuTest2 == null) }
if (gpuTest2 == null) {
try { try {
gpuTest2 = DisplayManager.INSTANCE.engine.loadFont("gputest2"); gpuTest2 = DisplayManager.INSTANCE.engine.loadFont("gputest2");
} catch (Exception ex) {} } catch (final Exception ex) {}
if (gpuTest1 == null) }
if (gpuTest1 == null) {
try { try {
gpuTest1 = DisplayManager.INSTANCE.engine.loadFont("gputest12"); gpuTest1 = DisplayManager.INSTANCE.engine.loadFont("gputest12");
gpuTest12 = true; gpuTest12 = true;
StaticVars.windowZoom = 1; StaticVars.windowZoom = 1;
} catch (Exception ex) { } catch (final Exception ex) {
gpuTest12 = false; gpuTest12 = false;
try { try {
gpuTest1 = DisplayManager.INSTANCE.engine.loadFont("gputest1"); gpuTest1 = DisplayManager.INSTANCE.engine.loadFont("gputest1");
} catch (Exception ex2) {} } catch (final Exception ex2) {}
} }
if (gpuTest3 == null) }
if (gpuTest3 == null) {
try { try {
gpuTest3 = DisplayManager.INSTANCE.engine.loadSkin("font_gputest3.png"); gpuTest3 = DisplayManager.INSTANCE.engine.loadSkin("font_gputest3.png");
} catch (Exception ex) {} } catch (final Exception ex) {}
}
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -99,7 +104,7 @@ public class MarioScreen extends Screen {
gpuCharTest1Num = (gpuCharTest1Num + 1) % gpuCharTest1.length; gpuCharTest1Num = (gpuCharTest1Num + 1) % gpuCharTest1.length;
gpuCharTestt1Elapsed -= 1.5; gpuCharTestt1Elapsed -= 1.5;
} }
DisplayManager.INSTANCE.renderer.glClearColor(0xff000000); DisplayManager.INSTANCE.renderer.glClearColor(0xff000000);
} }
} }
@ -110,23 +115,23 @@ public class MarioScreen extends Screen {
DisplayManager.INSTANCE.renderer.glDrawStringLeft(0, 20, "ERROR"); DisplayManager.INSTANCE.renderer.glDrawStringLeft(0, 20, "ERROR");
} else { } else {
if (groundskin != null) { if (groundskin != null) {
double playerX = g.getPlayer().getX(); final double playerX = g.getPlayer().getX();
double playerY = g.getPlayer().getY(); final double playerY = g.getPlayer().getY();
groundskin.use(DisplayManager.INSTANCE.engine); groundskin.use(DisplayManager.INSTANCE.engine);
MarioWorld w = g.getCurrentWorld(); final MarioWorld w = g.getCurrentWorld();
int width = w.getWidth(); final int width = w.getWidth();
int height = w.getHeight(); final int height = w.getHeight();
float screenX = DisplayManager.INSTANCE.engine.getWidth()/2f - 8f; final float screenX = DisplayManager.INSTANCE.engine.getWidth() / 2f - 8f;
float screenY = DisplayManager.INSTANCE.engine.getHeight()/2f - 8f; final float screenY = DisplayManager.INSTANCE.engine.getHeight() / 2f - 8f;
float shiftX = -8 + 16 * (float)playerX; final float shiftX = -8 + 16 * (float) playerX;
float shiftY = -8 + 16 * (height - (float)playerY); final float shiftY = -8 + 16 * (height - (float) playerY);
int blue = -1; int blue = -1;
for (int ix = 0; ix < width; ix++) { for (int ix = 0; ix < width; ix++) {
for (int iy = 0; iy < height; iy++) { for (int iy = 0; iy < height; iy++) {
double distX = Math.abs(playerX - ix); final double distX = Math.abs(playerX - ix);
double distY = Math.abs(playerY - iy - 1.5d); final double distY = Math.abs(playerY - iy - 1.5d);
if ((distX*distX + distY*distY/2d) < 25d) { if ((distX * distX + distY * distY / 2d) < 25d) {
byte b = w.getBlockIdAt(ix, iy); final byte b = w.getBlockIdAt(ix, iy);
if (b == 0) { if (b == 0) {
if (blue != 1) { if (blue != 1) {
blue = 1; blue = 1;
@ -138,7 +143,7 @@ public class MarioScreen extends Screen {
blue = 0; blue = 0;
DisplayManager.INSTANCE.renderer.glColor(0xffffffff); DisplayManager.INSTANCE.renderer.glColor(0xffffffff);
} }
DisplayManager.INSTANCE.renderer.glFillRect(screenX - shiftX+ 16 * ix, screenY - shiftY + 16 * (height - iy), 16, 16, 0, 0, 16, 16); DisplayManager.INSTANCE.renderer.glFillRect(screenX - shiftX + 16 * ix, screenY - shiftY + 16 * (height - iy), 16, 16, 0, 0, 16, 16);
} }
} }
} }
@ -150,17 +155,14 @@ public class MarioScreen extends Screen {
//DRAW MARIO //DRAW MARIO
skin.use(DisplayManager.INSTANCE.engine); skin.use(DisplayManager.INSTANCE.engine);
DisplayManager.INSTANCE.renderer.glFillRect(screenX - (g.getPlayer().flipped ? 3 : 0), screenY, DisplayManager.INSTANCE.renderer.glFillRect(screenX - (g.getPlayer().flipped ? 3 : 0), screenY, 35, 27, 35 * (g.getPlayer().marioSkinPos[0] + (g.getPlayer().flipped ? 2 : 1)), 27 * g.getPlayer().marioSkinPos[1], 35 * (g.getPlayer().flipped ? -1 : 1), 27);
35, 27,
35 * (g.getPlayer().marioSkinPos[0] + (g.getPlayer().flipped ? 2 : 1)), 27 * g.getPlayer().marioSkinPos[1],
35 * (g.getPlayer().flipped ? -1 : 1), 27);
// PIDisplay.renderer.glDrawSkin(getPosX() - 18, 25 + getPosY(), 35 * (marioSkinPos[0] + (flipped ? 2 : 1)), 27 * marioSkinPos[1], 35 * (marioSkinPos[0] + (flipped ? 1 : 2)), 27 * (marioSkinPos[1] + 1), true); // PIDisplay.renderer.glDrawSkin(getPosX() - 18, 25 + getPosY(), 35 * (marioSkinPos[0] + (flipped ? 2 : 1)), 27 * marioSkinPos[1], 35 * (marioSkinPos[0] + (flipped ? 1 : 2)), 27 * (marioSkinPos[1] + 1), true);
} }
// GPU PERFORMANCE TEST // GPU PERFORMANCE TEST
if (gpuTest1 != null) { if (gpuTest1 != null) {
DisplayManager.INSTANCE.renderer.glColor3f(1,1,1); DisplayManager.INSTANCE.renderer.glColor3f(1, 1, 1);
DisplayManager.INSTANCE.renderer.glFillColor(DisplayManager.INSTANCE.engine.getWidth()-(gpuTest12 ? 512 : 256), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuTest12 ? 512 : 256, gpuTest12 ? 512 : 256); DisplayManager.INSTANCE.renderer.glFillColor(DisplayManager.INSTANCE.engine.getWidth() - (gpuTest12 ? 512 : 256), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuTest12 ? 512 : 256, gpuTest12 ? 512 : 256);
gpuTest1.use(DisplayManager.INSTANCE.engine); gpuTest1.use(DisplayManager.INSTANCE.engine);
DisplayManager.INSTANCE.renderer.glColor3f(0, 0, 0); DisplayManager.INSTANCE.renderer.glColor3f(0, 0, 0);
DisplayManager.INSTANCE.renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth(), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuCharTest1[gpuCharTest1Num]); DisplayManager.INSTANCE.renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth(), DisplayManager.INSTANCE.engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuCharTest1[gpuCharTest1Num]);

View File

@ -38,7 +38,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class MathInputScreen extends Screen { public class MathInputScreen extends Screen {
private static final BinaryFont fontBig = Utils.getFont(false); private static final BinaryFont fontBig = Utils.getFont(false);
public MathContext calc; public MathContext calc;
public InputContext ic; public InputContext ic;
public InputContainer userInput; public InputContainer userInput;
@ -93,7 +93,7 @@ public class MathInputScreen extends Screen {
} }
if (computingResult) { if (computingResult) {
computingElapsedTime += dt; computingElapsedTime += dt;
computingAnimationElapsedTime+=dt; computingAnimationElapsedTime += dt;
if (computingAnimationElapsedTime > 0.1) { if (computingAnimationElapsedTime > 0.1) {
computingAnimationElapsedTime -= 0.1; computingAnimationElapsedTime -= 0.1;
computingAnimationIndex = (computingAnimationIndex + 1) % 16; computingAnimationIndex = (computingAnimationIndex + 1) % 16;
@ -101,7 +101,7 @@ public class MathInputScreen extends Screen {
} }
if (computingElapsedTime > 5) { if (computingElapsedTime > 5) {
computingBreakTipVisible = true; computingBreakTipVisible = true;
} }
} else { } else {
computingElapsedTime = 0; computingElapsedTime = 0;
computingAnimationElapsedTime = 0; computingAnimationElapsedTime = 0;
@ -109,6 +109,7 @@ public class MathInputScreen extends Screen {
computingBreakTipVisible = false; computingBreakTipVisible = false;
} }
} }
@Override @Override
public void render() { public void render() {
final Renderer renderer = DisplayManager.INSTANCE.renderer; final Renderer renderer = DisplayManager.INSTANCE.renderer;
@ -130,7 +131,7 @@ public class MathInputScreen extends Screen {
if (computingBreakTipVisible) { if (computingBreakTipVisible) {
Utils.getFont(false).use(DisplayManager.INSTANCE.engine); Utils.getFont(false).use(DisplayManager.INSTANCE.engine);
renderer.glColor3f(0.75f, 0, 0); renderer.glColor3f(0.75f, 0, 0);
renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth() - 4 - size - 4, DisplayManager.INSTANCE.engine.getHeight() - size/2 - renderer.getCurrentFont().getCharacterHeight()/2 - 4, "Press (=) to stop"); renderer.glDrawStringRight(DisplayManager.INSTANCE.engine.getWidth() - 4 - size - 4, DisplayManager.INSTANCE.engine.getHeight() - size / 2 - renderer.getCurrentFont().getCharacterHeight() / 2 - 4, "Press (=) to stop");
} }
} else { } else {
if (!result.isContentEmpty()) { if (!result.isContentEmpty()) {
@ -155,7 +156,6 @@ public class MathInputScreen extends Screen {
renderer.glFillRect(2 + 18 * pos + 2 * spacersNumb, 2, 16, 16, 16 * skinN, 16 * 0, 16, 16); renderer.glFillRect(2 + 18 * pos + 2 * spacersNumb, 2, 16, 16, 16 * skinN, 16 * 0, 16, 16);
} }
@Override @Override
public boolean mustBeRefreshed() { public boolean mustBeRefreshed() {
if (mustRefresh) { if (mustRefresh) {
@ -193,7 +193,9 @@ public class MathInputScreen extends Screen {
case STEP: case STEP:
currentStep++; currentStep++;
case SIMPLIFY: case SIMPLIFY:
if (!step) currentStep = 0; if (!step) {
currentStep = 0;
}
if (DisplayManager.INSTANCE.error != null) { if (DisplayManager.INSTANCE.error != null) {
//TODO: make the error management a global API rather than being relegated to this screen. //TODO: make the error management a global API rather than being relegated to this screen.
Utils.out.println(1, "Resetting after error..."); Utils.out.println(1, "Resetting after error...");
@ -205,11 +207,11 @@ public class MathInputScreen extends Screen {
} else { } else {
if (!computingResult) { if (!computingResult) {
computingResult = true; computingResult = true;
computingThread = new Thread(()-> { computingThread = new Thread(() -> {
try { try {
try { try {
if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) { if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) {
Expression expr = MathParser.parseInput(calc, userInput); final Expression expr = MathParser.parseInput(calc, userInput);
if (calc.f == null | calc.f2 == null) { if (calc.f == null | calc.f2 == null) {
calc.f = new ObjectArrayList<>(); calc.f = new ObjectArrayList<>();
calc.f2 = new ObjectArrayList<>(); calc.f2 = new ObjectArrayList<>();
@ -219,14 +221,14 @@ public class MathInputScreen extends Screen {
} }
calc.f.add(expr); calc.f.add(expr);
Utils.out.println(2, "INPUT: " + expr); Utils.out.println(2, "INPUT: " + expr);
MathSolver ms = new MathSolver(expr); final MathSolver ms = new MathSolver(expr);
ObjectArrayList<ObjectArrayList<Function>> resultSteps = ms.solveAllSteps(); final ObjectArrayList<ObjectArrayList<Function>> resultSteps = ms.solveAllSteps();
resultSteps.add(0, Utils.newArrayList(expr)); resultSteps.add(0, Utils.newArrayList(expr));
ObjectArrayList<Function> resultExpressions = resultSteps.get(resultSteps.size() - 1); final ObjectArrayList<Function> resultExpressions = resultSteps.get(resultSteps.size() - 1);
for (Function rr : resultExpressions) { for (final Function rr : resultExpressions) {
Utils.out.println(0, "RESULT: " + rr.toString()); Utils.out.println(0, "RESULT: " + rr.toString());
} }
ObjectArrayList<ObjectArrayList<Block>> resultBlocks = MathParser.parseOutput(calc, resultExpressions); final ObjectArrayList<ObjectArrayList<Block>> resultBlocks = MathParser.parseOutput(calc, resultExpressions);
result.setContentAsMultipleGroups(resultBlocks); result.setContentAsMultipleGroups(resultBlocks);
// showVariablesDialog(() -> { // showVariablesDialog(() -> {
// currentExpression = newExpression; // currentExpression = newExpression;
@ -454,7 +456,7 @@ public class MathInputScreen extends Screen {
} }
} }
} }
} catch (Exception ex) { } catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return true; return true;
} }

View File

@ -52,11 +52,14 @@ public interface Function {
* @return Calculator mathContext * @return Calculator mathContext
*/ */
public MathContext getMathContext(); public MathContext getMathContext();
/** /**
* Simplify the current function or it's children using the specified <b>rule</b> * Simplify the current function or it's children using the specified
* <b>rule</b>
*
* @param rule * @param rule
* @return A list of the resulting Functions if the rule is applicable and something changed, <b>null</b> otherwise * @return A list of the resulting Functions if the rule is applicable and
* something changed, <b>null</b> otherwise
* @throws Error * @throws Error
* @throws InterruptedException * @throws InterruptedException
*/ */

View File

@ -90,15 +90,19 @@ public abstract class FunctionDynamic implements Function {
@Override @Override
public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException { public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
final Function[] fncs = getParameters(); final Function[] fncs = getParameters();
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
ObjectArrayList<Function> result = new ObjectArrayList<>(); throw new InterruptedException();
}
final ObjectArrayList<Function> result = new ObjectArrayList<>();
final ObjectArrayList<ObjectArrayList<Function>> ln = new ObjectArrayList<>(); final ObjectArrayList<ObjectArrayList<Function>> ln = new ObjectArrayList<>();
boolean alreadySolved = true; boolean alreadySolved = true;
for (final Function fnc : fncs) { for (final Function fnc : fncs) {
final ObjectArrayList<Function> l = new ObjectArrayList<>(); final ObjectArrayList<Function> l = new ObjectArrayList<>();
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
ObjectArrayList<Function> simplifiedFnc = fnc.simplify(rule); throw new InterruptedException();
}
final ObjectArrayList<Function> simplifiedFnc = fnc.simplify(rule);
if (simplifiedFnc == null) { if (simplifiedFnc == null) {
l.add(fnc); l.add(fnc);
} else { } else {
@ -107,8 +111,10 @@ public abstract class FunctionDynamic implements Function {
} }
ln.add(l); ln.add(l);
} }
if (alreadySolved) return rule.execute(this); if (alreadySolved) {
return rule.execute(this);
}
final Function[][] results = Utils.joinFunctionsResults(ln); final Function[][] results = Utils.joinFunctionsResults(ln);

View File

@ -116,35 +116,49 @@ public abstract class FunctionOperator implements Function {
@Override @Override
public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException { public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
ObjectArrayList<Function> simplifiedParam1 = parameter1.simplify(rule); final ObjectArrayList<Function> simplifiedParam1 = parameter1.simplify(rule);
ObjectArrayList<Function> simplifiedParam2 = parameter2.simplify(rule); final ObjectArrayList<Function> simplifiedParam2 = parameter2.simplify(rule);
try { try {
if (simplifiedParam1 == null & simplifiedParam2 == null) return rule.execute(this); if (simplifiedParam1 == null & simplifiedParam2 == null) {
} catch (Exception e) { return rule.execute(this);
Error err = new Error(Errors.ERROR, "Error while executing rule '" + rule.getRuleName() + "'!\n" + e.getMessage()); }
} catch (final Exception e) {
final Error err = new Error(Errors.ERROR, "Error while executing rule '" + rule.getRuleName() + "'!\n" + e.getMessage());
err.initCause(e); err.initCause(e);
throw err; throw err;
} }
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
ObjectArrayList<Function> result = new ObjectArrayList<>(); throw new InterruptedException();
}
final ObjectArrayList<Function> result = new ObjectArrayList<>();
final ObjectArrayList<Function> l1 = new ObjectArrayList<>(); final ObjectArrayList<Function> l1 = new ObjectArrayList<>();
final ObjectArrayList<Function> l2 = new ObjectArrayList<>(); final ObjectArrayList<Function> l2 = new ObjectArrayList<>();
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
if (simplifiedParam1 == null) { if (simplifiedParam1 == null) {
l1.add(parameter1); l1.add(parameter1);
} else { } else {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
l1.addAll(simplifiedParam1); l1.addAll(simplifiedParam1);
} }
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
if (simplifiedParam2 == null) { if (simplifiedParam2 == null) {
l2.add(parameter2); l2.add(parameter2);
} else { } else {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
l2.addAll(simplifiedParam2); l2.addAll(simplifiedParam2);
} }
@ -153,7 +167,7 @@ public abstract class FunctionOperator implements Function {
for (final Function[] f : results) { for (final Function[] f : results) {
result.add(setParameter1(f[0]).setParameter2(f[1])); result.add(setParameter1(f[0]).setParameter2(f[1]));
} }
return result; return result;
} }
@ -170,6 +184,6 @@ public abstract class FunctionOperator implements Function {
@Override @Override
public String toString() { public String toString() {
return this.getClass().getSimpleName() + "(" + this.getParameter1() + "," + this.getParameter2() + ")"; return this.getClass().getSimpleName() + "(" + getParameter1() + "," + getParameter2() + ")";
} }
} }

View File

@ -98,10 +98,12 @@ public abstract class FunctionSingle implements Function {
@Override @Override
public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException { public final ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
ObjectArrayList<Function> simplifiedParam = parameter.simplify(rule); final ObjectArrayList<Function> simplifiedParam = parameter.simplify(rule);
if (simplifiedParam == null) return rule.execute(this); if (simplifiedParam == null) {
return rule.execute(this);
ObjectArrayList<Function> result = new ObjectArrayList<>(); }
final ObjectArrayList<Function> result = new ObjectArrayList<>();
for (final Function f : simplifiedParam) { for (final Function f : simplifiedParam) {
result.add(this.setParameter(f)); result.add(this.setParameter(f));
} }

View File

@ -14,7 +14,7 @@ public class Division extends FunctionOperator {
public Division(MathContext root, Function value1, Function value2) { public Division(MathContext root, Function value1, Function value2) {
super(root, value1, value2); super(root, value1, value2);
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof Division) { if (o instanceof Division) {
@ -36,16 +36,16 @@ public class Division extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub1 = getParameter1().toBlock(context); final ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
ObjectArrayList<Block> sub2 = getParameter2().toBlock(context); final ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
BlockDivision bd = new BlockDivision(); final BlockDivision bd = new BlockDivision();
BlockContainer uc = bd.getUpperContainer(); final BlockContainer uc = bd.getUpperContainer();
BlockContainer lc = bd.getLowerContainer(); final BlockContainer lc = bd.getLowerContainer();
for (Block b : sub1) { for (final Block b : sub1) {
uc.appendBlockUnsafe(b); uc.appendBlockUnsafe(b);
} }
for (Block b : sub2) { for (final Block b : sub2) {
lc.appendBlockUnsafe(b); lc.appendBlockUnsafe(b);
} }
uc.recomputeDimensions(); uc.recomputeDimensions();

View File

@ -26,7 +26,7 @@ public class Expression extends FunctionSingle {
super(root, value); super(root, value);
} }
private boolean initialParenthesis = false; private final boolean initialParenthesis = false;
@Deprecated @Deprecated
public Expression(MathContext root, String string) throws Error { public Expression(MathContext root, String string) throws Error {
@ -570,11 +570,11 @@ public class Expression extends FunctionSingle {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub = getParameter(0).toBlock(context); final ObjectArrayList<Block> sub = getParameter(0).toBlock(context);
BlockParenthesis bp = new BlockParenthesis(); final BlockParenthesis bp = new BlockParenthesis();
BlockContainer bpc = bp.getNumberContainer(); final BlockContainer bpc = bp.getNumberContainer();
for (Block b : sub) { for (final Block b : sub) {
bpc.appendBlockUnsafe(b); bpc.appendBlockUnsafe(b);
} }
bpc.recomputeDimensions(); bpc.recomputeDimensions();
@ -602,7 +602,7 @@ public class Expression extends FunctionSingle {
} else { } else {
final Function f = (Function) o; final Function f = (Function) o;
if (f instanceof Expression) { if (f instanceof Expression) {
return (getParameter(0).equals(((Expression)f).getParameter(0))); return (getParameter(0).equals(((Expression) f).getParameter(0)));
} else { } else {
return (getParameter(0).equals(f)); return (getParameter(0).equals(f));
} }

View File

@ -1,10 +1,8 @@
package org.warp.picalculator.math.functions; package org.warp.picalculator.math.functions;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors;
import org.warp.picalculator.gui.expression.blocks.Block; import org.warp.picalculator.gui.expression.blocks.Block;
import org.warp.picalculator.gui.expression.blocks.BlockContainer; import org.warp.picalculator.gui.expression.blocks.BlockContainer;
import org.warp.picalculator.gui.expression.blocks.BlockDivision;
import org.warp.picalculator.gui.expression.blocks.BlockLogarithm; import org.warp.picalculator.gui.expression.blocks.BlockLogarithm;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
@ -34,16 +32,16 @@ public class Logarithm extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub1 = getParameter1().toBlock(context); final ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
ObjectArrayList<Block> sub2 = getParameter2().toBlock(context); final ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
BlockLogarithm bd = new BlockLogarithm(); final BlockLogarithm bd = new BlockLogarithm();
BlockContainer uc = bd.getBaseContainer(); final BlockContainer uc = bd.getBaseContainer();
BlockContainer lc = bd.getNumberContainer(); final BlockContainer lc = bd.getNumberContainer();
for (Block b : sub1) { for (final Block b : sub1) {
uc.appendBlockUnsafe(b); uc.appendBlockUnsafe(b);
} }
for (Block b : sub2) { for (final Block b : sub2) {
lc.appendBlockUnsafe(b); lc.appendBlockUnsafe(b);
} }
uc.recomputeDimensions(); uc.recomputeDimensions();

View File

@ -40,19 +40,19 @@ public class Multiplication extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
Function par1 = getParameter1(); final Function par1 = getParameter1();
Function par2 = getParameter2(); final Function par2 = getParameter2();
ObjectArrayList<Block> sub1 = par1.toBlock(context); final ObjectArrayList<Block> sub1 = par1.toBlock(context);
ObjectArrayList<Block> sub2 = par2.toBlock(context); final ObjectArrayList<Block> sub2 = par2.toBlock(context);
Block nearLeft = sub1.get(sub1.size() - 1); final Block nearLeft = sub1.get(sub1.size() - 1);
Block nearRight = sub2.get(0); final Block nearRight = sub2.get(0);
if (par1 instanceof Number && ((Number) par1).equals(new Number(context, -1))) { if (par1 instanceof Number && ((Number) par1).equals(new Number(context, -1))) {
result.add(new BlockChar(MathematicalSymbols.MINUS)); result.add(new BlockChar(MathematicalSymbols.MINUS));
if (new Expression(context, par2).parenthesisNeeded()) { if (new Expression(context, par2).parenthesisNeeded()) {
ObjectArrayList<Block> parBlocks = par2.toBlock(context); final ObjectArrayList<Block> parBlocks = par2.toBlock(context);
BlockParenthesis par = new BlockParenthesis(parBlocks); final BlockParenthesis par = new BlockParenthesis(parBlocks);
result.add(par); result.add(par);
} else { } else {
result.addAll(sub2); result.addAll(sub2);
@ -60,23 +60,20 @@ public class Multiplication extends FunctionOperator {
return result; return result;
} else { } else {
if (new Expression(context, par1).parenthesisNeeded()) { if (new Expression(context, par1).parenthesisNeeded()) {
ObjectArrayList<Block> parBlocks = par1.toBlock(context); final ObjectArrayList<Block> parBlocks = par1.toBlock(context);
BlockParenthesis par = new BlockParenthesis(parBlocks); final BlockParenthesis par = new BlockParenthesis(parBlocks);
result.add(par); result.add(par);
} else { } else {
result.addAll(sub1); result.addAll(sub1);
} }
if ((nearLeft instanceof BlockChar && nearRight instanceof BlockChar) if ((nearLeft instanceof BlockChar && nearRight instanceof BlockChar) && !(par2 instanceof Negative) && !(par1 instanceof Number && par2 instanceof Number)) {
&& !(par2 instanceof Negative)
&& !(par1 instanceof Number && par2 instanceof Number)
) {
} else { } else {
result.add(new BlockChar(MathematicalSymbols.MULTIPLICATION)); result.add(new BlockChar(MathematicalSymbols.MULTIPLICATION));
} }
if (new Expression(context, par2).parenthesisNeeded()) { if (new Expression(context, par2).parenthesisNeeded()) {
ObjectArrayList<Block> parBlocks = par2.toBlock(context); final ObjectArrayList<Block> parBlocks = par2.toBlock(context);
BlockParenthesis par = new BlockParenthesis(parBlocks); final BlockParenthesis par = new BlockParenthesis(parBlocks);
result.add(par); result.add(par);
} else { } else {
result.addAll(sub2); result.addAll(sub2);
@ -84,11 +81,11 @@ public class Multiplication extends FunctionOperator {
return result; return result;
} }
} }
public boolean isNegative() { public boolean isNegative() {
return parameter1.equals(new Number(getMathContext(), -1)) || parameter2.equals(new Number(getMathContext(), -1)); return parameter1.equals(new Number(getMathContext(), -1)) || parameter2.equals(new Number(getMathContext(), -1));
} }
public Function toPositive() { public Function toPositive() {
if (parameter1.equals(new Number(getMathContext(), -1))) { if (parameter1.equals(new Number(getMathContext(), -1))) {
return parameter2; return parameter2;
@ -98,7 +95,7 @@ public class Multiplication extends FunctionOperator {
return null; return null;
} }
} }
public static Multiplication newNegative(MathContext context, Function value2) { public static Multiplication newNegative(MathContext context, Function value2) {
return new Multiplication(context, new Number(context, -1), value2); return new Multiplication(context, new Number(context, -1), value2);
} }

View File

@ -32,12 +32,12 @@ public class Negative extends FunctionSingle {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> blocks = new ObjectArrayList<Block>(); final ObjectArrayList<Block> blocks = new ObjectArrayList<>();
blocks.add(new BlockChar(MathematicalSymbols.MINUS)); blocks.add(new BlockChar(MathematicalSymbols.MINUS));
if (new Expression(context, getParameter()).parenthesisNeeded()) { if (new Expression(context, getParameter()).parenthesisNeeded()) {
BlockParenthesis par = new BlockParenthesis(); final BlockParenthesis par = new BlockParenthesis();
ObjectArrayList<Block> parBlocks = getParameter().toBlock(context); final ObjectArrayList<Block> parBlocks = getParameter().toBlock(context);
for (Block b : parBlocks) { for (final Block b : parBlocks) {
par.getNumberContainer().appendBlockUnsafe(b); // Skips recomputeDimension par.getNumberContainer().appendBlockUnsafe(b); // Skips recomputeDimension
} }
par.recomputeDimensions(); // Recompute dimensions after appendBlockUnsafe par.recomputeDimensions(); // Recompute dimensions after appendBlockUnsafe

View File

@ -76,7 +76,9 @@ public class Number implements Function {
if (Utils.isIntegerValue(f.term)) { if (Utils.isIntegerValue(f.term)) {
final BigInteger bi = f.term.toBigInteger().abs(); final BigInteger bi = f.term.toBigInteger().abs();
for (BigInteger i = BigInteger.ZERO; i.compareTo(bi) < 0; i = i.add(BigInteger.ONE)) { for (BigInteger i = BigInteger.ZERO; i.compareTo(bi) < 0; i = i.add(BigInteger.ONE)) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
ret = ret.multiply(new Number(root, getTerm())); ret = ret.multiply(new Number(root, getTerm()));
} }
if (f.term.signum() == -1) { if (f.term.signum() == -1) {
@ -231,16 +233,16 @@ public class Number implements Function {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) { public ObjectArrayList<Block> toBlock(MathContext context) {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
String numberString = this.toString(); final String numberString = toString();
if (numberString.contains("")) { if (numberString.contains("")) {
String[] numberParts = numberString.split("", 2); final String[] numberParts = numberString.split("", 2);
BlockPower bp = new BlockExponentialNotation(); final BlockPower bp = new BlockExponentialNotation();
BlockContainer bpec = bp.getExponentContainer(); final BlockContainer bpec = bp.getExponentContainer();
for (char c : numberParts[0].toCharArray()) { for (final char c : numberParts[0].toCharArray()) {
result.add(new BlockChar(c)); result.add(new BlockChar(c));
} }
for (char c : numberParts[1].toCharArray()) { for (final char c : numberParts[1].toCharArray()) {
bpec.appendBlockUnsafe(new BlockChar(c)); bpec.appendBlockUnsafe(new BlockChar(c));
} ; } ;
bpec.recomputeDimensions(); bpec.recomputeDimensions();
@ -248,7 +250,7 @@ public class Number implements Function {
result.add(bp); result.add(bp);
return result; return result;
} else { } else {
for (char c : numberString.toCharArray()) { for (final char c : numberString.toCharArray()) {
result.add(new BlockChar(c)); result.add(new BlockChar(c));
} }
} }

View File

@ -32,13 +32,13 @@ public class Power extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub1 = getParameter1().toBlock(context); final ObjectArrayList<Block> sub1 = getParameter1().toBlock(context);
ObjectArrayList<Block> sub2 = getParameter2().toBlock(context); final ObjectArrayList<Block> sub2 = getParameter2().toBlock(context);
BlockPower bp = new BlockPower(); final BlockPower bp = new BlockPower();
BlockContainer ec = bp.getExponentContainer(); final BlockContainer ec = bp.getExponentContainer();
result.addAll(sub1); result.addAll(sub1);
for (Block b : sub2) { for (final Block b : sub2) {
ec.appendBlockUnsafe(b); ec.appendBlockUnsafe(b);
} }
ec.recomputeDimensions(); ec.recomputeDimensions();

View File

@ -32,10 +32,10 @@ public class RootSquare extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
BlockSquareRoot bsqr = new BlockSquareRoot(); final BlockSquareRoot bsqr = new BlockSquareRoot();
BlockContainer bsqrc = bsqr.getNumberContainer(); final BlockContainer bsqrc = bsqr.getNumberContainer();
for (Block b : getParameter2().toBlock(context)) { for (final Block b : getParameter2().toBlock(context)) {
bsqrc.appendBlockUnsafe(b); bsqrc.appendBlockUnsafe(b);
} }
bsqrc.recomputeDimensions(); bsqrc.recomputeDimensions();

View File

@ -32,7 +32,7 @@ public class Subtraction extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.addAll(getParameter1().toBlock(context)); result.addAll(getParameter1().toBlock(context));
result.add(new BlockChar(MathematicalSymbols.SUBTRACTION)); result.add(new BlockChar(MathematicalSymbols.SUBTRACTION));
result.addAll(getParameter2().toBlock(context)); result.addAll(getParameter2().toBlock(context));

View File

@ -35,7 +35,7 @@ public class Sum extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.addAll(getParameter1().toBlock(context)); result.addAll(getParameter1().toBlock(context));
result.add(new BlockChar(MathematicalSymbols.SUM)); result.add(new BlockChar(MathematicalSymbols.SUM));
result.addAll(getParameter2().toBlock(context)); result.addAll(getParameter2().toBlock(context));

View File

@ -32,7 +32,7 @@ public class SumSubtraction extends FunctionOperator {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.addAll(getParameter1().toBlock(context)); result.addAll(getParameter1().toBlock(context));
result.add(new BlockChar(MathematicalSymbols.SUM_SUBTRACTION)); result.add(new BlockChar(MathematicalSymbols.SUM_SUBTRACTION));
result.addAll(getParameter2().toBlock(context)); result.addAll(getParameter2().toBlock(context));

View File

@ -49,11 +49,11 @@ public class Undefined implements Function {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) { public ObjectArrayList<Block> toBlock(MathContext context) {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
result.add(new BlockUndefined()); result.add(new BlockUndefined());
return result; return result;
} }
@Override @Override
public String toString() { public String toString() {
return "UNDEFINED"; return "UNDEFINED";

View File

@ -55,7 +55,7 @@ public class Variable implements Function {
this.n = n; this.n = n;
} }
} }
@Override @Override
public ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException { public ObjectArrayList<Function> simplify(Rule rule) throws Error, InterruptedException {
return rule.execute(this); return rule.execute(this);
@ -100,7 +100,7 @@ public class Variable implements Function {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) { public ObjectArrayList<Block> toBlock(MathContext context) {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
//TODO: Temporary solution. In near future Variables will be distint objects and they will have a color. So they will be no longer a BlockChar/FeatureChar //TODO: Temporary solution. In near future Variables will be distint objects and they will have a color. So they will be no longer a BlockChar/FeatureChar
result.add(new BlockChar(getChar())); result.add(new BlockChar(getChar()));
return result; return result;

View File

@ -33,11 +33,11 @@ public class Sine extends FunctionSingle {
@Override @Override
public ObjectArrayList<Block> toBlock(MathContext context) throws Error { public ObjectArrayList<Block> toBlock(MathContext context) throws Error {
ObjectArrayList<Block> result = new ObjectArrayList<>(); final ObjectArrayList<Block> result = new ObjectArrayList<>();
ObjectArrayList<Block> sub = getParameter(0).toBlock(context); final ObjectArrayList<Block> sub = getParameter(0).toBlock(context);
BlockSine bs = new BlockSine(); final BlockSine bs = new BlockSine();
BlockContainer bpc = bs.getNumberContainer(); final BlockContainer bpc = bs.getNumberContainer();
for (Block b : sub) { for (final Block b : sub) {
bpc.appendBlockUnsafe(b); bpc.appendBlockUnsafe(b);
} }
bpc.recomputeDimensions(); bpc.recomputeDimensions();

View File

@ -45,10 +45,11 @@ public class MathParser {
public static ObjectArrayList<ObjectArrayList<Block>> parseOutput(MathContext context, public static ObjectArrayList<ObjectArrayList<Block>> parseOutput(MathContext context,
ObjectArrayList<Function> resultExpressions) throws Error { ObjectArrayList<Function> resultExpressions) throws Error {
final ObjectArrayList<ObjectArrayList<Block>> result = new ObjectArrayList<>(); final ObjectArrayList<ObjectArrayList<Block>> result = new ObjectArrayList<>();
for (Function resultExpression : resultExpressions) { for (final Function resultExpression : resultExpressions) {
ObjectArrayList<Block> resultBlocks = resultExpression.toBlock(context); final ObjectArrayList<Block> resultBlocks = resultExpression.toBlock(context);
if (resultBlocks == null) if (resultBlocks == null) {
throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + resultExpression.getClass().getSimpleName()); throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + resultExpression.getClass().getSimpleName());
}
result.add(resultBlocks); result.add(resultBlocks);
} }
return result; return result;
@ -61,9 +62,10 @@ public class MathParser {
ObjectArrayList<Function> process = new ObjectArrayList<>(); ObjectArrayList<Function> process = new ObjectArrayList<>();
for (final Feature f : features) { for (final Feature f : features) {
Function fnc = f.toFunction(context); final Function fnc = f.toFunction(context);
if (fnc == null) if (fnc == null) {
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!"); throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!");
}
process.add(fnc); process.add(fnc);
} }
@ -78,35 +80,28 @@ public class MathParser {
private static ObjectArrayList<Function> fixStack(MathContext context, ObjectArrayList<Function> functionsList) private static ObjectArrayList<Function> fixStack(MathContext context, ObjectArrayList<Function> functionsList)
throws Error { throws Error {
final MathParserStep[] steps = new MathParserStep[] { final MathParserStep[] steps = new MathParserStep[] { new JoinNumberAndVariables(context), new FixSingleFunctionArgs(), new RemoveParentheses(context), new FixMultiplicationsAndDivisions(), new FixSumsAndSubtractions(), new AddImplicitMultiplications(context), };
new JoinNumberAndVariables(context),
new FixSingleFunctionArgs(),
new RemoveParentheses(context),
new FixMultiplicationsAndDivisions(),
new FixSumsAndSubtractions(),
new AddImplicitMultiplications(context),
};
boolean lastLoopDidSomething; boolean lastLoopDidSomething;
Function lastElement; Function lastElement;
if (StaticVars.debugOn) { if (StaticVars.debugOn) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: "); Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: ");
for (Function f : functionsList) { for (final Function f : functionsList) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString()); Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString());
} }
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE);
} }
for (MathParserStep step : steps) { for (final MathParserStep step : steps) {
if (StaticVars.debugOn) { if (StaticVars.debugOn) {
Utils.out.println(2, "Stack fixing step \"" + step.getStepName() + "\""); Utils.out.println(2, "Stack fixing step \"" + step.getStepName() + "\"");
} }
int stepQty = step.requiresReversedIteration() ? -1 : 1, final int stepQty = step.requiresReversedIteration() ? -1 : 1,
initialIndex = step.requiresReversedIteration() ? functionsList.size() - 1 : 0; initialIndex = step.requiresReversedIteration() ? functionsList.size() - 1 : 0;
do { do {
lastLoopDidSomething = false; lastLoopDidSomething = false;
lastElement = null; lastElement = null;
IntegerObj curIndex = new IntegerObj(initialIndex); final IntegerObj curIndex = new IntegerObj(initialIndex);
while (curIndex.i >= 0 && curIndex.i < functionsList.size()) { while (curIndex.i >= 0 && curIndex.i < functionsList.size()) {
final int i = curIndex.i; final int i = curIndex.i;
final Function f = functionsList.get(i); final Function f = functionsList.get(i);
@ -122,7 +117,7 @@ public class MathParser {
if (StaticVars.debugOn) { if (StaticVars.debugOn) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: "); Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: ");
for (Function f : functionsList) { for (final Function f : functionsList) {
Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString()); Utils.out.print(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString());
} }
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE);
@ -192,7 +187,7 @@ public class MathParser {
break; break;
} }
for (char var : MathematicalSymbols.variables) { for (final char var : MathematicalSymbols.variables) {
if (featureChar == var) { if (featureChar == var) {
result = new FeatureVariable(featureChar, V_TYPE.VARIABLE); result = new FeatureVariable(featureChar, V_TYPE.VARIABLE);
break; break;

View File

@ -3,7 +3,6 @@ package org.warp.picalculator.math.parser.features;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.functions.Logarithm; import org.warp.picalculator.math.functions.Logarithm;
import org.warp.picalculator.math.functions.Power;
public class FeatureLogarithm extends FeatureDoubleImpl { public class FeatureLogarithm extends FeatureDoubleImpl {

View File

@ -13,7 +13,7 @@ public class FeatureParenthesis extends FeatureSingleImpl {
@Override @Override
public Function toFunction(MathContext context) throws Error { public Function toFunction(MathContext context) throws Error {
return new Expression(context, this.getFunction1()); return new Expression(context, getFunction1());
} }
} }

View File

@ -13,7 +13,7 @@ public class FeatureSine extends FeatureSingleImpl {
@Override @Override
public Function toFunction(MathContext context) throws Error { public Function toFunction(MathContext context) throws Error {
return new Sine(context, this.getFunction1()); return new Sine(context, getFunction1());
} }
} }

View File

@ -10,7 +10,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class AddImplicitMultiplications implements MathParserStep { public class AddImplicitMultiplications implements MathParserStep {
private MathContext context; private final MathContext context;
public AddImplicitMultiplications(MathContext context) { public AddImplicitMultiplications(MathContext context) {
this.context = context; this.context = context;

View File

@ -13,14 +13,15 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class JoinNumberAndVariables implements MathParserStep { public class JoinNumberAndVariables implements MathParserStep {
private MathContext context; private final MathContext context;
public JoinNumberAndVariables(MathContext context) { public JoinNumberAndVariables(MathContext context) {
this.context = context; this.context = context;
} }
@Override @Override
public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction, ObjectArrayList<Function> functionsList) { public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction,
ObjectArrayList<Function> functionsList) {
if (currentFunction instanceof Number | currentFunction instanceof Variable | currentFunction instanceof Division) { if (currentFunction instanceof Number | currentFunction instanceof Variable | currentFunction instanceof Division) {
if (lastFunction instanceof Variable | lastFunction instanceof Number | (lastFunction instanceof Multiplication && ((Multiplication) lastFunction).getParameter2() != null)) { if (lastFunction instanceof Variable | lastFunction instanceof Number | (lastFunction instanceof Multiplication && ((Multiplication) lastFunction).getParameter2() != null)) {
final Function a = currentFunction; final Function a = currentFunction;

View File

@ -10,19 +10,20 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class RemoveParentheses implements MathParserStep { public class RemoveParentheses implements MathParserStep {
private MathContext context; private final MathContext context;
public RemoveParentheses(MathContext context) { public RemoveParentheses(MathContext context) {
this.context = context; this.context = context;
} }
@Override @Override
public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction, ObjectArrayList<Function> functionsList) { public boolean eval(IntegerObj curIndex, Function lastFunction, Function currentFunction,
ObjectArrayList<Function> functionsList) {
if (currentFunction instanceof Expression) { if (currentFunction instanceof Expression) {
if (((Expression)currentFunction).getParameter() == null) { if (((Expression) currentFunction).getParameter() == null) {
functionsList.remove(curIndex.i); functionsList.remove(curIndex.i);
} else { } else {
functionsList.set(curIndex.i, ((Expression)currentFunction).getParameter()); functionsList.set(curIndex.i, ((Expression) currentFunction).getParameter());
} }
return true; return true;
} }

View File

@ -8,12 +8,14 @@ import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
/** /**
* Rule interface * Rule interface
*
* @author Andrea Cavalli * @author Andrea Cavalli
* *
*/ */
public interface Rule { public interface Rule {
/** /**
* Get rule name * Get rule name
*
* @return * @return
*/ */
public default String getRuleName() { public default String getRuleName() {
@ -22,16 +24,23 @@ public interface Rule {
/** /**
* Get rule type * Get rule type
*
* @return * @return
*/ */
@SpecializedFunction @SpecializedFunction
public RuleType getRuleType(); public RuleType getRuleType();
/** /**
* *
* @param func * @param func
* @return <ul><li><code>null</code> if it's not executable on the function <b>func</b></li><li>An <code>ObjectArrayList&lt;Function&gt;</code> if it did something</li></ul> * @return
* @throws Error * <ul>
* <li><code>null</code> if it's not executable on the function
* <b>func</b></li>
* <li>An <code>ObjectArrayList&lt;Function&gt;</code> if it did
* something</li>
* </ul>
* @throws Error
*/ */
public ObjectArrayList<Function> execute(Function func) throws Error, InterruptedException; public ObjectArrayList<Function> execute(Function func) throws Error, InterruptedException;
} }

View File

@ -2,11 +2,13 @@ package org.warp.picalculator.math.rules;
public enum RuleType { public enum RuleType {
/** /**
* A rule that tries to factorize and group a polynomial expression into a shorter expression * A rule that tries to factorize and group a polynomial expression into a
* shorter expression
*/ */
REDUCTION, REDUCTION,
/** /**
* A rule that tries to transform an expression to a simple polynomial expression * A rule that tries to transform an expression to a simple polynomial
* expression
*/ */
EXPANSION, EXPANSION,
/** /**

View File

@ -28,18 +28,17 @@ import org.warp.picalculator.math.solver.MathSolver;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class RulesManager { public class RulesManager {
public static ObjectArrayList<Rule>[] rules; public static ObjectArrayList<Rule>[] rules;
private RulesManager() { private RulesManager() {}
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void initialize() { public static void initialize() {
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loading the rules"); Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loading the rules");
rules = new ObjectArrayList[RuleType.values().length]; rules = new ObjectArrayList[RuleType.values().length];
for (RuleType val : RuleType.values()) { for (final RuleType val : RuleType.values()) {
rules[val.ordinal()] = new ObjectArrayList<Rule>(); rules[val.ordinal()] = new ObjectArrayList<>();
} }
try { try {
boolean compiledSomething = false; boolean compiledSomething = false;
@ -47,31 +46,29 @@ public class RulesManager {
if (!Files.exists(defaultRulesPath)) { if (!Files.exists(defaultRulesPath)) {
throw new FileNotFoundException("default-rules.lst not found!"); throw new FileNotFoundException("default-rules.lst not found!");
} }
List<String> ruleLines = new ArrayList<String>(); final List<String> ruleLines = new ArrayList<>();
Path rulesPath = Paths.get("rules/"); final Path rulesPath = Paths.get("rules/");
if (rulesPath.toFile().exists()) { if (rulesPath.toFile().exists()) {
try (Stream<Path> paths = Files.walk(rulesPath)) { try (Stream<Path> paths = Files.walk(rulesPath)) {
paths paths.filter(Files::isRegularFile).forEach((Path p) -> {
.filter(Files::isRegularFile) if (p.toString().endsWith(".java")) {
.forEach((Path p) -> { String path = rulesPath.relativize(p).toString();
if (p.toString().endsWith(".java")) { path = path.substring(0, path.length() - ".java".length());
String path = rulesPath.relativize(p).toString(); ruleLines.add(path);
path = path.substring(0, path.length() - ".java".length()); Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + p.toAbsolutePath().toString());
ruleLines.add(path); System.err.println(path);
Utils.out.print(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + p.toAbsolutePath().toString()); }
System.err.println(path); });
} }
});
}
} }
ruleLines.addAll(Files.readAllLines(defaultRulesPath)); ruleLines.addAll(Files.readAllLines(defaultRulesPath));
boolean useCache = false; boolean useCache = false;
Path tDir = Paths.get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator").resolve("rules-rt"); final Path tDir = Paths.get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator").resolve("rules-rt");
// try { // try {
// final Path defaultResource = Utils.getResource("/math-rules-cache.zip"); // final Path defaultResource = Utils.getResource("/math-rules-cache.zip");
// } // }
Path cacheFilePath = Utils.getResource("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath(); final Path cacheFilePath = Utils.getResource("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath();
if (cacheFilePath.toFile().exists()) { if (cacheFilePath.toFile().exists()) {
try { try {
if (tDir.toFile().exists()) { if (tDir.toFile().exists()) {
@ -79,19 +76,19 @@ public class RulesManager {
} }
Utils.unzip(cacheFilePath.toString(), tDir.getParent().toString(), ""); Utils.unzip(cacheFilePath.toString(), tDir.getParent().toString(), "");
useCache = !Utils.debugCache; useCache = !Utils.debugCache;
} catch (Exception ex) { } catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
for (String rulesLine : ruleLines) { for (final String rulesLine : ruleLines) {
if (rulesLine.length() > 0) { if (rulesLine.length() > 0) {
String[] ruleDetails = rulesLine.split(",", 1); final String[] ruleDetails = rulesLine.split(",", 1);
String ruleName = ruleDetails[0]; final String ruleName = ruleDetails[0];
String ruleNameEscaped = ruleName.replace(".", "_"); final String ruleNameEscaped = ruleName.replace(".", "_");
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Evaluating /rules/" + ruleNameEscaped + ".java"); Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Evaluating /rules/" + ruleNameEscaped + ".java");
String pathWithoutExtension = "/rules/" + ruleNameEscaped; final String pathWithoutExtension = "/rules/" + ruleNameEscaped;
String scriptFile = pathWithoutExtension + ".java"; final String scriptFile = pathWithoutExtension + ".java";
InputStream resourcePath = Utils.getResourceStream(scriptFile); final InputStream resourcePath = Utils.getResourceStream(scriptFile);
if (resourcePath == null) { if (resourcePath == null) {
System.err.println(new FileNotFoundException("/rules/" + ruleName + ".java not found!")); System.err.println(new FileNotFoundException("/rules/" + ruleName + ".java not found!"));
} else { } else {
@ -103,7 +100,7 @@ public class RulesManager {
if (r != null) { if (r != null) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Loaded cached rule"); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Loaded cached rule");
} }
} catch (Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule!"); Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule!");
} }
@ -116,7 +113,7 @@ public class RulesManager {
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException e) { } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (r != null) { if (r != null) {
RulesManager.addRule(r); RulesManager.addRule(r);
@ -137,21 +134,21 @@ public class RulesManager {
System.exit(1); System.exit(1);
} }
} }
public static Rule compileJavaRule(String scriptFile, Path tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException { public static Rule compileJavaRule(String scriptFile, Path tDir) throws IOException, URISyntaxException,
InputStream resource = Utils.getResourceStream(scriptFile); InstantiationException, IllegalAccessException, ClassNotFoundException {
String text = Utils.read(resource); final InputStream resource = Utils.getResourceStream(scriptFile);
String[] textArray = text.split("\\n", 5); final String text = Utils.read(resource);
String javaClassDeclaration = textArray[2].substring(6); final String[] textArray = text.split("\\n", 5);
final String javaClassDeclaration = textArray[2].substring(6);
int extIndex = javaClassDeclaration.lastIndexOf('.'); int extIndex = javaClassDeclaration.lastIndexOf('.');
String javaClassNameOnly = javaClassDeclaration.substring(extIndex + 1, javaClassDeclaration.length()); final String javaClassNameOnly = javaClassDeclaration.substring(extIndex + 1, javaClassDeclaration.length());
String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassDeclaration).toString(); final String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassDeclaration).toString();
extIndex = javaClassNameAndPath.lastIndexOf('.'); extIndex = javaClassNameAndPath.lastIndexOf('.');
String javaCode = new StringBuilder("package ").append(javaClassNameAndPath.substring(0, extIndex >= 0 ? extIndex : javaClassNameAndPath.length())).append(";\n") final String javaCode = new StringBuilder("package ").append(javaClassNameAndPath.substring(0, extIndex >= 0 ? extIndex : javaClassNameAndPath.length())).append(";\n").append(textArray[4]).toString();
.append(textArray[4]).toString(); final Path tDirPath = tDir.resolve(javaClassNameAndPath.replace('.', File.separatorChar)).getParent();
Path tDirPath = tDir.resolve(javaClassNameAndPath.replace('.', File.separatorChar)).getParent(); final Path tFileJava = tDirPath.resolve(javaClassNameOnly + ".java");
Path tFileJava = tDirPath.resolve(javaClassNameOnly + ".java"); final Path tFileClass = tDirPath.resolve(javaClassNameOnly + ".class");
Path tFileClass = tDirPath.resolve(javaClassNameOnly + ".class");
if (!tDirPath.toFile().exists()) { if (!tDirPath.toFile().exists()) {
Files.createDirectories(tDirPath); Files.createDirectories(tDirPath);
} }
@ -159,7 +156,7 @@ public class RulesManager {
tFileJava.toFile().delete(); tFileJava.toFile().delete();
} }
Files.write(tFileJava, javaCode.getBytes("UTF-8"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); Files.write(tFileJava, javaCode.getBytes("UTF-8"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
boolean compiled = org.eclipse.jdt.internal.compiler.batch.Main.compile(new String[] {"-nowarn", "-1.8", tFileJava.toString()}, new PrintWriter(System.out), new PrintWriter(System.err), null); final boolean compiled = org.eclipse.jdt.internal.compiler.batch.Main.compile(new String[] { "-nowarn", "-1.8", tFileJava.toString() }, new PrintWriter(System.out), new PrintWriter(System.err), null);
if (Utils.debugCache) { if (Utils.debugCache) {
tFileJava.toFile().deleteOnExit(); tFileJava.toFile().deleteOnExit();
} else { } else {
@ -172,41 +169,43 @@ public class RulesManager {
throw new IOException("Can't build script file '" + scriptFile + "'"); throw new IOException("Can't build script file '" + scriptFile + "'");
} }
} }
public static Rule loadClassRuleFromSourceFile(String scriptFile, Path tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException { public static Rule loadClassRuleFromSourceFile(String scriptFile, Path tDir) throws IOException, URISyntaxException,
InputStream resource = Utils.getResourceStream(scriptFile); InstantiationException, IllegalAccessException, ClassNotFoundException {
String text = Utils.read(resource); final InputStream resource = Utils.getResourceStream(scriptFile);
String[] textArray = text.split("\\n", 5); final String text = Utils.read(resource);
String javaClassName = textArray[2].substring(6); final String[] textArray = text.split("\\n", 5);
String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassName).toString(); final String javaClassName = textArray[2].substring(6);
final String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassName).toString();
try { try {
return loadClassRuleDirectly(javaClassNameAndPath, tDir); return loadClassRuleDirectly(javaClassNameAndPath, tDir);
} catch (Exception ex) { } catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return null; return null;
} }
} }
public static Rule loadClassRuleDirectly(String javaClassNameAndPath, Path tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException { public static Rule loadClassRuleDirectly(String javaClassNameAndPath, Path tDir) throws IOException,
URLClassLoader cl = new URLClassLoader(new URL[] {tDir.toUri().toURL()}); URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
Class<?> aClass = cl.loadClass(javaClassNameAndPath); final URLClassLoader cl = new URLClassLoader(new URL[] { tDir.toUri().toURL() });
final Class<?> aClass = cl.loadClass(javaClassNameAndPath);
cl.close(); cl.close();
return (Rule) aClass.newInstance(); return (Rule) aClass.newInstance();
} }
public static void warmUp() throws Error, InterruptedException { public static void warmUp() throws Error, InterruptedException {
ObjectArrayList<Function> uselessResult = null; ObjectArrayList<Function> uselessResult = null;
boolean uselessVariable = false; boolean uselessVariable = false;
for (RuleType val : RuleType.values()) { for (final RuleType val : RuleType.values()) {
final ObjectArrayList<Rule> ruleList = rules[val.ordinal()]; final ObjectArrayList<Rule> ruleList = rules[val.ordinal()];
for (final Rule rule : ruleList) { for (final Rule rule : ruleList) {
String ruleName = "<null>"; String ruleName = "<null>";
try { try {
ruleName = rule.getRuleName(); ruleName = rule.getRuleName();
ObjectArrayList<Function> uselessResult2 = rule.execute(generateUselessExpression()); final ObjectArrayList<Function> uselessResult2 = rule.execute(generateUselessExpression());
uselessVariable = (uselessResult == null ? new ObjectArrayList<>() : uselessResult).equals(uselessResult2); uselessVariable = (uselessResult == null ? new ObjectArrayList<>() : uselessResult).equals(uselessResult2);
uselessResult = uselessResult2; uselessResult = uselessResult2;
} catch (Exception e) { } catch (final Exception e) {
if (uselessVariable || true) { if (uselessVariable || true) {
System.err.println("Exception thrown by rule '" + ruleName + "'!"); System.err.println("Exception thrown by rule '" + ruleName + "'!");
e.printStackTrace(); e.printStackTrace();
@ -220,14 +219,14 @@ public class RulesManager {
e.printStackTrace(); e.printStackTrace();
} }
} }
private static Function generateUselessExpression() { private static Function generateUselessExpression() {
MathContext mc = new MathContext(); final MathContext mc = new MathContext();
Function expr = new Expression(mc); Function expr = new Expression(mc);
expr = expr.setParameter(0, new Variable(mc, 'x', V_TYPE.VARIABLE)); expr = expr.setParameter(0, new Variable(mc, 'x', V_TYPE.VARIABLE));
return expr; return expr;
} }
public static void addRule(Rule rule) { public static void addRule(Rule rule) {
rules[rule.getRuleType().ordinal()].add(rule); rules[rule.getRuleType().ordinal()].add(rule);
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", rule.getRuleName(), "Loaded as " + rule.getRuleType() + " rule"); Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", rule.getRuleName(), "Loaded as " + rule.getRuleType() + " rule");

View File

@ -41,9 +41,9 @@ public class DivisionRule1 {
}*/ }*/
final int[] size = new int[] { elements[0].size(), elements[1].size() }; final int[] size = new int[] { elements[0].size(), elements[1].size() };
Function separatedDivision = new Division(root, elem1, elem2); final Function separatedDivision = new Division(root, elem1, elem2);
Function[] resultDivisionArray = new Function[2]; final Function[] resultDivisionArray = new Function[2];
Function prec; Function prec;
for (int part = 0; part < 2; part++) { for (int part = 0; part < 2; part++) {
prec = null; prec = null;
@ -76,7 +76,9 @@ public class DivisionRule1 {
final ObjectArrayList<Function> elementsNumerator = new ObjectArrayList<>(); final ObjectArrayList<Function> elementsNumerator = new ObjectArrayList<>();
Function numMult = division.getParameter1(); Function numMult = division.getParameter1();
while (numMult instanceof Multiplication) { while (numMult instanceof Multiplication) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
elementsNumerator.add(((Multiplication) numMult).getParameter1()); elementsNumerator.add(((Multiplication) numMult).getParameter1());
numMult = ((Multiplication) numMult).getParameter2(); numMult = ((Multiplication) numMult).getParameter2();
} }
@ -85,7 +87,9 @@ public class DivisionRule1 {
final ObjectArrayList<Function> elementsDenominator = new ObjectArrayList<>(); final ObjectArrayList<Function> elementsDenominator = new ObjectArrayList<>();
Function denomMult = division.getParameter2(); Function denomMult = division.getParameter2();
while (denomMult instanceof Multiplication) { while (denomMult instanceof Multiplication) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
elementsDenominator.add(((Multiplication) denomMult).getParameter1()); elementsDenominator.add(((Multiplication) denomMult).getParameter1());
denomMult = ((Multiplication) denomMult).getParameter2(); denomMult = ((Multiplication) denomMult).getParameter2();
} }
@ -94,7 +98,8 @@ public class DivisionRule1 {
return new ObjectArrayList[] { elementsNumerator, elementsDenominator }; return new ObjectArrayList[] { elementsNumerator, elementsDenominator };
} }
private static int[] getFirstWorkingDivisionCouple(ObjectArrayList<Function>[] elements) throws InterruptedException { private static int[] getFirstWorkingDivisionCouple(ObjectArrayList<Function>[] elements)
throws InterruptedException {
return null; return null;
//TODO: //TODO:
// final int[] size = new int[] { elements[0].size(), elements[1].size() }; // final int[] size = new int[] { elements[0].size(), elements[1].size() };

View File

@ -30,7 +30,9 @@ public class MultiplicationMethod1 {
final int size = elements.size(); final int size = elements.size();
Function prec = new Multiplication(root, elem1, elem2); Function prec = new Multiplication(root, elem1, elem2);
for (int i = size - 1; i >= 0; i--) { for (int i = size - 1; i >= 0; i--) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
if (i != workingElementCouple[0] & i != workingElementCouple[1]) { if (i != workingElementCouple[0] & i != workingElementCouple[1]) {
final Function a = prec; final Function a = prec;
final Function b = elements.get(i); final Function b = elements.get(i);
@ -48,7 +50,9 @@ public class MultiplicationMethod1 {
private static ObjectArrayList<Function> getMultiplicationElements(Function mult) throws InterruptedException { private static ObjectArrayList<Function> getMultiplicationElements(Function mult) throws InterruptedException {
final ObjectArrayList<Function> elements = new ObjectArrayList<>(); final ObjectArrayList<Function> elements = new ObjectArrayList<>();
while (mult instanceof Multiplication) { while (mult instanceof Multiplication) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
elements.add(((Multiplication) mult).getParameter1()); elements.add(((Multiplication) mult).getParameter1());
mult = ((Multiplication) mult).getParameter2(); mult = ((Multiplication) mult).getParameter2();
} }
@ -56,7 +60,8 @@ public class MultiplicationMethod1 {
return elements; return elements;
} }
private static int[] getFirstWorkingMultiplicationCouple(ObjectArrayList<Function> elements) throws InterruptedException { private static int[] getFirstWorkingMultiplicationCouple(ObjectArrayList<Function> elements)
throws InterruptedException {
return null; return null;
// TODO: // TODO:
// final int size = elements.size(); // final int size = elements.size();

View File

@ -41,7 +41,9 @@ public class SumMethod1 {
Function prec = new Sum(root, elem1, elem2); Function prec = new Sum(root, elem1, elem2);
for (int i = size - 1; i >= 0; i--) { for (int i = size - 1; i >= 0; i--) {
if (i != workingElementCouple[0] & i != workingElementCouple[1]) { if (i != workingElementCouple[0] & i != workingElementCouple[1]) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
final Function a = prec; final Function a = prec;
final Function b = elements.get(i); final Function b = elements.get(i);
if (b instanceof Negative) { if (b instanceof Negative) {
@ -67,7 +69,9 @@ public class SumMethod1 {
final MathContext root = sum.getMathContext(); final MathContext root = sum.getMathContext();
final ObjectArrayList<Function> elements = new ObjectArrayList<>(); final ObjectArrayList<Function> elements = new ObjectArrayList<>();
while (sum instanceof Sum || sum instanceof Subtraction) { while (sum instanceof Sum || sum instanceof Subtraction) {
if (Thread.interrupted()) throw new InterruptedException(); if (Thread.interrupted()) {
throw new InterruptedException();
}
if (sum instanceof Sum) { if (sum instanceof Sum) {
elements.add(((FunctionOperator) sum).getParameter2()); elements.add(((FunctionOperator) sum).getParameter2());
} else { } else {
@ -79,7 +83,8 @@ public class SumMethod1 {
return elements; return elements;
} }
private static int[] getFirstWorkingSumCouple(MathContext root, ObjectArrayList<Function> elements) throws InterruptedException { private static int[] getFirstWorkingSumCouple(MathContext root, ObjectArrayList<Function> elements)
throws InterruptedException {
return null; return null;
// final int size = elements.size(); // final int size = elements.size();
// Function a; // Function a;

View File

@ -14,34 +14,33 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException; import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class MathSolver { public class MathSolver {
private final Function initialFunction; private final Function initialFunction;
private AtomicInteger stepState = new AtomicInteger(0); private final AtomicInteger stepState = new AtomicInteger(0);
private int stepStateRepetitions = 0; private int stepStateRepetitions = 0;
private int consecutiveNullSteps = 0; private int consecutiveNullSteps = 0;
private enum StepState { private enum StepState {
_1_CALCULATION, _1_CALCULATION, _2_EXPANSION, _3_CALCULATION, _4_REDUCTION
_2_EXPANSION,
_3_CALCULATION,
_4_REDUCTION
} }
private final StepState[] stepStates = StepState.values(); private final StepState[] stepStates = StepState.values();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private final ObjectArrayList<Function>[][] lastFunctions = new ObjectArrayList[2][stepStates.length]; private final ObjectArrayList<Function>[][] lastFunctions = new ObjectArrayList[2][stepStates.length];
public MathSolver(Function initialFunction) { public MathSolver(Function initialFunction) {
this.initialFunction = initialFunction; this.initialFunction = initialFunction;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public ObjectArrayList<ObjectArrayList<Function>> solveAllSteps() throws InterruptedException, Error { public ObjectArrayList<ObjectArrayList<Function>> solveAllSteps() throws InterruptedException, Error {
ObjectArrayList<ObjectArrayList<Function>> steps = new ObjectArrayList<>(); final ObjectArrayList<ObjectArrayList<Function>> steps = new ObjectArrayList<>();
ObjectArrayList<Function> lastFnc = null, currFnc = new ObjectArrayList<>(); ObjectArrayList<Function> lastFnc = null, currFnc = new ObjectArrayList<>();
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Solving all steps. Input: " + initialFunction.toString()); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Solving all steps. Input: " + initialFunction.toString());
currFnc.add(initialFunction); currFnc.add(initialFunction);
long stepNumber = 0; long stepNumber = 0;
int initStepState = 0, endStepState = 0; int initStepState = 0, endStepState = 0;
AtomicInteger stepState = new AtomicInteger(0); final AtomicInteger stepState = new AtomicInteger(0);
do { do {
lastFunctions[1] = lastFunctions[0]; lastFunctions[1] = lastFunctions[0];
lastFunctions[0] = new ObjectArrayList[stepStates.length]; lastFunctions[0] = new ObjectArrayList[stepStates.length];
@ -52,9 +51,9 @@ public class MathSolver {
lastFnc = currFnc; lastFnc = currFnc;
initStepState = stepState.get(); initStepState = stepState.get();
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Starting step " + stepStates[initStepState] + ". Input: " + currFnc); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Starting step " + stepStates[initStepState] + ". Input: " + currFnc);
ObjectArrayList<Function> stepResult = solveStep(lastFnc, stepState); final ObjectArrayList<Function> stepResult = solveStep(lastFnc, stepState);
if (stepResult != null) { if (stepResult != null) {
for (Function result : stepResult) { for (final Function result : stepResult) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, result.toString()); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, result.toString());
} }
currFnc = stepResult; currFnc = stepResult;
@ -72,7 +71,7 @@ public class MathSolver {
if (StaticVars.debugOn) { if (StaticVars.debugOn) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, currFnc + " is " + (checkEquals(currFnc, lastFunctions[1][endStepState]) ? "" : "not ") + "equals to [1]:" + lastFunctions[1][endStepState]); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, currFnc + " is " + (checkEquals(currFnc, lastFunctions[1][endStepState]) ? "" : "not ") + "equals to [1]:" + lastFunctions[1][endStepState]);
} }
} while(consecutiveNullSteps < stepStates.length && !checkEquals(currFnc, lastFunctions[0][endStepState]) && !checkEquals(currFnc, lastFunctions[1][endStepState])); } while (consecutiveNullSteps < stepStates.length && !checkEquals(currFnc, lastFunctions[0][endStepState]) && !checkEquals(currFnc, lastFunctions[1][endStepState]));
if (consecutiveNullSteps >= stepStates.length) { if (consecutiveNullSteps >= stepStates.length) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Loop ended because " + consecutiveNullSteps + " >= " + stepStates.length); Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Loop ended because " + consecutiveNullSteps + " >= " + stepStates.length);
} else if (checkEquals(currFnc, lastFunctions[0][endStepState])) { } else if (checkEquals(currFnc, lastFunctions[0][endStepState])) {
@ -105,14 +104,15 @@ public class MathSolver {
private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs) throws InterruptedException, Error { private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs) throws InterruptedException, Error {
return solveStep(fncs, stepState); return solveStep(fncs, stepState);
} }
private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs, AtomicInteger stepState) throws InterruptedException, Error { private ObjectArrayList<Function> solveStep(ObjectArrayList<Function> fncs, AtomicInteger stepState)
ObjectArrayList<Function> processedFncs = applyRules(fncs, RuleType.EXISTENCE); // Apply existence rules before everything throws InterruptedException, Error {
final ObjectArrayList<Function> processedFncs = applyRules(fncs, RuleType.EXISTENCE); // Apply existence rules before everything
if (processedFncs != null) { if (processedFncs != null) {
fncs = processedFncs; fncs = processedFncs;
} }
RuleType currentAcceptedRules; RuleType currentAcceptedRules;
switch(stepStates[stepState.get()]) { switch (stepStates[stepState.get()]) {
case _1_CALCULATION: { case _1_CALCULATION: {
currentAcceptedRules = RuleType.CALCULATION; currentAcceptedRules = RuleType.CALCULATION;
break; break;
@ -133,8 +133,8 @@ public class MathSolver {
System.err.println("Unknown Step State"); System.err.println("Unknown Step State");
throw new NotImplementedException(); throw new NotImplementedException();
} }
ObjectArrayList<Function> results = applyRules(fncs, currentAcceptedRules); final ObjectArrayList<Function> results = applyRules(fncs, currentAcceptedRules);
switch(stepStates[stepState.get()]) { switch (stepStates[stepState.get()]) {
case _1_CALCULATION: { case _1_CALCULATION: {
if (results == null) { if (results == null) {
stepState.incrementAndGet(); stepState.incrementAndGet();
@ -195,17 +195,20 @@ public class MathSolver {
} }
return null; return null;
} }
private ObjectArrayList<Function> applyRules(ObjectArrayList<Function> fncs, RuleType currentAcceptedRules) throws InterruptedException, Error { private ObjectArrayList<Function> applyRules(ObjectArrayList<Function> fncs, RuleType currentAcceptedRules)
ObjectArrayList<Rule> rules = initialFunction.getMathContext().getAcceptableRules(currentAcceptedRules); throws InterruptedException, Error {
final ObjectArrayList<Rule> rules = initialFunction.getMathContext().getAcceptableRules(currentAcceptedRules);
ObjectArrayList<Function> results = null; ObjectArrayList<Function> results = null;
Rule appliedRule = null; Rule appliedRule = null;
out: { out: {
for (Function fnc : fncs) { for (final Function fnc : fncs) {
for (Rule rule : rules) { for (final Rule rule : rules) {
List<Function> ruleResults = fnc.simplify(rule); final List<Function> ruleResults = fnc.simplify(rule);
if (ruleResults != null && !ruleResults.isEmpty()) { if (ruleResults != null && !ruleResults.isEmpty()) {
if (results == null) results = new ObjectArrayList<Function>(); if (results == null) {
results = new ObjectArrayList<>();
}
results.addAll(ruleResults); results.addAll(ruleResults);
appliedRule = rule; appliedRule = rule;
break; break;