diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b82e452 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +applet/ +application.*/ +*.zip +*.tmproj +support/*.class +support/prelude/*.class +support/prelude/*.jar +support/windows/*.class diff --git a/BinaryThing.pde b/BinaryThing.pde new file mode 100644 index 0000000..400e52f --- /dev/null +++ b/BinaryThing.pde @@ -0,0 +1,455 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.lang.reflect.Array; +import java.nio.Buffer; +import java.nio.IntBuffer; +import java.nio.FloatBuffer; + +static class BinaryThing { + + static final Class supportedTypes[] = { Integer.TYPE, Float.TYPE, SparseMatrix.class }; + + Class type = null; + int size[] = null; + Object blob = null; + + BinaryThing() {} + BinaryThing(Object blob) { setBlob(blob); } + + Class getType() { return type; } + int[] getSize() { return size; } + int getSize(int i) { return ((size != null) && (i >= 0) && (i < size.length)) ? size[i] : 0; } + boolean is(Class t, int s[]) { return (blob != null) && (type == t) && Arrays.equals(size, s); } + boolean isInt2(int NN) { return is(Integer.TYPE, new int[] { NN, NN }); } + boolean isFloat1(int NN) { return is(Float.TYPE, new int[] { 1, NN }); } + boolean isFloat2(int NN) { return is(Float.TYPE, new int[] { NN, NN }); } + boolean isSparse(int NN) { return (type == SparseMatrix.class) && (getSparseMatrix().N == NN); } + + Object getBlob() { return blob; } + int[][] getIntArray() { return (blob != null) && (type == Integer.TYPE) && (size.length == 2) ? (int[][])blob : null; } + float[][] getFloatArray() { return (blob != null) && (type == Float.TYPE) && (size.length == 2) ? (float[][])blob : null; } + SparseMatrix getSparseMatrix() { return (blob instanceof SparseMatrix) ? (SparseMatrix)blob : null; } + + void setBlob(Object blob) { + this.type = null; + this.size = null; + this.blob = blob; + if (blob == null) return; + type = blob.getClass(); + size = new int[0]; + while (type.isArray()) { + type = type.getComponentType(); + size = append(size, (blob == null) ? 0 : Array.getLength(blob)); + blob = (Array.getLength(blob) > 0) ? Array.get(blob, 0) : null; // we've saved the original blob to this.blob already + // FIXME: bad things would happen if the sub-arrays are not all of the same length, but I am too lazy to check here... + } + } + + static BinaryThing parseFromXML(XMLElement xml) throws Exception { return parseFromXML(xml, null); } + static BinaryThing parseFromXML(XMLElement xml, TConsole.Message msg) throws Exception { + if (xml == null) return null; + BinaryThing res = new BinaryThing(); + res.type = null; res.size = null; res.blob = null; + XMLElement tmp[] = null; // will hold the slice/values/source children + XMLElement xmlp = xml; // the first non-snapshot ancestor + while (xmlp.getName().equals("snapshot")) + if ((xmlp = xmlp.getParent()) == null) + throw new Exception("choked on orphaned snapshot"); + // determine type + if (xmlp.getName().equals("slices")) { + res.type = Integer.TYPE; + tmp = xml.getChildren("slice"); + } else if (xmlp.getName().equals("data")) { + res.type = Float.TYPE; + tmp = xml.getChildren("values"); + } else if (xmlp.getName().equals("links")) { + res.type = SparseMatrix.class; + tmp = xml.getChildren("source"); + } else + throw new Exception("unsupported XML element \u2018" + xmlp.getName() + "\u2019"); + if (((tmp == null) || (tmp.length == 0)) && (res.type != SparseMatrix.class)) + throw new Exception("no values found"); + // determine size and create blob + int N = tmp.length, NN = 0; + if (res.type == SparseMatrix.class) { + N = xml.getInt("size"); + for (int i = 0; i < tmp.length; i++) { + N = max(N, tmp[i].getInt("index")); + XMLElement tmp2[] = tmp[i].getChildren("target"); + for (int j = 0; j < tmp2.length; j++) + N = max(N, tmp2[j].getInt("index", 0)); + if (msg != null) msg.updateProgress(i, 2*N); + } + res.blob = new SparseMatrix(N); + } else { + if (tmp[0].getContent() == null) + throw new Exception("no values in first " + tmp[0].getName() + " element"); + NN = splitTokens(trim(tmp[0].getContent())).length; + if (!((N == NN) || (N == 1))) + throw new Exception("wrong number of " + tmp[0].getName() + " elements"); + res.size = new int[] { N, NN }; + res.blob = Array.newInstance(res.type, res.size); + } + // parse values + boolean filled[] = new boolean[N]; // track which indices have been filled already + String indexAttr = (res.type == SparseMatrix.class) ? "index" : "root"; + for (int i = 0; i < N; i++) { + String inElemStr = " in " + tmp[i].getName() + " element " + (i+1); + int ii = (N == 1) ? 0 : tmp[i].getInt(indexAttr, 0) - 1; + if ((ii < 0) || (ii >= N)) + throw new Exception("invalid " + indexAttr + " " + tmp[i].getString(indexAttr) + inElemStr); + if (filled[ii]) + throw new Exception("duplicate " + indexAttr + " value" + inElemStr); + if (res.type == SparseMatrix.class) { + SparseMatrix matrix = (SparseMatrix)res.blob; + XMLElement tmp2[] = tmp[i].getChildren("target"); + matrix.index[ii] = new int[tmp2.length]; + matrix.value[ii] = new float[tmp2.length]; + boolean filled2[] = new boolean[N]; + for (int j = 0; j < tmp2.length; j++) { + String inElemStr2 = inElemStr + ", " + tmp2[j].getName() + " " + (j+1); + int jj = matrix.index[ii][j] = tmp2[j].getInt("index", 0) - 1; + if ((jj < 0) || (jj >= N)) + throw new Exception("invalid index " + tmp2[j].getString("index") + inElemStr2); + if (filled2[jj]) + throw new Exception("duplicate index value" + inElemStr2); + if (Float.isNaN(matrix.value[ii][j] = tmp2[j].getFloat("weight", Float.NaN))) + throw new Exception("invalid weight value " + tmp[j].getString("weight") + inElemStr2); + } + if (msg != null) msg.updateProgress(i + N, 2*N); + } else { + if (tmp[i].getContent() == null) + throw new Exception("no values" + inElemStr); + Object row = parseLine(tmp[i].getContent(), ' ', res.type); + if (Array.getLength(row) != NN) + throw new Exception("wrong number of values" + inElemStr); + Array.set(res.blob, ii, row); + if (msg != null) msg.updateProgress(i, N); + } + } + // post-process if necessary + if (xml.getName().equals("slices")) { + int pred[][] = (int[][])res.blob; + for (int r = 0; r < NN; r++) + for (int i = 0; i < NN; i++) + pred[r][i]--; // indices are 1-based in XML, but 0-based in binary + } + return res; + } + + static BinaryThing parseFromText(String lines[], char sep) throws Exception { + return parseFromText(lines, sep, Float.TYPE, null); } + static BinaryThing parseFromText(String lines[], char sep, TConsole.Message msg) throws Exception { + return parseFromText(lines, sep, Float.TYPE, msg); } + static BinaryThing parseFromText(String lines[], char sep, Class type) throws Exception { + return parseFromText(lines, sep, type, null); } + static BinaryThing parseFromText(String lines[], char sep, Class type, TConsole.Message msg) throws Exception { + if (type == SparseMatrix.class) + return parseSparseFromText(lines, sep, msg); + if ((lines == null) || (lines.length == 0) || + (lines[0] == null) || (Array.getLength(parseLine(lines[0], sep, type)) == 0)) + throw new Exception("no data to parse"); + BinaryThing res = new BinaryThing(); + res.type = type; + res.size = new int[] { lines.length, Array.getLength(parseLine(lines[0], sep, type)) }; + res.blob = Array.newInstance(res.type, res.size); + int i = -1; + try { + for (i = 0; i < res.size[0]; i++) { + Object row = parseLine(lines[i], sep, res.type); + if (Array.getLength(row) != res.size[1]) throw new Exception("wrong number of elements"); + Array.set(res.blob, i, row); + if (msg != null) msg.updateProgress(i, res.size[0]); + } + } catch (Exception e) { throw new Exception("line " + (i+1) + ": " + e.getMessage()); } + return res; + } + + static private Object parseLine(String line, char sep, Class type) throws Exception { + String pieces[] = (sep == ' ') ? splitTokens(trim(line), WHITESPACE) : split(line, sep); + Object result = Array.newInstance(type, new int[] { pieces.length }); + int i = -1; + try { + for (i = 0; i < pieces.length; i++) + if (type == Integer.TYPE) Array.set(result, i, Integer.valueOf(pieces[i]).intValue()); + else Array.set(result, i, Float.valueOf(pieces[i]).floatValue()); + } catch (Exception e) { throw new Exception("not a number: " + pieces[i]); } + return result; + } + + static private BinaryThing parseSparseFromText(String lines[], char sep, TConsole.Message msg) throws Exception { + if ((lines == null) || (lines.length % 2 != 0)) + throw new Exception("no data or odd number of lines"); + SparseMatrix matrix = new SparseMatrix(lines.length/2); + int i = -1; + try { + for (i = 0; i < lines.length/2; i++) { + matrix.index[i] = (int[])parseLine(lines[2*i+0], sep, Integer.TYPE); + for (int j = 0; j < matrix.index[i].length; j++) + if (--matrix.index[i][j] < 0) // indices are 1-based in text files + throw new Exception("invalid index: " + (matrix.index[i][j]+1)); + matrix.value[i] = (float[])parseLine(lines[2*i+1], sep, Float.TYPE); + if (matrix.index[i].length != matrix.value[i].length) + throw new Exception("index/value length mismatch"); + } + } catch (Exception e) { throw new Exception("row " + (i+1) + ": " + e.getMessage()); } + return new BinaryThing(matrix); + } + + static BinaryThing loadFromStream(DataInputStream in) throws Exception { return loadFromStream(in, null); } + static BinaryThing loadFromStream(DataInputStream in, TConsole.Message msg) throws Exception { + BinaryThing res = new BinaryThing(); + res.blob = null; res.type = null; res.size = null; + // read type + int tmp = in.readInt(); + if ((tmp < 0) || (tmp >= supportedTypes.length)) + throw new Exception("unknown data type"); + res.type = supportedTypes[tmp]; + // read array size + if (res.type == SparseMatrix.class) + res.blob = new SparseMatrix(in.readInt()); + else { + res.size = new int[0]; + while ((tmp = in.readInt()) != -1) + res.size = append(res.size, tmp); + } + // read data + if (res.type == SparseMatrix.class) { + SparseMatrix matrix = res.getSparseMatrix(); + for (int i = 0; i < matrix.N; i++) { + int M = in.readInt(); + matrix.index[i] = (int[])loadFromStream(in, new int[M]); + matrix.value[i] = (float[])loadFromStream(in, new float[M]); + if (msg != null) msg.updateProgress(i, matrix.N); + } + } else { + res.blob = Array.newInstance(res.type, res.size); + for (int i = 0; i < res.size[0]; i++) { + Array.set(res.blob, i, loadFromStream(in, Array.get(res.blob, i))); + if (msg != null) msg.updateProgress(i, res.size[0]); + } + } + return res; + } + static private Object loadFromStream(DataInputStream in, Object o) throws Exception { + // read single value if o is not an array + if (!o.getClass().isArray()) { + if (o.getClass().getComponentType() == Integer.TYPE) return in.readInt(); + if (o.getClass().getComponentType() == Float.TYPE) return in.readFloat(); + return null; + } + // fill 1-D array with values from stream + Class type = o.getClass().getComponentType(); + if (!type.isArray()) { + byte bytes[] = new byte[4*Array.getLength(o)]; + ByteBuffer bbuf = ByteBuffer.wrap(bytes); + int off = 0, n; + while (off < bytes.length) + if ((n = in.read(bytes, off, bytes.length - off)) == -1) + throw new IOException("unexpected end-of-file"); + else off += n; + if (type == Integer.TYPE) bbuf.asIntBuffer().get((int[])o); + else if (type == Float.TYPE) bbuf.asFloatBuffer().get((float[])o); + return o; + } + // recursively fill multi-dim array + for (int i = 0; i < Array.getLength(o); i++) + Array.set(o, i, loadFromStream(in, Array.get(o, i))); + return o; + } + + void saveToStream(DataOutputStream out) throws Exception { saveToStream(out, null); } + void saveToStream(DataOutputStream out, TConsole.Message msg) throws Exception { + if ((type == null) || (blob == null)) return; + // write type + int typeID = -1; + for (int i = 0; i < supportedTypes.length; i++) + if (type == supportedTypes[i]) + typeID = i; + if (typeID == -1) + throw new Exception("unsupported data type"); + out.writeInt(typeID); + // write size + if (blob instanceof SparseMatrix) + out.writeInt(getSparseMatrix().N); + else { + for (int i = 0; i < size.length; i++) + out.writeInt(size[i]); + out.writeInt(-1); // array size terminator + } + // write data + if (blob instanceof SparseMatrix) { + SparseMatrix matrix = getSparseMatrix(); + for (int i = 0; i < matrix.N; i++) { + if (matrix.index[i].length != matrix.value[i].length) + throw new Exception("index/value length mismatch at row " + (i+1)); + out.writeInt(matrix.index[i].length); + saveToStream(out, matrix.index[i]); + saveToStream(out, matrix.value[i]); + if (msg != null) msg.updateProgress(i, matrix.N); + } + } else { + for (int i = 0; i < size[0]; i++) { + saveToStream(out, Array.get(blob, i)); + if (msg != null) msg.updateProgress(i, size[0]); + } + } + } + private void saveToStream(DataOutputStream out, Object o) throws Exception { + Class type = null; + if (!(type = o.getClass()).isArray()) { // write single value + if (type == Integer.TYPE) out.writeInt(((Integer)o).intValue()); + else if (type == Float.TYPE) out.writeFloat(((Float)o).floatValue()); + } else if (!(type = o.getClass().getComponentType()).isArray()) { // write 1-D array + byte bytes[] = new byte[4*Array.getLength(o)]; + ByteBuffer bbuf = ByteBuffer.wrap(bytes); + Buffer buf = (type == Integer.TYPE) ? bbuf.asIntBuffer() : + (type == Float.TYPE) ? bbuf.asFloatBuffer() : null; + if (type == Integer.TYPE) ((IntBuffer)buf).put((int[])o); + else if (type == Float.TYPE) ((FloatBuffer)buf).put((float[])o); + out.write(bytes, 0, bytes.length); + } else { // recursively write multi-dim array + for (int i = 0; i < Array.getLength(o); i++) + saveToStream(out, Array.get(o, i)); + } + } + + /* If size.length == 2, this will replace the blob with a new array of size { size[1] size[0] }, + * such that newblob[i][j] == oldblob[j][i]. If size.length != 2, nothing happens. FIXME: throw exception? */ + void transpose() { + if ((type == null) || (blob == null)) return; + if (blob instanceof SparseMatrix) { + BinaryThing bt = new BinaryThing(((SparseMatrix)blob).getFullMatrix()); + bt.transpose(); + blob = new SparseMatrix(bt.getFloatArray()); + } else { + if ((size == null) || (size.length != 2)) return; + Object oldblob = blob; + size = new int[] { size[1], size[0] }; + blob = Array.newInstance(type, size); + for (int i = 0; i < size[0]; i++) + for (int j = 0; j < size[1]; j++) + Array.set(Array.get(blob, i), j, + Array.get(Array.get(oldblob, j), i)); + } + } + + /* Reshapes the current data to fit the new size if prod(newsize) == prod(size). It does so by + * reshaping into a linear array and then into the new format. Linearization/delinearization is + * row-first; i.e. the last dimension will be filled up first. */ + void reshape(int newsize[]) { + if ((type == null) || (size == null) || (newsize == null) || (size.length*newsize.length == 0)) return; + int prodsize = 1; for (int i = 0; i < size.length; i++) prodsize *= size[i]; + int prodnewsize = 1; for (int i = 0; i < newsize.length; i++) prodnewsize *= newsize[i]; + if (prodsize != prodnewsize) return; + // reshape into linear blob + Object linear = Array.newInstance(type, new int[] { (int)prodsize }); + linearize(blob, linear); + // create new blob and delinearize + blob = Array.newInstance(type, size = newsize); + delinearize(linear, blob); + } + + private void linearize(Object src, Object dst) { linearize(src, dst, 0, 0, Array.getLength(dst)); } + private void linearize(Object src, Object dst, int dim, int offset, int prodsize) { + prodsize /= size[dim]; + for (int i = 0; i < Array.getLength(src); i++) + if (dim == size.length-1) Array.set(dst, offset + i, Array.get(src, i)); + else linearize(Array.get(src, i), dst, dim+1, offset + i*prodsize, prodsize); + } + + private void delinearize(Object src, Object dst) { delinearize(src, dst, 0, 0, Array.getLength(src)); } + private void delinearize(Object src, Object dst, int dim, int offset, int prodsize) { + prodsize /= size[dim]; + for (int i = 0; i < Array.getLength(dst); i++) + if (dim == size.length-1) Array.set(dst, i, Array.get(src, offset + i)); + else delinearize(src, Array.get(dst, i), dim+1, offset + i*prodsize, prodsize); + } + + String toString() { + if ((type == null) || (blob == null)) + return "null"; + if (blob instanceof SparseMatrix) + return "SparseMatrix(" + getSparseMatrix().N + ")"; + String res = type.getName(); + if (size != null) + for (int i = 0; i < size.length; i++) + res += "[" + size[i] + "]"; + return res; + } + +} + +static class SparseMatrix { + int N; // FIXME: should this be generalized to hold non-square sparse matrices as well? + int index[][]; + float value[][]; + + SparseMatrix(int N) { + this.N = N; + index = new int[N][]; value = new float[N][]; + for (int i = 0; i < N; i++) { index[i] = new int[0]; value[i] = new float[0]; } + } + + SparseMatrix(float data[][]) { + this(data.length); + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if (data[i][j] == 0) continue; + index[i] = (int[])append(index[i], j); + value[i] = (float[])append(value[i], data[i][j]); + } + } + } + + SparseMatrix(int N, int ii[], int jj[]) { this(N, ii, jj, null); } + SparseMatrix(int N, int ii[], int jj[], float val[]) { + this(N); + for (int l = 0; l < ii.length; l++) { + index[ii[l]] = (int[])append(index[ii[l]], jj[l]); + value[ii[l]] = (float[])append(value[ii[l]], (val != null) ? val[l] : 1f); + } + } + + SparseMatrix(int ii[], int jj[]) { this(ii, jj, null); } + SparseMatrix(int ii[], int jj[], float val[]) { + N = 0; + for (int l = 0; l < ii.length; l++) + N = max(N, max(ii[l], jj[l]) + 1); + index = new int[N][]; value = new float[N][]; + for (int i = 0; i < N; i++) { + index[i] = new int[0]; + value[i] = new float[0]; + } + for (int l = 0; l < ii.length; l++) { + index[ii[l]] = (int[])append(index[ii[l]], jj[l]); + value[ii[l]] = (float[])append(value[ii[l]], (val != null) ? val[l] : 1f); + } + } + + float[][] getFullMatrix() { + float result[][] = (float[][])Array.newInstance(Float.TYPE, new int[] { N, N }); + for (int i = 0; i < N; i++) + for (int j = 0; j < index[i].length; j++) + result[i][index[i][j]] = value[i][j]; + return result; + } +} \ No newline at end of file diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/CSVParser.pde b/CSVParser.pde new file mode 100644 index 0000000..96d7ff4 --- /dev/null +++ b/CSVParser.pde @@ -0,0 +1,68 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +public class CSVParser { + // ATTN: does not support line breaks in enclosed fields + + protected String lines[] = null; + + public static final char WHITESPACE = 0; + protected char delim = ','; // field deliminator + protected char enclose = '"'; // (optional) field enclosing char + protected char escape = '\\'; // escape char for enclose char + protected char decim = '.'; // decimal point + + public CSVParser(String lines[]) { this.lines = lines; } + + public String[][] getFields() { return getFields(delim, enclose, escape); } + + public String[][] getFields(char delim, char enclose, char escape) { + String fields[][] = new String[lines.length][]; + for (int i = 0; i < lines.length; i++) + fields[i] = parseRecord(lines[i]).toArray(new String[0]); + return fields; + } + + protected Vector parseRecord(String record) { return parseRecord(record, delim, enclose, escape); } + + protected Vector parseRecord(String record, char delim, char enclose, char escape) { + Vector fields = new Vector(); // return value + String currentField = ""; // current field + boolean enclosed = false; + boolean escaped = false; + for (int i = 0; i < record.length(); i++) { + char c = record.charAt(i); + if (((delim == WHITESPACE) ? Character.isWhitespace(c) : (c == delim)) && !enclosed) { + fields.add(currentField); + currentField = ""; + } else if ((c == escape) && (i < record.length() - 1) && (record.charAt(i+1) == enclose)) { + escaped = true; + } else if ((c == enclose) && !escaped) { + enclosed = !enclosed; + } else { + currentField += c; + escaped = false; + } + } + fields.add(currentField); + return fields; + } + +} \ No newline at end of file diff --git a/Colormap.pde b/Colormap.pde new file mode 100644 index 0000000..cce8edf --- /dev/null +++ b/Colormap.pde @@ -0,0 +1,145 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +// FIXME: This should be refactored such that different colormaps are different subclasses of Colormap + +class Colormap { + XMLElement xml = null; + int NDC = 20; // number of colors in "discrete" + int colormap = 0; + boolean logscale = false; + float minval = 0, maxval = 1; + + String colormaps[] = { "default", "jet", "bluered", "grayredblue", "thresholded", "discrete" }; + + Colormap() { this(null); } + Colormap(XMLElement xml) { this(xml, 0, 1); } + Colormap(XMLElement xml, float defaultMin, float defaultMax) { + this(xml == null ? "default" : xml.getString("name", "default"), + xml == null ? false : xml.getBoolean("log"), + xml == null ? defaultMin : xml.getFloat("minval", defaultMin), + xml == null ? defaultMax : xml.getFloat("maxval", defaultMax)); + this.xml = xml; + } + Colormap(String cm, boolean log) { this(cm, log, 0, 1); } + Colormap(String cm, boolean log, float minval, float maxval) { + setColormap(cm); logscale = log; setBounds(minval, maxval); } + + String getColormapName() { return colormaps[colormap]; } + void setColormap(String cm) { + for (int i = 0; i < colormaps.length; i++) + if (colormaps[i].equals(cm)) + colormap = i; + if (xml != null) + xml.setString("name", colormaps[colormap]); + } + + boolean isLogscale() { return logscale; } + void setLogscale(boolean log) { logscale = log; if (xml != null) xml.setBoolean("log", log); } + + float getMinVal() { return minval; } + float getMaxVal() { return maxval; } + void setMinVal(float minval) { this.minval = minval; if (xml != null) xml.setFloat("minval", minval); } + void setMaxVal(float maxval) { this.maxval = maxval; if (xml != null) xml.setFloat("maxval", maxval); } + void setBounds(float minval, float maxval) { setMinVal(minval); setMaxVal(maxval); } + + color getColor(float val) { return getColor(val, minval, maxval); } + color getColor(float val, float minval, float maxval) { + val = constrain(val, minval, maxval); + // discrete + if (colormap == 5) return getColorDiscrete((int)val); + // apply log() if requested + if (logscale) { val = log(val); minval = minval > 0 ? log(minval) : Float.NaN; maxval = log(maxval); } + // thresholded + if (colormap == 4) return getColorDiscrete((int)(val/(maxval/float(NDC)))); + // continuous colormaps + float v = Float.isNaN(minval) ? val/maxval : (val - minval)/(maxval - minval); + if (Float.isNaN(v)) return color(0); + // blue to red colormap + if (colormap == 2) return color(255*v, 0, 255*(1-v)); + // gray to red to blue colormap + if (colormap == 3) { + if (v < 0.5) return color(127 + 127*v/0.5, 127 - 127*v/0.5, 127 - 127*v/0.5); // gray to red + return color(255 - 255*(v - 0.5)/0.5, 0, 255*(v - 0.5)/0.5); // red to blue + } + // jet colormap + if (colormap == 1) { + if (v < .125) return color(0, 0, 128 + 127*v/.125); + if (v < .375) return color(0, 255*(v-.125)/.250, 255); + if (v < .625) return color(255*(v-.375)/.250, 255, 255*(1 - (v-.375)/.250)); + if (v < .875) return color(255, 255*(1 - (v-.625)/.250), 0); + return color(255 - 127*(v-.875)/.125, 0, 0); + } + // return color from default colormap + if (v < .25) return color(255, 255*4*v, 0); + if (v < .5) return color(255*(1 - 4*(v-.25)), 255, 0); + if (v < .75) return color(0, 255, 255*4*(v-.5)); + return color(0, 255*(1 - 4*(v-.75)), 255); + } + + color getColorDiscrete(int v) { + switch ((v-1) % 20) { + case 2: return color(255, 0, 0); + case 1: return color(191, 191, 0); + case 0: return color( 0, 191, 0); + case 5: return color( 0, 191, 191); + case 4: return color( 0, 0, 255); + case 3: return color(255, 0, 255); + case 6: return color(255, 127, 0); + case 7: return color(127, 127, 127); + case 8: return color(127, 0, 255); + case 9: return color( 0, 0, 0); + + case 12: return color(127, 0, 0); + case 11: return color( 80, 80, 0); + case 10: return color( 0, 80, 0); + case 15: return color( 0, 80, 80); + case 14: return color( 0, 0, 127); + case 13: return color(127, 0, 127); + case 16: return color(127, 63, 0); + case 17: return color( 63, 63, 63); + case 18: return color( 63, 0, 127); + case 19: return color(191, 191, 191); + } + return color(0); // should never happen... + } + + + class Renderer extends TChoice.StringRenderer { + public TComponent.Dimension getPreferredSize(TChoice c, Object o, boolean inMenu) { + TComponent.Dimension d = super.getPreferredSize(c, o, inMenu); + d.width += 305; return d; + } + public void draw(TChoice c, PGraphics g, Object o, TComponent.Rectangle bounds, boolean inMenu) { + bounds.x += 305; bounds.width -= 305; + super.draw(c, g, o, bounds, inMenu); + bounds.x -= 305; bounds.width += 305; + int cm = colormap; // save original colormap + setColormap((String)o); + g.noFill(); + for (int i = 0; i < 300; i++) { + g.stroke(getColor((colormap == 5) ? i*NDC/300.f : i, 0, 300)); + g.line(bounds.x + i, bounds.y + .25f*bounds.height, bounds.x + i, bounds.y + .75f*bounds.height); + } + colormap = cm; // restore original colormap + } + } + +} \ No newline at end of file diff --git a/DataImport.pde b/DataImport.pde new file mode 100644 index 0000000..9a6d9cf --- /dev/null +++ b/DataImport.pde @@ -0,0 +1,77 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +class DataImportWizard extends TFrame { + + TConsole console; + File file = null; + String str = null; + ExecutorService worker = null; + + DataImportWizard() { + super(SPaTo_Visual_Explorer.this.gui, "Data Import Wizard"); + setActionEventHandler(this); + guiSetup(); + worker = Executors.newSingleThreadExecutor(); + } + + DataImportWizard(File file) { + this(); setTitle(file.getName()); + this.file = file; + try { +// reader = new BufferedReader(new FileReader(f)); + } catch (Exception e) { + console.logError("Could not open file for reading: ", e); + e.printStackTrace(); + } + } + + DataImportWizard(String str) { + this(); setTitle("Pasted/dropped text data"); + this.str = str; + try { +// reader = new BufferedReader(new StringReader(str)); + } catch (Exception e) { + console.logError("Could not read text data: ", e); + e.printStackTrace(); + } + } + + void guiSetup() { + setBounds(100, 100, 300, 200); + console = gui.createConsole("import"); + add(console, TBorderLayout.SOUTH); + } + + void start() { + validate(); gui.add(this); gui.requestFocus(this); +// worker.submit(new ) + } + + void finish() { + worker.shutdown(); + gui.remove(this); + } + + void actionPerformed(String cmd) { + // + } + +} diff --git a/DataTransfer.pde b/DataTransfer.pde new file mode 100644 index 0000000..5f42adc --- /dev/null +++ b/DataTransfer.pde @@ -0,0 +1,166 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.awt.dnd.*; +import java.awt.datatransfer.*; + +TWindow winDropStatus = null; + +void setupDropTarget() { + winDropStatus = new TWindow(gui); + winDropStatus.setFocusable(false); + winDropStatus.setBackground(color(225, 225, 175, 225)); + winDropStatus.setPadding(15); + // + DropTargetListener dtl = new DropTargetAdapter() { + public void dragEnter(DropTargetDragEvent event) { +// showDropStatus(event.toString(), event.getTransferable()); + event.acceptDrag(DnDConstants.ACTION_COPY); + } + public void dragExit(DropTargetEvent event) { +// hideDropStatus(); + } + public void drop(DropTargetDropEvent event) { + if (canAccept(event.getTransferable())) { + event.acceptDrop(DnDConstants.ACTION_COPY); + handleTransferable(event.getTransferable()); +// showDropStatus(event.toString(), event.getTransferable()); +// hideDropStatus(); + event.dropComplete(true); + } else { + event.rejectDrop(); + } + if (!focused) redraw(); // go back into CPU-cycle saving mode, but erase drop status + } + }; + // + new DropTarget(this, DnDConstants.ACTION_COPY, dtl, true); +} + +boolean canAccept(Transferable t) { + return true;//t.isDataFlavorSupported(DataFlavor.javaFileListFlavor); +} + +void showDropStatus(String str, Transferable t) { + str += "\n\nFlavors:\n"; + for (DataFlavor f : t.getTransferDataFlavors()) + str += " " + f + "\n"; + Reader reader = null; + BufferedReader bufreader = null; + try { + DataFlavor flavor = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors()); + str += "\n\nFlavor: " + flavor + "\n"; + reader = flavor.getReaderForText(t); + str += "\nReader: " + reader + "\n"; + bufreader = new BufferedReader(reader); + str += "BufferedReader: " + bufreader + "\n\n"; + String line; int i = 0; + while ((line = bufreader.readLine()) != null) + str += "[" + i + "] " + line + "\n"; + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { bufreader.close(); } catch (Exception e) {} + } + try { + java.util.List ff = (java.util.List)t.getTransferData(DataFlavor.javaFileListFlavor); + str += "\n\nList: " + ff + "\n\n"; + for (Object f : ff) + str += f + "\n"; + } catch (Exception e) { + str += " XXX " + e.getMessage(); + } + try { + str += "\n\nString: "; + String s = (String)t.getTransferData(DataFlavor.stringFlavor); + str += s + "\n\n"; + } catch (Exception e) { + str += " XXX " + e.getMessage(); + } + // + println("=========================================================="); + print(str); + println("=========================================================="); + synchronized (gui) { + winDropStatus.removeAll(); + winDropStatus.add(gui.createLabel(str)); + TComponent.Dimension d = winDropStatus.getPreferredSize(); + winDropStatus.setBounds(width/2 - d.width/2, height/2 - d.height/2, d.width, d.height); + gui.add(winDropStatus); + } +} + +void hideDropStatus() { + gui.remove(winDropStatus); +} + +boolean handleTransferable(Transferable t) { + // handle dropped files + if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + File ff[]; + try { + ff = (File[])((java.util.List)t.getTransferData(DataFlavor.javaFileListFlavor)).toArray(new File[0]); + } catch (Exception e) { + console.logError("Error while getting the names of the dropped/pasted files: ", e); + e.printStackTrace(); + return false; + } + handleDroppedFiles(ff); + return true; + } + // handle dropped or pasted text + if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) { + String str = null; + try { + str = (String)t.getTransferData(DataFlavor.stringFlavor); + } catch (Exception e) { + console.logError("Error while retrieving the dropped/pasted text: ", e); + e.printStackTrace(); + return false; + } + if (str.startsWith("file://")) { // Linux reports file drops as lists of file URLs + File ff[] = new File[0]; + for (String line : split(str, "\n")) { + line = trim(line); + if ((line.length() > 0) && line.startsWith("file://")) + ff = (File[])append(ff, new File(line.substring(7))); + } + handleDroppedFiles(ff); + } else + new DataImportWizard(str).start(); + return true; + } + // don't know what to do + return false; +} + +void handleDroppedFiles(File ff[]) { + for (File f : ff) { + if (f.getName().endsWith(".spato")) + openDocument(f); + else if (f.getName().endsWith(".mat")) + ;//FIXME//new Thread(new MatFileImport(f)).start(); + else + new DataImportWizard(f).start(); + } +} + + + diff --git a/Dijkstra.pde b/Dijkstra.pde new file mode 100644 index 0000000..b51e3f8 --- /dev/null +++ b/Dijkstra.pde @@ -0,0 +1,220 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +static class Dijkstra { + + /** + * Fibonacci Heap + * http://en.wikipedia.org/wiki/Fibonacci_heap + * http://www.cs.princeton.edu/~wayne/cs423/lectures/fibonacci-4up.pdf + * http://www.cs.princeton.edu/~wayne/cs423/fibonacci/FibonacciHeapAlgorithm.html + * This version only implements what we need for Dijkstra. + * Also, only non-negative integers can be "elements" of the heap. + */ + static class FibonacciHeap extends Object { + static class Node { + int element; + float key; + boolean marked; + int degree; + Node prev, next, child, parent; // only one child is pointed to; + // its siblings are organized in a double-linked list via prev/next + Node(int element, float key) { this.element = element; this.key = key; + marked = false; degree = 0; + next = this; prev = this; child = null; parent = null; } + } + + int N, Nt; // number of nodes and number of trees + Node nodes[]; // wasteful array to quickly find an element by its "element" value + Node min; // minimum node (the root of the tree) + + FibonacciHeap(int maxElement) { + N = Nt = 0; + min = null; + nodes = new Node[maxElement+1]; + } + + void insert(int element, float key) { + Node n = new Node(element, key); + nodes[element] = n; // link in nodes array for quick access + if (min == null) // if heap is empty, this element will be the new minimum + min = n; + else { // otherwise add to the left of min and update min + n.next = min; + n.prev = min.prev; + min.prev = n; + n.prev.next = n; + if (key < min.key) + min = n; + } + N++; Nt++; + } + + int deleteMin() { + if (min == null) return -1; // nothing to do + // calculate max degree + int maxdegree = (int)Math.ceil(Math.log(N)/Math.log(1.619)); + // REMOVE MIN + int element = min.element; // save return value + N--; Nt--; // we'll remove min, thus one root node less in heap + Nt += min.degree; // but we'll add so many new root nodes + // if heap is empty now, set min to null and return + if (N == 0) { min = null; return element; } + // update root list: replace min with its children + if (min.next == min) // min was the only tree left + min = min.child; // min's children are the new root list + else { + if (min.child == null) { + // simply remove min + min.prev.next = min.next; + min.next.prev = min.prev; + } else { + // link last child to right neighbor of min + min.child.prev.next = min.next; + min.next.prev = min.child.prev; + // link first child to left neighbor of min + min.child.prev = min.prev; + min.prev.next = min.child; + } + } + // compile a list of root nodes + Node roots[] = new Node[Nt]; + for (int i = 0; i < Nt; i++) { + min = min.next; // get next root node + roots[i] = min; // and add it to the array + roots[i].parent = null; // this overrides all min childrens' parent pointers + roots[i].marked = false; // root nodes should not be marked + } + roots[0].prev = roots[Nt-1]; roots[Nt-1].next = roots[0]; // close cycle again + min = roots[0]; // updating min: first guess... + // CONSOLIDATE + Node A[] = new Node[maxdegree+1]; // degree pointer array + for (int i = 0; i < A.length; i++) + A[i] = null; + for (int i = 0; i < roots.length; i++) { + Node x = roots[i]; + while (A[x.degree] != null) { // merge x and y + Node y = A[x.degree]; + A[x.degree] = null; + // make sure that x has the lower key of the two + if (y.key < x.key) { Node tmp = y; y = x; x = tmp; } + if (min == y) min = x; // this can happen if y.key == x.key; make sure min stays a pointer to a root + // remove y from root list + y.prev.next = y.next; y.next.prev = y.prev; Nt--; + // make y a child of x and unmark it + y.parent = x; + y.marked = false; + if (x.child == null) + x.child = y.next = y.prev = y; + else { + y.next = x.child.next; + y.next.prev = y; + x.child.next = y; + y.prev = x.child; + } + x.degree++; + } + A[x.degree] = x; + if (x.key < min.key) + min = x; + } + // remove min from easy-access list and return + nodes[element] = null; + return element; + } + + void decreaseKey(int element, float key) { + Node z = nodes[element]; + // if element is not on heap or new key is not lower, then there's nothing to do + if ((z == null) || (z.key <= key)) return; + // decrease key of z + z.key = key; + // update tree structure if necessary + if ((z.parent != null) && (z.key < z.parent.key)) { + Node x = z; + do { + // CUT + Node y = x.parent; + // remove x from the child list of y + if (x.next == x) // only child? + y.child = null; + else { + if (y.child == x) y.child = x.next; + x.prev.next = x.next; + x.next.prev = x.prev; + } + y.degree--; + // add x to root list + x.next = min.next; x.next.prev = x; + x.prev = min; min.next = x; + Nt++; + // update accounting + x.marked = false; + x.parent = null; + // CASCADING-CUT decision + if (y.marked) // if parent was already marked + x = y; // now y will cut in the next iteration (if it's not a root node already) + else if (y.parent != null) // if parent was not marked before and is not a root node... + y.marked = true; // ...mark it and leave x as it is (thus x.parent == null and the while-loop will exit) + } while (x.parent != null); + } + // update min pointer + if (z.key < min.key) + min = z; + } + + boolean isEmpty() { return min == null; } + } + + static void calculateShortestPathTree(int edges[][], float weights[][], int i0, int pred[], float dist[]) { + calculateShortestPathTree(edges, weights, i0, pred, dist, false); } + // if useInv is true, 1/weights will be used + static void calculateShortestPathTree(int edges[][], float weights[][], int i0, int pred[], float dist[], boolean useInv) { + int N = edges.length; + boolean optimal[] = new boolean[N]; + FibonacciHeap Q = new FibonacciHeap(N); + for (int i = 0; i < N; i++) { + dist[i] = Float.POSITIVE_INFINITY; + pred[i] = -1; + optimal[i] = false; + Q.insert(i, dist[i]); + } + dist[i0] = 0; + Q.decreaseKey(i0, 0); + while (!Q.isEmpty()) { + int u = Q.deleteMin(); + optimal[u] = true; + int edgesu[] = edges[u]; + float weightsu[] = weights[u]; + float distu = dist[u]; + for (int n = 0; n < edgesu.length; n++) { + int v = edgesu[n]; + if (optimal[v]) continue; + float alt = distu + (useInv ? 1/weightsu[n] : weightsu[n]); + if (alt < dist[v]) { + dist[v] = alt; + Q.decreaseKey(v, alt); + pred[v] = u; + } + } + } + } + +} diff --git a/Fireworks.pde b/Fireworks.pde new file mode 100644 index 0000000..33ff0f1 --- /dev/null +++ b/Fireworks.pde @@ -0,0 +1,400 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +boolean fireworks = false; +Fireworks fw = null; + +void startFireworks() { + gui.setVisible(false); + gui.setEnabled(false); + fw = new Fireworks(); + fireworks = true; + fw.setup(); +} + +void disposeFireworks() { + fireworks = false; + fw = null; + gui.setEnabled(true); + gui.setVisible(true); +} + +// How to make this class: +// 1) Copy'n'paste all PDE files from /Users/ct/Processing/Fireworks +// 2) Check setup() and out-comment inappropriate stuff (the size(...) should stay) +// 3) Replace "exit()" at the end of draw() with "alpha = tAlpha = 0;" +// 4) Out-comment "background(255);" in draw() +class Fireworks { + + Launcher ll[] = null; + float t0, tt, t, dt, t0max, tFinish = Float.NaN; + + boolean started = false, finished = false; + float scale = 4; + float alpha = 0; + float grav = -9.81; + + color colors[] = new color[] { + color(255, 0, 0), // red + color(255, 150, 20), // orange + color(255, 225, 20), // yellow + //color(160, 250, 160), // light green + color( 50, 255, 50), // solid green + //color( 15, 250, 160), // cyan + color( 0, 127, 255), // light blue + color(180, 130, 250), // light purple + color(200, 40, 220), // solid purple + }; + + +// int T = 0; +// int millis() { return super.millis() + T*1000; } + + void setup() { + randomSeed(second() + 60*minute() + 3600*hour()); + // size(1280, 720); + size(800, 800*9/16); +// frameRate(30); +// smooth(); + t0 = tt = millis()/1000.; + // T = 40; + ll = new Launcher[] { + new RocketLauncher(30, t0 + 2, 18), + new TrailingRocketLauncher(10, t0 + 27, 8, 4, 75, true), + new TrailingRocketLauncher(11, t0 + 35, 6, 3, 75, true), + new TrailingRocketLauncher(11, t0 + 35, 6, 3, 75, false), + new ShellLauncher(10, t0 + 36, 5, true, color(250)),//, 240, 200)), + new ShellLauncher(20, t0 + 42, 20), + new ShellLauncher(5, t0 + 47, 15, true), + new ShellLauncher(30, t0 + 52, 10), + new ShellLauncher(1, t0 + 61, 1, true), + }; + t0max = 0; for (Launcher l : ll) t0max = max(t0max, l.t0); + } + + void draw() { + t = millis()/1000.; dt = t - tt; tt = t; + if (alpha == 1) + background(0); + else { + //background(255); + noStroke(); fill(0, 255*alpha); rect(0, 0, width, height); + } + //if (frameCount % 30 == 0) println((t - t0) + " " + frameRate); + float tAlpha = alpha; + if (!started) { + if (alpha < .999) tAlpha = 1; else { alpha = tAlpha = 1; started = true; } + } else if (started && !finished) { + noFill(); + pushMatrix(); + translate(width/2, height); + scale(scale*width/1280, -scale*height/720); + finished = (t > t0max); // will be overriden if any of the launchers is still busy + for (Launcher l : ll) { + l.draw(); + if (!l.finished) + finished = false; + } + popMatrix(); + } else { // finished + if (Float.isNaN(tFinish)) tFinish = t; + if (t > tFinish + 5) tAlpha = 0; // fade out five seconds after last shell burned out + if (alpha < 0.001) alpha = tAlpha = 0; + } + alpha += 3*(tAlpha - alpha)*min(dt, 1/3.); + } + class Particle { + float t0, x, y, vx, vy, ax, ay; // creation time, position, velocity, acceleration + float f = .1; // friction + color c; // color + float alpha = 1; + boolean solid = false, slowDecay = false; + boolean sparkling = false, isSparkling = false; + + Particle(float t0, float x0, float y0, float vx0, float vy0, color c) { + this(t0, x0, y0, vx0, vy0, 0, 0, c); } + Particle(float t0, float x0, float y0, float vx0, float vy0, float ax0, float ay0, color c) { + this.t0 = t0; x = x0; y = y0; vx = vx0; vy = vy0; ax = ax0; ay = ay0; this.c = c; } + + void draw() { + color cc = c; + vx += ax*dt; vy += (ay + grav)*dt; + vx += -f*vx*dt; vy += -f*vy*dt; + x += vx*dt; y += vy*dt; + if (!solid) { + alpha -= (t - t0)*random(slowDecay ? .25 : 1)*dt; + cc = lerpColor(color(255), c, min(1, (.5 + .5*noise(x, y, t/10))*(t - t0)/.75)); + } + if (sparkling) { + if (t - t0 > random(1, 2)) isSparkling = true; + if (alpha < 0) alpha = random(0, 1); + if (isSparkling && (random(1) < .25)) cc = color(255); + if (t - t0 > random(3.5, 4.5)) sparkling = false; + } + alpha = max(0, alpha); + stroke(cc, 255*alpha); + point(x, y); + } + } + + + class Launcher { + Shell rr[] = new Shell[0]; + boolean finished = true; + float t0; + + Launcher(float t0) { this.t0 = t0; } + + void draw() { + finished = true; + for (Shell r : rr) { + if (t < r.t0) continue; + r.draw(); + if (!r.finished) + finished = false; + } + } + + } + + class ShellLauncher extends Launcher { + ShellLauncher(int N, float t0, float deltat) { this(N, t0, deltat, false); } + ShellLauncher(int N, float t0, float deltat, boolean sparkling) { this(N, t0, deltat, sparkling, 0); } + ShellLauncher(int N, float t0, float deltat, boolean sparkling, color c) { + super(t0); + rr = new Shell[N]; + for (int i = 0; i < N; i++) { + float x0 = 3*round((sparkling ? 5 : 10)*random(-1, 1)) + random(-1,1); + float vx = (sparkling ? 5 : 10)*random(-1, 1); + rr[i] = new Shell(random(t0, t0 + deltat), x0, 0, vx, random(45, 55), sparkling, c); + } + } + } + + class RocketLauncher extends Launcher { + RocketLauncher(int N, float t0, float deltat) { + super(t0); + rr = new Shell[N]; + for (int i = 0; i < N; i++) + rr[i] = new Skyrocket(random(t0, t0 + deltat), random(-2, 2), 0, + random(-2, 2), random(15, 25), -1.5*grav); + } + } + + class TrailingRocketLauncher extends Launcher { + TrailingRocketLauncher(int N, float t0, float deltat, int Ni, float v0) { + this(N, t0, deltat, Ni, v0, true); } + TrailingRocketLauncher(int N, float t0, float deltat, int Ni, float v0, boolean ltr) { + super(t0); + rr = new Shell[N*Ni]; int index = 0; + float dt = deltat/(Ni*(N + 1)); // time between individual rocket launches + float dx = 10; + float x0max = dx*(N-1)/2.; + for (int ii = 0; ii < Ni; ii++) { + for (int i = 0; i < N; i++) { + float rt0 = t0 + (ii*(N-1) + i)*dt; + float x0 = dx*((ltr ? i : (N-1-i)) - (N-1)/2.); + if (Ni > 1) x0 += (ltr ? -1 : 1)*.25*dx; + float angle = PI/5 * x0/x0max; + float v = v0*random(0.95, 1.05); + rr[index] = new TrailingSkyrocket(rt0, x0, 0, v*sin(angle), v*cos(angle), -.5*grav); + rr[index].t1 = .5; + index++; + } + ltr = !ltr; + } + } + } + class Shell extends Particle { + boolean mortarLaunch = true; + Particle pp[] = null; + float t1, x0; + boolean exploded = false; + boolean finished = false; + + Shell(float t0, float x0, float y0, float vx0, float vy0) { + this(t0, x0, y0, vx0, vy0, false); } + Shell(float t0, float x0, float y0, float vx0, float vy0, boolean sparkling) { + this(t0, x0, y0, vx0, vy0, sparkling, 0); } + Shell(float t0, float x0, float y0, float vx0, float vy0, boolean sparkling, color c) { + super(t0, x0, y0, vx0, vy0, color(20)); f /= 10; solid = true; + t1 = random(3, 4); + this.x0 = x0; + createParticles(sparkling, c); + } + + void createParticles(boolean sparkling, color c) { + pp = new Particle[floor(sparkling ? random(150, 200) : random(100, 150))]; + if (c == 0) c = colors[floor(random(0, colors.length))]; + float size = sparkling ? random(30, 31) : random(8, 10); + for (int i = 0; i < pp.length; i++) { + float theta = random(-PI, PI); + float phi = random(0, PI); + float nv = size*random(0.9, 1.0); + float nvx = nv*sin(theta)*cos(phi); + float nvy = nv*cos(theta);//sin(theta)*sin(phi); + // c = random(0, 1) < 0.8 ? colors[0] : color(255); + pp[i] = new Particle(0, 0, -100, nvx, nvy, c); + pp[i].sparkling = sparkling; + if (sparkling) pp[i].f *= 5; + } + } + + void draw() { + // shell physics + alpha = 1; + super.draw(); + // trigger explosion + if (!exploded && (t - t0 > t1)) { + for (Particle p : pp) { p.t0 = t; p.x = x; p.y = y; p.vx += vx; p.vy += vy; } + exploded = true; + } + // draw crown particles + if (exploded) { + finished = true; + for (Particle p : pp) { + p.draw(); + if (p.alpha > 1/255.) finished = false; + } + } + // draw launch + if (mortarLaunch && (t - t0 < .25)) { + float nu = (1 - (t - t0)/.25); + stroke(lerpColor(color(255), color(255, 127, 0), nu), 255*nu); + point(x0, 2/scale); + } + } + } + + + class Skyrocket extends Shell { + Particle trail[] = new Particle[50]; int trailPointer = 0; float trailLast = 0; + float a; + + class TrailParticle extends Particle { + float tau = .1; + TrailParticle(float t0, float x0, float y0, float vx0, float vy0) { + super(t0, x0, y0, vx0, vy0, color(255)); alpha = 0.3; f *= 10; } + void draw() { + if (t - t0 < 1*tau) c = lerpColor(color(255, 255, 255), color(255, 255, 0), (t - t0)/tau); + else if (t - t0 < 2*tau) c = lerpColor(color(255, 255, 0), color(255, 0, 0), (t - t0)/tau - 1); + else if (t - t0 < 3*tau) c = lerpColor(color(255, 0, 0), color(127, 127, 127), (t - t0)/tau - 2); + else c = color(127, 127, 127); + alpha -= 0.2*dt; + if (random(0, 10) < t - t0) alpha -= 0.05; + alpha = max(0, min(1, alpha)); + vx += random(-1, 1)*20*dt; + vx += ax*dt; vy += (ay + grav)*dt; + vx += -f*vx*dt; vy += -f*vy*dt; + x += vx*dt; y += vy*dt; + stroke(c, 255*alpha); noFill(); + point(x, y); + } + } + + Skyrocket(float t0, float x0, float y0, float vx0, float vy0, float a) { + super(t0, x0, y0, vx0, vy0); this.a = a; + mortarLaunch = false; + createParticles(); + } + + void createParticles() { + pp = new Particle[floor(random(50, 150))]; + color c = colors[floor(random(0, colors.length))]; + float size = random(5, 10); + for (int i = 0; i < pp.length; i++) { + float theta = random(-PI, PI); + float phi = random(0, PI); + float nv = size*random(0.5, 1.5); + float nvx = nv*sin(theta)*cos(phi); + float nvy = nv*cos(theta);//sin(theta)*sin(phi); + // c = random(0, 1) < 0.8 ? colors[0] : color(255); + pp[i] = new Particle(0, 0, -100, nvx, nvy, c); + } + } + + void generateTrail() { + if ((a > 0) && (t > trailLast + .05)) { + trail[trailPointer] = new TrailParticle(t, x, y, vx, vy); + trailPointer = (trailPointer + 1) % trail.length; + trailLast = t; + } + } + + void draw() { + // draw tail + for (int i = 0; i < trail.length; i++) { + if (trail[i] == null) continue; + trail[i].draw(); + if (trail[i].alpha < 1/255.) trail[i] = null; + } + // propulsion + if (!exploded) { + if (t - t0 > t1 - 1) a = 0; + float v = sqrt(vx*vx + vy*vy); + ax = a*vx/v; ay = a*vy/v; + } + // generate trail + generateTrail(); + // physics & draw + super.draw(); + } + } + + + // does not explode; the trail is the effect + class TrailingSkyrocket extends Skyrocket { + float initTrailRate, trailRate = -1; + + TrailingSkyrocket(float t0, float x0, float y0, float vx0, float vy0, float a) { + super(t0, x0, y0, vx0, vy0, a); f = 0; + pp = new Particle[0]; // no crown + trail = new Particle[500]; + trailRate = initTrailRate = 7*sqrt(sq(vx0) + sq(vy0)); + } + + void generateTrail() { + if (a == 0) trailRate = max(0, trailRate - .66*initTrailRate*dt); + int N = floor(trailRate*dt); + if (random(1) < trailRate*dt - N) N++; + for (int i = 0; i < N; i++) { + float vx0 = 5*sqrt(sqrt(t - t0))*random(-1, 1); + float vy0 = 5*sqrt(sqrt(t - t0))*random(-1, 1); + trail[trailPointer] = new Particle(t, x - vx*dt*i/N, y - vy*dt*i/N, vx0, vy0, 0, -0.9*grav, + (random(1) < .25) ? color(255) : color(255, 225, 64)); + trail[trailPointer].alpha = 0.3; + trail[trailPointer].slowDecay = true; + trail[trailPointer].f *= 10; + trailPointer = (trailPointer + 1) % trail.length; + trailLast = t; + } + } + + void draw() { + super.draw(); + finished = (a == 0); + for (Particle p : trail) + if ((p != null) && (p.alpha > 1/255.)) + finished = false; + } + + } + +} \ No newline at end of file diff --git a/Layout.pde b/Layout.pde new file mode 100644 index 0000000..2938b12 --- /dev/null +++ b/Layout.pde @@ -0,0 +1,176 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.util.Vector; +import java.util.Collections; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +HashMap layoutCache = new HashMap(); // FIXME: layout handling is still screwed up... + +class Layout { + Projection proj; + Scaling scal; + String projection, scaling, order; + int NN = -1; + int pred[][]; // input data + float phi[][]; // posphi[r][i] is angular position of node i if r is root + int r = -1; // currently loaded slice + + class Cache { + Vector children[]; + int numTotalChildren[]; + float sortValue[]; + + Cache(int r, float val[], boolean sortRecursively) { + children = new Vector[NN]; + for (int i = 0; i < NN; i++) children[i] = new Vector(); + numTotalChildren = new int[NN]; + if (val != null) sortValue = new float[NN]; + // setup children vector + for (int i = 0; i < NN; i++) + if (pred[r][i] >= 0) + children[pred[r][i]].add(new Integer(i)); // i is a child of s.pred[i] (by definition) + // setup numTotalChildren and sortValue vectors + setupRecursively(r, val, sortRecursively); + // sort children vector + if (val != null) + for (int i = 0; i < NN; i++) + Collections.sort(children[i], new Comparator() { int compare(Object o1, Object o2) { + float v1 = sortValue[((Integer)o1).intValue()], v2 = sortValue[((Integer)o2).intValue()]; + return (v1 < v2) ? -1 : (v1 > v2) ? +1 : 0; } }); + } + + void setupRecursively(int j, float val[], boolean sortRecursively) { + numTotalChildren[j] = children[j].size(); + if (val != null) sortValue[j] = val[j]; + float sortTmp = 0; + for (int ii = 0; ii < children[j].size(); ii++) { + int i = ((Integer)children[j].get(ii)).intValue(); + setupRecursively(i, val, sortRecursively); + numTotalChildren[j] += numTotalChildren[i]; + if (sortRecursively) sortTmp += sortValue[i]; + } + if (sortRecursively) sortValue[j] += sortTmp/10000; + } + } + + Layout(int[][] pred, String spec) { + this.pred = pred; + NN = pred.length; + parseSpecification(spec); + setupProjection(projection); + setupScaling(scaling); + String hash = spec + "##" + pred.toString(); + if (!layoutCache.containsKey(hash)) { + phi = new float[NN][NN]; + float sortData[] = getSortData(); + calculateLayout(sortData); + layoutCache.put(hash, phi); + } + phi = (float[][])layoutCache.get(hash); + } + + String getSpecification() { return projection + "_" + scaling + (!order.equals("unsorted") ? "__" + order : ""); } + + void setupProjection(String projection) { + if (!TomProjectionFactory.canProduce(projection)) { + console.logWarning("Unknown tomogram projection " + projection + ", using default"); + projection = TomProjectionFactory.getDefaultProduct(); + } + proj = TomProjectionFactory.produce(projection, NN); + this.projection = projection; + } + + void setupScaling(String scaling) { setupScaling(scaling, 1); } + void setupScaling(String scaling, float x0) { + if (!ScalingFactory.canProduce(scaling)) { + console.logWarning("Unknown scaling " + scaling + ", using default"); + scaling = ScalingFactory.getDefaultProduct(); + } + scal = ScalingFactory.produce(scaling, NN); + if (scaling.equals("log")) ((LogScaling)scal).x0 = x0; + this.scaling = scaling; + } + + void updateProjection(int r, float D[][]) { proj.setPoints(scal.f(D[r]), phi[r]); this.r = r; } + + void parseSpecification(String spec) { + order = "unsorted"; + String pieces[] = split(spec, "__"); + if (pieces.length > 1) order = pieces[1]; + pieces = split(pieces[0], '_'); + projection = pieces[0]; + scaling = (pieces.length > 1) ? pieces[1] : "id"; + } + + float[] getSortData() { + return null; // FIXME: re-implement this feature... + /*if (order.equals("unsorted")) return null; + try { + String pieces[] = split(order, '_'); + SVE2View.Dataset ds = null; + for (int d = 0; d < view.ND; d++) + if (view.data[d].xml.getString("id").equals(pieces[0])) + ds = view.data[d]; + if (ds == null) throw new Exception("Dataset " + pieces[0] + " not found"); + if (pieces.length < 2) throw new Exception("Quantity not specified"); + SVE2View.Data data = null; + for (int q = 0; q < ds.NQ; q++) + if (ds.data[q].xml.getString("id").equals(pieces[1])) + data = ds.data[q]; + return data.data; + } catch (Exception e) { + console.logWarning("" + e.getMessage() + ", defaulting to unsorted layout"); + order = "unsorted"; + return null; + }*/ + } + + void calculateLayout(float sortData[]) { + console.logProgress("Calculating layout " + getSpecification()); + for (int r = 0; r < NN; r++) { + Cache cache = new Cache(r, sortData, order.endsWith("_r")); + phi[r][r] = PI; // we do this to move the root in the middle in LinearProjection + calculateLayoutRecursively(cache, r, r, 0, 0, 2*PI); + console.updateProgress(r, NN); + } + console.finishProgress(); + } + + // cache, root node, current layout node, tree depth of node j, min and max angles + void calculateLayoutRecursively(Cache cache, int r, int j, int d, float phimin, float phimax) { + int sumNTC = cache.numTotalChildren[j], cumNTC = 0; // sum of total children, cumulative sum + Vector I = cache.children[j]; + for (int ii = 0; ii < I.size(); ii++) { + int i = ((Integer)I.get(ii)).intValue(); + float iphimin = phimin + (phimax - phimin)*cumNTC/sumNTC; + cumNTC += cache.numTotalChildren[i] + 1; // sum of i's children plus i itself + float iphimax = phimin + (phimax - phimin)*cumNTC/sumNTC; + phi[r][i] = (iphimin + iphimax)/2; + //doc.slices[r].d[i] = d; + calculateLayoutRecursively(cache, r, i, d + 1, iphimin, iphimax); + } + } +} + + diff --git a/MacMagic.java b/MacMagic.java new file mode 100644 index 0000000..cdb775d --- /dev/null +++ b/MacMagic.java @@ -0,0 +1,68 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.io.File; +import com.apple.eawt.Application; +import com.apple.eawt.ApplicationAdapter; +import com.apple.eawt.ApplicationEvent; + +/** + * This class deals with all the Mac-related goodies, specifically opening documents + * when double-clicked in the Finder. It should be instantiated using reflection, + * so that the class does not get loaded if we are not running on a Mac platform + * (otherwise the above import statements may cause things to break). + * + * http://developer.apple.com/library/mac/#documentation/Java/Conceptual/Java14Development/07-NativePlatformIntegration/NativePlatformIntegration.html%23//apple_ref/doc/uid/TP40001909-SW1 + * http://developer.apple.com/library/mac/documentation/Java/Reference/1.5.0/appledoc/api/index.html + */ +public class MacMagic extends ApplicationAdapter { + + protected SPaTo_Visual_Explorer app = null; + + public MacMagic(SPaTo_Visual_Explorer app) { + this.app = app; + Application.getApplication().addApplicationListener(this); + } + + public void handleOpenFile(ApplicationEvent event) { + // wait for application setup to be done (causes otherwise NullPointerExceptions otherwise) + while (!app.canHandleOpenFileEvents) try { Thread.sleep(25); } catch (Exception e) {} + // check for valid file type and load the file + if (event.getFilename().endsWith(".spato")) { + app.openDocument(new File(event.getFilename())); + event.setHandled(true); + } else if (event.getFilename().endsWith(".sve")) { + app.openWorkspace(new File(event.getFilename())); + event.setHandled(true); + } else + // FIXME: in-app error message? + javax.swing.JOptionPane.showMessageDialog(null, "Unknown file type: " + event.getFilename(), + "Open Workspace", javax.swing.JOptionPane.ERROR_MESSAGE); + } + + public void handleOpenApplication(ApplicationEvent event) { + event.setHandled(true); + } + + public void handleQuit(ApplicationEvent event) { + event.setHandled(true); // FIXME: check for unsaved files + } + +} \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f4fb008 --- /dev/null +++ b/Makefile @@ -0,0 +1,74 @@ + +VERSION ?= dev + + +apps: app.win app.lin app.mac + +packages: + rm -f application.macosx/SPaTo_Visual_Explorer.dmg + cd support/macosx; ./create_dmg.sh; cd .. + mv application.macosx/SPaTo_Visual_Explorer.dmg SPaTo_Visual_Explorer_$(VERSION).dmg + cd application.linux; tar cvzf ../SPaTo_Visual_Explorer_$(VERSION).tar.gz SPaTo_Visual_Explorer; cd .. + cd application.windows; zip -r -9 ../SPaTo_Visual_Explorer_$(VERSION).zip SPaTo\ Visual\ Explorer; cd .. + + +APP_PACKAGE = application.macosx/SPaTo_Visual_Explorer.app + +app.mac: application.macosx + rm -rf $(APP_PACKAGE)/Contents/Resources/update + rm -rf $(APP_PACKAGE)/Contents/Resources/Java/tmp + cp -p support/macosx/Info.plist $(APP_PACKAGE)/Contents + cp -p support/macosx/Info.plist $(APP_PACKAGE)/Contents/Info.plist.orig + cp -p support/macosx/ApplicationUpdateWrapper $(APP_PACKAGE)/Contents/MacOS + cp -p support/macosx/*icns $(APP_PACKAGE)/Contents/Resources + rm -f $(APP_PACKAGE)/Contents/Resources/sketch.icns + make -C support/prelude + cp -p support/prelude/SPaTo_Prelude.{class,jar} $(APP_PACKAGE)/Contents/Resources/Java + cp -p $(WIN_PACKAGE)/lib/SPaTo_Visual_Explorer.jar $(APP_PACKAGE)/Contents/Resources/Java + + +LIN_PACKAGE = application.linux/SPaTo_Visual_Explorer + +app.lin: application.linux + -cp application.linux/SPaTo_Visual_Explorer application.linux/SPaTo_Visual_Explorer.sh + rm -rf $(LIN_PACKAGE) + mkdir -p $(LIN_PACKAGE)/lib + cp -p application.linux/lib/*.jar $(LIN_PACKAGE)/lib + cp -p $(WIN_PACKAGE)/lib/SPaTo_Visual_Explorer.jar $(LIN_PACKAGE)/lib + cp -p support/linux/SPaTo_Visual_Explorer $(LIN_PACKAGE) + cp -p support/linux/config.sh $(LIN_PACKAGE)/lib + cp -p support/linux/config.sh $(LIN_PACKAGE)/lib/config.sh.orig + cp -p support/linux/SPaTo_Visual_Explorer.png $(LIN_PACKAGE)/lib + cp -p support/linux/SPaTo_Visual_Explorer.desktop $(LIN_PACKAGE)/lib + cp -p support/linux/spato-mime.xml $(LIN_PACKAGE)/lib + cp -p support/linux/application-x-spato.png $(LIN_PACKAGE)/lib + cp -p support/linux/application-x-spato-uncompressed.png $(LIN_PACKAGE)/lib + cp -p support/linux/application-x-spato-workspace.png $(LIN_PACKAGE)/lib + make -C support/prelude + cp -p support/prelude/SPaTo_Prelude.{class,jar} $(LIN_PACKAGE)/lib + + +WIN_PACKAGE = application.windows/SPaTo\ Visual\ Explorer + +app.win: application.windows + rm -rf $(WIN_PACKAGE) + mkdir -p $(WIN_PACKAGE)/lib + cp -p application.windows/lib/*.jar $(WIN_PACKAGE)/lib + cp -p support/windows/SPaTo\ Visual\ Explorer.{exe,ini} $(WIN_PACKAGE) + cp -p support/windows/SPaTo_{Prelude,Visual_Explorer}.ini $(WIN_PACKAGE)/lib + cp -p support/windows/SPaTo_Visual_Explorer.ini $(WIN_PACKAGE)/lib/SPaTo_Visual_Explorer.ini.orig + cp -p support/windows/WinRun4J.jar $(WIN_PACKAGE)/lib + cp -p support/windows/spato-16x16.png $(WIN_PACKAGE)/lib + make -C support/prelude + cp -p support/prelude/SPaTo_Prelude.{class,jar} $(WIN_PACKAGE)/lib + make -C support/windows WindowsMagic.class + jar uf $(WIN_PACKAGE)/lib/SPaTo_Visual_Explorer.jar -C support/windows WindowsMagic.class + + +PASSWORD = `security -q find-internet-password -g -r "ftp " -a ftp1032083-spato -s wp255.webpack.hosteurope.de 2>&1 | grep password: | awk '{ print $$2; }' | awk -F '"' '{ print $$2; }'` +FTPSITE = ftp://ftp1032083-spato:$(PASSWORD)@wp255.webpack.hosteurope.de/www/download + +upload: application.linux/SPaTo_Visual_Explorer.tar.gz application.macosx/SPaTo_Visual_Explorer.dmg application.windows/SPaTo_Visual_Explorer.zip + ftp -u $(FTPSITE)/SPaTo_Visual_Explorer_$(VERSION).tar.gz application.linux/SPaTo_Visual_Explorer.tar.gz + ftp -u $(FTPSITE)/SPaTo_Visual_Explorer_$(VERSION).dmg application.macosx/SPaTo_Visual_Explorer.dmg + ftp -u $(FTPSITE)/SPaTo_Visual_Explorer_$(VERSION).zip application.windows/SPaTo_Visual_Explorer.zip diff --git a/PlatformMagic.pde b/PlatformMagic.pde new file mode 100644 index 0000000..8f9bccd --- /dev/null +++ b/PlatformMagic.pde @@ -0,0 +1,112 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import javax.swing.JFrame; +import javax.swing.UIManager; + +JFrame jframe = null; +String defaultTitle = null; +Object macmagic = null; // holds a MacMagic instance if platform is MACOSX +Object winmagic = null; // holds a WindowsMagic instance if platform is MACOSX + +// called by setup() +public void setupPlatformMagic() { + if (platform == MACOSX) macmagic = loadMagicClass("Mac"); + if (platform == WINDOWS) winmagic = loadMagicClass("Windows"); + if (platform == WINDOWS) setSystemLookAndFeel(); +} + +// called by guiFastUpdate() +public void updatePlatformMagic() { + if (platform == MACOSX) { + boolean showDoc = ((doc != null) && !fireworks); + if (defaultTitle == null) defaultTitle = frame.getTitle(); + frame.setTitle(showDoc ? doc.getFile().getAbsolutePath() : defaultTitle); + jframe.getRootPane().putClientProperty("Window.documentFile", showDoc ? doc.getFile() : null); + jframe.getRootPane().putClientProperty("Window.documentModified", showDoc && doc.isModified()); + } +} + +public Object loadMagicClass(String platform) { + try { + return Class.forName(platform + "Magic"). + getConstructor(new Class[] { SPaTo_Visual_Explorer.class }). + newInstance(new Object[] { this }); + } catch (Exception e) { + e.printStackTrace(); + return null; + } +} + +public boolean setSystemLookAndFeel() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } +} + +// overriding main() to create the applet within a JFrame (needed to do much of the Mac magic). +public static void main(String args[]) { + SPaTo_Visual_Explorer applet = new SPaTo_Visual_Explorer(); + if (platform == MACOSX) { + // Wrap the applet into a JFrame for maximum MacMagic! + // setup various stuff (see PApplet.runSketch) + applet.sketchPath = System.getProperty("user.dir"); + applet.args = (args.length > 1) ? subset(args, 1) : new String[0]; + for (int i = 0; i < args.length; i++) { + if (args[i].startsWith(ARGS_SKETCH_FOLDER)) + applet.sketchPath = args[i].substring(args[i].indexOf('=') + 1); + } + // setup shiny JFrame + applet.frame = applet.jframe = new JFrame(); + applet.jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + applet.jframe.setLayout(new BorderLayout()); + applet.jframe.add(applet, BorderLayout.CENTER); + // ... and go! + applet.init(); + while (applet.defaultSize && !applet.finished) // see PApplet.runSketch + try { Thread.sleep(5); } catch (InterruptedException e) {} + applet.jframe.pack(); + applet.jframe.setLocation((applet.screenWidth - applet.width)/2, (applet.screenHeight - applet.height)/2); + if (applet.displayable()) + applet.jframe.setVisible(true); + applet.requestFocus(); + } else { + // pass the constructed applet to PApplet.runSketch + PApplet.runSketch(new String[] { "SPaTo_Visual_Explorer" }, applet); + if (platform == LINUX) try { + String filename = System.getProperty("spato.app-dir") + "/lib/SPaTo_Visual_Explorer.png"; + applet.frame.setIconImage(Toolkit.getDefaultToolkit().createImage(filename)); + } catch (Exception e) { /* ignore */ } + } + // handle possible command-line arguments + if (args.length > 1) { + // wait for applet to initialize + while (!applet.canHandleOpenFileEvents) try { Thread.sleep(25); } catch (Exception e) {} + // parse command line for files + File ff[] = new File[args.length - 1]; + for (int i = 1; i < args.length; i++) + ff[i-1] = new File(args[i]); + applet.handleDroppedFiles(ff); + } +} \ No newline at end of file diff --git a/Projection.pde b/Projection.pde new file mode 100644 index 0000000..d51224f --- /dev/null +++ b/Projection.pde @@ -0,0 +1,175 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +static abstract class Projection { + int N = 0; + float x[] = null, y[] = null; + float minx, maxx, miny, maxy; + float cx, cy, w, h, sx, sy; // center, and width and height of the used space, and scaling + + Projection() {} + Projection(int N) { this.N = N; x = new float[N]; y = new float[N]; } + + void setScalingToFitWithin(float width, float height) { + // fit within dimensions with preserving aspect ratio of the data + sx = sy = min((w == 0) ? 1e-5 : width/w, (h == 0) ? 1e-5 : height/h); + } + + void beginData() { + minx = miny = Float.POSITIVE_INFINITY; + maxx = maxy = Float.NEGATIVE_INFINITY; + cx = cy = w = h = 0; + sx = sy = 1; + } + + void setPoint(int i, float x, float y) { + this.x[i] = x; + this.y[i] = y; + if (!Float.isInfinite(x) && !Float.isInfinite(y)) { + minx = min(minx, x); + maxx = max(maxx, x); + miny = min(miny, y); + maxy = max(maxy, y); + } + } + + void endData() { + cx = (minx + maxx)/2; + cy = (miny + maxy)/2; + w = maxx - minx; + h = maxy - miny; + } + + void setPoints(float x[], float y[]) { + beginData(); + for (int i = 0; i < N; i++) + setPoint(i, x[i], y[i]); + endData(); + } +} + +static class MapProjectionFactory { + static String[] productNames = { "LonLat", "LonLat Roll", "Albers" }; + + static boolean canProduce(String name) { + if (name == null) return false; + for (int i = 0; i < productNames.length; i++) + if (name.equals(productNames[i])) + return true; + return false; + } + static String getDefaultProduct() { return productNames[0]; } + + static Projection produce(String name, int N) { + if (name == null) return null; + if (name.equals("LonLat")) return new LonLatProjection(N); + if (name.equals("LonLat Roll")) return new LonLatProjection(N, true); + if (name.equals("Albers")) return new AlbersProjection(N); + return null; + } +} + +static class TomProjectionFactory { + static String[] productNames = { "linear", "radial" }; + + static boolean canProduce(String name) { + if (name == null) return false; + for (int i = 0; i < productNames.length; i++) + if (name.equals(productNames[i])) + return true; + return false; + } + static String getDefaultProduct() { return productNames[0]; } + + static Projection produce(String name, int N) { + if (name == null) return null; + if (name.equals("linear")) return new LinearProjection(N); + if (name.equals("radial")) return new RadialProjection(N); + return null; + } +} + +/********************************************************************** + * Projections used with tomogram layouts + **********************************************************************/ + +// Linear projection +static class LinearProjection extends Projection { + LinearProjection(int NN) { super(NN); } + void setPoint(int i, float r, float phi) { super.setPoint(i, -(phi - PI), -r); } + void setScalingToFitWithin(float width, float height) { + // aspect ratio is not important in LinearProjection + sx = (w == 0) ? 1e-5 : width/w; sy = (h == 0) ? 1e-5 : height/h; } +} + +// Polar coordinates to cartesian +static class RadialProjection extends Projection { + RadialProjection(int NN) { super(NN); } + void setPoint(int i, float r, float phi) { super.setPoint(i, -r*cos(phi), -r*sin(phi)); } + void endData() { w = 2*max(abs(minx), abs(maxx)); h = 2*max(abs(miny), abs(maxy)); } +} + +/********************************************************************** + * Projections used with geographic maps + **********************************************************************/ + +// Flat map projection +static class LonLatProjection extends Projection { + boolean complete = false; // whether the projection will always scale such that the whole longitude spectrum is shown + LonLatProjection(int NN) { this(NN, false); } + LonLatProjection(int NN, boolean complete) { super(NN); this.complete = complete; } + void setPoint(int i, float lat, float lon) { super.setPoint(i, lon, -lat); } + void endData() { super.endData(); if (complete) { cx = 0; w = 360; } } +} + +// Albers projection +static class AlbersProjection extends Projection { + // float phi0 = 38*PI/180, lam0 = -100*PI/180, phi1 = 23*PI/180, phi2 = 50*PI/180; // for the continental US + float lat[] = null, lon[] = null; // temp arrays (need all lat/lon data to determine Albers parameters) + + AlbersProjection(int NN) { super(NN); } + + void beginData() { super.beginData(); lat = new float[N]; lon = new float[N]; } + + // collect points in temporary arrays + void setPoint(int i, float lat, float lon) { this.lat[i] = lat; this.lon[i] = lon; } + + // determine parameters and project the points + void endData() { + float minlat = min(lat), maxlat = max(lat), dlat = maxlat - minlat; + float minlon = min(lon), maxlon = max(lon); + float phi0 = (minlat + maxlat)/2*PI/180, lam0 = (minlon + maxlon)/2*PI/180; // projection origin + float phi1 = (minlat + dlat/6)*PI/180, phi2 = (maxlat - dlat/6)*PI/180; // standard parallels + float n = 0.5*(sin(phi1) + sin(phi2)); + float C = cos(phi1)*cos(phi1) + 2*n*sin(phi1); + float rho0 = sqrt(C - 2*n*sin(phi0))/n; + float rho, theta; + for (int i = 0; i < N; i++) { + rho = sqrt(C - 2*n*sin(lat[i]*PI/180))/n; + theta = n*(lon[i]*PI/180 - lam0); + super.setPoint(i, rho*sin(theta), -(rho0 - rho*cos(theta))); + } + super.endData(); + lat = null; lon = null; + } +} + + + diff --git a/SPaTo_Visual_Explorer.pde b/SPaTo_Visual_Explorer.pde new file mode 100644 index 0000000..1ebfb5d --- /dev/null +++ b/SPaTo_Visual_Explorer.pde @@ -0,0 +1,258 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import processing.pdf.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.prefs.Preferences; +import java.text.SimpleDateFormat; + +String version = "1.2.2"; +String versionDebug = "beta"; +String versionTimestamp = "20110604T220000"; +String versionDate = new SimpleDateFormat("MMMM d, yyyy", Locale.US).format(parseISO8601(versionTimestamp)); + +ExecutorService worker = Executors.newSingleThreadExecutor(); +Preferences prefs = Preferences.userRoot().node("/net/spato/SPaTo_Visual_Explorer"); +boolean canHandleOpenFileEvents = false; // indicates that GUI and workspace are ready to open files + +float t, tt, dt; // this frame's time, last frame's time, and delta between the two +boolean screenshot = false; // if true, draw() will render one frame to PDF + +boolean resizeRequest = false; +int resizeWidth, resizeHeight; + +void setup() { + setupPlatformMagic(); + checkForUpdates(false); + // start caching PDF fonts in a new thread (otherwise the program might stall for up + // to a minute or more when taking the first screenshot) + Thread th = new Thread(new Runnable() { + public void run() { PGraphicsPDF.listFonts(); } + }, "PDF Font Caching"); + th.setPriority(Thread.MIN_PRIORITY); + th.start(); + // setup window + int w = prefs.getInt("window.width", 1280); + int h = prefs.getInt("window.height", 720); + if (w > screen.width) { w = screen.width; h = 9*w/16; } + if (h > screen.height) { h = (int)round(0.9*screen.height); w = 16*h/9; } + size(w, h); + frame.setTitle("SPaTo Visual Explorer " + version + ((versionDebug.length() > 0) ? " (" + versionDebug + ")" : "")); + frame.setResizable(true); + for (java.awt.event.ComponentListener cl : getComponentListeners()) + if (cl.getClass().getName().startsWith("processing.core.PApplet")) + removeComponentListener(cl); // ouch, all of this is so hacked... + addComponentListener(new java.awt.event.ComponentAdapter() { + public void componentResized(java.awt.event.ComponentEvent e) { + java.awt.Component comp = e.getComponent(); + // ensure minimum size + int cw = comp.getWidth(), ch = comp.getHeight(), fw = frame.getWidth(), fh = frame.getHeight(); + int minWidth = 500, minHeight = 500; + if ((cw < minWidth) || (ch < minHeight)) { + if (cw < minWidth) { fw += (minWidth - cw); cw = minWidth; } + if (ch < minHeight) { fh += (minHeight - ch); ch = minHeight; } + comp.setPreferredSize(new Dimension(cw, ch)); + frame.pack(); + } + // request applet resizing (duplicating code from PApplet) + resizeRequest = true; resizeWidth = cw; resizeHeight = ch; + // save new size in preferences + prefs.putInt("window.width", cw); prefs.putInt("window.height", ch); + } + }); + addMouseWheelListener(new java.awt.event.MouseWheelListener() { + public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { + mouseWheel(evt.getWheelRotation()); } }); + smooth(); + randomSeed(second() + 60*minute() + 3600*hour()); + // setup GUI + guiSetup(); + guiUpdate(); + // go + tt = millis()/1000.; + if (prefs.getBoolean("workspace.auto-recover", false)) + replaceWorkspace(XMLElement.parse(prefs.get("workspace", ""))); + canHandleOpenFileEvents = true; +} + +void focusGained() { loop(); } +void focusLost() { if (!fireworks) noLoop(); } + +void draw() { + if (resizeRequest) { resizeRenderer(resizeWidth, resizeHeight); resizeRequest = false; } // handle resize (duplicated from PApplet.run()) + t = millis()/1000.; dt = t - tt; tt = t; + if (fireworks && fw.alpha == 1) { fw.draw(); return; } + // prepare drawing + if (screenshot) { + String filename = "SVE_screenshot_" + (new SimpleDateFormat("yyyyMMdd'T'HHmmss").format(new Date())) + ".pdf"; + filename = System.getProperty("user.home") + ((platform == MACOSX) ? "/Desktop" : "") + File.separator + filename; + beginRecord(PDF, filename); + fastNodes = false; // always draw circles in screenshots + console.logNote("Recording screenshot to " + filename); + } else + background(255); + // draw + if (doc != null) + doc.view.draw(); + // post-drawing stuff + if (screenshot) { + endRecord(); + screenshot = false; + } + guiFastUpdate(); + if (searchMsg != null) { + textFont(fnMedium); noStroke(); + fill(searchMsg.startsWith("E") ? 255 : 0, 0, 0); + TransparentGUI.Point p = tfSearch.getLocationOnScreen(); + text(searchMsg.substring(1), p.x, p.y + tfSearch.getHeight() + 15); + } + // fireworks transition drawing and finishing + if (fireworks) { + fw.draw(); + if (fw.finished && (fw.alpha == 0)) + disposeFireworks(); + } +} + +boolean dragged = false; + +void mouseReleased() { + if (fireworks) return; + if (dragged) { dragged = false; return; } + if (mouseEvent.isConsumed()) return; + if (doc == null) return; + switch (mouseButton) { + case LEFT: + doc.view.setRootNode(doc.view.ih); break; + case RIGHT: + if ((doc.view.viewMode == SVE2View.VIEW_MAP) && btnTom.isEnabled()) + btnTom.handleMouseClicked(); + else if ((doc.view.viewMode == SVE2View.VIEW_TOM) && btnMap.isEnabled()) + btnMap.handleMouseClicked(); + } +} + +void mouseDragged() { + if (fireworks) return; + dragged = true; + if (mouseEvent.isConsumed()) return; + if (doc == null) return; + if (mouseButton == LEFT) { + doc.view.xoff[doc.view.viewMode] += mouseX - pmouseX; + doc.view.yoff[doc.view.viewMode] += mouseY - pmouseY; + } else if (mouseButton == RIGHT) { + float refX = width/2 + doc.view.xoff[doc.view.viewMode]; + float refY = height/2 + doc.view.yoff[doc.view.viewMode]; + changeZoom(dist(refX, refY, mouseX, mouseY)/dist(refX, refY, pmouseX, pmouseY)); + } +} + +boolean isAltDown = false; + +void keyPressed() { + if (fireworks) { + if (keyCode == ESC) disposeFireworks(); + return; + } + isAltDown = keyEvent.isAltDown(); + if (keyEvent.isConsumed()) return; + if (keyEvent.isControlDown() || keyEvent.isMetaDown()) { + if (keyEvent.isAltDown()) { // FIXME: All this could be handled by TPopupMenu + switch (keyEvent.getKeyCode()) { + case KeyEvent.VK_O: actionPerformed("workspace##open"); return; + case KeyEvent.VK_S: if (docs.size() > 0) actionPerformed("workspace##save" + (keyEvent.isShiftDown() ? "As" : "")); return; + case KeyEvent.VK_F: startFireworks(); return; + } + return; + } + switch (keyEvent.getKeyCode()) { + case KeyEvent.VK_N: actionPerformed("document##new"); return; + case KeyEvent.VK_O: actionPerformed("document##open"); return; + case KeyEvent.VK_S: if (doc != null) actionPerformed("document##save" + (keyEvent.isShiftDown() ? "As" : "")); return; + case KeyEvent.VK_W: if (doc != null) actionPerformed("document##close"); return; + } + return; + } + switch (key) { + case '{': linkLineWidth = max(0.25, linkLineWidth - 0.25); console.logNote("Link line width is now " + linkLineWidth); return; + case '}': linkLineWidth = min(1, linkLineWidth + 0.25); console.logNote("Link line width is now " + linkLineWidth); return; + } + if (doc == null) return; + if (keyEvent.isAltDown()) switch (keyCode) { + case 91/*{*/: doc.view.nodeSizeFactor = max(0.05, doc.view.nodeSizeFactor/1.5); console.logNote("Node size factor is now " + doc.view.nodeSizeFactor); return; + case 93/*}*/: doc.view.nodeSizeFactor = min(2.00, doc.view.nodeSizeFactor*1.5); console.logNote("Node size factor is now " + doc.view.nodeSizeFactor); return; + } + switch (key) { + case '=': doc.view.zoom[doc.view.viewMode] = 1; doc.view.xoff[doc.view.viewMode] = doc.view.yoff[doc.view.viewMode] = 0; return; + case '[': changeZoom(.5); return; + case ']': changeZoom(2); return; + case 's': screenshot = true; return; + case 'r': // random walk + //if (doc.view.hasLinks && (doc.view.links.index[doc.view.r].length > 0)) + // doc.view.setRootNode(doc.view.links.index[doc.view.r][floor(random(doc.view.links.index[doc.view.r].length))]); + //else + doc.view.setRootNode(floor(random(doc.view.NN))); + return; + case '@': if (doc.view.hasNodes && (doc.view.ih != -1)) doc.view.nodes[doc.view.ih].showLabel = !doc.view.nodes[doc.view.ih].showLabel; return; + } + if (doc.getAlbum() != null) switch (key) { + case 'A': doc.setSelectedSnapshot(doc.getAlbum(), -1, true); guiUpdateAlbumControls(); return; + case 'a': doc.setSelectedSnapshot(doc.getAlbum(), +1, true); guiUpdateAlbumControls(); return; + } + if ((doc.getSelectedQuantity() != null) && + (doc.getSelectedSnapshot(doc.getSelectedQuantity()) != doc.getSelectedQuantity())) switch (key) { + case '<': doc.setSelectedSnapshot(doc.getSelectedQuantity(), -10, true); return; + case '>': doc.setSelectedSnapshot(doc.getSelectedQuantity(), +10, true); return; + } +} + +void keyReleased() { + isAltDown = keyEvent.isAltDown(); +} + +// Overriding exit() to prevent program being closed by ESC or Ctrl/Cmd-W. This is somewhat stupidly hacked... +void exit() { + if ((keyEvent != null) && + ((key == KeyEvent.VK_ESCAPE) || ((keyEvent.getModifiers() == MENU_SHORTCUT) && (keyEvent.getKeyCode() == 'W')))) + return; // looks like exit() was called upon hitting these keys; but we don't want that + super.exit(); +} + +void mouseWheel(int delta) { + if (fireworks) return; + if ((gui.componentAtMouse == null) && (gui.componentMouseClicked == null)) + changeZoom((delta < 0) ? (1 - .05*delta) : 1/(1 + .05*delta)); +} + +void changeZoom(float f) { + if (doc == null) return; + f = max(f, 1/doc.view.zoom[doc.view.viewMode]); // do not allow zoom < 1 + f = min(f, 10/doc.view.zoom[doc.view.viewMode]); // do not allow zoom > 10 + doc.view.zoom[doc.view.viewMode] *= f; + doc.view.xoff[doc.view.viewMode] *= f; + doc.view.yoff[doc.view.viewMode] *= f; +} + +void checkForUpdates(boolean force) { + if (force) prefs.remove("update.skip"); + if (prefs.getBoolean("update.check", true) || force) + new Updater(force).start(); +} diff --git a/SVE2Document.pde b/SVE2Document.pde new file mode 100644 index 0000000..fa0be38 --- /dev/null +++ b/SVE2Document.pde @@ -0,0 +1,818 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.FloatBuffer; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +int untitledCounter = 0; // counter for uniquely numbering untitled documents + +/* + * Visual Explorer Document / Data Provider + */ + +class SVE2Document { + + XMLElement xmlDocument = new XMLElement("document"); + SVE2View view = null; + + File file = null; // corresponding file on disk + String name = null; // short name (basename of file or "") + boolean compressed = false; // is this document in a zip archive or in a directory? + ZipFile zipfile = null; + ZipOutputStream zipout = null; + + boolean modified = false; + + HashMap blobCache = new HashMap(); + + SVE2Document() { this(null); } + SVE2Document(File file) { setFile(file); this.view = new SVE2View(this); } + + /* + * Metadata Accessors + */ + + File getFile() { return file; } + void setFile(File file) { + // assume it's a zip archive if it's not a directory; create zip files by default + setFile(file, (file == null) || !file.isDirectory()); + } + void setFile(File file, boolean compressed) { + try { this.file = file.getCanonicalFile(); } // try to normalize file path (remove "../" etc.) + catch (Exception e) { this.file = file; } // otherwise use original file + this.compressed = compressed; + this.name = null; // reset name + } + + boolean isCompressed() { return compressed; } + void setCompressed(boolean compressed) { this.compressed = compressed; } + void setCompressed() { setCompressed(true); } + + boolean isModified() { return modified; } + + String getName() { + if (name == null) { + if (file != null) { + name = file.getName(); // strip directory part + if (name.endsWith(".spato")) name = name.substring(0, name.length()-6); // strip .spato extension + } else + name = ""; + } + return name; + } + + String getTitle() { + XMLElement xmlTitle = xmlDocument.getChild("title"); + if (xmlTitle != null) { + String title = xmlTitle.getContent(); + if (title != null) + return trim(title); + } + return "Untitled Network"; + } + + String getDescription() { + XMLElement xmlDescription = xmlDocument.getChild("description"); + if (xmlDescription != null) { + String desc = xmlDescription.getContent(); + if (desc != null) + return join(trim(split(desc, '\n')), '\n'); + } + return ""; + } + + /* + * Data Accessors + */ + + XMLElement getNodes() { return xmlDocument.getChild("nodes"); } + XMLElement getNode(int i) { return getChild("nodes/node[" + i + "]"); } + int getNodeCount() { return getChildren("nodes/node").length; } + + XMLElement getAlbum() { return xmlDocument == null ? null : xmlDocument.getChild("album"); } // FIXME: concurrency problems... + XMLElement[] getAlbums() { return xmlDocument.getChildren("album"); } + XMLElement getAlbum(String id) { return getChild("album[@id=" + id + "]"); } + + XMLElement getLinks() { return xmlDocument.getChild("links"); } + + XMLElement getSlices() { return xmlDocument.getChild("slices"); } + + XMLElement[] getDatasets() { return xmlDocument.getChildren("dataset"); } + XMLElement getDataset(String id) { return getChild("dataset[@id=" + id + "]"); } + + XMLElement[] getAllQuantities() { return getChildren("dataset/data"); } + XMLElement[] getQuantities() { return getChildren("dataset[@selected]/data"); } + XMLElement[] getQuantities(XMLElement xmlDataset) { return xmlDataset.getChildren("data"); } + XMLElement getQuantity(XMLElement xmlDataset, String id) { + return getChild(xmlDataset, "data[@id=" + id + "]"); } + + XMLElement[] getDistanceQuantities() { //return getChildren("dataset/data[@blobtype=float[N][N]]"); } + XMLElement res[] = new XMLElement[0]; + for (XMLElement xmlData : getAllQuantities()) + if (getSelectedSnapshot(xmlData).getString("blobtype", "").equals("float[N][N]")) + res = (XMLElement[])append(res, xmlData); + return res; + } + + XMLElement getSelectedDataset() { return getChild("dataset[@selected]"); } + XMLElement getSelectedQuantity() { return getChild("dataset[@selected]/data[@selected]"); } + XMLElement getSelectedQuantity(XMLElement xmlDataset) { + return getChild(xmlDataset, "data[@selected]"); } + + void setSelectedDataset(XMLElement xmlDataset) { + XMLElement xmlOldDataset = getSelectedDataset(); + if ((xmlDataset != null) && (xmlDataset == xmlOldDataset)) + return; // nothing to do + if (xmlOldDataset != null) // unselect previously selected dataset + xmlOldDataset.remove("selected"); + if (xmlDataset != null) { // select new dataset and make sure some quantity in it is selected + xmlDataset.setBoolean("selected", true); + if (getSelectedQuantity(xmlDataset) == null) + setSelectedQuantity(xmlDataset.getChild("data")); + } + view.setNodeColoringData(getSelectedQuantity()); + } + + void setSelectedQuantity(XMLElement xmlData) { + XMLElement xmlOldData = getSelectedQuantity(); + if ((xmlData != null) && (xmlData == xmlOldData)) + return; // nothing to do + if ((xmlOldData != null) && ((xmlData == null) || (xmlOldData.getParent() == xmlData.getParent()))) + xmlOldData.remove("selected"); // only unselect previous quantity if it's in the same dataset + if (xmlData != null) { // select new quantity and make sure the correct dataset is selected + xmlData.setBoolean("selected", true); + setSelectedDataset(xmlData.getParent()); + } + view.setNodeColoringData(xmlData); + guiUpdateNodeColoring(); + } + + XMLElement getDistanceQuantity() { return getChild("dataset/data[@distmat]"); } + + void setDistanceQuantity(XMLElement xmlData) { + if ((xmlData != null) && (xmlData == view.xmlDistMat)) + return; // nothing to do + if (view.xmlDistMat != null) view.xmlDistMat.remove("distmat"); + view.setDistanceMatrix(xmlData); + if (xmlData != null) xmlData.setBoolean("distmat", true); + guiUpdateProjection(); + } + + /* + * Snapshot Handling + */ + + XMLElement getSelectedSnapshot(XMLElement xml) { return getSelectedSnapshot(xml, true); } + XMLElement getSelectedSnapshot(XMLElement xml, boolean recursive) { + if ((xml == null) || (xml.getChild("snapshot") == null)) + return xml; // the snapshots are not strong in this one... + XMLElement result = null; + String album = xml.getChild("snapshot").getString("album"); + if (album == null) { // this is a snapshot series, which means it's easy to find the selected snapshot + result = getChild(xml, "snapshot[@selected]"); + if (result == null) { // looks like we're missing a 'selected' attribute... + result = xml.getChild("snapshot"); // ... so select the first one as default + if (result != null) xml.setBoolean("selected", true); + } + } else { // ... otherwise we have to do some more work + XMLElement xmlAlbum = getChild("album[@id=" + album + "]"); + if (xmlAlbum == null) // this should not happen... + console.logError("Could not find album \u2018" + album + "\u2019, referenced in " + xml.getName() + + " \u201C" + xml.getString("name", xml.getString("id")) + "\u201D"); + else { + XMLElement xmlSnapshot = getChild(xmlAlbum, "snapshot[@selected]"); + if (xmlSnapshot == null) { // no snapshot is selected, try to select first one + xmlSnapshot = xmlAlbum.getChild("snapshot"); + if (xmlSnapshot != null) xmlSnapshot.setBoolean("selected", true); + } + if (xmlSnapshot != null) + result = getChild(xml, "snapshot[@id=" + xmlSnapshot.getString("id") + "]"); + } + } + return recursive ? getSelectedSnapshot(result) : result; + } + + /** Returns the XML element containing the appropriate anonymous snapshot series (if any) of xml. */ + XMLElement getSelectedSnapshotSeriesContainer(XMLElement xml) { + while ((xml != null) && (xml.getChild("snapshot") != null) && (xml.getChild("snapshot").getString("album") != null)) + xml = getSelectedSnapshot(xml, false); + return ((xml == null) || (xml.getChild("snapshot") == null)) ? null : xml; + } + + /** Returns the index of the currently selected snapshot in an album or an anonymous snapshot series. */ + int getSelectedSnapshotIndex(XMLElement xml) { + if (xml == null) return -1; + if (!xml.getName().equals("album")) + xml = getSelectedSnapshotSeriesContainer(xml); + XMLElement snapshots[] = xml.getChildren("snapshot"); + if (snapshots == null) return -1; + for (int i = 0; i < snapshots.length; i++) + if (snapshots[i].getBoolean("selected")) + return i; + if (snapshots.length > 0) { // no snapshot marked as selected? + snapshots[0].setBoolean("selected", true); // then mark the first one + return 0; + } + return -1; + } + + void setSelectedSnapshot(XMLElement xml, int index) { setSelectedSnapshot(xml, index, false); } + void setSelectedSnapshot(XMLElement xml, int index, boolean relative) { + boolean isAlbum = xml.getName().equals("album"); + if (!isAlbum) + xml = getSelectedSnapshotSeriesContainer(xml); + // find currently selected snapshot + XMLElement snapshots[] = xml.getChildren("snapshot"); + if (snapshots == null) return; // should not happen + int selectedIndex = 0; + for (int i = snapshots.length - 1; i >= 0; i--) { + if (snapshots[i].getBoolean("selected")) selectedIndex = i; + snapshots[i].remove("selected"); + } + // update currently selected snapshot + selectedIndex = relative ? selectedIndex + index : index; + while (selectedIndex < 0) selectedIndex += snapshots.length; + while (selectedIndex >= snapshots.length) selectedIndex -= snapshots.length; + snapshots[selectedIndex].setBoolean("selected", true); + // update view and GUI + if (isAlbum || (xml == getLinks())) { view.setLinks(getLinks()); } + if (isAlbum || (xml == getSlices())) { + view.setSlices(getSlices()); view.setTomLayout(); + view.setDistanceMatrix(getDistanceQuantity()); + /* FIXME: layout handling is bad... */ } + if (isAlbum || (xml == getSelectedQuantity())) { view.setNodeColoringData(getSelectedQuantity()); guiUpdateNodeColoring(); } + if (isAlbum || (xml == getDistanceQuantity())) { view.setDistanceMatrix(getDistanceQuantity()); guiUpdateProjection(); } + } + + XMLElement getColormap(XMLElement xml) { + xml = getSelectedSnapshot(xml); + while ((xml != null) && (xml.getChild("colormap") == null) && (xml.getName().equals("snapshot"))) + xml = xml.getParent(); + return (xml != null) ? xml.getChild("colormap") : null; + } + + /* + * Binary Cache Accessors + */ + + BinaryThing getBlob(XMLElement xml) { + xml = getSelectedSnapshot(xml); + if (xml == null) return null; + BinaryThing blob = null; + if (!blobCache.containsKey(xml)) { + String xmlPretty = xml.getString("name", ""); + if (xmlPretty.length() > 0) xmlPretty = " \u201C" + xmlPretty + "\u201D"; + xmlPretty = xml.getName() + xmlPretty; + String name = xml.getString("blob"); + InputStream stream = null; + try { + TConsole.Message msg = console.logProgress((name != null) + ? "Loading " + xmlPretty + " from blob " + name + : "Parsing " + xmlPretty); + if (name != null) { + if ((stream = createDocPartInput("blobs" + File.separator + name)) != null) + blob = BinaryThing.loadFromStream(new DataInputStream(stream), msg); + } else + blob = BinaryThing.parseFromXML(xml, msg); + console.finishProgress(); + } catch (Exception e) { + console.abortProgress("Error: ", e); + } + blobCache.put(xml, blob); + } + blob = blobCache.get(xml); + if (blob != null) + xml.setString("blobtype", getBlobType(blob)); + return blob; + } + + /* This is used to ensure a set of blobs is loaded. */ + void loadBlobs(XMLElement xml) { loadBlobs(new XMLElement[] { xml }); } + void loadBlobs(XMLElement xml[]) { + if (xml == null) return; + for (int i = 0; i < xml.length; i++) { + XMLElement snapshots[] = xml[i].getChildren("snapshot"); + if ((snapshots != null) && (snapshots.length > 0)) + loadBlobs(snapshots); // load all snapshots (xml[i] holds no valid data) + else + getBlob(xml[i]); // getBlob will load/parse the data if not already cached + } + } + + void setBlob(XMLElement xml, Object blob) { setBlob(xml, blob, false); } + void setBlob(XMLElement xml, Object blob, boolean persistent) { + if ((xml == null) || (blob == null)) return; + BinaryThing bt = new BinaryThing(blob); + blobCache.put(xml, bt); + xml.setString("blobtype", getBlobType(bt)); + if (persistent) { + String blobname = xml.getString("id", generateID(xml.getString("label"))); + XMLElement tmp = xml; + while ((tmp != null) && (tmp.getName().equals("snapshot"))) + blobname = (tmp = tmp.getParent()).getString("id", generateID()) + "_" + blobname; + xml.setString("blob", blobname); + } else + xml.remove("blob"); + } + + /* This functions removes all stuff from the xml element that can be reproduced from the elements blob. */ + // FIXME: this is not used at the moment; offer a choiceQuantity context menu item to call this + void stripXMLData(XMLElement xml) { + XMLElement child = null; + if (xml.getName().equals("slices")) + while ((child = xml.getChild("slice")) != null) + xml.removeChild(child); + if (xml.getName().equals("data")) + while ((child = xml.getChild("values")) != null) + xml.removeChild(child); + // FIXME: handle links and snapshots + } + + /* This returns a short description of the blob type/shape. */ + String getBlobType(BinaryThing blob) { + String s = blob.toString(); + s = s.replaceAll("([^0-9])" + getNodeCount() + "([^0-9])", "$1N$2"); + s = s.replaceAll("([^0-9])[23456789][0-9]*([^0-9])", "$1M$2"); // FIXME: replaces M for any number + return s; + } + + /* + * Document Modification + */ + + void addDataset(XMLElement xmlDataset) { + xmlDocument.removeChild(xmlDataset); // avoid having it in there twice + if (xmlDataset.getString("id") == null) + xmlDataset.setString("id", generateID()); + xmlDocument.addChild(xmlDataset); + guiUpdateNodeColoring(); + } + + void removeDataset(XMLElement xmlDataset) { + for (XMLElement xmlData : xmlDataset.getChildren("data")) + removeQuantity(xmlData); + if (xmlDataset.getBoolean("selected")) + setSelectedDataset((XMLElement)previousOrNext(getDatasets(), xmlDataset)); + xmlDataset.getParent().removeChild(xmlDataset); + guiUpdateNodeColoring(); + } + + void addQuantity(XMLElement xmlDataset, XMLElement xmlData) { addQuantity(xmlDataset, xmlData, null); } + void addQuantity(XMLElement xmlDataset, XMLElement xmlData, Object blob) { + xmlDataset.removeChild(xmlData); // make sure we won't add an already existing quantity + if (xmlData.getString("id") == null) xmlData.setString("id", generateID()); + xmlDataset.addChild(xmlData); + if (blob != null) doc.setBlob(xmlData, blob, true); + guiUpdateNodeColoring(); + guiUpdateProjection(); + } + + void removeQuantity(XMLElement xmlData) { + if (xmlData == view.xmlDistMat) + view.setDistanceMatrix((XMLElement)previousOrNext(getDistanceQuantities(), xmlData)); + xmlData.getParent().removeChild(xmlData); + if (xmlData.getBoolean("selected")) + setSelectedQuantity((XMLElement)previousOrNext(getQuantities(), xmlData)); + } + + /* + * Loading/Saving Functions + */ + + Runnable newLoadingTask() { + return new Runnable() { + public void run() { loadFromDisk(); } + }; + } + + Runnable newSavingTask() { + return new Runnable() { + public void run() { saveToDisk(); } + }; + } + + void loadFromDisk(File file) { setFile(file); loadFromDisk(); } + void loadFromDisk() { + TConsole.Message msg = console.logInfo("Loading from " + file.getAbsolutePath()).sticky(); + // open zipfile or make sure the directory exists + try { + if (compressed) zipfile = new ZipFile(file); + else if (!file.exists()) throw new IOException("directory not found"); + } catch (Exception e) { + console.logError("Error opening '" + file.getAbsolutePath() + "': ", e); + console.popSticky(); + return; + } + // read XML document + if ((xmlDocument = addAutoIDs(readMultiPartXML("document.xml"))) != null) { + // setup nodes and map projection + XMLElement xmlNodes = getNodes(); + if ((xmlNodes == null) || (getNodeCount() == 0)) + console.logError("No nodes found"); + else { + view.setNodes(xmlNodes); + view.setMapProjection(xmlNodes.getChild("projection")); + } + guiUpdateAlbumControls(); + // setup links + view.setLinks(getLinks()); + if (getLinks() != null) + loadBlobs(getLinks()); // make sure all links snapshots are loaded + // setup data + view.setNodeColoringData(getSelectedQuantity()); + loadBlobs(getAllQuantities()); // make sure all data is loaded + guiUpdateNodeColoring(); + // setup slices + view.setSlices(getSlices()); + loadBlobs(getSlices()); // make sure all slices snapshots are loaded + generateLayouts(getSlices()); // FIXME + // setup tomogram layout + view.tomLayouts = xmlDocument.getString("tomLayouts", null); // FIXME: layouts should be specified by tags or something + view.setTomLayout(); + view.setDistanceMatrix(getDistanceQuantity()); + guiUpdateProjection(); + } + // clean-up and done + if (compressed) { try { zipfile.close(); } catch (Exception e) {}; zipfile = null; } + console.popSticky(); + msg.text += " \u2013 done"; + } + void generateLayouts(XMLElement xml) { // FIXME + if (xml.getChild("snapshot") != null) // FIXME + for (XMLElement snapshot : xml.getChildren("snapshot")) // FIXME + generateLayouts(snapshot); // FIXME + else // FIXME + new Layout(getBlob(xml).getIntArray(), "radial_id"); // FIXME: the horror! + } // FIXME + + void saveToDisk() { + TConsole.Message msg = console.logInfo("Saving to " + file.getAbsolutePath()).sticky(); + // open zipout or make sure the directory exists + try { + if (compressed) { + if (file.exists() && file.isDirectory()) + if (!clearDirectory(file) || !file.delete()) // remove directory to be able to create regular file + throw new IOException("is a directory and could not be deleted"); + zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file))); + zipout.setLevel(9); + } else { + if (file.exists() && !file.isDirectory()) + if (!file.delete()) // remove regular file to be able to create directory + throw new IOException("file already exists and could not be deleted"); + file.mkdirs(); + if (!clearDirectory(file)) + throw new IOException("could not clear the directory"); + } + } catch (Exception e) { + console.logError("Error opening '" + file.getAbsolutePath() + "': ", e); + console.popSticky(); + return; + } + // write XML document + writeMultiPartXML("document.xml", xmlDocument); + // write persistent blobs + Iterator xmlit = blobCache.keySet().iterator(); + while (xmlit.hasNext()) { + XMLElement xml = xmlit.next(); + String name = xml.getString("blob"); + if (name == null) continue; // not a persistant BinaryThing + if (!compressed) new File(file, "blobs").mkdirs(); + OutputStream stream = createDocPartOutput("blobs" + File.separator + name); + if (stream != null) try { + String xmlPretty = xml.getString("name", ""); + if (xmlPretty.length() > 0) xmlPretty = " \u201C" + xmlPretty + "\u201D"; + xmlPretty = xml.getName() + xmlPretty; + TConsole.Message msgBlob = console.logProgress("Saving " + xmlPretty + " to blob " + name); + blobCache.get(xml).saveToStream(new DataOutputStream(stream), msgBlob); + console.finishProgress(); + if (!compressed) stream.close(); + } catch (Exception e) { console.abortProgress("Error saving blob " + name + ": ", e); } + } + // clean-up and done + if (compressed) { try { zipout.close(); } catch (Exception e) {}; zipout = null; } + console.popSticky(); + msg.text += " \u2013 done"; + } + + InputStream createDocPartInput(String name) { + InputStream stream = null; + if (compressed) { + name = name.replace(File.separatorChar, '/'); // always use / as file separator in zip files + try { stream = zipfile.getInputStream(zipfile.getEntry(name)); } + catch (Exception e) { stream = null; } + } else + stream = createInput(new File(file, name).getAbsolutePath()); + if (stream == null) + console.logError("Could not find or read '" + name + "' in '" + file.getAbsolutePath() + "'"); + return new BufferedInputStream(stream); + } + + OutputStream createDocPartOutput(String name) { + OutputStream stream = null; + if (compressed) { + name = name.replace(File.separatorChar, '/'); // always use / as file separator in zip files + try { zipout.putNextEntry(new ZipEntry(name)); stream = zipout; } + catch (Exception e) { stream = null; } + } else + stream = createOutput(new File(file, name).getAbsolutePath()); + if (stream == null) + console.logError("Error opening '" + name + "' in '" + file.getAbsolutePath() + "' for writing"); + return compressed ? stream : new BufferedOutputStream(stream); // zipout is already buffered + } + + Reader createDocPartReader(String name) { + try { return new InputStreamReader(createDocPartInput(name)); } catch (Exception e) { return null; } } + Writer createDocPartWriter(String name) { + try { return new OutputStreamWriter(createDocPartOutput(name)); } catch (Exception e) { return null; } } + + /* Copy of processing.xml.XMLElement.parseFromReader(...), modified to fit our needs (i.e., catch parsing + * exceptions and return null instead of silently ignoring and returning a crippled document). */ + XMLElement readXML(String name) { + Reader reader = new File(name).isAbsolute() ? createReader(name) : createDocPartReader(name); + if (reader == null) return null; + XMLElement xml = new XMLElement(); + try { + console.logProgress("Parsing " + name).indeterminate(); + StdXMLParser parser = new StdXMLParser(); + parser.setBuilder(new StdXMLBuilder(xml)); + parser.setValidator(new XMLValidator()); + parser.setReader(new StdXMLReader(reader)); + parser.parse(); + console.finishProgress(); + } catch (Exception e) { + console.abortProgress("XML parsing error in " + name + ": ", e); + xml = null; + } + try { reader.close(); } catch (Exception e) { } + return xml; + } + + void writeXML(String name, XMLElement xml) { + Writer writer = new File(name).isAbsolute() ? createWriter(name) : createDocPartWriter(name); + if (writer == null) return; + try { + console.logProgress("Writing " + name).indeterminate(); + writer.write("\n"); + new XMLWriter(writer).write(xml, true); + if (!compressed) writer.close(); // we're directly writing into the zipfile, which will be closed by saveToDisk + console.finishProgress(); + } catch (Exception e) { + console.abortProgress("XML writing error in " + name + ": ", e); + } + } + + /* This function reads the XML document found in file specified by name. It then traverses + * all child tags and wherever it finds a "src" attribute it will interpret its value as + * a URI (absolute or relative to the document base) of an additional XML file. That file is + * parsed and searched for a tag (either top-level or child of top-level) that matches the + * tag in the original document in name and (if existent) "id" attribute value. If a match is + * found, the tag from the external document is merged into the tag in the original document, + * that is, tag attributes are added and the tag's children are appended to the original tag's + * children. The returned XMLElement is the merged full document. + */ + XMLElement readMultiPartXML(String name) { + XMLElement doc = readXML(name); + if (doc == null) return null; + for (int i = 0; i < doc.getChildCount(); i++) { + XMLElement child = doc.getChild(i); + // load external XML document + String src = child.getString("src"); + if (src == null) continue; + XMLElement idoc = readXML(src); + if (idoc == null) continue; + // find the matching node to merge into the original document + XMLElement merge = equalNameAndID(child, idoc, true) ? idoc : null; + if (merge == null) + for (int j = 0; j < idoc.getChildCount(); j++) + if (equalNameAndID(child, idoc.getChild(j), false)) + merge = idoc.getChild(j); + if (merge == null) { + console.logError(child.getName() + ": no match found in " + src); + continue; + } + // merge node with 'child' + String[] attr = merge.listAttributes(); + for (int j = 0; j < attr.length; j++) + if (!attr[j].equals("src")) + child.setString(attr[j], merge.getString(attr[j])); + XMLElement[] children = merge.getChildren(); + for (int j = 0; j < children.length; j++) + child.addChild(children[j]); + } + return doc; + } + + /* Being the counterpart to readMultiPartXML, this function traverses the children of the document doc + * to extract all parts which should go into a separate file. The first child with a "src" attribute + * that is not already recorded in the map will be replaced by a new element that has the same tag name, + * same "id" attribute (if applicable), and the same "src" attribute (as a hint for subsequent reading from disk). + * The "src" value and the extracted element are added to the hash map and the function calls itself recursively. + * Afterwards, the removed element is re-added into the document. If no such children are found, + * the remaining document is written to the file specified by name, and all extracted children to their + * respective files. */ + void writeMultiPartXML(String name, XMLElement doc) { writeMultiPartXML(name, doc, null); } + void writeMultiPartXML(String name, XMLElement doc, HashMap map) { + if (doc == null) return; + if (map == null) map = new HashMap(); + int iChild = -1; XMLElement child = null; String src = null; + for (int i = 0; i < doc.getChildCount(); i++) { + child = doc.getChild(i); + src = child.getString("src"); + if ((src != null) && notInMap(map, src, child)) { iChild = i; break; } + } + if (iChild == -1) { + // write doc to name + writeXML(name, doc); + // write all extracted children to their respective files + Object srcs[] = map.keySet().toArray(); + for (int i = 0; i < srcs.length; i++) { + XMLElement[] elems = map.get(srcs[i]); + XMLElement out = new XMLElement("includes"); + for (int j = 0; j < elems.length; j++) elems[j].remove("src"); + if (elems.length == 1) + out = elems[0]; // no need to wrap into another element if we write only one anyway + else for (int j = 0; j < elems.length; j++) + out.addChild(elems[j]); + writeXML((String)srcs[i], out); + for (int j = 0; j < elems.length; j++) elems[j].setString("src", (String)srcs[i]); + } + } else { + // add child to map + if (!map.containsKey(src)) map.put(src, new XMLElement[0]); + map.put(src, (XMLElement[])append(map.get(src), child)); + // extract from doc + XMLElement childPlaceholder = new XMLElement(child.getName()); + if (child.getString("id") != null) + childPlaceholder.setString("id", child.getString("id")); + childPlaceholder.setString("src", src); + doc.insertChild(childPlaceholder, iChild); + doc.removeChild(child); + // recurse on doc + writeMultiPartXML(name, doc, map); + // re-insert child + doc.insertChild(child, iChild); + doc.removeChild(childPlaceholder); + } + } + boolean notInMap(HashMap map, String src, XMLElement child) { + if (!map.containsKey(src)) return true; + XMLElement elems[] = map.get(src); + for (int i = 0; i < elems.length; i++) if (equalNameAndID(elems[i], child, false)) return false; + return true; + } + + /* This function traverses the XML document and adds auto-generated id attribute values + * to all links, slices, dataset, and data tags, if they are missing their id attribute. + * Note that this function will alter its argument doc (and return a reference to it). */ + XMLElement addAutoIDs(XMLElement doc) { return addAutoIDs(doc, ""); } + XMLElement addAutoIDs(XMLElement doc, String hashPrefix) { + if (doc == null) return null; + String tags[] = { "links", "slices", "dataset", "data" }; + for (int t = 0; t < tags.length; t++) { + XMLElement elems[] = doc.getChildren(tags[t]); + for (int i = 0; i < elems.length; i++) { + if (elems[i].getString("id") == null) + elems[i].setString("id", generateID(hashPrefix + elems[i].getString("name", ""))); + if (tags[t].equals("dataset")) + addAutoIDs(elems[i], elems[i].getString("id")); + } + } + return doc; + } + + /* + * Small Helper Functions + */ + + /* Returns true if the names of a and b match (or are both null) and if the "id" attributes + * of a and b match. If laxID is true, the test still passes if a has an id attribute but + * b does not. */ + boolean equalNameAndID(XMLElement a, XMLElement b, boolean laxID) { + return (((b.getName() == null) && (a.getName() == null)) || + ((b.getName() != null) && b.getName().equals(a.getName()))) && + (((b.getString("id") == null) && (laxID || (a.getString("id") == null))) || + ((b.getString("id") != null) && b.getString("id").equals(a.getString("id")))); + } + + /* This function will always return a most-probably unique 8-digit hex-character sequence. + * It does so by returning the first 8 characters of the MD5 hash of the argument name, + * or a random sequence if name is null, an empty string, or something goes wrong with MD5. */ + String generateID() { return generateID(null); } + String generateID(String name) { + byte[] digest = new byte[4]; + // generate random 8-byte sequence as a backup + for (int i = 0; i < 4; i++) + digest[i] = (byte)int(random(256)); + // try calculating MD5 hash if name argument is sane + if ((name != null) && !name.equals("")) + try { digest = java.security.MessageDigest.getInstance("MD5").digest(name.getBytes()); } catch (Exception e) { } + // serialize and return whatever we got + String id = ""; + for (int i = 0; i < 4; i++) + id += String.format("%02x", digest[i] & 0xff); + return id; + } + + /* Recursively removes the contents of the specified directory. */ + boolean clearDirectory(File f) throws Exception { + if (!f.isDirectory()) return false; + File ff[] = f.listFiles(); + for (int i = 0; i < ff.length; i++) { + if (ff[i].isDirectory() && !clearDirectory(ff[i])) return false; + if (!ff[i].delete()) return false; + } + return true; + } + + /* If needle is in the array haystack, then the element before needle is returned. + * If needle is the first element in haystack, the element after needle is returned. + * If haystack only contains needle, null is returned. */ + Object previousOrNext(Object haystack, Object needle) { + if ((Array.getLength(haystack) > 1) && (Array.get(haystack, 0) == needle)) + return Array.get(haystack, 1); // return second element if needle is first + for (int i = 1; i < Array.getLength(haystack); i++) + if (Array.get(haystack, i) == needle) + return Array.get(haystack, i - 1); // return element before needle + return null; // needle was not in haystack + } + + /* Evaluates an XPath expression on xmlDocument. Only understands a limited subet of XPath! */ + XMLElement[] getChildren(String path) { return getChildren(xmlDocument, path); } + XMLElement[] getChildren(XMLElement xml, String path) { + XMLElement result[] = new XMLElement[0]; + if ((xml == null) || (path == null)) + return result; + String name = path, conds = "", subpath = null; int p; + if ((p = path.indexOf('/')) > -1) { + name = path.substring(0, p); + subpath = path.substring(p+1); + } + if ((p = name.indexOf('[')) > -1) { + conds = name.substring(p); + name = name.substring(0, p); + } + XMLElement tmp[] = name.equals("*") ? xml.getChildren() : xml.getChildren(name); + int level = 0, i0 = 0; + for (int i = 0; i < conds.length(); i++) { + if (conds.charAt(i) == '[') + if (level++ == 0) i0 = i; + if (conds.charAt(i) == ']') + if (--level == 0) + tmp = xpathFilter(tmp, conds.substring(i0 + 1, i)); + } + if (subpath != null) { + for (int i = 0; i < tmp.length; i++) + result = (XMLElement[])concat(result, getChildren(tmp[i], subpath)); + } else + result = tmp; + return result; + } + + XMLElement getChild(String path) { return getChild(xmlDocument, path); } + XMLElement getChild(XMLElement xml, String path) { + XMLElement result[] = getChildren(xml, path); + return ((result != null) && (result.length > 0)) ? result[0] : null; + } + + XMLElement[] xpathFilter(XMLElement xml[], String condition) { + if (xml == null) + return new XMLElement[0]; + if ((xml.length == 0) || (condition == null) || (condition.length() == 0)) + return xml; + if (condition.charAt(0) == '@') { + int p = condition.indexOf('='); + String attr = (p > -1) ? condition.substring(1, p) : condition.substring(1); + String value = (p > -1) ? condition.substring(p+1) : null; // FIXME: '/" unwrapping + XMLElement result[] = new XMLElement[0]; + for (int i = 0; i < xml.length; i++) { + if (xml[i].getString(attr) == null) continue; + if ((value != null) && !value.equals(xml[i].getString(attr))) continue; + result = (XMLElement[])append(result, xml[i]); + } + return result; + } else + return xml; + } + +} + diff --git a/SVE2GUI.pde b/SVE2GUI.pde new file mode 100644 index 0000000..c7fa595 --- /dev/null +++ b/SVE2GUI.pde @@ -0,0 +1,712 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.awt.event.KeyEvent; + +TransparentGUI gui; +TConsole console; +TTextField tfSearch; +TToggleButton btnRegexpSearch; +TChoiceWithRollover choiceNetwork; +TButton btnWorkspaceRecovery; +TChoice choiceMapProjection, choiceTomProjection, choiceTomScaling, choiceDistMat; +TChoice choiceDataset, choiceQuantity, choiceColormap; +TToggleButton btnColormapLog; +TToggleButton btnNodes, btnLinks, btnSkeleton, btnNeighbors, btnNetwork, btnLabels; +TToggleButton btnMap, btnTom; +NetworkDetailPanel networkDetail; +TLabel lblStatus; +// snapshot controls for node coloring quantity +TButton btnQuantityPrevSnapshot, btnQuantityNextSnapshot; +TSlider sldQuantitySnapshot; +// snapshot controls for album +TLabel lblAlbumName, lblAlbumSnapshot; +TButton btnAlbumPrevSnapshot, btnAlbumNextSnapshot; +TSlider sldAlbumSnapshot; + +int fnsizeSmall = 10, fnsizeMedium = 12, fnsizeLarge = 14; +PFont fnSmall, fnMedium, fnLarge, fnLargeBold; +boolean fastNodes = false; + +boolean searchMatchesValid = false; +boolean searchMatches[] = null; // this is true for nodes which are matched by the search phrase +int searchMatchesChild[] = null; // this is 1 for nodes which have any node in their branch that matches the search phrase +String searchMsg = null; +int searchUniqueMatch = -1; + +void guiSetup() { + gui = new TransparentGUI(this); + fnSmall = gui.createFont("GillSans", fnsizeSmall); + fnMedium = gui.createFont("GillSans", fnsizeMedium); + fnLarge = gui.createFont("GillSans", fnsizeLarge); + fnLargeBold = gui.createFont("GillSans-Bold", fnsizeLarge); + // setup top panel + TPanel panel = gui.createPanel(new TBorderLayout()); + panel.setPadding(5); + choiceMapProjection = gui.createChoice("projMap##"); + choiceMapProjection.add(MapProjectionFactory.productNames); + choiceTomProjection = gui.createChoice("projTom##"); + choiceTomProjection.add(TomProjectionFactory.productNames); + choiceTomScaling = gui.createChoice("scal##"); + choiceTomScaling.add(ScalingFactory.productNames); + choiceDistMat = gui.createChoice("distMat##", true); + choiceDistMat.setNoneString("Tree Depth"); + choiceDistMat.setRenderer(new XMLElementRenderer(true)); + panel.add(gui.createCompactGroup(new TComponent[] { + gui.createLabel("Projection:"), choiceMapProjection }), TBorderLayout.EAST); + panel.add(gui.createCompactGroup(new TComponent[] { + gui.createLabel("Projection:"), choiceTomProjection, choiceTomScaling, choiceDistMat }), TBorderLayout.EAST); + // + tfSearch = gui.createTextField("search"); + tfSearch.setEmptyText("Search"); + btnRegexpSearch = gui.createToggleButton("RegExp", prefs.getBoolean("search.regexp", false)); + panel.add(gui.createCompactGroup(new TComponent[] { tfSearch, btnRegexpSearch }), TBorderLayout.EAST); + // + btnNodes = gui.createToggleButton("Nodes", true); + btnLinks = gui.createToggleButton("Links", true); + btnSkeleton = gui.createToggleButton("Skeleton", false); + btnNeighbors = gui.createToggleButton("Neighbors", false); btnNeighbors.setVisible(false); // enabled but invis for now... + btnNetwork = gui.createToggleButton("Network", false); btnNetwork.setVisible(false); // enabled but invis for now... + btnLabels = gui.createToggleButton("Labels", true); + TPanel linksGroup = gui.createCompactGroup(new TComponent[] { btnLinks, btnSkeleton, btnNeighbors, btnNetwork }, new TComponent.Spacing(0)); + linksGroup.setBorderColor(color(200, 0, 0)); + panel.add(gui.createCompactGroup(new TComponent[] { + gui.createLabel("Show:"), btnNodes, linksGroup, btnLabels }), TBorderLayout.WEST); + // + lblAlbumName = gui.createLabel("Album:"); + btnAlbumPrevSnapshot = gui.createButton("<"); btnAlbumPrevSnapshot.setActionCommand("snapshot##album##prev"); + btnAlbumNextSnapshot = gui.createButton(">"); btnAlbumNextSnapshot.setActionCommand("snapshot##album##next"); + sldAlbumSnapshot = gui.createSlider("snapshot##album"); + lblAlbumSnapshot = gui.createLabel("Snapshot"); + panel.add(gui.createCompactGroup(new TComponent[] { + lblAlbumName, btnAlbumPrevSnapshot, sldAlbumSnapshot, btnAlbumNextSnapshot, lblAlbumSnapshot }), TBorderLayout.WEST); + // + panel.add(gui.createLabel(""), TBorderLayout.WEST); // place-holder to keep choiceNetwork in place + // + gui.add(panel, TBorderLayout.NORTH); + // setup network and map/tom switcher + panel = gui.createPanel(new TBorderLayout()); + panel.setPadding(5, 10); + choiceNetwork = new TChoiceWithRollover(gui, "network##"); choiceNetwork.setFont(fnLargeBold); + choiceNetwork.setEmptyString("right-click here"); + choiceNetwork.setContextMenu(gui.createPopupMenu(new String[][] { + { "New document\u2026", "document##new" }, + { "Open document\u2026", "document##open" }, + { "Save document", "document##save" }, + { "Save document as\u2026", "document##saveAs" }, + { "Save uncompressed", "document##compressed" }, + { "Close document", "document##close" }, + null, + { "Open workspace\u2026", "workspace##open" }, + { "Save workspace", "workspace##save" }, + { "Save workspace as\u2026", "workspace##saveAs" }, + null, + { "Check for updates", "update" } + })); + panel.add(gui.createCompactGroup(new TComponent[] { choiceNetwork }, 5), TBorderLayout.WEST); + btnMap = gui.createToggleButton("Map"); btnMap.setFont(fnLargeBold); + btnTom = gui.createToggleButton("Tom"); btnTom.setFont(fnLargeBold); + new TButtonGroup(new TToggleButton[] { btnMap, btnTom }); + panel.add(gui.createCompactGroup(new TComponent[] { btnMap, btnTom }, 5), TBorderLayout.EAST); + gui.add(panel, TBorderLayout.NORTH); + // setup workspace recovery button + XMLElement xmlWorkspace = XMLElement.parse(prefs.get("workspace", "")); + if ((xmlWorkspace != null) && (xmlWorkspace.getChildren("document").length > 0)) { + btnWorkspaceRecovery = gui.createButton("Recover previous workspace"); + btnWorkspaceRecovery.setActionCommand("workspace##recover"); + String tooltip = "Attempts to reload all documents that were open\n" + + "when the application was closed the last time:\n"; + XMLElement xmlDocument[] = xmlWorkspace.getChildren("document"); + for (int i = 0; i < xmlDocument.length; i++) { + tooltip += " " + (i+1) + ". " + xmlDocument[i].getString("src") + "\n"; + // File f = new File(xmlDocument[i].getString("src")); + // tooltip += (i+1) + ". "; + // tooltip += "[color=127,127,127]" + f.getParent() + File.separator + "[/color]"; + // String name = f.getName(); + // String ext = null; + // if (name.endsWith(".spato")) { name = name.substring(0, name.length() - 7); ext = ".spato"; } + // tooltip += name; + // if (ext != null) tooltip += "[color=127,127,127]" + ext + "[/color]"; + // tooltip += "\n"; + } + btnWorkspaceRecovery.setToolTip(tooltip); + btnWorkspaceRecovery.getToolTip().setID("workspace##recover"); + panel = gui.createPanel(new TBorderLayout()); + panel.setPadding(5, 10); + panel.add(gui.createCompactGroup(new TComponent[] { btnWorkspaceRecovery }, 2), TBorderLayout.WEST); + gui.add(panel, TBorderLayout.NORTH); + } + // setup bottom panel + panel = gui.createPanel(new TBorderLayout()); + panel.setPadding(5); + choiceDataset = gui.createChoice("dataset##", true); + choiceDataset.setEmptyString("\u2014 right-click to create new dataset \u2014"); + choiceDataset.setRenderer(new XMLElementRenderer()); + // choiceDataset.setContextMenu(gui.createPopupMenu(new String[][] { + // { "New", "dataset####new" }, + // { "Rename", "dataset####rename" }, + // { "Delete", "dataset####delete" } + // })); + choiceQuantity = gui.createChoice("quantity##", true); + choiceQuantity.setRenderer(new XMLElementRenderer()); + // choiceQuantity.setContextMenu(gui.createPopupMenu(new String[][] { + // { "Import\u2026", "quantity####import" }, + // { "Rename", "quantity####rename" }, + // { "Delete", "quantity####delete" } + // })); + choiceColormap = gui.createChoice("colormap##"); + choiceColormap.setEmptyString("\u2014 no quantity selected \u2014"); + btnColormapLog = gui.createToggleButton("log"); + btnQuantityPrevSnapshot = gui.createButton("<"); btnQuantityPrevSnapshot.setActionCommand("snapshot##quantity##prev"); + btnQuantityNextSnapshot = gui.createButton(">"); btnQuantityNextSnapshot.setActionCommand("snapshot##quantity##next"); + sldQuantitySnapshot = gui.createSlider("snapshot##quantity"); + // FIXME: snapshot controls still wiggle due to stupid XMLElementRenderer + panel.add(gui.createCompactGroup(new TComponent[] { + gui.createLabel("Node Coloring:"), choiceDataset, gui.createLabel("/"), choiceQuantity, + gui.createCompactGroup(new TComponent[] { btnQuantityPrevSnapshot, sldQuantitySnapshot, btnQuantityNextSnapshot }), + gui.createLabel("/"), choiceColormap, btnColormapLog }), TBorderLayout.WEST); + gui.add(panel, TBorderLayout.SOUTH); + // node coloring quantity snapshot controls + // btnQuantityPrevSnapshot = gui.createButton("<"); btnQuantityPrevSnapshot.setActionCommand("snapshot##quantity##prev"); + // btnQuantityNextSnapshot = gui.createButton(">"); btnQuantityNextSnapshot.setActionCommand("snapshot##quantity##next"); + // sldQuantitySnapshot = gui.createSlider("snapshot##quantity"); + // panel.add(gui.createCompactGroup(new TComponent[] { btnQuantityPrevSnapshot, sldQuantitySnapshot, btnQuantityNextSnapshot }), TBorderLayout.WEST); + // TWindow win = new TWindow(gui, new TCompactGroupLayout(0)); + // win.setMargin(1, 3); + // win.add(btnQuantityPrevSnapshot); + // win.add(sldQuantitySnapshot); + // win.add(btnQuantityNextSnapshot); + // win.setVisible(false); + // gui.add(win); + // status bar + lblStatus = gui.createLabel(""); + lblStatus.setAlignment(TLabel.ALIGN_RIGHT); + lblStatus.setFont(gui.createFont("GillSans-Bold", 10)); + panel.add(lblStatus, TBorderLayout.CENTER); + // network details panel + panel = gui.createPanel(new TBorderLayout()); + panel.setPadding(0, 10); + networkDetail = new NetworkDetailPanel(gui); + networkDetail.setVisible(false); + choiceNetwork.rollOverComponent = networkDetail; + panel.add(networkDetail, TBorderLayout.NORTH); + gui.add(panel, TBorderLayout.WEST); + // setup console + console = gui.createConsole(versionDebug.equals("alpha")); + int tE = 5000; + console.logInfo("SPaTo Visual Explorer").tE = tE; + console.logNote("Version " + version + ((versionDebug.length() > 0) ? " " + versionDebug : "") + " (" + versionDate + ")").tE = tE; + if (versionDebug.equals("alpha")) console.logError("This is an alpha version \u2013 don't use it unless you know what you are doing").tE = tE; + else if (versionDebug.equals("beta")) console.logWarning("This is a beta version \u2013 expect unexpected behavior").tE = tE; + console.logNote("Copyright (C) 2008–2011 by Christian Thiemann").tE = tE; + console.logNote("Research on Complex Systems, Northwestern University").tE = tE; + console.logDebug("--------------------------------------------------------"); + console.logDebug("[OS] " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")"); + console.logDebug("[JRE] " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version")); + console.logDebug("[JVM] " + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor") + ") [" + (com.sun.jna.Platform.is64Bit() ? "64" : "32") + "-bit]"); + console.logDebug("[path] " + System.getenv(((platform != WINDOWS) ? ((platform == MACOSX) ? "DY" : "") + "LD_LIBRARY_" : "") + "PATH")); + console.logDebug("[mem] max: " + (Runtime.getRuntime().maxMemory()/1024/1024) + " MB"); + // if (!JNMatLib.isLoaded() && (versionDebug.length() > 0)) console.logError("[JNMatLib] " + JNMatLib.getError().getMessage()); + console.logDebug("--------------------------------------------------------"); + gui.add(console); + // setup hotkeys and drop target + guiSetupHotkeys(); + setupDropTarget(); +} + +void guiSetupHotkeys() { + tfSearch.setHotKey(KeyEvent.VK_F, MENU_SHORTCUT); + if (btnWorkspaceRecovery != null) btnWorkspaceRecovery.setHotKey(KeyEvent.VK_R, MENU_SHORTCUT); + else btnRegexpSearch.setHotKey(KeyEvent.VK_R, MENU_SHORTCUT); + btnNodes.setHotKey(KeyEvent.VK_N); + btnLinks.setHotKey(KeyEvent.VK_L); + btnSkeleton.setHotKey(KeyEvent.VK_B); + btnNeighbors.setHotKey(KeyEvent.VK_E); + btnNetwork.setHotKey(KeyEvent.VK_F); + btnLabels.setHotKey(KeyEvent.VK_L, KeyEvent.SHIFT_MASK); + // + btnMap.setHotKey(KeyEvent.VK_V); + btnTom.setHotKey(KeyEvent.VK_V); + choiceDistMat.setHotKeyChar('d'); + choiceNetwork.setHotKeyChar('~'); + choiceDataset.setHotKeyChar(TAB); + choiceDataset.setShortcutChars(new char[] { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }); + choiceQuantity.setHotKeyChar('`'); + choiceQuantity.setShortcutChars(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }); + choiceColormap.setHotKeyChar('c'); + btnColormapLog.setHotKey(KeyEvent.VK_C, KeyEvent.SHIFT_MASK); + btnQuantityPrevSnapshot.setHotKey(KeyEvent.VK_COMMA); + btnQuantityNextSnapshot.setHotKey(KeyEvent.VK_PERIOD); +} + +void guiUpdate() { + guiFastUpdate(); + choiceNetwork.removeAll(); + if (docs.size() > 0) { + choiceNetwork.add(docs.toArray()); + if (doc != null) + choiceNetwork.select(docs.indexOf(doc)); + } + choiceNetwork.getContextMenu().setEnabled("document##save", doc != null); + choiceNetwork.getContextMenu().setEnabled("document##saveAs", doc != null); + choiceNetwork.getContextMenu().setEnabled("document##compressed", doc != null); + choiceNetwork.getContextMenu().getItem("document##compressed").setText( + ((doc != null) && doc.compressed) ? "Save uncompressed" : "Save compressed"); + choiceNetwork.getContextMenu().setEnabled("document##close", doc != null); + choiceNetwork.getContextMenu().setEnabled("workspace##save", docs.size() > 0); + choiceNetwork.getContextMenu().setEnabled("workspace##saveAs", docs.size() > 0); + if ((btnWorkspaceRecovery != null) && !showWorkspaceRecoveryButton) { + gui.remove(btnWorkspaceRecovery.getParent().getParent()); // remove the button from the GUI + btnWorkspaceRecovery.setHotKey(0); // release hotkey + btnWorkspaceRecovery = null; // ... and we don't need that anymore + btnRegexpSearch.setHotKey(KeyEvent.VK_R, MENU_SHORTCUT); // re-bind hotkey to Regexp toggle + } + guiUpdateProjection(); + guiUpdateNodeColoring(); + guiUpdateAlbumControls(); +} + +void guiFastUpdate() { + // update visibility of components + btnNodes.getParent().setVisibleAndEnabled(doc != null); + tfSearch.getParent().setVisibleAndEnabled(doc != null); + tfSearch.setEmptyText("Search" + (btnRegexpSearch.isSelected() ? " (RegExp)" : "")); + btnMap.getParent().setVisibleAndEnabled(doc != null); + choiceMapProjection.getParent().setVisibleAndEnabled((doc != null) && (doc.view.viewMode == SVE2View.VIEW_MAP)); + choiceTomProjection.getParent().setVisibleAndEnabled((doc != null) && (doc.view.viewMode == SVE2View.VIEW_TOM)); + choiceDataset.getParent().setVisibleAndEnabled(doc != null); + btnNodes.getParent().setVisibleAndEnabled(doc != null); + sldAlbumSnapshot.getParent().setVisibleAndEnabled((doc != null) && (doc.getAlbum() != null)); + lblStatus.setText(((doc == null) || (doc.view.ih == -1)) ? "" : doc.view.nodes[doc.view.ih].name); + updatePlatformMagic(); + if (doc == null) return; + choiceMapProjection.setEnabled(doc.view.hasMapLayout); + choiceTomProjection.setEnabled(doc.view.hasTomLayout); + choiceTomScaling.setEnabled(doc.view.hasTomLayout); + choiceDistMat.setEnabled(doc.view.hasTomLayout); + btnMap.setEnabled(doc.view.hasMapLayout); + btnTom.setEnabled(doc.view.hasTomLayout); + switch (doc.view.viewMode) { + case SVE2View.VIEW_MAP: btnMap.getButtonGroup().setSelected(btnMap); break; + case SVE2View.VIEW_TOM: btnTom.getButtonGroup().setSelected(btnTom); break; + } + btnNodes.setSelected(doc.view.showNodes); + btnLinks.setSelected((doc.view.showLinks && !doc.view.showSkeleton && !doc.view.showNeighbors && !doc.view.showNetwork) || + (doc.view.showSkeleton && doc.view.showLinksWithSkeleton) || + (doc.view.showNeighbors && doc.view.showLinksWithNeighbors) || + (doc.view.showNetwork && doc.view.showLinksWithSkeleton)); + btnLinks.getParent().setBorder(doc.view.showSkeleton || doc.view.showNeighbors || doc.view.showNetwork ? 1 : 0); + btnSkeleton.setSelected(doc.view.showSkeleton); + btnNeighbors.setSelected(doc.view.showNeighbors); + btnNetwork.setSelected(doc.view.showNetwork); + btnLabels.setSelected(doc.view.showLabels); + if (frameRate < 15) fastNodes = true; + if (frameRate > 30) fastNodes = false; + if (versionDebug.equals("beta")) { + if (frameRate < 14) console.setShowDebug(true); + if (frameRate > 20) console.setShowDebug(false); + } + // update search matches if necessary + if (!searchMatchesValid) + guiUpdateSearchMatches(); +} + +void guiUpdateProjection() { + if (doc == null) return; + if (doc.view.hasMapLayout) + choiceMapProjection.select(doc.view.xmlProjection.getString("name")); + if (doc.view.hasTomLayout) { + choiceTomProjection.select(doc.view.layouts[doc.view.l].projection); + choiceTomScaling.select(doc.view.layouts[doc.view.l].scaling); + choiceDistMat.removeAll(); + choiceDistMat.add(doc.getDistanceQuantities()); + choiceDistMat.select(doc.view.xmlDistMat); + } +} + +void guiUpdateNodeColoring() { + if (doc == null) { choiceDataset.getParent().setVisibleAndEnabled(false); return; } + choiceDataset.getParent().setVisibleAndEnabled(true); + // + choiceDataset.removeAll(); + choiceDataset.add(doc.getDatasets()); + choiceDataset.select(doc.getSelectedDataset()); + // choiceDataset.getContextMenu().setEnabled("dataset####rename", choiceDataset.getSelectedItem() != null); + // choiceDataset.getContextMenu().setEnabled("dataset####delete", choiceDataset.getSelectedItem() != null); + // + choiceQuantity.removeAll(); + if (doc.getSelectedDataset() != null) { + choiceQuantity.add(doc.getQuantities()); + choiceQuantity.select(doc.getSelectedQuantity()); + } + // choiceQuantity.getContextMenu().setEnabled("quantity####import", choiceDataset.getSelectedItem() != null); + // choiceQuantity.getContextMenu().setEnabled("quantity####rename", choiceQuantity.getSelectedItem() != null); + // choiceQuantity.getContextMenu().setEnabled("quantity####delete", choiceQuantity.getSelectedItem() != null); + choiceQuantity.setEmptyString((doc.getSelectedDataset() == null) + ? "\u2014 no dataset selected \u2014" : "\u2014 right-click to import data \u2014"); + // + choiceColormap.removeAll(); + if (doc.view.hasData) { + choiceColormap.setRenderer(doc.view.colormap.new Renderer()); + choiceColormap.add(doc.view.colormap.colormaps); + choiceColormap.select(doc.view.colormap.getColormapName()); + } + // + btnColormapLog.setVisibleAndEnabled(doc.view.hasData && !doc.view.colormap.getColormapName().equals("discrete")); + if (doc.view.hasData) btnColormapLog.setSelected(doc.view.colormap.logscale); + // +// TWindow win = (TWindow)sldQuantitySnapshot.getParent(); + TPanel win = (TPanel)sldQuantitySnapshot.getParent(); + win.setVisibleAndEnabled(false); + XMLElement series = doc.getSelectedSnapshotSeriesContainer(doc.getSelectedQuantity()); + if (series != null) { + XMLElement snapshots[] = series.getChildren("snapshot"); + sldQuantitySnapshot.setValueBounds(0, snapshots.length-1); + sldQuantitySnapshot.setValue(doc.getSelectedSnapshotIndex(series)); + sldQuantitySnapshot.setPreferredWidth(max(75, min(width-50, snapshots.length-1))); + win.setVisibleAndEnabled(true); + TComponent.Dimension d = win.getPreferredSize(); + gui.validate(); + TComponent.Point p = choiceQuantity.getLocationOnScreen(); + float x = max(3, p.x - btnQuantityPrevSnapshot.getPreferredSize().width/2); + x = min(width - 3 - win.getWidth(), x); + float y = p.y - d.height; +// win.setBounds(x, y, d.width, d.height); + } +} + +void guiUpdateAlbumControls() { + if (doc == null) return; // done + XMLElement xmlAlbum = doc.getAlbum(); + if (xmlAlbum == null) return; // done + lblAlbumName.setText(xmlAlbum.getString("name", xmlAlbum.getString("id", "Unnamed Album")) + ":"); + XMLElement snapshots[] = xmlAlbum.getChildren("snapshot"); + sldAlbumSnapshot.setValueBounds(0, snapshots.length-1); + sldAlbumSnapshot.setValue(doc.getSelectedSnapshotIndex(xmlAlbum)); + sldAlbumSnapshot.setPreferredWidth(max(100, min(width/2, snapshots.length-1))); + XMLElement snapshot = doc.getSelectedSnapshot(xmlAlbum); + lblAlbumSnapshot.setText("[" + snapshot.getString("label", snapshot.getString("id", "Unnamed Snapshot")) + "]"); +} + +void guiUpdateSearchMatches() { + searchMsg = null; + searchUniqueMatch = -1; + if ((doc == null) || !doc.view.hasNodes) return; + String searchPhrase = tfSearch.getText(); + if (searchPhrase.length() == 0) { + searchMatches = null; + return; + } + if (searchMatches == null) { + searchMatches = new boolean[doc.view.NN]; + searchMatchesChild = new int[doc.view.NN]; + } + if (btnRegexpSearch.isSelected()) { + try { + Pattern p = Pattern.compile(searchPhrase); + if (p.matcher("").find()) throw new PatternSyntaxException("Expression matches empty string", searchPhrase, -1); + for (int i = 0; i < doc.view.NN; i++) + searchMatches[i] = p.matcher(doc.view.nodes[i].label).find() || p.matcher(doc.view.nodes[i].name).find(); + } catch (PatternSyntaxException e) { + searchMsg = "E" + e.getDescription(); + if (e.getIndex() > -1) + searchMsg += ": " + e.getPattern().substring(0, e.getIndex()); + } + } else { + boolean caseSensitive = !searchPhrase.equals(searchPhrase.toLowerCase()); // ignore case if no upper-case letter present + for (int i = 0; i < doc.view.NN; i++) + searchMatches[i] = + (caseSensitive + ? doc.view.nodes[i].label.contains(searchPhrase) + : doc.view.nodes[i].label.toLowerCase().contains(searchPhrase)) + || + (caseSensitive + ? doc.view.nodes[i].name.contains(searchPhrase) + : doc.view.nodes[i].name.toLowerCase().contains(searchPhrase)); + } + searchMatchesValid = true; + for (int i = 0; i < doc.view.NN; i++) + if (searchMatches[i]) + if (searchUniqueMatch == -1) searchUniqueMatch = i; + else { searchUniqueMatch = -1; break; } + if (searchUniqueMatch > -1) + searchMsg = "M" + doc.view.nodes[searchUniqueMatch].name; +} + +void actionPerformed(String cmd) { + String argv[] = split(cmd, "##"); + if (argv[0].equals("workspace")) { + if (argv[1].equals("open")) openWorkspace(); + if (argv[1].equals("save")) saveWorkspace(); + if (argv[1].equals("saveAs")) saveWorkspace(true); + if (argv[1].equals("recover")) replaceWorkspace(XMLElement.parse(prefs.get("workspace", ""))); + } else if (argv[0].equals("document")) { + if (argv[1].equals("new")) newDocument(); + if (argv[1].equals("open")) openDocument(); + if (argv[1].equals("save")) saveDocument(); + if (argv[1].equals("saveAs")) saveDocument(true); + if (argv[1].equals("compressed")) { doc.setCompressed(!doc.isCompressed()); saveDocument(); } + if (argv[1].equals("close")) closeDocument(); + } else if (argv[0].equals("search")) { + searchMatchesValid = false; + if (argv[1].equals("enterKeyPressed") && (searchUniqueMatch > -1)) { + doc.view.setRootNode(searchUniqueMatch); + tfSearch.setText(""); + } + } else if (argv[0].equals("RegExp")) { + searchMatchesValid = false; + prefs.putBoolean("search.regexp", btnRegexpSearch.isSelected()); + } else if (argv[0].equals("network")) + switchToNetwork(argv[1]); + else if (argv[0].equals("projMap")) + doc.view.setMapProjection(argv[1]); + else if (argv[0].equals("projTom")) { + doc.view.layouts[0].setupProjection(argv[1]); + if (doc.view.r > -1) doc.view.layouts[0].updateProjection(doc.view.r, doc.view.D); + } else if (argv[0].equals("distMat")) + doc.setDistanceQuantity((XMLElement)choiceDistMat.getSelectedItem()); + else if (argv[0].equals("scal")) { + doc.view.layouts[0].setupScaling(argv[1], doc.view.minD/1.25); // FIXME: when does this insanity end? + if (doc.view.r > -1) doc.view.layouts[0].updateProjection(doc.view.r, doc.view.D); + if (doc.view.xmlDistMat != null) doc.view.xmlDistMat.setString("scaling", argv[1]); + } else if (argv[0].equals("Map")) + doc.view.viewMode = SVE2View.VIEW_MAP; + else if (argv[0].equals("Tom")) + doc.view.viewMode = SVE2View.VIEW_TOM; + else if (argv[0].equals("Nodes")) + doc.view.showNodes = !doc.view.showNodes; + else if (argv[0].equals("Links")) { + if (doc.view.showSkeleton) doc.view.showLinksWithSkeleton = !doc.view.showLinksWithSkeleton; + else if (doc.view.showNeighbors) doc.view.showLinksWithNeighbors = !doc.view.showLinksWithNeighbors; + else if (doc.view.showNetwork) doc.view.showLinksWithNetwork = !doc.view.showLinksWithNetwork; + else doc.view.showLinks = !doc.view.showLinks; + } else if (argv[0].equals("Skeleton")) { + doc.view.showSkeleton = !doc.view.showSkeleton; + if (doc.view.showSkeleton && doc.view.showNetwork) doc.view.showNetwork = false; + if (doc.view.showSkeleton && doc.view.showNeighbors) doc.view.showNeighbors = false; + } else if (argv[0].equals("Neighbors")) { + if (doc.view.hasLinks) { + doc.view.showNeighbors = !doc.view.showNeighbors; + if (doc.view.showNeighbors && doc.view.showSkeleton) doc.view.showSkeleton = false; + if (doc.view.showNeighbors && doc.view.showNetwork) doc.view.showNetwork = false; + } else + console.logWarning("Network links not available in data file"); + } else if (argv[0].equals("Network")) { + if (doc.view.hasLinks) { + doc.view.showNetwork = !doc.view.showNetwork; + if (doc.view.showNetwork && doc.view.showSkeleton) doc.view.showSkeleton = false; + if (doc.view.showNetwork && doc.view.showNeighbors) doc.view.showNeighbors = false; + } else + console.logWarning("Full network not available in data file"); + } else if (argv[0].equals("Labels")) + doc.view.showLabels = !doc.view.showLabels; + else if (argv[0].equals("dataset")) { + if (!argv[1].equals("")) + doc.setSelectedDataset((XMLElement)choiceDataset.getSelectedItem()); + else if (argv[2].equals("new")) { + XMLElement xmlDataset = new XMLElement("dataset"); + xmlDataset.setString("name", "New Dataset"); + doc.addDataset(xmlDataset); + doc.setSelectedDataset(xmlDataset); + guiUpdateNodeColoring(); + actionPerformed("dataset####rename"); + } else if (argv[2].equals("rename")) + new InPlaceRenamingTextField(gui, choiceDataset).show(); + else if (argv[2].equals("delete")) + doc.removeDataset((XMLElement)choiceDataset.getSelectedItem()); + } else if (argv[0].equals("quantity")) { + if (!argv[1].equals("")) + doc.setSelectedQuantity((XMLElement)choiceQuantity.getSelectedItem()); + // else if (argv[2].equals("import")) + // new QuantityImportWizard(doc).start(); + else if (argv[2].equals("rename")) + new InPlaceRenamingTextField(gui, choiceQuantity).show(); + else if (argv[2].equals("delete")) + doc.removeQuantity((XMLElement)choiceQuantity.getSelectedItem()); + } else if (argv[0].equals("colormap")) + doc.view.colormap.setColormap(argv[1]); + else if (argv[0].equals("log")) + doc.view.colormap.setLogscale(btnColormapLog.isSelected()); + else if (argv[0].equals("snapshot")) { + TSlider source = null; XMLElement target = null; + if (argv[1].equals("album")) { source = sldAlbumSnapshot; target = doc.getAlbum(); } + else if (argv[1].equals("quantity")) { source = sldQuantitySnapshot; target = doc.getSelectedQuantity(); } + else return; + if (argv[2].equals("valueChanged")) + doc.setSelectedSnapshot(target, source.getValue()); + else if (argv[2].equals("next")) + doc.setSelectedSnapshot(target, +1, true); + else if (argv[2].equals("prev")) + doc.setSelectedSnapshot(target, -1, true); + } else if (argv[0].equals("update")) + checkForUpdates(true); + guiUpdate(); +} + + +class XMLElementRenderer extends TChoice.StringRenderer { + boolean includeDataset = false; + XMLElementRenderer() { this(false); } + XMLElementRenderer(boolean includeDataset) { this.includeDataset = includeDataset; } + String getActionCommand(Object o) { + XMLElement xml = (XMLElement)o; + String str = xml.getString("id"); + if (includeDataset && xml.getName().equals("data") && (xml.getParent() != null)) + str = xml.getParent().getString("id") + "##" + str; + return str; + } + String getSnapshotLabel(XMLElement xml) { + String res = xml.getString("label"); + if (res == null) try { + res = doc.getChild(doc.getChild("album[@id=" + xml.getString("album") + "]"), "snapshot[@selected]").getString("label"); + } catch (Exception e) { /* ignore any NullPointerExceptions or other stuff */ } + return res; + } + // FIXME: maybe the string should be cached? (and erased on invalidate()) + String getString(Object o, boolean inMenu) { + XMLElement xml = (XMLElement)o; + String str = xml.getString("name", xml.getString("id")); + if (includeDataset && inMenu && xml.getName().equals("data") && (xml.getParent() != null)) + str = xml.getParent().getString("name", xml.getParent().getString("id")) + ": " + str; + XMLElement snapshot = doc.getSelectedSnapshot(xml); + if (!inMenu && (snapshot != null)) { + String strsnap = ""; + while (snapshot != xml) { + strsnap = strsnap + " [" + getSnapshotLabel(snapshot) + "]"; + snapshot = snapshot.getParent(); + } + str += strsnap; + } + return str; + } +} + +class TChoiceWithRollover extends TChoice { + class SVE2DocumentRenderer extends StringRenderer { + boolean getEnabled(Object o) { return ((SVE2Document)o).view.hasMapLayout || ((SVE2Document)o).view.hasTomLayout; } + String getActionCommand(Object o) { return ((SVE2Document)o).getName(); } + TComponent.Dimension getPreferredSize(TChoice c, Object o, boolean inMenu) { + SVE2Document doc = (SVE2Document)o; + TComponent.Dimension d = super.getPreferredSize(c, doc.getName(), inMenu); + if (inMenu) { + textFont(gui.style.getFont()); + String desc = !getEnabled(o) ? " (loading...)" : " – " + doc.getTitle(); + d.width += 5 + textWidth(desc); + } + return d; + } + void draw(TChoice c, PGraphics g, Object o, TComponent.Rectangle bounds, boolean inMenu) { + SVE2Document doc = (SVE2Document)o; + String name = doc.getName(); + noStroke(); + textFont(c.getFont()); + fill(getEnabled(o) ? c.getForeground() : color(127)); + textAlign(g.LEFT, g.BASELINE); + float x = bounds.x; + float y = bounds.y + bounds.height - g.textDescent(); + float h = g.textAscent() + g.textDescent(); + if (bounds.height > h) y -= (bounds.height - h)/2; + text(name, x, y); + if (inMenu) { + x += textWidth(name) + 5; + textFont(gui.style.getFont()); + String desc = !getEnabled(o) ? " (loading...)" : " – " + doc.getTitle(); + text(desc, x, y); + } + } + } + TComponent rollOverComponent = null; + TChoiceWithRollover(TransparentGUI gui, String actionCmdPrefix) { + super(gui, actionCmdPrefix); setRenderer(new SVE2DocumentRenderer()); } + void handleMouseEntered() { super.handleMouseEntered(); if (rollOverComponent != null) rollOverComponent.setVisible(true); } + void handleMouseExited() { super.handleMouseExited(); if (rollOverComponent != null) rollOverComponent.setVisible(false); } +} + +class NetworkDetailPanel extends TComponent { + NetworkDetailPanel(TransparentGUI gui) { super(gui); setPadding(5, 10); setMargin(0); + setBackgroundColor(gui.style.getBackgroundColorForCompactGroups()); } + TComponent.Dimension getMinimumSize() { + if ((doc == null) || !doc.view.hasNodes) return new TComponent.Dimension(0, 0); + textFont(fnLarge); + float width = textWidth(doc.getTitle()), height = textAscent() + 1.5*textDescent(); + textFont(fnMedium); + String networkMeta[] = split(doc.getDescription(), '\n'); + for (int i = 0; i < networkMeta.length; i++) { + width = max(width, textWidth(networkMeta[i])); + height += textAscent() + 1.5*textDescent(); + } + return new TComponent.Dimension(width, height); + } + void draw(PGraphics g) { + if ((doc == null) || !doc.view.hasNodes) return; + super.draw(g); + float x = bounds.x + padding.left, y = bounds.y + padding.top; + g.textAlign(LEFT, BASELINE); + g.textFont(fnLarge); + g.noStroke(); + g.fill(0); + y += g.textAscent() + .5*g.textDescent(); + g.text(doc.getTitle(), x, y); + y += g.textDescent(); + g.fill(127); + g.textFont(fnMedium); + String networkMeta[] = split(doc.getDescription(), '\n'); + for (int i = 0; i < networkMeta.length; i++) { + y += g.textAscent() + .5*g.textDescent(); + text(networkMeta[i], x, y); + y += g.textDescent(); + } + } +} + +class InPlaceRenamingTextField extends TTextField { + TChoice choice = null; + XMLElement xml = null; + + InPlaceRenamingTextField(TransparentGUI gui, TChoice choice) { super(gui); this.choice = choice; } + + TComponent.Dimension getPreferredSize() { + return new TComponent.Dimension(max(choice.getWidth(), 50), choice.getHeight()); } + + void show() { + xml = (XMLElement)choice.getSelectedItem(); + if (xml == null) return; + setText(xml.getString("name")); + setSelection(0, text.length()); + TContainer parent = choice.getParent(); + for (int i = 0; i < parent.getComponentCount(); i++) + if (parent.getComponent(i) == choice) + { parent.add(this, choice.getLayoutHint(), i); break; } + choice.setVisibleAndEnabled(false); + parent.validate(); + gui.requestFocus(this); + } + + void draw(PGraphics g) { + if (isFocusOwner()) + super.draw(g); + else { + if (text.length() > 0) + xml.setString("name", text); + choice.setVisibleAndEnabled(true); + getParent().remove(this); + } + } +} diff --git a/SVE2View.pde b/SVE2View.pde new file mode 100644 index 0000000..40de1e1 --- /dev/null +++ b/SVE2View.pde @@ -0,0 +1,682 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.FloatBuffer; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +float linkLineWidth = 0.25; + +/* + * Visual Explorer Document Viewer / Data Structures + */ + +class SVE2View { + + SVE2Document doc = null; + + SVE2View(SVE2Document doc) { this.doc = doc; } + + class Node { + String id, label, name; // node ID, short label and full name + float poslat, poslong, w; // geographical position and strength // FIXME: remove the node strength stuff and use proper showLabel framework + boolean showLabel; // whether or not the node should make cookies on every 2nd Friday of the spring months + float x, y, a; // current screen position, and alpha factor (0–1) + Node(XMLElement node) { + id = node.getString("id"); + label = node.getString("label", (id == null) ? "" : id); + name = node.getString("name", label); + w = node.getFloat("strength", 0); + showLabel = node.getBoolean("showlabel"); + String pieces[] = split(node.getString("location", random(-1,1) + "," + random(-1,1)), ','); + poslong = parseFloat(pieces[0]); + poslat = parseFloat(pieces[1]); + x = Float.NaN; + y = Float.NaN; + a = 0; + } + } + + class SortedLinkList { + int NN, NL; // number of nodes (max value in src[] and dst[]) and number of links + int src[] = null, dst[] = null; + float value[] = null; + float minval, maxval; + boolean sorted = false; + SortedLinkList(SparseMatrix sm) { this(sm, false, false, false); } + SortedLinkList(SparseMatrix sm, boolean logValues) { this(sm, logValues, false, false); } + SortedLinkList(SparseMatrix sm, boolean logValues, boolean asyncSort) { this(sm, logValues, asyncSort, false); } + SortedLinkList(SparseMatrix sm, boolean logValues, boolean asyncSort, boolean upperTriangleOnly) { + NN = sm.N; + // create arrays + NL = 0; for (int i = 0; i < NN; i++) NL += sm.index[i].length; + src = new int[NL]; dst = new int[NL]; value = new float[NL]; + // copy values + NL = 0; minval = Float.POSITIVE_INFINITY; maxval = Float.NEGATIVE_INFINITY; + for (int i = 0; i < NN; i++) { + for (int l = 0; l < sm.index[i].length; l++) { + if (upperTriangleOnly && (sm.index[i][l] < i)) continue; + src[NL] = i; dst[NL] = sm.index[i][l]; + value[NL] = logValues ? log(sm.value[i][l]) : sm.value[i][l]; + minval = min(minval, value[NL]); + maxval = max(maxval, value[NL]); + NL++; + } + } + // sort + if (asyncSort) worker.submit(new Runnable() { public void run() { sort(); } }); + else sort(); + } + void sort() { + // Is it stupid to manually implement a sort algorithm here? + // I don't want to use one Object per link and I'd like to have + // small synchronized {} brackets so that the drawing routing can + // already visualize the full network with partially sorted links. + sorted = false; + sort(0, NL); + sorted = true; + } + private void sort(int i0, int i1) { + // [in-place quicksort from wikipedia] + // * will sort sublist from index i0 to i1 (incl.) + // * assume no other concurring thread writes to the object, + // i.e., concurring read ops are ok, only need to sync write ops; + // other threads need to sync read ops as well + if (i1 <= i0) return; // only need to sort lists of length > 1 + // select pivot value (median of first/middle/last) + int ip = i0 + (i1 - i0)/2; // assume pivot is middle element + if (((value[i0] > value[ip]) && (value[i0] < value[i1])) || ((value[i0] < value[ip]) && (value[i0] > value[i1]))) + ip = i0; // first element is median of first/middle/last + else if (((value[i1] > value[ip]) && (value[i1] < value[i0])) || ((value[i1] < value[ip]) && (value[i1] > value[i0]))) + ip = i1; // last element is median of first/middle/last + // partition + float pivot = value[ip]; + synchronized (this) { // this could even go inside swap()... + swap(ip, i1); // "park" pivot at end + ip = i0; // assume pivot will go at the left end + for (int i = i0; i < i1; i++) + if (value[i] < pivot) // if i-th value is smaller than pivot + swap(i, ip++); // then add to left list and move pivot one to the right + swap(ip, i1); // put pivot value at proper position + } + // recurse + sort(i0, ip - 1); + sort(ip + 1, i1); + } + private void swap(int i, int j) { + int tmpi; float tmpf; + tmpi = src[i]; src[i] = src[j]; src[j] = tmpi; + tmpi = dst[i]; dst[i] = dst[j]; dst[j] = tmpi; + tmpf = value[i]; value[i] = value[j]; value[j] = tmpf; + } + } + + // nodes + boolean hasNodes = false; + int NN = -1, ih = -1; // number of nodes, currently hovered node + Node nodes[] = null; + // links + boolean hasLinks = false; + XMLElement xmlLinks = null; + SparseMatrix links = null; + SortedLinkList loglinks = null; + // map layout + boolean hasMapLayout = false; + XMLElement xmlProjection = null; + Projection projMap = null; + // node coloring data + boolean hasData = false; + XMLElement xmlData = null; + Colormap colormap = null; + final int DATA_1D = 0, DATA_2D = 1; + int datatype = DATA_1D; + float data[][] = null; + // slices + boolean hasSlices = false; + XMLElement xmlSlices = null; + int r = -1; // current root node + int pred[][] = null; // predecessor vectors + SparseMatrix salience = null; // salience matrix (fraction of slices in which each link participates) + // tomogram layouts + boolean hasTomLayout = false; + String tomLayouts = null; + int NL = -1, l = -1; + Layout layouts[] = null; + // tomogram distance matrix + XMLElement xmlDistMat = null; + float D[][] = null; // distance matrix + float minD = Float.POSITIVE_INFINITY, maxD = Float.NEGATIVE_INFINITY; + + // current view parameters + public final static int VIEW_MAP = 0; + public final static int VIEW_TOM = 1; + int viewMode = VIEW_MAP; + boolean showNodes = true; + boolean showLinks = true; + boolean showLinksWithSkeleton = false; + boolean showLinksWithNeighbors = false; + boolean showLinksWithNetwork = false; + boolean showSkeleton = false; + boolean showNeighbors = false; + boolean showNetwork = false; + boolean showLabels = true; + float zoom[] = { 1, 1 }; + float xoff[] = { 0, 0 }; + float yoff[] = { 0, 0 }; + float nodeSizeFactor = 0.2; + + void setNodes(XMLElement xmlNodes) { + hasNodes = false; + XMLElement tmp[] = null; + if ((xmlNodes == null) || ((tmp = xmlNodes.getChildren("node")).length < 1)) + return; + nodes = new Node[NN = tmp.length]; + for (int i = 0; i < NN; i++) + nodes[i] = new Node(tmp[i]); + float maxw = Float.NEGATIVE_INFINITY; + for (int i = 0; i < NN; i++) + if (nodes[i].w > maxw) { maxw = nodes[i].w; r = i; } + for (int i = 0; i < NN; i++) + nodes[i].showLabel = nodes[i].w > .4*maxw; + hasNodes = true; + } + + void setMapProjection(XMLElement xmlProjection) { + hasMapLayout = false; + if (!hasNodes) return; + this.xmlProjection = xmlProjection; + if ((xmlProjection == null) || !MapProjectionFactory.canProduce(xmlProjection.getString("name"))) + setMapProjection(MapProjectionFactory.getDefaultProduct()); + else { + projMap = MapProjectionFactory.produce(xmlProjection.getString("name"), NN); + projMap.beginData(); + for (int i = 0; i < NN; i++) + projMap.setPoint(i, nodes[i].poslat, nodes[i].poslong); + projMap.endData(); + hasMapLayout = true; + } + } + + void setMapProjection(String name) { + if (!hasNodes) return; + if (xmlProjection == null) + xmlProjection = new XMLElement("projection"); + xmlProjection.setString("name", name); + setMapProjection(xmlProjection); + } + + void setRootNode(int i) { + if (!hasNodes || (i < 0) || (i >= NN)) return; + r = i; + if (hasTomLayout) layouts[l].updateProjection(r, D); + } + + void setLinks(XMLElement xmlLinks) { setLinks(xmlLinks, console); } + void setLinks(XMLElement xmlLinks, TConsole console) { + hasLinks = false; + this.xmlLinks = xmlLinks; + if (!hasNodes || (xmlLinks == null)) return; + BinaryThing blob = doc.getBlob(xmlLinks); + if (blob == null) { console.logError("Data for links \u201C" + xmlLinks.getString("name", "") + "\u201D is corrupt"); return; } + if (!blob.isSparse(NN)) { console.logError("Data format error (expected SparseMatrix[" + NN + "]): " + blob); return; } + links = blob.getSparseMatrix(); + // BEGIN work-around (save_spato.m used to save matrices with 1-based indices in binary files before June 3, 2011) + if (xmlLinks.getString("blob") != null) { + boolean hasZeroIndex = false, hasIllegalIndices = false; + for (int i = 0; i < NN; i++) { + for (int l = 0; l < links.index[i].length; l++) { + if (links.index[i][l] == 0) hasZeroIndex = true; + if (links.index[i][l] >= NN) hasIllegalIndices = true; + } + } + if (!hasZeroIndex && hasIllegalIndices) { + console.logWarning("Correcting indices in the sparse weight matrix to zero-based"); + for (int i = 0; i < NN; i++) + for (int l = 0; l < links.index[i].length; l++) + links.index[i][l]--; + } + } + // END work-around + loglinks = new SortedLinkList(links, true, true, true); + hasLinks = true; + } + + void setSlices(XMLElement xmlSlices) { setSlices(xmlSlices, console); } + void setSlices(XMLElement xmlSlices, TConsole console) { + hasSlices = false; + if (!hasNodes || ((xmlSlices == null) && (!hasLinks))) return; + // prepare data structure + pred = new int[NN][NN]; + D = new float[NN][NN]; + // read data + if (xmlSlices != null) { + BinaryThing blob = doc.getBlob(xmlSlices); + if (blob == null) { console.logError("Data for slices \u201C" + xmlSlices.getString("name", "") + "\u201D is corrupt"); return; } + if (!blob.isInt2(NN)) { console.logError("Data format error (expected int[" + NN + "][" + NN + "]): " + blob); return; } + pred = blob.getIntArray(); + } else { + // calculate shortest path trees from scratch + boolean inverse = xmlLinks.getBoolean("inverse"); + console.logProgress("Calculating shortest-path trees"); + for (int r = 0; r < NN; r++) { + Dijkstra.calculateShortestPathTree(links.index, links.value, r, pred[r], D[r], inverse); + console.updateProgress(r, NN); + } + console.finishProgress(); + // process data + minD = Float.POSITIVE_INFINITY; + maxD = Float.NEGATIVE_INFINITY; + float mean = 0; int meanCount = 0; + for (int r = 0; r < NN; r++) { + maxD = max(maxD, max(D[r])); + for (int i = 0; i < NN; i++) { + if (r == i) continue; + minD = min(minD, D[r][i]); + mean += D[r][i]; meanCount++; + } + } + mean /= meanCount; + // add SPTs as slices + xmlSlices = doc.getSlices(); + if (xmlSlices == null) + xmlSlices = doc.getChild("slices[@name=Shortest-Path Trees]"); + if (xmlSlices == null) + doc.xmlDocument.addChild(xmlSlices = new XMLElement("slices")); + xmlSlices.setString("id", "spt"); + xmlSlices.setString("name", "Shortest-Path Trees"); + while (xmlSlices.hasChildren()) + xmlSlices.removeChild(0); + doc.setBlob(xmlSlices, pred, true); + // add SPD to distance measures dataset + XMLElement xmlDataset = doc.getDataset("dist"); + if (xmlDataset == null) // try by name + xmlDataset = doc.getChild("dataset[@name=Distance Measures]"); + if (xmlDataset == null) // create new + doc.xmlDocument.addChild(xmlDataset = new XMLElement("dataset")); + xmlDataset.setString("id", "dist"); + xmlDataset.setString("name", "Distance Measures"); + xmlDistMat = doc.getQuantity(xmlDataset, "spd"); + if (xmlDistMat == null) + xmlDistMat = doc.getChild(xmlDataset, "data[@name=SPD]"); + if (xmlDistMat == null) + xmlDataset.insertChild(xmlDistMat = new XMLElement("data"), 0); + xmlDistMat.setString("id", "spd"); + xmlDistMat.setString("name", "SPD"); + while (xmlDistMat.getChild("values") != null) + xmlDistMat.removeChild(xmlDistMat.getChild("values")); + while (xmlDistMat.getChild("colormap") != null) + xmlDistMat.removeChild(xmlDistMat.getChild("colormap")); + String clog = (meanCount > 0) && (mean < minD + (maxD - minD)/4) ? " log=\"true\"" : ""; + xmlDistMat.addChild(XMLElement.parse( + String.format("", clog, minD, maxD))); + doc.setBlob(xmlDistMat, D, true); + } + // calculate salience matrix + console.logProgress("Calculating salience matrix"); + int abundance[][] = new int[NN][NN]; + float salienceFull[][] = new float[NN][NN]; + for (int root = 0; root < NN; root++) { + for (int i = 0; i < NN; i++) + if (pred[root][i] != -1) + abundance[i][pred[root][i]]++; + console.updateProgress(root, 2*NN); + } + for (int i = 0; i < NN; i++) { + for (int j = 0; j < NN; j++) + salienceFull[i][j] = salienceFull[j][i] = (float)(abundance[i][j] + abundance[j][i])/NN; + console.updateProgress(NN+i, 2*NN); + } + salience = new SparseMatrix(salienceFull); // FIXME: performance? (SparseMatrix uses a lot of append()) + console.finishProgress(); + // done + this.xmlSlices = xmlSlices; + hasSlices = true; + } + + void setNodeColoringData(XMLElement xmlData) { + hasData = false; + data = null; + colormap = null; + this.xmlData = xmlData; + if (xmlData == null) return; + // read values + BinaryThing blob = doc.getBlob(xmlData); + if (blob == null) { console.logError("Data for quantity \u201C" + xmlData.getString("name", "") + "\u201D is corrupt"); return; } + if (blob.isFloat1(NN)) datatype = DATA_1D; + else if (blob.isFloat2(NN)) datatype = DATA_2D; + else { console.logError("Data format error (expected float[1][" + NN + "] or float[" + NN + "][" + NN + "]): " + blob); return; } + data = blob.getFloatArray(); + // process values + float mindata = Float.POSITIVE_INFINITY; + float maxdata = Float.NEGATIVE_INFINITY; + for (int root = 0; root < data.length; root++) { + for (int j = 0; j < data[root].length; j++) { + if (Float.isInfinite(data[root][j]) || Float.isNaN(data[root][j])) continue; + mindata = min(mindata, data[root][j]); + maxdata = max(maxdata, data[root][j]); + } + } + // setup colormap + XMLElement xmlColormap = doc.getColormap(xmlData); + if (xmlColormap == null) // make sure there is a tag we can write to later + xmlData.addChild(xmlColormap = new XMLElement("colormap")); + colormap = new Colormap(xmlColormap, mindata, maxdata); + //colormap = new Colormap(xmlColormap.getString("name", "default"), xmlColormap.getBoolean("log"), mindata, maxdata); // FIXME + // finished + hasData = true; + } + + void setTomLayout() { + hasTomLayout = false; + if (!hasNodes || !hasSlices) return; + if (tomLayouts == null) tomLayouts = "radial_id"; + String layoutNames[] = split(tomLayouts, ' '); + layouts = new Layout[NL = layoutNames.length]; + for (int l = 0; l < NL; l++) + layouts[l] = new Layout(pred, layoutNames[l]); + layouts[this.l = 0].updateProjection(r, D); + hasTomLayout = true; + } + + void setDistanceMatrix(XMLElement xmlData) { setDistanceMatrix(xmlData, console); } + void setDistanceMatrix(XMLElement xmlData, TConsole console) { + if (!hasTomLayout) return; + xmlDistMat = xmlData; + if (xmlData != null) { + // read values + BinaryThing blob = doc.getBlob(xmlData); + if (blob == null) { console.logError("Data for quantity \u201C" + xmlData.getString("name", "") + "\u201D is corrupt"); return; } + if (!blob.isFloat2(NN)) { console.logError("Data format error (expected float[" + NN + "][" + NN + "]): " + blob); return; } + D = blob.getFloatArray(); + } else + D = null; + // process values + if (D == null) D = new float[NN][NN]; + minD = Float.POSITIVE_INFINITY; + maxD = Float.NEGATIVE_INFINITY; + for (int root = 0; root < NN; root++) { + for (int j = 0; j < NN; j++) { + if ((pred[root][j] == -1) && (root != j)) // ignore values of disconnected nodes + D[root][j] = Float.POSITIVE_INFINITY; + if (!Float.isInfinite(D[root][j]) && D[root][j] > 0) // minD = 0 will mess up the log-scale calibration, so ensure minD > 0 + minD = min(minD, D[root][j]); + if (!Float.isInfinite(D[root][j]) && !Float.isNaN(D[root][j])) + maxD = max(maxD, D[root][j]); + } + } + // update projection etc. + String scaling = null; + if (xmlData != null) { + scaling = xmlData.getString("scaling", null); + if (scaling == null) { + XMLElement xmlColormap = doc.getColormap(xmlData); + if (xmlColormap != null) { + scaling = xmlColormap.getBoolean("log") ? "log" : "id"; + xmlData.setString("scaling", scaling); // save for later + } + } + } + if (scaling == null) + scaling = "id"; // default for tree depth distance + layouts[l].setupScaling(scaling, minD/1.25); + if (r > -1) layouts[l].updateProjection(r, D); + } + + + float a = 0, nodeSize = 0; + float[] tmpx = null, tmpy = null; + float viewWidth = width; + float aNodes = 0, aLinks = 0, aSkeleton = 0, aNeighbors = 0, aNetwork = 0, aLabels = 0; + + void draw() { + if (!hasNodes || (!hasMapLayout && !hasTomLayout)) return; // nothing to draw + if ((showNeighbors || showNetwork) && !hasLinks) { + showNeighbors = false; aNeighbors = 0; showNetwork = false; aNetwork = 0; } // can't draw full network + Projection p = ((viewMode == VIEW_MAP) || !hasTomLayout) ? projMap : layouts[0].proj; + boolean linksVisible = (showLinks && !showSkeleton && !showNeighbors && !showNetwork) || + (showSkeleton && showLinksWithSkeleton) || (showNeighbors && showLinksWithNeighbors) || (showNetwork && showLinksWithNetwork); + aNodes += 3*((showNodes ? 1 : 0) - aNodes)*min(dt, 1/3.); + aLinks += 3*((linksVisible ? 1 : 0) - aLinks)*min(dt, 1/3.); + aSkeleton += 3*((showSkeleton ? 1 : 0) - aSkeleton)*min(dt, 1/3.); + aNeighbors += 3*((showNeighbors ? 1 : 0) - aNeighbors)*min(dt, 1/3.); + aNetwork += 3*((showNetwork ? 1 : 0) - aNetwork)*min(dt, 1/3.); + aLabels += 3*((showLabels ? 1 : 0) - aLabels)*min(dt, 1/3.); + // get current data + float[] val = null; + if (hasData) { + switch (datatype) { + case DATA_1D: val = data[0]; break; + case DATA_2D: + if (!isAltDown && (r > -1)) val = data[r]; + if (isAltDown && (ih > -1)) val = data[ih]; + break; + } + } + if ((xmlDistMat == null) && (viewMode == VIEW_TOM)) { + minD = 1; + for (int i = 0; i < NN; i++) + maxD = max(maxD, D[r][i] = (pred[r][i] == -1) ? 0 : D[r][pred[r][i]] + 1); + layouts[l].updateProjection(r, D); + } + // update node positions and determine hovered node + boolean wrap = ((viewMode == VIEW_MAP) && xmlProjection.getString("name").equals("LonLat Roll")); + if ((tmpx == null) || (tmpx.length != NN)) { tmpx = new float[NN]; tmpy = new float[NN]; } + p.setScalingToFitWithin(wrap ? width : .9*width, .9*height); + if (wrap) { // FIXME: wrapping should be handled by the projection + float targetViewWidth = (wrap ? width : .9*width)*zoom[viewMode]; // width of the scaled data (used for wrapping) + viewWidth += 3*(targetViewWidth - viewWidth)*min(dt, 1/3.); + while (xoff[viewMode] > +viewWidth) { xoff[viewMode] -= viewWidth; for (int i = 0; i < NN; i++) nodes[i].x -= viewWidth; } + while (xoff[viewMode] < -viewWidth) { xoff[viewMode] += viewWidth; for (int i = 0; i < NN; i++) nodes[i].x += viewWidth; } + } + float mind = width*height; + ih = -1; // currently hovered node + for (int i = 0; i < NN; i++) { + boolean invis = (viewMode == VIEW_TOM) && (pred[i][r] == -1) && (i != r); + float tx = invis ? nodes[i].x : p.sx*(p.x[i] - p.cx)*zoom[viewMode] + xoff[viewMode] + width/2; + float ty = invis ? nodes[i].y : p.sy*(p.y[i] - p.cy)*zoom[viewMode] + yoff[viewMode] + height/2; + float ta = invis ? 0 : 1; + nodes[i].x = Float.isNaN(nodes[i].x) ? tx : nodes[i].x + 3*(tx - nodes[i].x)*min(dt, 1/3.); + nodes[i].y = Float.isNaN(nodes[i].y) ? ty : nodes[i].y + 3*(ty - nodes[i].y)*min(dt, 1/3.); + nodes[i].a += 3*(ta - nodes[i].a)*min(dt, 1/3.); + if (wrap) { + tmpx[i] = nodes[i].x; tmpy[i] = nodes[i].y; + if (nodes[i].x - width/2 > +viewWidth/2) nodes[i].x -= viewWidth; + if (nodes[i].x - width/2 < -viewWidth/2) nodes[i].x += viewWidth; + } + float d = dist(nodes[i].x, nodes[i].y, mouseX, mouseY); + if (!invis && + (gui.componentAtMouse == null) && (gui.componentMouseClicked == null) && + (d < 50) && (d < mind) && + (!searchMatchesValid || !tfSearch.isFocusOwner() || + searchMatches[i] || (searchMatchesChild[i] > 0))) { + mind = d; ih = i; } + } + // draw links + if (hasSlices && ((aLinks > 1/192.) || (aSkeleton > 1/192.) || (aNeighbors > 1/192.) || (aNetwork > 1/192.))) { + noFill(); strokeWeight(linkLineWidth); + // update search matches + if (searchMatchesValid) { + // update branch matching flags (would need to be recursive, but we are sloppy here) + // 1: node i matches search + // 0: node i does not match and we don't know of any children who match + // 2: node i does not match but we used to have matching children + for (int i = 0; i < NN; i++) + searchMatchesChild[i] = searchMatches[i] ? 1 : 2*searchMatchesChild[i]; + // if we think that node i has a matching child, tell the parent of node i + for (int i = 0; i < NN; i++) + if ((searchMatchesChild[i] > 0) && (pred[r][i] != -1)) + searchMatchesChild[pred[r][i]] = 1; + // if any of the nodes with status 2 has not been set to 1 by now, there is no matching child + for (int i = 0; i < NN; i++) + if (searchMatchesChild[i] == 2) + searchMatchesChild[i] = 0; + } + // visualize salience matrix + if (aSkeleton > 1/192.) { + for (int i = 0; i < NN; i++) { + for (int l = 0; l < salience.index[i].length; l++) { + int j = salience.index[i][l]; + if (j >= i) continue; // avoid drawing duplicate links + if (salience.value[i][l] == 0) continue; // not a salient link + stroke(192*(1 - salience.value[i][l]), 192*aSkeleton); + // FIXME: the following code is copy'n'pasted... + if (!wrap || (abs(nodes[i].x - nodes[j].x) < viewWidth/2)) + line(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y); + else { + if (nodes[i].x < nodes[j].x) { + line(nodes[i].x, nodes[i].y, nodes[j].x - viewWidth, nodes[j].y); + line(nodes[i].x + viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + } else { + line(nodes[i].x - viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + line(nodes[i].x, nodes[i].y, nodes[j].x + viewWidth, nodes[j].y); + } + } + } + } + } + // show direct neighbors of current root node + if (aNeighbors > 1/192.) synchronized (loglinks) { // sync against SortedLinkList.sort() + int i0 = isAltDown ? ih : r; // show neighbors of hovered node if Alt is held down + for (int l = 0; l < loglinks.NL; l++) { + int i = loglinks.src[l], j = loglinks.dst[l]; + if ((i != i0) && (j != i0)) continue; + stroke(192*(1 - (loglinks.value[l] - loglinks.minval)/(loglinks.maxval - loglinks.minval)), 192*aNeighbors); + // FIXME: the following code is copy'n'pasted... + if (!wrap || (abs(nodes[i].x - nodes[j].x) < viewWidth/2)) + line(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y); + else { + if (nodes[i].x < nodes[j].x) { + line(nodes[i].x, nodes[i].y, nodes[j].x - viewWidth, nodes[j].y); + line(nodes[i].x + viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + } else { + line(nodes[i].x - viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + line(nodes[i].x, nodes[i].y, nodes[j].x + viewWidth, nodes[j].y); + } + } + } + } + // show full network + if (aNetwork > 1/192.) synchronized (loglinks) { // sync against SortedLinkList.sort() + for (int l = 0; l < loglinks.NL; l++) { + int i = loglinks.src[l], j = loglinks.dst[l]; + stroke(192*(1 - (loglinks.value[l] - loglinks.minval)/(loglinks.maxval - loglinks.minval)), 192*aNetwork); + // FIXME: the following code is copy'n'pasted... + if (!wrap || (abs(nodes[i].x - nodes[j].x) < viewWidth/2)) + line(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y); + else { + if (nodes[i].x < nodes[j].x) { + line(nodes[i].x, nodes[i].y, nodes[j].x - viewWidth, nodes[j].y); + line(nodes[i].x + viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + } else { + line(nodes[i].x - viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + line(nodes[i].x, nodes[i].y, nodes[j].x + viewWidth, nodes[j].y); + } + } + } + } + // draw links in selected slice + if (aLinks > 1/192.) { + float aSNN = max(aSkeleton, max(aNeighbors, aNetwork)); + if (!showLinksWithSkeleton && !showLinksWithNeighbors && !showLinksWithNetwork && !(aSNN > 1 - 1/192.)) aSNN = 0; + float aN = (showLinksWithNetwork || (aNetwork > 1 - 1/192.)) ? aNetwork : 0; + strokeWeight(min(1, linkLineWidth + aN*aLinks)); // strongly emphasize slice if drawing over full network + stroke(64 + 128*aSNN, 64*(1 - aSNN), 64*(1 - aSNN), 192*aLinks + 63*aSNN); + for (int i = 0; i < NN; i++) { + int j = pred[r][i]; + if (j == -1) continue; // don't draw links from disconnected (or root) nodes + if (searchMatchesValid) { + float alphafactor = (searchMatches[i] || (searchMatchesChild[i] > 0)) ? 1.25 : 0.25; + stroke(64 + 128*aSNN, 64*(1 - aSNN), 64*(1 - aSNN), min(255, (192*aLinks + 63*aSNN)*alphafactor)); + strokeWeight((alphafactor > 1) ? 1 : 0.25); + } + if (!wrap || (abs(nodes[i].x - nodes[j].x) < viewWidth/2)) + line(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y); + else { + if (nodes[i].x < nodes[j].x) { + line(nodes[i].x, nodes[i].y, nodes[j].x - viewWidth, nodes[j].y); + line(nodes[i].x + viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + } else { + line(nodes[i].x - viewWidth, nodes[i].y, nodes[j].x, nodes[j].y); + line(nodes[i].x, nodes[i].y, nodes[j].x + viewWidth, nodes[j].y); + } + } + } + } + strokeWeight(1); + } + // draw nodes + rectMode(CENTER); + float nodeSize_target = nodeSizeFactor*sqrt(min(width, height))*sqrt(zoom[viewMode]); + nodeSize += 3*(nodeSize_target - nodeSize)*min(dt, 1/3.); + if (aNodes > 1/192.) { + noStroke(); + for (int i = 0; i < NN; i++) { + float alphafactor = !searchMatchesValid ? 1 : (searchMatches[i] ? 1.25 : 0.125); + fill((val == null) ? 127 : colormap.getColor(val[i]), 192*aNodes*nodes[i].a*alphafactor); + if (fastNodes) + rect(nodes[i].x + .5, nodes[i].y + .5, 3*nodeSize/4, 3*nodeSize/4); + else + ellipse(nodes[i].x, nodes[i].y, nodeSize, nodeSize); + } + } + // mark root node and hovered node (these are shown even if showNodes is false) + if (r > -1) { + stroke(255, 0, 0); noFill(); + if (fastNodes) rect(nodes[r].x, nodes[r].y, 3*nodeSize/4 + .5, 3*nodeSize/4 + .5); + else ellipse(nodes[r].x, nodes[r].y, nodeSize + .5, nodeSize + .5); + } + if (ih > -1) { + stroke(200, 0, 0); noFill(); + if (fastNodes) rect(nodes[ih].x, nodes[ih].y, 3*nodeSize/4 + .5, 3*nodeSize/4 + .5); + else ellipse(nodes[ih].x, nodes[ih].y, nodeSize + .5, nodeSize + .5); + } + rectMode(CORNER); + // draw labels + textFont(/*fnSmall*/fnMedium); + textAlign(LEFT, BASELINE); + noStroke(); + for (int i = 0; i < NN; i++) { + if ((i == r) || (i == ih) || ((aLabels > 1/255.) && nodes[i].showLabel && (!searchMatchesValid || searchMatches[i]))) { + fill(0, 255*aLabels*nodes[i].a); + text(nodes[i].label + (((i == ih) && (val != null)) ? " (" + format(val[i]) + ")" : ""), + nodes[i].x + nodeSize/4, nodes[i].y - nodeSize/4); + } + } + // reset nodes.x/y if wrapping is on + if (wrap) + for (int i = 0; i < NN; i++) + { nodes[i].x = tmpx[i]; nodes[i].y = tmpy[i]; } + } + + String format(float val) { + if (val == 0) + return "0"; + else if ((val > 1 - 1e-7) && (val < 100000)) { + int nd = 3; if (val >= 10) nd--; if (val >= 100) nd--; if (val >= 1000) nd--; + String res = nfc(val, nd); + if (nd > 0) res = res.replaceAll("0+$", "").replaceAll("\\.$", ""); + return res; + } else + return String.format("%.4g", val); + } +} + diff --git a/SVE2Workspace.pde b/SVE2Workspace.pde new file mode 100644 index 0000000..733181f --- /dev/null +++ b/SVE2Workspace.pde @@ -0,0 +1,203 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +File workspaceFile = null; +boolean showWorkspaceRecoveryButton = true; +SVE2Document doc = null; // current document +Vector docs = new Vector(); // all loaded documents + +/* + * Document Management + */ + +// This FileFilter accepts: +// 1) directories ending with ".spato" if they contain a document.xml +// 2) files ending with ".spato" if they are zip files +// 3) files named "document.xml" if they are in directory ending with ".spato" +// It's probably a good idea to allow case (3), because selecting directories might +// seem unusally awkward for some users (it's still possible, though). +static FileFilter ffDocuments = new FileFilter() { + public String getDescription() { return "SPaTo Documents"; } + public boolean accept(File f) { + if (f.getName().endsWith(".spato")) { + if (f.isDirectory()) { // accept .spato directory if it contains a document.xml + for (File ff : f.listFiles()) + if (ff.getName().equals("document.xml")) + return true; + return false; + } else // accept .spato files if it's a zip file + try { new ZipFile(f); return true; } catch (Exception e) { return false; } + } + if (f.getName().equals("document.xml")) // accept document.xml if it's inside a .spato directory + return f.getParent().endsWith(".spato"); + return false; + } +}; + +File[] selectDocumentFilesToOpen() { + File result[] = selectFiles(OPENMULTIPLE, "Open document", ffDocuments); + for (int i = 0; i < result.length; i++) // normalize filename if some + if (result[i].getName().equals("document.xml")) // blabla.spato/document.xml + result[i] = result[i].getParentFile(); // was selected + return result; +} +File selectDocumentFileToWrite() { return selectDocumentFileToWrite(null); } +File selectDocumentFileToWrite(File selectedFile) { + return ensureExtension("spato", selectFile(SAVE, "Save document", ffDocuments, selectedFile)); } + +void newDocument() { + SVE2Document newdoc = new SVE2Document(); + docs.add(newdoc); + switchToNetwork(newdoc); +// new LinksImportWizard(newdoc).start(); +} + +void openDocument() { openDocuments(selectDocumentFilesToOpen()); } +void openDocument(File file) { if (file != null) openDocuments(new File[] { file }); } +void openDocuments(File files[]) { + if (files == null) return; + for (File f : files) { + SVE2Document newdoc = null; + for (SVE2Document d : docs) + if (d.getFile().equals(f)) + newdoc = d; // this document is already open + if (newdoc == null) { // load if not already open + newdoc = new SVE2Document(f); + docs.add(newdoc); + worker.submit(newdoc.newLoadingTask()); + } + switchToNetwork(newdoc); + } +} + +void closeDocument() { + int i = docs.indexOf(doc); + if (i == -1) return; + docs.remove(i); + switchToNetwork((docs.size() > 0) ? docs.get(i % docs.size()) : null); + //worker.remove(doc); // cancel any jobs in the worker thread that are related to this document +} + +void saveDocument() { saveDocument(false); } +void saveDocument(boolean forceSelect) { + if (doc == null) return; + File file = doc.getFile(); + for (SVE2Document d : docs) + if ((d != doc) && d.getFile().equals(file)) + docs.remove(d); // prevent duplicate entries in docs + if ((file == null) || forceSelect) { + if ((file = selectDocumentFileToWrite(file)) == null) return; + boolean compressed = !file.exists() || !file.isDirectory(); // save compressed by default + doc.setFile(file, compressed); + updateWorkspacePref(); + } + worker.submit(doc.newSavingTask()); +} + +boolean switchToNetwork(int i) { return switchToNetwork(((i < 0) || (i >= docs.size())) ? docs.get(i) : null); } +boolean switchToNetwork(String name) { + SVE2Document newdoc = null; + for (int i = 0; i < docs.size(); i++) + if (name.equals(docs.get(i).getName())) + newdoc = docs.get(i); + return switchToNetwork(newdoc); +} +boolean switchToNetwork(SVE2Document newdoc) { + searchMatchesValid = false; + searchMatches = null; + doc = newdoc; + guiUpdate(); + updateWorkspacePref(); + return doc != null; +} + +/* + * Workspace Management + */ + +static FileFilter ffWorkspace = createFileFilter("sve", "SVE Workspaces"); + +File selectWorkspaceFileToOpen() { return selectFile(OPEN, "Open workspace", ffWorkspace); } +File selectWorkspaceFileToWrite() { return selectWorkspaceFileToWrite(null); } +File selectWorkspaceFileToWrite(File selectedFile) { + return ensureExtension("sve", selectFile(SAVE, "Save workspace", ffWorkspace, selectedFile)); } + +void openWorkspace() { openWorkspace(selectWorkspaceFileToOpen()); } +void openWorkspace(File file) { + if ((file == null) || file.equals(workspaceFile)) return; + try { + replaceWorkspace(new XMLElement(this, file.getAbsolutePath())); + } catch (Exception e) { + console.logError("Error reading workspace from " + file.getAbsolutePath() + ": ", e); + workspaceFile = null; + return; + } + console.logInfo("Opened workspace " + file.getAbsolutePath()); + workspaceFile = file; +} + +void saveWorkspace() { saveWorkspace(false); } +void saveWorkspace(boolean forceSelect) { + File file = workspaceFile; + if ((file == null) || forceSelect) + file = selectWorkspaceFileToWrite(file); + if (file == null) return; + try { + PrintWriter writer = createWriter(file.getAbsolutePath()); + writer.write("\n"); + new XMLWriter(writer).write(XMLElement.parse(prefs.get("workspace", "")), true); + writer.close(); + } catch (Exception e) { + console.logError("Error saving workspace to " + file.getAbsolutePath() + ": ", e); + return; + } + console.logInfo("Workspace saved to " + file.getAbsolutePath()); + workspaceFile = file; +} + +void updateWorkspacePref() { + String workspace = ""; + for (SVE2Document d : docs) + if (d.getFile() != null) + workspace += ""; + workspace = "" + workspace + ""; + prefs.put("workspace", workspace); + showWorkspaceRecoveryButton = false; +} + +void replaceWorkspace(XMLElement workspace) { + if (workspace == null) return; + doc = null; + docs.clear(); + XMLElement xmlDocuments[] = workspace.getChildren("document"); + for (XMLElement xmlDocument : xmlDocuments) { + String src = xmlDocument.getString("src"); + if (src == null) continue; // should not happen... + SVE2Document newdoc = new SVE2Document(new File(src)); + docs.add(newdoc); + worker.submit(newdoc.newLoadingTask()); + if (xmlDocument.getBoolean("selected")) + switchToNetwork(newdoc); + } + if ((doc == null) && (docs.size() > 0)) switchToNetwork(docs.get(0)); + else updateWorkspacePref(); + guiUpdate(); +} diff --git a/Scaling.pde b/Scaling.pde new file mode 100644 index 0000000..627ffde --- /dev/null +++ b/Scaling.pde @@ -0,0 +1,66 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +static abstract class Scaling { + int N = 0; + float sx[]; // scaled values + Scaling(int N) { this.N = N; sx = new float[N]; } + abstract float[] f(float[] x); +} + +static class ScalingFactory { + static String[] productNames = { "id", "sqrt", "log" }; + + static boolean canProduce(String name) { + for (int i = 0; i < productNames.length; i++) + if (name.equals(productNames[i])) + return true; + return false; + } + static String getDefaultProduct() { return productNames[0]; } + + static Scaling produce(String name, int N) { + if (name.equals("id")) return new IdScaling(N); + if (name.equals("sqrt")) return new SqrtScaling(N); + if (name.equals("log")) return new LogScaling(N); + return null; + } +} + +static class IdScaling extends Scaling { + IdScaling(int N) { super(N); } + float[] f(float[] x) { for (int i = 0; i < N; i++) sx[i] = x[i]; return sx; } +} + +static class SqrtScaling extends Scaling { + SqrtScaling(int N) { super(N); } + float[] f(float[] x) { for (int i = 0; i < N; i++) sx[i] = sqrt(x[i]); return sx; } +} + +static class LogScaling extends Scaling { + float x0 = 1; + LogScaling(int N) { super(N); } + LogScaling(int N, float x0) { super(N); this.x0 = x0; } + float[] f(float[] x) { + for (int i = 0; i < N; i++) + sx[i] = (x[i] == 0) ? 0 : log(x[i]/x0); + return sx; + } +} \ No newline at end of file diff --git a/Update.pde b/Update.pde new file mode 100644 index 0000000..b5aa494 --- /dev/null +++ b/Update.pde @@ -0,0 +1,289 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.security.PublicKey; +import java.security.Signature; +import java.security.KeyFactory; +import java.security.spec.X509EncodedKeySpec; +import javax.swing.JOptionPane; +import javax.swing.*; +import java.awt.*; + + +class Updater extends Thread { + + boolean force = false; + String updateURL = "http://update.spato.net/latest/"; + String releaseNotesURL = "http://update.spato.net/release-notes/"; + String indexName = null; + String appRootFolder = null; + String cacheFolder = null; + XMLElement index = null; + String updateVersion = null; + // public key for file verification (base64-encoded) + String pubKey64 = + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrWkHeVPecXQeOd2" + + "C3K4UUzgBqXYJwfGNKZnLp17wy/45nH7/llxBKR7eioJPdYCauxQ8M" + + "nuArSltlIV9AnBKxb8h28xoBsEx1ek04jvJEtd93Bw7ILa3eF4MDGl" + + "ZxwPnmTaTICIVUXtiZveOHDl1dQBKvinyU8fe3Xi7+j9klnwIDAQAB"; + + public Updater(boolean force) { + setPriority(Thread.MIN_PRIORITY); + this.force = force; + // if (System.getProperty("spato.app-dir") == null) + // System.setProperty("spato.app-dir", "/Users/ct/Documents/Processing/SPaTo/SPaTo_Visual_Explorer/application.macosx/SPaTo_Visual_Explorer.app"); + } + + void printOut(String msg) { System.out.println("+++ SPaTo Updater: " + msg); } + void printErr(String msg) { System.err.println("+++ SPaTo Updater: " + msg); } + + void setupEnvironment() { + printOut("updateURL = " + updateURL); + // determine which INDEX file to download + switch (platform) { + case LINUX: indexName = "INDEX.linux"; break; + case MACOSX: indexName = "INDEX.macosx"; break; + case WINDOWS: indexName = "INDEX.windows"; break; + default: throw new RuntimeException("unsupported platform"); + } + printOut("indexName = " + indexName); + // check application root folder + appRootFolder = System.getProperty("spato.app-dir"); + if ((appRootFolder == null) || !new File(appRootFolder).exists()) + throw new RuntimeException("invalid application root folder: " + appRootFolder); + if (!appRootFolder.endsWith(File.separator)) appRootFolder += File.separator; + printOut("appRootFolder = " + appRootFolder); + // check update cache folder + switch (platform) { + case LINUX: cacheFolder = System.getProperty("user.home") + "/.spato/update"; break; + case MACOSX: cacheFolder = appRootFolder + "Contents/Resources/update"; break; + default: cacheFolder = appRootFolder + "update"; break; + } + if ((cacheFolder == null) || !new File(cacheFolder).exists() && !new File(cacheFolder).mkdirs()) + throw new RuntimeException("could not create cache folder: " + cacheFolder); + if (!cacheFolder.endsWith(File.separator)) cacheFolder += File.separator; + printOut("cacheFolder = " + cacheFolder); + } + + boolean checkAndFetch() { // returns true if update is available + int count = 0, totalSize = 0; + BufferedReader reader = null; + // fetch the index + try { + // reader creation copied from PApplet so we can catch exceptions + InputStream is = new URL(updateURL + indexName).openStream(); + reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); + // XML parsing copied from XMLElement so we can catch exceptions + index = new XMLElement(); + StdXMLParser parser = new StdXMLParser(); + parser.setBuilder(new StdXMLBuilder(index)); + parser.setValidator(new XMLValidator()); + parser.setReader(new StdXMLReader(reader)); + parser.parse(); + } catch (XMLException xmle) { + index = null; + throw new RuntimeException("Not a valid XML file: " + updateURL + indexName + "
" + + "Are you properly connected to the interwebs?"); + } catch (Exception e) { // FIXME: react to specific exceptions + index = null; + throw new RuntimeException("could not download " + indexName, e); + } finally { + try { reader.close(); } catch (Exception e) { } + } + // check whether the user wants to ignore this update + try { updateVersion = index.getChild("release").getString("version"); } catch (Exception e) {} + printOut("INDEX is for version " + updateVersion); + if ((updateVersion != null) && updateVersion.equals(prefs.get("update.skip", null))) { + printOut("user requested to skip this version"); + return false; + } else + prefs.remove("update.skip"); + // delete possibly existing locally cached index + new File(cacheFolder + "INDEX").delete(); + // setup signature verification + Signature sig = null; + try { + sig = Signature.getInstance("MD5withRSA"); + X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(pubKey64)); + sig.initVerify(KeyFactory.getInstance("RSA").generatePublic(spec)); + } catch (Exception e) { throw new RuntimeException("failed to setup signature verification", e); } + // iterate over all file records + for (XMLElement file : index.getChildren("file")) { + XMLElement remote = file.getChild("remote"), local = file.getChild("local"); + // check if all information is present + if ((remote == null) || (remote.getString("path") == null) || (remote.getString("md5") == null) || + (local == null) || (local.getString("path") == null)) + throw new RuntimeException("malformed file record: " + file); + // check for signature and decode + byte signature[] = null; + if ((file.getChild("signature") == null) || (file.getChild("signature").getContent() == null)) + throw new RuntimeException("missing file signature: " + file); + try { signature = Base64.decode(file.getChild("signature").getContent()); } + catch (Exception e) { throw new RuntimeException("error decoding signature: " + file, e); } + // download update file if necessary + local.setString("md5", "" + MD5.digest(appRootFolder + local.getString("path"))); // "" forces "null" if md5 returns null + if (!remote.getString("md5").equals(local.getString("md5"))) { + count++; // count number of outdated files + String cacheFilename = cacheFolder + remote.getString("path").replace('/', File.separatorChar); + if (remote.getString("md5").equals(MD5.digest(cacheFilename))) + printOut(remote.getString("path") + " is outdated, but update is already cached"); + else { + printOut(remote.getString("path") + " is outdated, downloading update (" + remote.getInt("size") + " bytes)"); + byte buf[] = new byte[remote.getInt("size", 0)]; + InputStream is = null; + try { + int read = 0; + is = new URL(updateURL + remote.getString("path")).openStream(); + while (read < buf.length) + is.read(buf, read, buf.length - read); + } catch (Exception e) { + printErr("download failed"); e.printStackTrace(); return false; + } finally { + try { is.close(); } catch (Exception e) {} + } + try { sig.update(buf); if (!sig.verify(signature)) throw new Exception("signature verification failure"); } + catch (Exception e) { printErr("failed to verify file"); e.printStackTrace(); return false; } + saveBytes(cacheFilename, buf); + totalSize += remote.getInt("size"); // keep track of total download volume + if (!remote.getString("md5").equals(MD5.digest(cacheFilename))) + throw new RuntimeException("md5 mismatch: " + file); + } + } + } + // clean up and return + if (count > 0) { + printOut("updates available for " + count + " files, downloaded " + totalSize + " bytes"); + return true; + } else { + printOut("no updates available"); + new File(cacheFolder).delete(); + return false; + } + } + + String[] getRestartCmd() { + switch (platform) { + case LINUX: + return new String[] { appRootFolder + "SPaTo_Visual_Explorer", "--restart" }; + case MACOSX: + return new String[] { appRootFolder + "Contents/MacOS/ApplicationUpdateWrapper", "--restart" }; + case WINDOWS: + return new String[] { appRootFolder + "SPaTo Visual Explorer.exe", "sleep", "3" }; + default: + return null; + } + } + + final static int NOTHING = -1, IGNORE = 0, INSTALL = 1, RESTART = 2; + + int showReleaseNotesDialog(boolean canRestart) { + // construct URL request + String url = releaseNotesURL + "?version=" + version + "&index=" + indexName; + // setup HTML renderer for release notes + XHTMLPanel htmlView = new XHTMLPanel(); + try { htmlView.setDocument(url); } + catch (Exception e) { throw new RuntimeException("could not fetch release notes from " + url, e); } + JScrollPane scrollPane = new FSScrollPane(htmlView); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + // compose everything in a panel + JPanel panel = new JPanel(new BorderLayout(0, 10)); + panel.add(new JLabel("An update is available and can be applied the next time you start SPaTo Visual Explorer."), BorderLayout.NORTH); + panel.add(scrollPane, BorderLayout.CENTER); + panel.add(new JLabel("You are currently running version " + version + " (" + versionDate + ")."), BorderLayout.SOUTH); + panel.setPreferredSize(new Dimension(600, 400)); + panel.setMinimumSize(new Dimension(300, 200)); + // add the auto-check checkbox + JCheckBox cbAutoUpdate = new JCheckBox("Automatically check for updates in the future", + prefs.getBoolean("update.check", true)); + JPanel panel2 = new JPanel(new BorderLayout(0, 20)); + panel2.add(panel, BorderLayout.CENTER); + panel2.add(cbAutoUpdate, BorderLayout.SOUTH); + // setup the options + Object options[] = canRestart + ? new Object[] { "Restart now", "Restart later", "Skip this update" } + : new Object[] { "Awesome!", "Skip this update" }; + // show the dialog + int result = JOptionPane.showOptionDialog(frame, panel2, "Good news, everyone!", + JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, + options, options[0]); + // save the auto-check selection + prefs.putBoolean("update.check", cbAutoUpdate.isSelected()); + // return the proper action constant + if (result == (canRestart ? 2 : 1)) return IGNORE; // skip this update + if (result == (canRestart ? 1 : 0)) return INSTALL; // install on next application launch + if (result == 0 && canRestart) return RESTART; // install now + return NOTHING; // this will cause to do nothing (no kidding!) + } + + void askAndAct() { + while (fireworks) try { Thread.sleep(5000); } catch (Exception e) {} + String cmd[] = getRestartCmd(); + int action = showReleaseNotesDialog(cmd != null); + // check if the user wants to ignore this update + if (action == IGNORE) + prefs.put("update.skip", updateVersion); + // save the INDEX into the update cache folder to indicate that the update should be installed + if ((action == INSTALL) || (action == RESTART)) + index.write(createWriter(cacheFolder + "INDEX")); + // restart application if requested + if (action == RESTART) try { + new ProcessBuilder(cmd).start(); + exit(); // FIXME: unsaved documents? + } catch (Exception e) { // catch this one here to give a slightly more optimistic error message + printErr("could not restart application"); e.printStackTrace(); + JOptionPane.showMessageDialog(frame, + "The restart application could not be lauched:

" + + PApplet.join(cmd, " ") + "
" + e.getClass().getName() + ": " + e.getMessage() + "

" + + "However, the update should install automatically when you manually restart the application.", + "Slightly disappointing news", + JOptionPane.ERROR_MESSAGE); + } + } + + void run() { + try { + setupEnvironment(); + if (checkAndFetch()) + askAndAct(); + else if (force) + JOptionPane.showMessageDialog(frame, + "No updates available", "Update", JOptionPane.INFORMATION_MESSAGE); + } catch (Exception e) { + printErr("Something's wrong. Stack trace follows..."); e.printStackTrace(); + // prepare error dialog + JPanel panel = new JPanel(new BorderLayout(0, 20)); + String str = "Something went wrong while checking for updates.

" + + e.getMessage().substring(0, 1).toUpperCase() + e.getMessage().substring(1); + if (e.getCause() != null) + str += "\ndue to " + e.getCause().getClass().getName() + ": " + e.getCause().getMessage(); + str += ""; + panel.add(new JLabel(str), BorderLayout.CENTER); + JCheckBox cbAutoUpdate = new JCheckBox("Automatically check for updates in the future", + prefs.getBoolean("update.check", true)); + panel.add(cbAutoUpdate, BorderLayout.SOUTH); + // show dialog + JOptionPane.showMessageDialog(frame, panel, "Bollocks!", JOptionPane.ERROR_MESSAGE); + // save the auto-check selection + prefs.putBoolean("update.check", cbAutoUpdate.isSelected()); + } + } + +} diff --git a/Utilities.pde b/Utilities.pde new file mode 100644 index 0000000..a80fbfc --- /dev/null +++ b/Utilities.pde @@ -0,0 +1,241 @@ +/* + * Copyright 2011 Christian Thiemann + * Developed at Northwestern University + * + * This file is part of the SPaTo Visual Explorer (SPaTo). + * + * SPaTo is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SPaTo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with SPaTo. If not, see . + */ + +import java.awt.FileDialog; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; +import javax.swing.SwingUtilities; +import java.security.MessageDigest; +import java.security.DigestInputStream; + + +Date parseISO8601(String timestamp) { + try { return new SimpleDateFormat("yyyyMMdd'T'HHmmss").parse(timestamp); } + catch (Exception e) { e.printStackTrace(); return null; } +} + +static class MD5 { + static String digest(String file) { + if (!new File(file).exists()) return null; + try { + MessageDigest md5 = MessageDigest.getInstance("md5"); + DigestInputStream dis = new DigestInputStream(new FileInputStream(file), md5); + byte buf[] = new byte[8*1024]; + while (dis.read(buf, 0, buf.length) > 0) /* do nothing while md5 digests as data streams in */; + dis.close(); + return String.format("%032x", new java.math.BigInteger(1, md5.digest())); + } catch (Exception e) { + throw new RuntimeException("failed to calculate MD5 checksum of " + file, e); + } + } +} + +static class Base64 { + private static char map[] = new char[64]; + static { + for (int i = 00; i < 26; i++) map[i] = (char)('A' + (i - 00)); + for (int i = 26; i < 52; i++) map[i] = (char)('a' + (i - 26)); + for (int i = 52; i < 62; i++) map[i] = (char)('0' + (i - 52)); + map[62] = '+'; map[63] = '/'; + } + // this is incredibly inefficient, but ok for our purposes (only decoding short hashes and keys) + private static int unmap(char c) { + for (int i = 0; i < 64; i++) if (map[i] == c) return i; + throw new IllegalArgumentException("value " + c + " is not in the map"); + } + + static String encode(byte data[]) { return encode(data, 76); } + static String encode(byte data[], int wrapColumn) { + StringBuffer result = new StringBuffer(); + int input[] = new int[3]; + int output[] = new int[4]; + int lineLen = 0; + for (int i = 0; i < data.length; i += 3) { + int len = Math.min(3, data.length - i); + input[0] = 0xff & (int)data[i+0]; + input[1] = (len > 1) ? (0xff & (int)data[i+1]) : 0; + input[2] = (len > 2) ? (0xff & (int)data[i+2]) : 0; + output[0] = (0xfc & input[0]) >> 2; // get highest 6 bits of first input byte + output[1] = ((0x03 & input[0]) << 4) + ((0xf0 & input[1]) >> 4); // get lowest 2 bits of first and highest 4 bits of second input byte + output[2] = ((0x0f & input[1]) << 2) + ((0xc0 & input[2]) >> 6); // lowest 4 bits of second and hightes 2 bits of third input byte + output[3] = (0x3f & input[2]); // lowest 6 bits of third input byte + result.append(map[output[0]]); + if (++lineLen == wrapColumn) { result.append('\r'); result.append('\n'); lineLen = 0; } + result.append(map[output[1]]); + if (++lineLen == wrapColumn) { result.append('\r'); result.append('\n'); lineLen = 0; } + result.append(len > 1 ? map[output[2]] : '='); + if (++lineLen == wrapColumn) { result.append('\r'); result.append('\n'); lineLen = 0; } + result.append(len > 2 ? map[output[3]] : '='); + if (++lineLen == wrapColumn) { result.append('\r'); result.append('\n'); lineLen = 0; } + } + return result.toString(); + } + + static byte[] decode(String data) { + String lines[] = data.split("\n"); + data = ""; for (String line : lines) data += line.trim(); + if (data.length() % 4 != 0) throw new IllegalArgumentException("input length is not a multiple of four"); + int reslen = data.length()*3/4; + if (data.charAt(data.length() - 1) == '=') { reslen--; data = data.substring(0, data.length() - 1); } + if (data.charAt(data.length() - 1) == '=') { reslen--; data = data.substring(0, data.length() - 1); } + if (data.charAt(data.length() - 1) == '=') throw new IllegalArgumentException("input has to many padding characters"); + byte result[] = new byte[reslen]; + int input[] = new int[4]; + int output[] = new int[3]; + int ii = 0; + for (int i = 0; i < data.length(); i += 4) { + int len = Math.min(4, data.length() - i); + input[0] = unmap(data.charAt(i)); + input[1] = unmap(data.charAt(i + 1)); + input[2] = (len > 2) ? unmap(data.charAt(i + 2)) : 0; + input[3] = (len > 3) ? unmap(data.charAt(i + 3)) : 0; + output[0] = (input[0] << 2) + ((0x30 & input[1]) >> 4); + output[1] = ((0x0f & input[1]) << 4) + ((0x3c & input[2]) >> 2); + output[2] = ((0x03 & input[2]) << 6) + input[3]; + result[ii++] = (byte)output[0]; + if (len > 2) result[ii++] = (byte)output[1]; + if (len > 3) result[ii++] = (byte)output[2]; + } + return result; + } +} + + +/* + * FileDialog/JFileChooser-related things + */ + +static FileFilter createFileFilter(final String ext, final String desc) { + return createFileFilter(new String[] { ext }, desc); } +static FileFilter createFileFilter(final String exts[], final String desc) { + return new FileFilter() { + public String getDescription() { return desc; } + public boolean accept(File f) { + if (f.isDirectory()) return false; + for (String ext : exts) if (f.getName().endsWith("." + ext)) return true; + return false; + } + }; +} + +// Yeah, nice... JFileChooser uses a different way of filtering files (FileFilter) than FileDialog (FilenameFilter). +// This class acts as a FilenameFilter, but with a FileFilter the decision-making backend. +class FilenameFileFilterAdapter implements FilenameFilter { + FileFilter ff = null; + FilenameFileFilterAdapter(FileFilter ff) { this.ff = ff; } + public boolean accept(File dir, String name) { return ff.accept(new File(dir, name)); } +} + +// And also nice: JFileChooser on Windows does not display directories at all if they are rejected by +// the FileFilter, which means you cannot change into them, which means you most probably cannot reach +// any of the files of interest. So, this class accepts all directories before asking the real filter. +// The selectFiles method will sort out selected, non-acceptable directories afterwards. +class WindowsFileFilterAdapter extends FileFilter { + FileFilter ff = null; + WindowsFileFilterAdapter(FileFilter ff) { this.ff = ff; } + public String getDescription() { return ff.getDescription(); } + public boolean accept(File f) { return f.isDirectory() ? true : ff.accept(f); } +} + +static File ensureExtension(String ext, File file) { + if ((ext == null) || (file == null)) return null; + return file.getName().endsWith("." + ext) ? file : new File(file.getAbsolutePath() + "." + ext); +} + +static final int OPEN = 0; +static final int OPENMULTIPLE = 1; +static final int SAVE = 2; + +File selectFile(int mode) { return selectFile(mode, null, null, null); } +File selectFile(int mode, String title) { return selectFile(mode, title, null, null); } +File selectFile(int mode, String title, FileFilter ff) { return selectFile(mode, title, ff, null); } +File selectFile(int mode, String title, FileFilter ff, File selectedFile) { + File res[] = selectFiles(mode, title, ff, selectedFile); + return ((res != null) && (res.length > 0)) ? res[0] : null; +} + +File selectFilesResult[]; +File[] selectFiles(int mode) { return selectFiles(mode, null, null, null); } +File[] selectFiles(int mode, String title) { return selectFiles(mode, title, null, null); } +File[] selectFiles(int mode, String title, FileFilter ff) { return selectFiles(mode, title, ff, null); } +File[] selectFiles(final int mode, final String title, final FileFilter ff, final File selectedFile) { + checkParentFrame(); + try { + selectFilesResult = null; + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + File lastDir = new File(prefs.get("workspace.lastDirectory", "")); + if (lastDir.getAbsolutePath().equals("")) lastDir = null; + if (platform == MACOSX) { + // Use FileDialog instead of JFileChooser as per Apple recommendation. + // This is possible again because .spato-directories are Mac bundles now. + FileDialog fd = new FileDialog(parentFrame, + (title != null) ? title : (mode == SAVE) ? "Save..." : "Open...", + (mode == SAVE) ? FileDialog.SAVE : FileDialog.LOAD); + fd.setFilenameFilter(new FilenameFileFilterAdapter(ff)); + String dirname = null; + if (selectedFile != null) dirname = selectedFile.getParent(); + else if (lastDir != null) dirname = lastDir.getAbsolutePath(); + fd.setDirectory(dirname); + fd.setFile((selectedFile != null) ? selectedFile.getAbsolutePath() : null); + fd.setVisible(true); + selectFilesResult = new File[0]; + if ((fd.getFile() != null) && ((mode == SAVE) || ff.accept(new File(fd.getDirectory(), fd.getFile())))) + selectFilesResult = new File[] { new File(fd.getDirectory(), fd.getFile()) }; + } else { + JFileChooser fc = new JFileChooser(); + // set initial directory and possibly initially selected file + fc.setCurrentDirectory((selectedFile != null) ? selectedFile.getParentFile() : lastDir); + if (selectedFile != null) + fc.setSelectedFile(selectedFile); + // setup dialog look and feel + fc.setDialogTitle((title != null) ? title : (mode == SAVE) ? "Save..." : "Open..."); + fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); + fc.setMultiSelectionEnabled(mode == OPENMULTIPLE); // allow selecting multiple documents to load + fc.setAcceptAllFileFilterUsed(ff == null); + if (ff != null) fc.setFileFilter((platform == WINDOWS) ? new WindowsFileFilterAdapter(ff) : ff); + // run dialog + if (fc.showDialog(parentFrame, (mode == SAVE) ? "Save" : "Open") == JFileChooser.APPROVE_OPTION) { + // save current directory to preferences + File dir = fc.getCurrentDirectory(); + prefs.put("workspace.lastDirectory", (dir != null) ? dir.getAbsolutePath() : null); + // evaluate selection + File files[] = fc.isMultiSelectionEnabled() + ? fc.getSelectedFiles() : new File[] { fc.getSelectedFile() }; + if (mode != SAVE) + for (int i = 0; i < files.length; i++) + if ((ff != null) && !ff.accept(files[i])) + files[i] = null; + // transcribe selection into result array + selectFilesResult = new File[0]; + for (int i = 0; i < files.length; i++) + if (files[i] != null) + selectFilesResult = (File[])append(selectFilesResult, files[i]); + } + } + } + }); + return selectFilesResult; + } catch (Exception e) { + console.logError("Something went wrong: ", e); + e.printStackTrace(); + return null; + } +} diff --git a/code/README b/code/README new file mode 100644 index 0000000..e9e77e9 --- /dev/null +++ b/code/README @@ -0,0 +1,11 @@ +This directory contains various libraries used by the SPaTo Visual Explorer: + +jna.jar is the Java Native Access library + Copyright (c) 2007 Wayne Meissner, All Rights Reserved + Copyright (c) 2007, 2008, 2009 Timothy Wall, All Rights Reserved + +xhtmlrenderer.jar is the Flying Saucer XHTML renderer + +tGUI.jar is the TransparentGUI for Processing +jnmatlib.jar is the native interface for libmat and libmx + Copyright 2011 Christian Thiemann diff --git a/code/jna.jar b/code/jna.jar new file mode 100644 index 0000000..55ca1eb Binary files /dev/null and b/code/jna.jar differ diff --git a/code/jnmatlib.jar b/code/jnmatlib.jar new file mode 100644 index 0000000..165a488 Binary files /dev/null and b/code/jnmatlib.jar differ diff --git a/code/tGUI.jar b/code/tGUI.jar new file mode 100644 index 0000000..6be9521 Binary files /dev/null and b/code/tGUI.jar differ diff --git a/code/xhtmlrenderer.jar b/code/xhtmlrenderer.jar new file mode 100644 index 0000000..871fabf Binary files /dev/null and b/code/xhtmlrenderer.jar differ diff --git a/support/INDEX.linux b/support/INDEX.linux new file mode 100644 index 0000000..55edc34 --- /dev/null +++ b/support/INDEX.linux @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/INDEX.macosx b/support/INDEX.macosx new file mode 100644 index 0000000..1d3dcbe --- /dev/null +++ b/support/INDEX.macosx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/INDEX.windows b/support/INDEX.windows new file mode 100644 index 0000000..f4d9a25 --- /dev/null +++ b/support/INDEX.windows @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/Makefile b/support/Makefile new file mode 100644 index 0000000..da32517 --- /dev/null +++ b/support/Makefile @@ -0,0 +1,24 @@ + +VERSION ?= dev +PASSWORD = `security -q find-internet-password -g -r "ftp " -a ftp1032083-spato -s wp255.webpack.hosteurope.de 2>&1 | grep password: | awk '{ print $$2; }' | awk -F '"' '{ print $$2; }'` +PRIVKEYPASS = `security -q find-generic-password -g -a spato.update 2>&1 | grep password: | awk '{ print $$2; }' | awk -F '"' '{ print $$2; }'` + +update: SPaTo_Update_Builder.class + make -C .. apps + java -cp .:../application.macosx/SPaTo_Visual_Explorer.app/Contents/Resources/Java/SPaTo_Visual_Explorer.jar:../application.macosx/SPaTo_Visual_Explorer.app/Contents/Resources/Java/core.jar SPaTo_Update_Builder $(PRIVKEYPASS) + +SPaTo_Update_Builder.class: SPaTo_Update_Builder.java + javac -cp ../application.macosx/SPaTo_Visual_Explorer.app/Contents/Resources/Java/SPaTo_Visual_Explorer.jar:../application.macosx/SPaTo_Visual_Explorer.app/Contents/Resources/Java/core.jar $? + +symlink: + curl http://update.spato.net/symlink.php?latest=$(VERSION)\&magic=$(PASSWORD) + + +PROCESSING_SVN_ROOT = /Users/ct/Software/processing_r7148 + +updateApp: + rm -rf Processing.app + cp -a $(PROCESSING_SVN_ROOT)/build/macosx/work/Processing.app . + rm -rf Processing.app/Contents/Resources/Java/{examples,reference,tools} + rm -rf Processing.app/Contents/Resources/Java/libraries/{dxf,javascript,minim,net,opengl,serial,video} + diff --git a/support/Processing_core_src/README b/support/Processing_core_src/README new file mode 100644 index 0000000..2c38994 --- /dev/null +++ b/support/Processing_core_src/README @@ -0,0 +1,10 @@ +SPaTo currently uses a custom Processing core.jar, which is +based on revision r7148. The modified source code is made +available in this directory. + +The Procesing core library is released under the GNU Lesser +General Public License, and is part of the Processing project: +http://www.processing.org/ + Copyright (c) 2004-10 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + diff --git a/support/Processing_core_src/processing/core/PApplet.java b/support/Processing_core_src/processing/core/PApplet.java new file mode 100644 index 0000000..0133cb0 --- /dev/null +++ b/support/Processing_core_src/processing/core/PApplet.java @@ -0,0 +1,10373 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-10 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation, version 2.1. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.applet.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import java.io.*; +import java.lang.reflect.*; +import java.net.*; +import java.text.*; +import java.util.*; +import java.util.regex.*; +import java.util.zip.*; + +import javax.imageio.ImageIO; +import javax.swing.JFileChooser; +import javax.swing.SwingUtilities; + +import processing.core.PShape; +import processing.xml.XMLElement; + + +/** + * Base class for all sketches that use processing.core. + *

+ * Note that you should not use AWT or Swing components inside a Processing + * applet. The surface is made to automatically update itself, and will cause + * problems with redraw of components drawn above it. If you'd like to + * integrate other Java components, see below. + *

+ * As of release 0145, Processing uses active mode rendering in all cases. + * All animation tasks happen on the "Processing Animation Thread". The + * setup() and draw() methods are handled by that thread, and events (like + * mouse movement and key presses, which are fired by the event dispatch + * thread or EDT) are queued to be (safely) handled at the end of draw(). + * For code that needs to run on the EDT, use SwingUtilities.invokeLater(). + * When doing so, be careful to synchronize between that code (since + * invokeLater() will make your code run from the EDT) and the Processing + * animation thread. Use of a callback function or the registerXxx() methods + * in PApplet can help ensure that your code doesn't do something naughty. + *

+ * As of release 0136 of Processing, we have discontinued support for versions + * of Java prior to 1.5. We don't have enough people to support it, and for a + * project of our size, we should be focusing on the future, rather than + * working around legacy Java code. In addition, Java 1.5 gives us access to + * better timing facilities which will improve the steadiness of animation. + *

+ * This class extends Applet instead of JApplet because 1) historically, + * we supported Java 1.1, which does not include Swing (without an + * additional, sizable, download), and 2) Swing is a bloated piece of crap. + * A Processing applet is a heavyweight AWT component, and can be used the + * same as any other AWT component, with or without Swing. + *

+ * Similarly, Processing runs in a Frame and not a JFrame. However, there's + * nothing to prevent you from embedding a PApplet into a JFrame, it's just + * that the base version uses a regular AWT frame because there's simply + * no need for swing in that context. If people want to use Swing, they can + * embed themselves as they wish. + *

+ * It is possible to use PApplet, along with core.jar in other projects. + * In addition to enabling you to use Java 1.5+ features with your sketch, + * this also allows you to embed a Processing drawing area into another Java + * application. This means you can use standard GUI controls with a Processing + * sketch. Because AWT and Swing GUI components cannot be used on top of a + * PApplet, you can instead embed the PApplet inside another GUI the way you + * would any other Component. + *

+ * It is also possible to resize the Processing window by including + * frame.setResizable(true) inside your setup() method. + * Note that the Java method frame.setSize() will not work unless + * you first set the frame to be resizable. + *

+ * Because the default animation thread will run at 60 frames per second, + * an embedded PApplet can make the parent sluggish. You can use frameRate() + * to make it update less often, or you can use noLoop() and loop() to disable + * and then re-enable looping. If you want to only update the sketch + * intermittently, use noLoop() inside setup(), and redraw() whenever + * the screen needs to be updated once (or loop() to re-enable the animation + * thread). The following example embeds a sketch and also uses the noLoop() + * and redraw() methods. You need not use noLoop() and redraw() when embedding + * if you want your application to animate continuously. + *

+ * public class ExampleFrame extends Frame {
+ *
+ *     public ExampleFrame() {
+ *         super("Embedded PApplet");
+ *
+ *         setLayout(new BorderLayout());
+ *         PApplet embed = new Embedded();
+ *         add(embed, BorderLayout.CENTER);
+ *
+ *         // important to call this whenever embedding a PApplet.
+ *         // It ensures that the animation thread is started and
+ *         // that other internal variables are properly set.
+ *         embed.init();
+ *     }
+ * }
+ *
+ * public class Embedded extends PApplet {
+ *
+ *     public void setup() {
+ *         // original setup code here ...
+ *         size(400, 400);
+ *
+ *         // prevent thread from starving everything else
+ *         noLoop();
+ *     }
+ *
+ *     public void draw() {
+ *         // drawing code goes here
+ *     }
+ *
+ *     public void mousePressed() {
+ *         // do something based on mouse movement
+ *
+ *         // update the screen (run draw once)
+ *         redraw();
+ *     }
+ * }
+ * 
+ * + *

Processing on multiple displays

+ *

I was asked about Processing with multiple displays, and for lack of a + * better place to document it, things will go here.

+ *

You can address both screens by making a window the width of both, + * and the height of the maximum of both screens. In this case, do not use + * present mode, because that's exclusive to one screen. Basically it'll + * give you a PApplet that spans both screens. If using one half to control + * and the other half for graphics, you'd just have to put the 'live' stuff + * on one half of the canvas, the control stuff on the other. This works + * better in windows because on the mac we can't get rid of the menu bar + * unless it's running in present mode.

+ *

For more control, you need to write straight java code that uses p5. + * You can create two windows, that are shown on two separate screens, + * that have their own PApplet. this is just one of the tradeoffs of one of + * the things that we don't support in p5 from within the environment + * itself (we must draw the line somewhere), because of how messy it would + * get to start talking about multiple screens. It's also not that tough to + * do by hand w/ some Java code.

+ * @usage Web & Application + */ +@SuppressWarnings("serial") +public class PApplet extends Applet + implements PConstants, Runnable, + MouseListener, MouseMotionListener, KeyListener, FocusListener +{ + /** + * Full name of the Java version (i.e. 1.5.0_11). + * Prior to 0125, this was only the first three digits. + */ + public static final String javaVersionName = + System.getProperty("java.version"); + + /** + * Version of Java that's in use, whether 1.1 or 1.3 or whatever, + * stored as a float. + *

+ * Note that because this is stored as a float, the values may + * not be exactly 1.3 or 1.4. Instead, make sure you're + * comparing against 1.3f or 1.4f, which will have the same amount + * of error (i.e. 1.40000001). This could just be a double, but + * since Processing only uses floats, it's safer for this to be a float + * because there's no good way to specify a double with the preproc. + */ + public static final float javaVersion = + new Float(javaVersionName.substring(0, 3)).floatValue(); + + /** + * Current platform in use. + *

+ * Equivalent to System.getProperty("os.name"), just used internally. + */ + + /** + * Current platform in use, one of the + * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER. + */ + static public int platform; + + /** + * Name associated with the current 'platform' (see PConstants.platformNames) + */ + //static public String platformName; + + static { + String osname = System.getProperty("os.name"); + + if (osname.indexOf("Mac") != -1) { + platform = MACOSX; + + } else if (osname.indexOf("Windows") != -1) { + platform = WINDOWS; + + } else if (osname.equals("Linux")) { // true for the ibm vm + platform = LINUX; + + } else { + platform = OTHER; + } + } + + /** + * Setting for whether to use the Quartz renderer on OS X. The Quartz + * renderer is on its way out for OS X, but Processing uses it by default + * because it's much faster than the Sun renderer. In some cases, however, + * the Quartz renderer is preferred. For instance, fonts are less thick + * when using the Sun renderer, so to improve how fonts look, + * change this setting before you call PApplet.main(). + *

+   * static public void main(String[] args) {
+   *   PApplet.useQuartz = "false";
+   *   PApplet.main(new String[] { "YourSketch" });
+   * }
+   * 
+ * This setting must be called before any AWT work happens, so that's why + * it's such a terrible hack in how it's employed here. Calling setProperty() + * inside setup() is a joke, since it's long since the AWT has been invoked. + */ + static public boolean useQuartz = true; + //static public String useQuartz = "true"; + + /** + * Modifier flags for the shortcut key used to trigger menus. + * (Cmd on Mac OS X, Ctrl on Linux and Windows) + */ + static public final int MENU_SHORTCUT = + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); + + /** The PGraphics renderer associated with this PApplet */ + public PGraphics g; + + //protected Object glock = new Object(); // for sync + + /** The frame containing this applet (if any) */ + public Frame frame; + + /** + * The screen size when the applet was started. + *

+ * Access this via screen.width and screen.height. To make an applet + * run at full screen, use size(screen.width, screen.height). + *

+ * If you have multiple displays, this will be the size of the main + * display. Running full screen across multiple displays isn't + * particularly supported, and requires more monkeying with the values. + * This probably can't/won't be fixed until/unless I get a dual head + * system. + *

+ * Note that this won't update if you change the resolution + * of your screen once the the applet is running. + *

+ * This variable is not static because in the desktop version of Processing, + * not all instances of PApplet will necessarily be started on a screen of + * the same size. + */ + public int screenWidth, screenHeight; + + /** + * Use screenW and screenH instead. + * @deprecated + */ + public Dimension screen = + Toolkit.getDefaultToolkit().getScreenSize(); + + /** + * A leech graphics object that is echoing all events. + */ + public PGraphics recorder; + + /** + * Command line options passed in from main(). + *

+ * This does not include the arguments passed in to PApplet itself. + */ + public String args[]; + + /** Path to sketch folder */ + public String sketchPath; //folder; + + /** When debugging headaches */ + static final boolean THREAD_DEBUG = false; + + /** Default width and height for applet when not specified */ + static public final int DEFAULT_WIDTH = 100; + static public final int DEFAULT_HEIGHT = 100; + + /** + * Minimum dimensions for the window holding an applet. + * This varies between platforms, Mac OS X 10.3 can do any height + * but requires at least 128 pixels width. Windows XP has another + * set of limitations. And for all I know, Linux probably lets you + * make windows with negative sizes. + */ + static public final int MIN_WINDOW_WIDTH = 128; + static public final int MIN_WINDOW_HEIGHT = 128; + + /** + * Exception thrown when size() is called the first time. + *

+ * This is used internally so that setup() is forced to run twice + * when the renderer is changed. This is the only way for us to handle + * invoking the new renderer while also in the midst of rendering. + */ + static public class RendererChangeException extends RuntimeException { } + + /** + * true if no size() command has been executed. This is used to wait until + * a size has been set before placing in the window and showing it. + */ + public boolean defaultSize; + + volatile boolean resizeRequest; + volatile int resizeWidth; + volatile int resizeHeight; + + /** + * Array containing the values for all the pixels in the display window. These values are of the color datatype. This array is the size of the display window. For example, if the image is 100x100 pixels, there will be 10000 values and if the window is 200x300 pixels, there will be 60000 values. The index value defines the position of a value within the array. For example, the statment color b = pixels[230] will set the variable b to be equal to the value at that location in the array.

Before accessing this array, the data must loaded with the loadPixels() function. After the array data has been modified, the updatePixels() function must be run to update the changes. Without loadPixels(), running the code may (or will in future releases) result in a NullPointerException. + * Pixel buffer from this applet's PGraphics. + *

+ * When used with OpenGL or Java2D, this value will + * be null until loadPixels() has been called. + * + * @webref image:pixels + * @see processing.core.PApplet#loadPixels() + * @see processing.core.PApplet#updatePixels() + * @see processing.core.PApplet#get(int, int, int, int) + * @see processing.core.PApplet#set(int, int, int) + * @see processing.core.PImage + */ + public int pixels[]; + + /** width of this applet's associated PGraphics + * @webref environment + */ + public int width; + + /** height of this applet's associated PGraphics + * @webref environment + * */ + public int height; + + /** + * The system variable mouseX always contains the current horizontal coordinate of the mouse. + * @webref input:mouse + * @see PApplet#mouseY + * @see PApplet#mousePressed + * @see PApplet#mousePressed() + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + * + * */ + public int mouseX; + + /** + * The system variable mouseY always contains the current vertical coordinate of the mouse. + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mousePressed + * @see PApplet#mousePressed() + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + * */ + public int mouseY; + + /** + * Previous x/y position of the mouse. This will be a different value + * when inside a mouse handler (like the mouseMoved() method) versus + * when inside draw(). Inside draw(), pmouseX is updated once each + * frame, but inside mousePressed() and friends, it's updated each time + * an event comes through. Be sure to use only one or the other type of + * means for tracking pmouseX and pmouseY within your sketch, otherwise + * you're gonna run into trouble. + * @webref input:mouse + * @see PApplet#pmouseY + * @see PApplet#mouseX + * @see PApplet#mouseY + */ + public int pmouseX; + + /** + * @webref input:mouse + * @see PApplet#pmouseX + * @see PApplet#mouseX + * @see PApplet#mouseY + */ + public int pmouseY; + + /** + * previous mouseX/Y for the draw loop, separated out because this is + * separate from the pmouseX/Y when inside the mouse event handlers. + */ + protected int dmouseX, dmouseY; + + /** + * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) + * these are different because mouse events are queued to the end of + * draw, so the previous position has to be updated on each event, + * as opposed to the pmouseX/Y that's used inside draw, which is expected + * to be updated once per trip through draw(). + */ + protected int emouseX, emouseY; + + /** + * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, + * otherwise pmouseX/Y are always zero, causing a nasty jump. + *

+ * Just using (frameCount == 0) won't work since mouseXxxxx() + * may not be called until a couple frames into things. + */ + public boolean firstMouse; + + /** + * Processing automatically tracks if the mouse button is pressed and which button is pressed. + * The value of the system variable mouseButton is either LEFT, RIGHT, or CENTER depending on which button is pressed. + *

Advanced:

+ * If running on Mac OS, a ctrl-click will be interpreted as + * the righthand mouse button (unlike Java, which reports it as + * the left mouse). + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mousePressed() + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + */ + public int mouseButton; + + /** + * Variable storing if a mouse button is pressed. The value of the system variable mousePressed is true if a mouse button is pressed and false if a button is not pressed. + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + */ + public boolean mousePressed; + public MouseEvent mouseEvent; + + /** + * The system variable key always contains the value of the most recent key on the keyboard that was used (either pressed or released).

+ * For non-ASCII keys, use the keyCode variable. + * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode + * If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. + * Check for both ENTER and RETURN to make sure your program will work for all platforms. + * =advanced + * + * Last key pressed. + *

+ * If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT, + * this will be set to CODED (0xffff or 65535). + * @webref input:keyboard + * @see PApplet#keyCode + * @see PApplet#keyPressed + * @see PApplet#keyPressed() + * @see PApplet#keyReleased() + */ + public char key; + + /** + * The variable keyCode is used to detect special keys such as the UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. + * When checking for these keys, it's first necessary to check and see if the key is coded. This is done with the conditional "if (key == CODED)" as shown in the example. + *

The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode + * If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. + * Check for both ENTER and RETURN to make sure your program will work for all platforms. + *

For users familiar with Java, the values for UP and DOWN are simply shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. + * Other keyCode values can be found in the Java KeyEvent reference. + * + * =advanced + * When "key" is set to CODED, this will contain a Java key code. + *

+ * For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT. + * Also available are ALT, CONTROL and SHIFT. A full set of constants + * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables. + * @webref input:keyboard + * @see PApplet#key + * @see PApplet#keyPressed + * @see PApplet#keyPressed() + * @see PApplet#keyReleased() + */ + public int keyCode; + + /** + * The boolean system variable keyPressed is true if any key is pressed and false if no keys are pressed. + * @webref input:keyboard + * @see PApplet#key + * @see PApplet#keyCode + * @see PApplet#keyPressed() + * @see PApplet#keyReleased() + */ + public boolean keyPressed; + + /** + * the last KeyEvent object passed into a mouse function. + */ + public KeyEvent keyEvent; + + /** + * Gets set to true/false as the applet gains/loses focus. + * @webref environment + */ + public boolean focused = false; + + /** + * true if the applet is online. + *

+ * This can be used to test how the applet should behave + * since online situations are different (no file writing, etc). + * @webref environment + */ + public boolean online = false; + + /** + * Time in milliseconds when the applet was started. + *

+ * Used by the millis() function. + */ + long millisOffset; + + /** + * The current value of frames per second. + *

+ * The initial value will be 10 fps, and will be updated with each + * frame thereafter. The value is not instantaneous (since that + * wouldn't be very useful since it would jump around so much), + * but is instead averaged (integrated) over several frames. + * As such, this value won't be valid until after 5-10 frames. + */ + public float frameRate = 10; + /** Last time in nanoseconds that frameRate was checked */ + protected long frameRateLastNanos = 0; + + /** As of release 0116, frameRate(60) is called as a default */ + protected float frameRateTarget = 60; + protected long frameRatePeriod = 1000000000L / 60L; + + protected boolean looping; + + /** flag set to true when a redraw is asked for by the user */ + protected boolean redraw; + + /** + * How many frames have been displayed since the applet started. + *

+ * This value is read-only do not attempt to set it, + * otherwise bad things will happen. + *

+ * Inside setup(), frameCount is 0. + * For the first iteration of draw(), frameCount will equal 1. + */ + public int frameCount; + + /** + * true if this applet has had it. + */ + public volatile boolean finished; + + /** + * true if the animation thread is paused. + */ + public volatile boolean paused; + + /** + * true if exit() has been called so that things shut down + * once the main thread kicks off. + */ + protected boolean exitCalled; + + Thread thread; + + protected RegisteredMethods sizeMethods; + protected RegisteredMethods preMethods, drawMethods, postMethods; + protected RegisteredMethods mouseEventMethods, keyEventMethods; + protected RegisteredMethods disposeMethods; + + // messages to send if attached as an external vm + + /** + * Position of the upper-lefthand corner of the editor window + * that launched this applet. + */ + static public final String ARGS_EDITOR_LOCATION = "--editor-location"; + + /** + * Location for where to position the applet window on screen. + *

+ * This is used by the editor to when saving the previous applet + * location, or could be used by other classes to launch at a + * specific position on-screen. + */ + static public final String ARGS_EXTERNAL = "--external"; + + static public final String ARGS_LOCATION = "--location"; + + static public final String ARGS_DISPLAY = "--display"; + + static public final String ARGS_BGCOLOR = "--bgcolor"; + + static public final String ARGS_PRESENT = "--present"; + + static public final String ARGS_EXCLUSIVE = "--exclusive"; + + static public final String ARGS_STOP_COLOR = "--stop-color"; + + static public final String ARGS_HIDE_STOP = "--hide-stop"; + + /** + * Allows the user or PdeEditor to set a specific sketch folder path. + *

+ * Used by PdeEditor to pass in the location where saveFrame() + * and all that stuff should write things. + */ + static public final String ARGS_SKETCH_FOLDER = "--sketch-path"; + + /** + * When run externally to a PdeEditor, + * this is sent by the applet when it quits. + */ + //static public final String EXTERNAL_QUIT = "__QUIT__"; + static public final String EXTERNAL_STOP = "__STOP__"; + + /** + * When run externally to a PDE Editor, this is sent by the applet + * whenever the window is moved. + *

+ * This is used so that the editor can re-open the sketch window + * in the same position as the user last left it. + */ + static public final String EXTERNAL_MOVE = "__MOVE__"; + + /** true if this sketch is being run by the PDE */ + boolean external = false; + + + static final String ERROR_MIN_MAX = + "Cannot use min() or max() on an empty array."; + + + // during rev 0100 dev cycle, working on new threading model, + // but need to disable and go conservative with changes in order + // to get pdf and audio working properly first. + // for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs. + //static final boolean CRUSTY_THREADS = false; //true; + + public void init() { +// println("init() called " + Integer.toHexString(hashCode())); + // using a local version here since the class variable is deprecated + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + screenWidth = screen.width; + screenHeight = screen.height; + + // send tab keys through to the PApplet + setFocusTraversalKeysEnabled(false); + + millisOffset = System.currentTimeMillis(); + + finished = false; // just for clarity + + // this will be cleared by draw() if it is not overridden + looping = true; + redraw = true; // draw this guy once + firstMouse = true; + + // these need to be inited before setup + sizeMethods = new RegisteredMethods(); + preMethods = new RegisteredMethods(); + drawMethods = new RegisteredMethods(); + postMethods = new RegisteredMethods(); + mouseEventMethods = new RegisteredMethods(); + keyEventMethods = new RegisteredMethods(); + disposeMethods = new RegisteredMethods(); + + try { + getAppletContext(); + online = true; + } catch (NullPointerException e) { + online = false; + } + + try { + if (sketchPath == null) { + sketchPath = System.getProperty("user.dir"); + } + } catch (Exception e) { } // may be a security problem + + Dimension size = getSize(); + if ((size.width != 0) && (size.height != 0)) { + // When this PApplet is embedded inside a Java application with other + // Component objects, its size() may already be set externally (perhaps + // by a LayoutManager). In this case, honor that size as the default. + // Size of the component is set, just create a renderer. + g = makeGraphics(size.width, size.height, sketchRenderer(), null, true); + // This doesn't call setSize() or setPreferredSize() because the fact + // that a size was already set means that someone is already doing it. + + } else { + // Set the default size, until the user specifies otherwise + this.defaultSize = true; + int w = sketchWidth(); + int h = sketchHeight(); + g = makeGraphics(w, h, sketchRenderer(), null, true); + // Fire component resize event +println("init(): setSize(" + w + ", " + h + ")"); + setSize(w, h); + setPreferredSize(new Dimension(w, h)); + } + width = g.width; + height = g.height; + + addListeners(); + + // this is automatically called in applets + // though it's here for applications anyway + start(); + } + + + public int sketchWidth() { + return DEFAULT_WIDTH; + } + + + public int sketchHeight() { + return DEFAULT_HEIGHT; + } + + + public String sketchRenderer() { + return JAVA2D; + } + + + /** + * Called by the browser or applet viewer to inform this applet that it + * should start its execution. It is called after the init method and + * each time the applet is revisited in a Web page. + *

+ * Called explicitly via the first call to PApplet.paint(), because + * PAppletGL needs to have a usable screen before getting things rolling. + */ + public void start() { +// println("start() called"); +// new Exception().printStackTrace(System.out); + + finished = false; + paused = false; // unpause the thread + + // if this is the first run, setup and run the thread + if (thread == null) { + thread = new Thread(this, "Animation Thread"); + thread.start(); + } + } + + + /** + * Called by the browser or applet viewer to inform + * this applet that it should stop its execution. + *

+ * Unfortunately, there are no guarantees from the Java spec + * when or if stop() will be called (i.e. on browser quit, + * or when moving between web pages), and it's not always called. + */ + public void stop() { + // this used to shut down the sketch, but that code has + // been moved to dispose() + + paused = true; // causes animation thread to sleep + + //TODO listeners + } + + + /** + * Called by the browser or applet viewer to inform this applet + * that it is being reclaimed and that it should destroy + * any resources that it has allocated. + *

+ * destroy() supposedly gets called as the applet viewer + * is shutting down the applet. stop() is called + * first, and then destroy() to really get rid of things. + * no guarantees on when they're run (on browser quit, or + * when moving between pages), though. + */ + public void destroy() { + ((PApplet)this).exit(); + } + + + /** + * This returns the last width and height specified by the user + * via the size() command. + */ +// public Dimension getPreferredSize() { +// return new Dimension(width, height); +// } + + +// public void addNotify() { +// super.addNotify(); +// println("addNotify()"); +// } + + + + ////////////////////////////////////////////////////////////// + + + public class RegisteredMethods { + int count; + Object objects[]; + Method methods[]; + + + // convenience version for no args + public void handle() { + handle(new Object[] { }); + } + + public void handle(Object oargs[]) { + for (int i = 0; i < count; i++) { + try { + //System.out.println(objects[i] + " " + args); + methods[i].invoke(objects[i], oargs); + } catch (Exception e) { + if (e instanceof InvocationTargetException) { + InvocationTargetException ite = (InvocationTargetException) e; + ite.getTargetException().printStackTrace(); + } else { + e.printStackTrace(); + } + } + } + } + + public void add(Object object, Method method) { + if (objects == null) { + objects = new Object[5]; + methods = new Method[5]; + } + if (count == objects.length) { + objects = (Object[]) PApplet.expand(objects); + methods = (Method[]) PApplet.expand(methods); +// Object otemp[] = new Object[count << 1]; +// System.arraycopy(objects, 0, otemp, 0, count); +// objects = otemp; +// Method mtemp[] = new Method[count << 1]; +// System.arraycopy(methods, 0, mtemp, 0, count); +// methods = mtemp; + } + objects[count] = object; + methods[count] = method; + count++; + } + + + /** + * Removes first object/method pair matched (and only the first, + * must be called multiple times if object is registered multiple times). + * Does not shrink array afterwards, silently returns if method not found. + */ + public void remove(Object object, Method method) { + int index = findIndex(object, method); + if (index != -1) { + // shift remaining methods by one to preserve ordering + count--; + for (int i = index; i < count; i++) { + objects[i] = objects[i+1]; + methods[i] = methods[i+1]; + } + // clean things out for the gc's sake + objects[count] = null; + methods[count] = null; + } + } + + protected int findIndex(Object object, Method method) { + for (int i = 0; i < count; i++) { + if (objects[i] == object && methods[i].equals(method)) { + //objects[i].equals() might be overridden, so use == for safety + // since here we do care about actual object identity + //methods[i]==method is never true even for same method, so must use + // equals(), this should be safe because of object identity + return i; + } + } + return -1; + } + } + + + public void registerSize(Object o) { + Class methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; + registerWithArgs(sizeMethods, "size", o, methodArgs); + } + + public void registerPre(Object o) { + registerNoArgs(preMethods, "pre", o); + } + + public void registerDraw(Object o) { + registerNoArgs(drawMethods, "draw", o); + } + + public void registerPost(Object o) { + registerNoArgs(postMethods, "post", o); + } + + public void registerMouseEvent(Object o) { + Class methodArgs[] = new Class[] { MouseEvent.class }; + registerWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); + } + + + public void registerKeyEvent(Object o) { + Class methodArgs[] = new Class[] { KeyEvent.class }; + registerWithArgs(keyEventMethods, "keyEvent", o, methodArgs); + } + + public void registerDispose(Object o) { + registerNoArgs(disposeMethods, "dispose", o); + } + + + protected void registerNoArgs(RegisteredMethods meth, + String name, Object o) { + Class c = o.getClass(); + try { + Method method = c.getMethod(name, new Class[] {}); + meth.add(o, method); + + } catch (NoSuchMethodException nsme) { + die("There is no public " + name + "() method in the class " + + o.getClass().getName()); + + } catch (Exception e) { + die("Could not register " + name + " + () for " + o, e); + } + } + + + protected void registerWithArgs(RegisteredMethods meth, + String name, Object o, Class cargs[]) { + Class c = o.getClass(); + try { + Method method = c.getMethod(name, cargs); + meth.add(o, method); + + } catch (NoSuchMethodException nsme) { + die("There is no public " + name + "() method in the class " + + o.getClass().getName()); + + } catch (Exception e) { + die("Could not register " + name + " + () for " + o, e); + } + } + + + public void unregisterSize(Object o) { + Class methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; + unregisterWithArgs(sizeMethods, "size", o, methodArgs); + } + + public void unregisterPre(Object o) { + unregisterNoArgs(preMethods, "pre", o); + } + + public void unregisterDraw(Object o) { + unregisterNoArgs(drawMethods, "draw", o); + } + + public void unregisterPost(Object o) { + unregisterNoArgs(postMethods, "post", o); + } + + public void unregisterMouseEvent(Object o) { + Class methodArgs[] = new Class[] { MouseEvent.class }; + unregisterWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); + } + + public void unregisterKeyEvent(Object o) { + Class methodArgs[] = new Class[] { KeyEvent.class }; + unregisterWithArgs(keyEventMethods, "keyEvent", o, methodArgs); + } + + public void unregisterDispose(Object o) { + unregisterNoArgs(disposeMethods, "dispose", o); + } + + + protected void unregisterNoArgs(RegisteredMethods meth, + String name, Object o) { + Class c = o.getClass(); + try { + Method method = c.getMethod(name, new Class[] {}); + meth.remove(o, method); + } catch (Exception e) { + die("Could not unregister " + name + "() for " + o, e); + } + } + + + protected void unregisterWithArgs(RegisteredMethods meth, + String name, Object o, Class cargs[]) { + Class c = o.getClass(); + try { + Method method = c.getMethod(name, cargs); + meth.remove(o, method); + } catch (Exception e) { + die("Could not unregister " + name + "() for " + o, e); + } + } + + + ////////////////////////////////////////////////////////////// + + + public void setup() { + } + + + public void draw() { + // if no draw method, then shut things down + //System.out.println("no draw method, goodbye"); + finished = true; + } + + + ////////////////////////////////////////////////////////////// + + + protected void resizeRenderer(int iwidth, int iheight) { +// println("resizeRenderer request for " + iwidth + " " + iheight); + if (width != iwidth || height != iheight) { +// println(" former size was " + width + " " + height); + g.setSize(iwidth, iheight); + width = iwidth; + height = iheight; + } + } + + + /** + * Defines the dimension of the display window in units of pixels. The size() function must be the first line in setup(). If size() is not called, the default size of the window is 100x100 pixels. The system variables width and height are set by the parameters passed to the size() function.

+ * Do not use variables as the parameters to size() command, because it will cause problems when exporting your sketch. When variables are used, the dimensions of your sketch cannot be determined during export. Instead, employ numeric values in the size() statement, and then use the built-in width and height variables inside your program when you need the dimensions of the display window are needed.

+ * The MODE parameters selects which rendering engine to use. For example, if you will be drawing 3D shapes for the web use P3D, if you want to export a program with OpenGL graphics acceleration use OPENGL. A brief description of the four primary renderers follows:

JAVA2D - The default renderer. This renderer supports two dimensional drawing and provides higher image quality in overall, but generally slower than P2D.

P2D (Processing 2D) - Fast 2D renderer, best used with pixel data, but not as accurate as the JAVA2D default.

P3D (Processing 3D) - Fast 3D renderer for the web. Sacrifices rendering quality for quick 3D drawing.

OPENGL - High speed 3D graphics renderer that makes use of OpenGL-compatible graphics hardware is available. Keep in mind that OpenGL is not magic pixie dust that makes any sketch faster (though it's close), so other rendering options may produce better results depending on the nature of your code. Also note that with OpenGL, all graphics are smoothed: the smooth() and noSmooth() commands are ignored.

PDF - The PDF renderer draws 2D graphics directly to an Acrobat PDF file. This produces excellent results when you need vector shapes for high resolution output or printing. You must first use Import Library → PDF to make use of the library. More information can be found in the PDF library reference. + * If you're manipulating pixels (using methods like get() or blend(), or manipulating the pixels[] array), P2D and P3D will usually be faster than the default (JAVA2D) setting, and often the OPENGL setting as well. Similarly, when handling lots of images, or doing video playback, P2D and P3D will tend to be faster.

+ * The P2D, P3D, and OPENGL renderers do not support strokeCap() or strokeJoin(), which can lead to ugly results when using strokeWeight(). (Bug 955)

+ * For the most elegant and accurate results when drawing in 2D, particularly when using smooth(), use the JAVA2D renderer setting. It may be slower than the others, but is the most complete, which is why it's the default. Advanced users will want to switch to other renderers as they learn the tradeoffs.

+ * Rendering graphics requires tradeoffs between speed, accuracy, and general usefulness of the available features. None of the renderers are perfect, so we provide multiple options so that you can decide what tradeoffs make the most sense for your project. We'd prefer all of them to have perfect visual accuracy, high performance, and support a wide range of features, but that's simply not possible.

+ * The maximum width and height is limited by your operating system, and is usually the width and height of your actual screen. On some machines it may simply be the number of pixels on your current screen, meaning that a screen that's 800x600 could support size(1600, 300), since it's the same number of pixels. This varies widely so you'll have to try different rendering modes and sizes until you get what you're looking for. If you need something larger, use createGraphics to create a non-visible drawing surface. + *

Again, the size() method must be the first line of the code (or first item inside setup). Any code that appears before the size() command may run more than once, which can lead to confusing results. + * + * =advanced + * Starts up and creates a two-dimensional drawing surface, + * or resizes the current drawing surface. + *

+ * This should be the first thing called inside of setup(). + *

+ * If using Java 1.3 or later, this will default to using + * PGraphics2, the Java2D-based renderer. If using Java 1.1, + * or if PGraphics2 is not available, then PGraphics will be used. + * To set your own renderer, use the other version of the size() + * method that takes a renderer as its last parameter. + *

+ * If called once a renderer has already been set, this will + * use the previous renderer and simply resize it. + * + * @webref structure + * @param iwidth width of the display window in units of pixels + * @param iheight height of the display window in units of pixels + */ + public void size(int iwidth, int iheight) { + size(iwidth, iheight, JAVA2D, null); + } + + /** + * + * @param irenderer Either P2D, P3D, JAVA2D, or OPENGL + */ + public void size(int iwidth, int iheight, String irenderer) { + size(iwidth, iheight, irenderer, null); + } + + + /** + * Creates a new PGraphics object and sets it to the specified size. + * + * Note that you cannot change the renderer once outside of setup(). + * In most cases, you can call size() to give it a new size, + * but you need to always ask for the same renderer, otherwise + * you're gonna run into trouble. + * + * The size() method should *only* be called from inside the setup() or + * draw() methods, so that it is properly run on the main animation thread. + * To change the size of a PApplet externally, use setSize(), which will + * update the component size, and queue a resize of the renderer as well. + */ + public void size(final int iwidth, final int iheight, + String irenderer, String ipath) { + // Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing) + SwingUtilities.invokeLater(new Runnable() { + public void run() { + // Set the preferred size so that the layout managers can handle it + setPreferredSize(new Dimension(iwidth, iheight)); + setSize(iwidth, iheight); + } + }); + + // ensure that this is an absolute path + if (ipath != null) ipath = savePath(ipath); + + String currentRenderer = g.getClass().getName(); + if (currentRenderer.equals(irenderer)) { + // Avoid infinite loop of throwing exception to reset renderer + resizeRenderer(iwidth, iheight); + //redraw(); // will only be called insize draw() + + } else { // renderer is being changed + // otherwise ok to fall through and create renderer below + // the renderer is changing, so need to create a new object + g = makeGraphics(iwidth, iheight, irenderer, ipath, true); + width = iwidth; + height = iheight; + + // fire resize event to make sure the applet is the proper size +// setSize(iwidth, iheight); + // this is the function that will run if the user does their own + // size() command inside setup, so set defaultSize to false. + defaultSize = false; + + // throw an exception so that setup() is called again + // but with a properly sized render + // this is for opengl, which needs a valid, properly sized + // display before calling anything inside setup(). + throw new RendererChangeException(); + } + } + + + /** + * Creates and returns a new PGraphics object of the types P2D, P3D, and JAVA2D. Use this class if you need to draw into an off-screen graphics buffer. It's not possible to use createGraphics() with OPENGL, because it doesn't allow offscreen use. The DXF and PDF renderers require the filename parameter. + *

It's important to call any drawing commands between beginDraw() and endDraw() statements. This is also true for any commands that affect drawing, such as smooth() or colorMode(). + *

Unlike the main drawing surface which is completely opaque, surfaces created with createGraphics() can have transparency. This makes it possible to draw into a graphics and maintain the alpha channel. By using save() to write a PNG or TGA file, the transparency of the graphics object will be honored. Note that transparency levels are binary: pixels are either complete opaque or transparent. For the time being (as of release 0127), this means that text characters will be opaque blocks. This will be fixed in a future release (Bug 641). + * + * =advanced + * Create an offscreen PGraphics object for drawing. This can be used + * for bitmap or vector images drawing or rendering. + *

    + *
  • Do not use "new PGraphicsXxxx()", use this method. This method + * ensures that internal variables are set up properly that tie the + * new graphics context back to its parent PApplet. + *
  • The basic way to create bitmap images is to use the saveFrame() + * function. + *
  • If you want to create a really large scene and write that, + * first make sure that you've allocated a lot of memory in the Preferences. + *
  • If you want to create images that are larger than the screen, + * you should create your own PGraphics object, draw to that, and use + * save(). + * For now, it's best to use P3D in this scenario. + * P2D is currently disabled, and the JAVA2D default will give mixed + * results. An example of using P3D: + *
    +   *
    +   * PGraphics big;
    +   *
    +   * void setup() {
    +   *   big = createGraphics(3000, 3000, P3D);
    +   *
    +   *   big.beginDraw();
    +   *   big.background(128);
    +   *   big.line(20, 1800, 1800, 900);
    +   *   // etc..
    +   *   big.endDraw();
    +   *
    +   *   // make sure the file is written to the sketch folder
    +   *   big.save("big.tif");
    +   * }
    +   *
    +   * 
    + *
  • It's important to always wrap drawing to createGraphics() with + * beginDraw() and endDraw() (beginFrame() and endFrame() prior to + * revision 0115). The reason is that the renderer needs to know when + * drawing has stopped, so that it can update itself internally. + * This also handles calling the defaults() method, for people familiar + * with that. + *
  • It's not possible to use createGraphics() with the OPENGL renderer, + * because it doesn't allow offscreen use. + *
  • With Processing 0115 and later, it's possible to write images in + * formats other than the default .tga and .tiff. The exact formats and + * background information can be found in the developer's reference for + * PImage.save(). + *
+ * + * @webref rendering + * @param iwidth width in pixels + * @param iheight height in pixels + * @param irenderer Either P2D (not yet implemented), P3D, JAVA2D, PDF, DXF + * + * @see processing.core.PGraphics + * + */ + public PGraphics createGraphics(int iwidth, int iheight, + String irenderer) { + PGraphics pg = makeGraphics(iwidth, iheight, irenderer, null, false); + //pg.parent = this; // make save() work + return pg; + } + + + /** + * Create an offscreen graphics surface for drawing, in this case + * for a renderer that writes to a file (such as PDF or DXF). + * @param ipath the name of the file (can be an absolute or relative path) + */ + public PGraphics createGraphics(int iwidth, int iheight, + String irenderer, String ipath) { + if (ipath != null) { + ipath = savePath(ipath); + } + PGraphics pg = makeGraphics(iwidth, iheight, irenderer, ipath, false); + pg.parent = this; // make save() work + return pg; + } + + + /** + * Version of createGraphics() used internally. + * + * @param ipath must be an absolute path, usually set via savePath() + * @oaram applet the parent applet object, this should only be non-null + * in cases where this is the main drawing surface object. + */ + protected PGraphics makeGraphics(int iwidth, int iheight, + String irenderer, String ipath, + boolean iprimary) { + if (irenderer.equals(OPENGL)) { + if (PApplet.platform == WINDOWS) { + String s = System.getProperty("java.version"); + if (s != null) { + if (s.equals("1.5.0_10")) { + System.err.println("OpenGL support is broken with Java 1.5.0_10"); + System.err.println("See http://dev.processing.org" + + "/bugs/show_bug.cgi?id=513 for more info."); + throw new RuntimeException("Please update your Java " + + "installation (see bug #513)"); + } + } + } + } + +// if (irenderer.equals(P2D)) { +// throw new RuntimeException("The P2D renderer is currently disabled, " + +// "please use P3D or JAVA2D."); +// } + + String openglError = + "Before using OpenGL, first select " + + "Import Library > opengl from the Sketch menu."; + + try { + /* + Class rendererClass = Class.forName(irenderer); + + Class constructorParams[] = null; + Object constructorValues[] = null; + + if (ipath == null) { + constructorParams = new Class[] { + Integer.TYPE, Integer.TYPE, PApplet.class + }; + constructorValues = new Object[] { + new Integer(iwidth), new Integer(iheight), this + }; + } else { + constructorParams = new Class[] { + Integer.TYPE, Integer.TYPE, PApplet.class, String.class + }; + constructorValues = new Object[] { + new Integer(iwidth), new Integer(iheight), this, ipath + }; + } + + Constructor constructor = + rendererClass.getConstructor(constructorParams); + PGraphics pg = (PGraphics) constructor.newInstance(constructorValues); + */ + + Class rendererClass = + Thread.currentThread().getContextClassLoader().loadClass(irenderer); + + //Class params[] = null; + //PApplet.println(rendererClass.getConstructors()); + Constructor constructor = rendererClass.getConstructor(new Class[] { }); + PGraphics pg = (PGraphics) constructor.newInstance(); + + pg.setParent(this); + pg.setPrimary(iprimary); + if (ipath != null) pg.setPath(ipath); + pg.setSize(iwidth, iheight); + + // everything worked, return it + return pg; + + } catch (InvocationTargetException ite) { + String msg = ite.getTargetException().getMessage(); + if ((msg != null) && + (msg.indexOf("no jogl in java.library.path") != -1)) { + throw new RuntimeException(openglError + + " (The native library is missing.)"); + + } else { + ite.getTargetException().printStackTrace(); + Throwable target = ite.getTargetException(); + if (platform == MACOSX) target.printStackTrace(System.out); // bug + // neither of these help, or work + //target.printStackTrace(System.err); + //System.err.flush(); + //System.out.println(System.err); // and the object isn't null + throw new RuntimeException(target.getMessage()); + } + + } catch (ClassNotFoundException cnfe) { + if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsGL") != -1) { + throw new RuntimeException(openglError + + " (The library .jar file is missing.)"); + } else { + throw new RuntimeException("You need to use \"Import Library\" " + + "to add " + irenderer + " to your sketch."); + } + + } catch (Exception e) { + //System.out.println("ex3"); + if ((e instanceof IllegalArgumentException) || + (e instanceof NoSuchMethodException) || + (e instanceof IllegalAccessException)) { + e.printStackTrace(); + /* + String msg = "public " + + irenderer.substring(irenderer.lastIndexOf('.') + 1) + + "(int width, int height, PApplet parent" + + ((ipath == null) ? "" : ", String filename") + + ") does not exist."; + */ + String msg = irenderer + " needs to be updated " + + "for the current release of Processing."; + throw new RuntimeException(msg); + + } else { + if (platform == MACOSX) e.printStackTrace(System.out); + throw new RuntimeException(e.getMessage()); + } + } + } + + + /** + * Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play with. Set the size of the buffer with the width and height parameters. The format parameter defines how the pixels are stored. See the PImage reference for more information. + *

Be sure to include all three parameters, specifying only the width and height (but no format) will produce a strange error. + *

Advanced users please note that createImage() should be used instead of the syntax new PImage(). + * =advanced + * Preferred method of creating new PImage objects, ensures that a + * reference to the parent PApplet is included, which makes save() work + * without needing an absolute path. + * + * @webref image + * @param wide width in pixels + * @param high height in pixels + * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel) + * + * @see processing.core.PImage + * @see processing.core.PGraphics + */ + public PImage createImage(int wide, int high, int format) { + PImage image = new PImage(wide, high, format); + image.parent = this; // make save() work + return image; + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + public void update(Graphics screen) { + paint(screen); + } + + + //synchronized public void paint(Graphics screen) { // shutting off for 0146 + public void paint(Graphics screen) { + // ignore the very first call to paint, since it's coming + // from the o.s., and the applet will soon update itself anyway. + if (frameCount == 0) { +// println("Skipping frame"); + // paint() may be called more than once before things + // are finally painted to the screen and the thread gets going + return; + } + + // without ignoring the first call, the first several frames + // are confused because paint() gets called in the midst of + // the initial nextFrame() call, so there are multiple + // updates fighting with one another. + + // g.image is synchronized so that draw/loop and paint don't + // try to fight over it. this was causing a randomized slowdown + // that would cut the frameRate into a third on macosx, + // and is probably related to the windows sluggishness bug too + + // make sure the screen is visible and usable + // (also prevents over-drawing when using PGraphicsOpenGL) + if ((g != null) && (g.image != null)) { +// println("inside paint(), screen.drawImage()"); + screen.drawImage(g.image, 0, 0, null); + } + } + + + // active paint method + protected void paint() { + try { + Graphics screen = this.getGraphics(); + if (screen != null) { + if ((g != null) && (g.image != null)) { + screen.drawImage(g.image, 0, 0, null); + } + Toolkit.getDefaultToolkit().sync(); + } + } catch (Exception e) { + // Seen on applet destroy, maybe can ignore? + e.printStackTrace(); + +// } finally { +// if (g != null) { +// g.dispose(); +// } + } + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Main method for the primary animation thread. + * + * Painting in AWT and Swing + */ + public void run() { // not good to make this synchronized, locks things up + long beforeTime = System.nanoTime(); + long overSleepTime = 0L; + + int noDelays = 0; + // Number of frames with a delay of 0 ms before the + // animation thread yields to other running threads. + final int NO_DELAYS_PER_YIELD = 15; + + /* + // this has to be called after the exception is thrown, + // otherwise the supporting libs won't have a valid context to draw to + Object methodArgs[] = + new Object[] { new Integer(width), new Integer(height) }; + sizeMethods.handle(methodArgs); + */ + + while ((Thread.currentThread() == thread) && !finished) { + while (paused) { +// println("paused..."); + try { + Thread.sleep(100L); + } catch (InterruptedException e) { + //ignore? + } + } + + // Don't resize the renderer from the EDT (i.e. from a ComponentEvent), + // otherwise it may attempt a resize mid-render. + if (resizeRequest) { + resizeRenderer(resizeWidth, resizeHeight); + resizeRequest = false; + } + + // render a single frame + handleDraw(); + + if (frameCount == 1) { + // Call the request focus event once the image is sure to be on + // screen and the component is valid. The OpenGL renderer will + // request focus for its canvas inside beginDraw(). + // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html + // Disabling for 0185, because it causes an assertion failure on OS X + // http://code.google.com/p/processing/issues/detail?id=258 + // requestFocus(); + + // Changing to this version for 0187 + // http://code.google.com/p/processing/issues/detail?id=279 + requestFocusInWindow(); + } + + // wait for update & paint to happen before drawing next frame + // this is necessary since the drawing is sometimes in a + // separate thread, meaning that the next frame will start + // before the update/paint is completed + + long afterTime = System.nanoTime(); + long timeDiff = afterTime - beforeTime; + //System.out.println("time diff is " + timeDiff); + long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; + + if (sleepTime > 0) { // some time left in this cycle + try { +// Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds + Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); + noDelays = 0; // Got some sleep, not delaying anymore + } catch (InterruptedException ex) { } + + overSleepTime = (System.nanoTime() - afterTime) - sleepTime; + //System.out.println(" oversleep is " + overSleepTime); + + } else { // sleepTime <= 0; the frame took longer than the period +// excess -= sleepTime; // store excess time value + overSleepTime = 0L; + + if (noDelays > NO_DELAYS_PER_YIELD) { + Thread.yield(); // give another thread a chance to run + noDelays = 0; + } + } + + beforeTime = System.nanoTime(); + } + + dispose(); // call to shutdown libs? + + // If the user called the exit() function, the window should close, + // rather than the sketch just halting. + if (exitCalled) { + exit2(); + } + } + + //synchronized public void handleDisplay() { + public void handleDraw() { + if (g != null && (looping || redraw)) { + if (!g.canDraw()) { + // Don't draw if the renderer is not yet ready. + // (e.g. OpenGL has to wait for a peer to be on screen) + return; + } + + //System.out.println("handleDraw() " + frameCount); + + g.beginDraw(); + if (recorder != null) { + recorder.beginDraw(); + } + + long now = System.nanoTime(); + + if (frameCount == 0) { + try { + //println("Calling setup()"); + setup(); + //println("Done with setup()"); + + } catch (RendererChangeException e) { + // Give up, instead set the new renderer and re-attempt setup() + return; + } + this.defaultSize = false; + + } else { // frameCount > 0, meaning an actual draw() + // update the current frameRate + double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0); + float instantaneousRate = (float) rate / 1000.0f; + frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f); + + preMethods.handle(); + + // use dmouseX/Y as previous mouse pos, since this is the + // last position the mouse was in during the previous draw. + pmouseX = dmouseX; + pmouseY = dmouseY; + + //println("Calling draw()"); + draw(); + //println("Done calling draw()"); + + // dmouseX/Y is updated only once per frame (unlike emouseX/Y) + dmouseX = mouseX; + dmouseY = mouseY; + + // these are called *after* loop so that valid + // drawing commands can be run inside them. it can't + // be before, since a call to background() would wipe + // out anything that had been drawn so far. + dequeueMouseEvents(); + dequeueKeyEvents(); + + drawMethods.handle(); + + redraw = false; // unset 'redraw' flag in case it was set + // (only do this once draw() has run, not just setup()) + + } + + g.endDraw(); + if (recorder != null) { + recorder.endDraw(); + } + + frameRateLastNanos = now; + frameCount++; + + // Actively render the screen + paint(); + +// repaint(); +// getToolkit().sync(); // force repaint now (proper method) + + postMethods.handle(); + } + } + + + ////////////////////////////////////////////////////////////// + + + + synchronized public void redraw() { + if (!looping) { + redraw = true; +// if (thread != null) { +// // wake from sleep (necessary otherwise it'll be +// // up to 10 seconds before update) +// if (CRUSTY_THREADS) { +// thread.interrupt(); +// } else { +// synchronized (blocker) { +// blocker.notifyAll(); +// } +// } +// } + } + } + + + synchronized public void loop() { + if (!looping) { + looping = true; + } + } + + + synchronized public void noLoop() { + if (looping) { + looping = false; + } + } + + + ////////////////////////////////////////////////////////////// + + + public void addListeners() { + addMouseListener(this); + addMouseMotionListener(this); + addKeyListener(this); + addFocusListener(this); + + addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + Component c = e.getComponent(); + //System.out.println("componentResized() " + c); + Rectangle bounds = c.getBounds(); + resizeRequest = true; + resizeWidth = bounds.width; + resizeHeight = bounds.height; + } + }); + } + + + ////////////////////////////////////////////////////////////// + + + MouseEvent mouseEventQueue[] = new MouseEvent[10]; + int mouseEventCount; + + protected void enqueueMouseEvent(MouseEvent e) { + synchronized (mouseEventQueue) { + if (mouseEventCount == mouseEventQueue.length) { + MouseEvent temp[] = new MouseEvent[mouseEventCount << 1]; + System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount); + mouseEventQueue = temp; + } + mouseEventQueue[mouseEventCount++] = e; + } + } + + protected void dequeueMouseEvents() { + synchronized (mouseEventQueue) { + for (int i = 0; i < mouseEventCount; i++) { + mouseEvent = mouseEventQueue[i]; + handleMouseEvent(mouseEvent); + } + mouseEventCount = 0; + } + } + + + /** + * Actually take action based on a mouse event. + * Internally updates mouseX, mouseY, mousePressed, and mouseEvent. + * Then it calls the event type with no params, + * i.e. mousePressed() or mouseReleased() that the user may have + * overloaded to do something more useful. + */ + protected void handleMouseEvent(MouseEvent event) { + int id = event.getID(); + + // http://dev.processing.org/bugs/show_bug.cgi?id=170 + // also prevents mouseExited() on the mac from hosing the mouse + // position, because x/y are bizarre values on the exit event. + // see also the id check below.. both of these go together + if ((id == MouseEvent.MOUSE_DRAGGED) || + (id == MouseEvent.MOUSE_MOVED)) { + pmouseX = emouseX; + pmouseY = emouseY; + mouseX = event.getX(); + mouseY = event.getY(); + } + + mouseEvent = event; + + int modifiers = event.getModifiers(); + if ((modifiers & InputEvent.BUTTON1_MASK) != 0) { + mouseButton = LEFT; + } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) { + mouseButton = CENTER; + } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) { + mouseButton = RIGHT; + } + // if running on macos, allow ctrl-click as right mouse + if (platform == MACOSX) { + if (mouseEvent.isPopupTrigger()) { + mouseButton = RIGHT; + } + } + + mouseEventMethods.handle(new Object[] { event }); + + // this used to only be called on mouseMoved and mouseDragged + // change it back if people run into trouble + if (firstMouse) { + pmouseX = mouseX; + pmouseY = mouseY; + dmouseX = mouseX; + dmouseY = mouseY; + firstMouse = false; + } + + //println(event); + + switch (id) { + case MouseEvent.MOUSE_PRESSED: + mousePressed = true; + mousePressed(); + break; + case MouseEvent.MOUSE_RELEASED: + mousePressed = false; + mouseReleased(); + break; + case MouseEvent.MOUSE_CLICKED: + mouseClicked(); + break; + case MouseEvent.MOUSE_DRAGGED: + mouseDragged(); + break; + case MouseEvent.MOUSE_MOVED: + mouseMoved(); + break; + } + + if ((id == MouseEvent.MOUSE_DRAGGED) || + (id == MouseEvent.MOUSE_MOVED)) { + emouseX = mouseX; + emouseY = mouseY; + } + } + + + /** + * Figure out how to process a mouse event. When loop() has been + * called, the events will be queued up until drawing is complete. + * If noLoop() has been called, then events will happen immediately. + */ + protected void checkMouseEvent(MouseEvent event) { + if (looping) { + enqueueMouseEvent(event); + } else { + handleMouseEvent(event); + } + } + + + /** + * If you override this or any function that takes a "MouseEvent e" + * without calling its super.mouseXxxx() then mouseX, mouseY, + * mousePressed, and mouseEvent will no longer be set. + */ + public void mousePressed(MouseEvent e) { + checkMouseEvent(e); + } + + public void mouseReleased(MouseEvent e) { + checkMouseEvent(e); + } + + public void mouseClicked(MouseEvent e) { + checkMouseEvent(e); + } + + public void mouseEntered(MouseEvent e) { + checkMouseEvent(e); + } + + public void mouseExited(MouseEvent e) { + checkMouseEvent(e); + } + + public void mouseDragged(MouseEvent e) { + checkMouseEvent(e); + } + + public void mouseMoved(MouseEvent e) { + checkMouseEvent(e); + } + + + /** + * The mousePressed() function is called once after every time a mouse button is pressed. The mouseButton variable (see the related reference entry) can be used to determine which button has been pressed. + * =advanced + * + * If you must, use + * int button = mouseEvent.getButton(); + * to figure out which button was clicked. It will be one of: + * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3 + * Note, however, that this is completely inconsistent across + * platforms. + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mousePressed + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + */ + public void mousePressed() { } + + /** + * The mouseReleased() function is called every time a mouse button is released. + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mousePressed + * @see PApplet#mousePressed() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + */ + public void mouseReleased() { } + + /** + * The mouseClicked() function is called once after a mouse button has been pressed and then released. + * =advanced + * When the mouse is clicked, mousePressed() will be called, + * then mouseReleased(), then mouseClicked(). Note that + * mousePressed is already false inside of mouseClicked(). + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mouseButton + * @see PApplet#mousePressed() + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + * @see PApplet#mouseDragged() + */ + public void mouseClicked() { } + + /** + * The mouseDragged() function is called once every time the mouse moves and a mouse button is pressed. + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mousePressed + * @see PApplet#mousePressed() + * @see PApplet#mouseReleased() + * @see PApplet#mouseMoved() + */ + public void mouseDragged() { } + + /** + * The mouseMoved() function is called every time the mouse moves and a mouse button is not pressed. + * @webref input:mouse + * @see PApplet#mouseX + * @see PApplet#mouseY + * @see PApplet#mousePressed + * @see PApplet#mousePressed() + * @see PApplet#mouseReleased() + * @see PApplet#mouseDragged() + */ + public void mouseMoved() { } + + + ////////////////////////////////////////////////////////////// + + + KeyEvent keyEventQueue[] = new KeyEvent[10]; + int keyEventCount; + + protected void enqueueKeyEvent(KeyEvent e) { + synchronized (keyEventQueue) { + if (keyEventCount == keyEventQueue.length) { + KeyEvent temp[] = new KeyEvent[keyEventCount << 1]; + System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount); + keyEventQueue = temp; + } + keyEventQueue[keyEventCount++] = e; + } + } + + protected void dequeueKeyEvents() { + synchronized (keyEventQueue) { + for (int i = 0; i < keyEventCount; i++) { + keyEvent = keyEventQueue[i]; + handleKeyEvent(keyEvent); + } + keyEventCount = 0; + } + } + + + protected void handleKeyEvent(KeyEvent event) { + keyEvent = event; + key = event.getKeyChar(); + keyCode = event.getKeyCode(); + + keyEventMethods.handle(new Object[] { event }); + + switch (event.getID()) { + case KeyEvent.KEY_PRESSED: + keyPressed = true; + keyPressed(); + break; + case KeyEvent.KEY_RELEASED: + keyPressed = false; + keyReleased(); + break; + case KeyEvent.KEY_TYPED: + keyTyped(); + break; + } + + // if someone else wants to intercept the key, they should + // set key to zero (or something besides the ESC). + if (event.getID() == KeyEvent.KEY_PRESSED) { + if (key == KeyEvent.VK_ESCAPE) { + exit(); + } + // When running tethered to the Processing application, respond to + // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior + // when running independently, because this sketch may be one component + // embedded inside an application that has its own close behavior. + if (external && + event.getModifiers() == MENU_SHORTCUT && + event.getKeyCode() == 'W') { + exit(); + } + } + } + + + protected void checkKeyEvent(KeyEvent event) { + if (looping) { + enqueueKeyEvent(event); + } else { + handleKeyEvent(event); + } + } + + + /** + * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key', + * 'keyCode', and 'keyEvent' variables to no longer work; + * key events will no longer be queued until the end of draw(); + * and the keyPressed(), keyReleased() and keyTyped() methods + * will no longer be called. + */ + public void keyPressed(KeyEvent e) { checkKeyEvent(e); } + public void keyReleased(KeyEvent e) { checkKeyEvent(e); } + public void keyTyped(KeyEvent e) { checkKeyEvent(e); } + + + /** + * + * The keyPressed() function is called once every time a key is pressed. The key that was pressed is stored in the key variable. + *

For non-ASCII keys, use the keyCode variable. + * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode + * If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. + * Check for both ENTER and RETURN to make sure your program will work for all platforms.

Because of how operating systems handle key repeats, holding down a key may cause multiple calls to keyPressed() (and keyReleased() as well). + * The rate of repeat is set by the operating system and how each computer is configured. + * =advanced + * + * Called each time a single key on the keyboard is pressed. + * Because of how operating systems handle key repeats, holding + * down a key will cause multiple calls to keyPressed(), because + * the OS repeat takes over. + *

+ * Examples for key handling: + * (Tested on Windows XP, please notify if different on other + * platforms, I have a feeling Mac OS and Linux may do otherwise) + *

+   * 1. Pressing 'a' on the keyboard:
+   *    keyPressed  with key == 'a' and keyCode == 'A'
+   *    keyTyped    with key == 'a' and keyCode ==  0
+   *    keyReleased with key == 'a' and keyCode == 'A'
+   *
+   * 2. Pressing 'A' on the keyboard:
+   *    keyPressed  with key == 'A' and keyCode == 'A'
+   *    keyTyped    with key == 'A' and keyCode ==  0
+   *    keyReleased with key == 'A' and keyCode == 'A'
+   *
+   * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off):
+   *    keyPressed  with key == CODED and keyCode == SHIFT
+   *    keyPressed  with key == 'A'   and keyCode == 'A'
+   *    keyTyped    with key == 'A'   and keyCode == 0
+   *    keyReleased with key == 'A'   and keyCode == 'A'
+   *    keyReleased with key == CODED and keyCode == SHIFT
+   *
+   * 4. Holding down the 'a' key.
+   *    The following will happen several times,
+   *    depending on your machine's "key repeat rate" settings:
+   *    keyPressed  with key == 'a' and keyCode == 'A'
+   *    keyTyped    with key == 'a' and keyCode ==  0
+   *    When you finally let go, you'll get:
+   *    keyReleased with key == 'a' and keyCode == 'A'
+   *
+   * 5. Pressing and releasing the 'shift' key
+   *    keyPressed  with key == CODED and keyCode == SHIFT
+   *    keyReleased with key == CODED and keyCode == SHIFT
+   *    (note there is no keyTyped)
+   *
+   * 6. Pressing the tab key in an applet with Java 1.4 will
+   *    normally do nothing, but PApplet dynamically shuts
+   *    this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows).
+   *    Java 1.1 (Microsoft VM) passes the TAB key through normally.
+   *    Not tested on other platforms or for 1.3.
+   * 
+ * @see PApplet#key + * @see PApplet#keyCode + * @see PApplet#keyPressed + * @see PApplet#keyReleased() + * @webref input:keyboard + */ + public void keyPressed() { } + + + /** + * The keyReleased() function is called once every time a key is released. The key that was released will be stored in the key variable. See key and keyReleased for more information. + * + * @see PApplet#key + * @see PApplet#keyCode + * @see PApplet#keyPressed + * @see PApplet#keyPressed() + * @webref input:keyboard + */ + public void keyReleased() { } + + + /** + * Only called for "regular" keys like letters, + * see keyPressed() for full documentation. + */ + public void keyTyped() { } + + + ////////////////////////////////////////////////////////////// + + // i am focused man, and i'm not afraid of death. + // and i'm going all out. i circle the vultures in a van + // and i run the block. + + + public void focusGained() { } + + public void focusGained(FocusEvent e) { + focused = true; + focusGained(); + } + + + public void focusLost() { } + + public void focusLost(FocusEvent e) { + focused = false; + focusLost(); + } + + + ////////////////////////////////////////////////////////////// + + // getting the time + + + /** + * Returns the number of milliseconds (thousandths of a second) since starting an applet. This information is often used for timing animation sequences. + * + * =advanced + *

+ * This is a function, rather than a variable, because it may + * change multiple times per frame. + * + * @webref input:time_date + * @see processing.core.PApplet#second() + * @see processing.core.PApplet#minute() + * @see processing.core.PApplet#hour() + * @see processing.core.PApplet#day() + * @see processing.core.PApplet#month() + * @see processing.core.PApplet#year() + * + */ + public int millis() { + return (int) (System.currentTimeMillis() - millisOffset); + } + + /** Seconds position of the current time. + * + * @webref input:time_date + * @see processing.core.PApplet#millis() + * @see processing.core.PApplet#minute() + * @see processing.core.PApplet#hour() + * @see processing.core.PApplet#day() + * @see processing.core.PApplet#month() + * @see processing.core.PApplet#year() + * */ + static public int second() { + return Calendar.getInstance().get(Calendar.SECOND); + } + + /** + * Processing communicates with the clock on your computer. The minute() function returns the current minute as a value from 0 - 59. + * + * @webref input:time_date + * @see processing.core.PApplet#millis() + * @see processing.core.PApplet#second() + * @see processing.core.PApplet#hour() + * @see processing.core.PApplet#day() + * @see processing.core.PApplet#month() + * @see processing.core.PApplet#year() + * + * */ + static public int minute() { + return Calendar.getInstance().get(Calendar.MINUTE); + } + + /** + * Processing communicates with the clock on your computer. The hour() function returns the current hour as a value from 0 - 23. + * =advanced + * Hour position of the current time in international format (0-23). + *

+ * To convert this value to American time:
+ *

int yankeeHour = (hour() % 12);
+   * if (yankeeHour == 0) yankeeHour = 12;
+ * + * @webref input:time_date + * @see processing.core.PApplet#millis() + * @see processing.core.PApplet#second() + * @see processing.core.PApplet#minute() + * @see processing.core.PApplet#day() + * @see processing.core.PApplet#month() + * @see processing.core.PApplet#year() + * + */ + static public int hour() { + return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + } + + /** + * Processing communicates with the clock on your computer. The day() function returns the current day as a value from 1 - 31. + * =advanced + * Get the current day of the month (1 through 31). + *

+ * If you're looking for the day of the week (M-F or whatever) + * or day of the year (1..365) then use java's Calendar.get() + * + * @webref input:time_date + * @see processing.core.PApplet#millis() + * @see processing.core.PApplet#second() + * @see processing.core.PApplet#minute() + * @see processing.core.PApplet#hour() + * @see processing.core.PApplet#month() + * @see processing.core.PApplet#year() + */ + static public int day() { + return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + } + + /** + * Processing communicates with the clock on your computer. The month() function returns the current month as a value from 1 - 12. + * + * @webref input:time_date + * @see processing.core.PApplet#millis() + * @see processing.core.PApplet#second() + * @see processing.core.PApplet#minute() + * @see processing.core.PApplet#hour() + * @see processing.core.PApplet#day() + * @see processing.core.PApplet#year() + */ + static public int month() { + // months are number 0..11 so change to colloquial 1..12 + return Calendar.getInstance().get(Calendar.MONTH) + 1; + } + + /** + * Processing communicates with the clock on your computer. + * The year() function returns the current year as an integer (2003, 2004, 2005, etc). + * + * @webref input:time_date + * @see processing.core.PApplet#millis() + * @see processing.core.PApplet#second() + * @see processing.core.PApplet#minute() + * @see processing.core.PApplet#hour() + * @see processing.core.PApplet#day() + * @see processing.core.PApplet#month() + */ + static public int year() { + return Calendar.getInstance().get(Calendar.YEAR); + } + + + ////////////////////////////////////////////////////////////// + + // controlling time (playing god) + + + /** + * The delay() function causes the program to halt for a specified time. + * Delay times are specified in thousandths of a second. For example, + * running delay(3000) will stop the program for three seconds and + * delay(500) will stop the program for a half-second. Remember: the + * display window is updated only at the end of draw(), so putting more + * than one delay() inside draw() will simply add them together and the new + * frame will be drawn when the total delay is over. + *

+ * I'm not sure if this is even helpful anymore, as the screen isn't + * updated before or after the delay, meaning which means it just + * makes the app lock up temporarily. + */ + public void delay(int napTime) { + if (frameCount != 0) { + if (napTime > 0) { + try { + Thread.sleep(napTime); + } catch (InterruptedException e) { } + } + } + } + + + /** + * Specifies the number of frames to be displayed every second. + * If the processor is not fast enough to maintain the specified rate, it will not be achieved. + * For example, the function call frameRate(30) will attempt to refresh 30 times a second. + * It is recommended to set the frame rate within setup(). The default rate is 60 frames per second. + * =advanced + * Set a target frameRate. This will cause delay() to be called + * after each frame so that the sketch synchronizes to a particular speed. + * Note that this only sets the maximum frame rate, it cannot be used to + * make a slow sketch go faster. Sketches have no default frame rate + * setting, and will attempt to use maximum processor power to achieve + * maximum speed. + * @webref environment + * @param newRateTarget number of frames per second + * @see PApplet#delay(int) + */ + public void frameRate(float newRateTarget) { + frameRateTarget = newRateTarget; + frameRatePeriod = (long) (1000000000.0 / frameRateTarget); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Reads the value of a param. + * Values are always read as a String so if you want them to be an integer or other datatype they must be converted. + * The param() function will only work in a web browser. + * The function should be called inside setup(), + * otherwise the applet may not yet be initialized and connected to its parent web browser. + * + * @webref input:web + * @usage Web + * + * @param what name of the param to read + */ + public String param(String what) { + if (online) { + return getParameter(what); + + } else { + System.err.println("param() only works inside a web browser"); + } + return null; + } + + + /** + * Displays message in the browser's status area. This is the text area in the lower left corner of the browser. + * The status() function will only work when the Processing program is running in a web browser. + * =advanced + * Show status in the status bar of a web browser, or in the + * System.out console. Eventually this might show status in the + * p5 environment itself, rather than relying on the console. + * + * @webref input:web + * @usage Web + * @param what any valid String + */ + public void status(String what) { + if (online) { + showStatus(what); + + } else { + System.out.println(what); // something more interesting? + } + } + + + public void link(String here) { + link(here, null); + } + + + /** + * Links to a webpage either in the same window or in a new window. The complete URL must be specified. + * =advanced + * Link to an external page without all the muss. + *

+ * When run with an applet, uses the browser to open the url, + * for applications, attempts to launch a browser with the url. + *

+ * Works on Mac OS X and Windows. For Linux, use: + *

open(new String[] { "firefox", url });
+ * or whatever you want as your browser, since Linux doesn't + * yet have a standard method for launching URLs. + * + * @webref input:web + * @param url complete url as a String in quotes + * @param frameTitle name of the window to load the URL as a string in quotes + * + */ + public void link(String url, String frameTitle) { + if (online) { + try { + if (frameTitle == null) { + getAppletContext().showDocument(new URL(url)); + } else { + getAppletContext().showDocument(new URL(url), frameTitle); + } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Could not open " + url); + } + } else { + try { + if (platform == WINDOWS) { + // the following uses a shell execute to launch the .html file + // note that under cygwin, the .html files have to be chmodded +x + // after they're unpacked from the zip file. i don't know why, + // and don't understand what this does in terms of windows + // permissions. without the chmod, the command prompt says + // "Access is denied" in both cygwin and the "dos" prompt. + //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + + // referenceFile + ".html"); + + // replace ampersands with control sequence for DOS. + // solution contributed by toxi on the bugs board. + url = url.replaceAll("&","^&"); + + // open dos prompt, give it 'start' command, which will + // open the url properly. start by itself won't work since + // it appears to need cmd + Runtime.getRuntime().exec("cmd /c start " + url); + + } else if (platform == MACOSX) { + //com.apple.mrj.MRJFileUtils.openURL(url); + try { +// Class mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); +// Method openMethod = +// mrjFileUtils.getMethod("openURL", new Class[] { String.class }); + Class eieio = Class.forName("com.apple.eio.FileManager"); + Method openMethod = + eieio.getMethod("openURL", new Class[] { String.class }); + openMethod.invoke(null, new Object[] { url }); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + //throw new RuntimeException("Can't open URLs for this platform"); + // Just pass it off to open() and hope for the best + open(url); + } + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Could not open " + url); + } + } + } + + + /** + * Attempts to open an application or file using your platform's launcher. The file parameter is a String specifying the file name and location. The location parameter must be a full path name, or the name of an executable in the system's PATH. In most cases, using a full path is the best option, rather than relying on the system PATH. Be sure to make the file executable before attempting to open it (chmod +x). + *

+ * The args parameter is a String or String array which is passed to the command line. If you have multiple parameters, e.g. an application and a document, or a command with multiple switches, use the version that takes a String array, and place each individual item in a separate element. + *

+ * If args is a String (not an array), then it can only be a single file or application with no parameters. It's not the same as executing that String using a shell. For instance, open("jikes -help") will not work properly. + *

+ * This function behaves differently on each platform. On Windows, the parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the "open" command is used (type "man open" in Terminal.app for documentation). On Linux, it first tries gnome-open, then kde-open, but if neither are available, it sends the command to the shell without any alterations. + *

+ * For users familiar with Java, this is not quite the same as Runtime.exec(), because the launcher command is prepended. Instead, the exec(String[]) function is a shortcut for Runtime.getRuntime.exec(String[]). + * + * @webref input:files + * @param filename name of the file + * @usage Application + */ + static public void open(String filename) { + open(new String[] { filename }); + } + + + static String openLauncher; + + /** + * Launch a process using a platforms shell. This version uses an array + * to make it easier to deal with spaces in the individual elements. + * (This avoids the situation of trying to put single or double quotes + * around different bits). + * + * @param list of commands passed to the command line + */ + static public Process open(String argv[]) { + String[] params = null; + + if (platform == WINDOWS) { + // just launching the .html file via the shell works + // but make sure to chmod +x the .html files first + // also place quotes around it in case there's a space + // in the user.dir part of the url + params = new String[] { "cmd", "/c" }; + + } else if (platform == MACOSX) { + params = new String[] { "open" }; + + } else if (platform == LINUX) { + if (openLauncher == null) { + // Attempt to use gnome-open + try { + Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" }); + /*int result =*/ p.waitFor(); + // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04) + openLauncher = "gnome-open"; + } catch (Exception e) { } + } + if (openLauncher == null) { + // Attempt with kde-open + try { + Process p = Runtime.getRuntime().exec(new String[] { "kde-open" }); + /*int result =*/ p.waitFor(); + openLauncher = "kde-open"; + } catch (Exception e) { } + } + if (openLauncher == null) { + System.err.println("Could not find gnome-open or kde-open, " + + "the open() command may not work."); + } + if (openLauncher != null) { + params = new String[] { openLauncher }; + } + //} else { // give up and just pass it to Runtime.exec() + //open(new String[] { filename }); + //params = new String[] { filename }; + } + if (params != null) { + // If the 'open', 'gnome-open' or 'cmd' are already included + if (params[0].equals(argv[0])) { + // then don't prepend those params again + return exec(argv); + } else { + params = concat(params, argv); + return exec(params); + } + } else { + return exec(argv); + } + } + + + static public Process exec(String[] argv) { + try { + return Runtime.getRuntime().exec(argv); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Could not open " + join(argv, ' ')); + } + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Function for an applet/application to kill itself and + * display an error. Mostly this is here to be improved later. + */ + public void die(String what) { + dispose(); + throw new RuntimeException(what); + } + + + /** + * Same as above but with an exception. Also needs work. + */ + public void die(String what, Exception e) { + if (e != null) e.printStackTrace(); + die(what); + } + + + /** + * Call to safely exit the sketch when finished. For instance, + * to render a single frame, save it, and quit. + */ + public void exit() { + if (thread == null) { + // exit immediately, dispose() has already been called, + // meaning that the main thread has long since exited + exit2(); + + } else if (looping) { + // dispose() will be called as the thread exits + finished = true; + // tell the code to call exit2() to do a System.exit() + // once the next draw() has completed + exitCalled = true; + + } else if (!looping) { + // if not looping, shut down things explicitly, + // because the main thread will be sleeping + dispose(); + + // now get out + exit2(); + } + } + + void exit2() { + try { + System.exit(0); + } catch (SecurityException e) { + // don't care about applet security exceptions + } + } + + /** + * Called to dispose of resources and shut down the sketch. + * Destroys the thread, dispose the renderer,and notify listeners. + *

+ * Not to be called or overriden by users. If called multiple times, + * will only notify listeners once. Register a dispose listener instead. + */ + public void dispose(){ + // moved here from stop() + finished = true; // let the sketch know it is shut down time + + // don't run the disposers twice + if (thread == null) return; + thread = null; + + // shut down renderer + if (g != null) g.dispose(); + disposeMethods.handle(); + } + + ////////////////////////////////////////////////////////////// + + public void method(String name) { +// final Object o = this; +// final Class c = getClass(); + try { + Method method = getClass().getMethod(name, new Class[] {}); + method.invoke(this, new Object[] { }); + + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.getTargetException().printStackTrace(); + } catch (NoSuchMethodException nsme) { + System.err.println("There is no public " + name + "() method " + + "in the class " + getClass().getName()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + public void thread(final String name) { + Thread later = new Thread() { + public void run() { + method(name); + } + }; + later.start(); + } + + + /* + public void thread(String name) { + final Object o = this; + final Class c = getClass(); + try { + final Method method = c.getMethod(name, new Class[] {}); + Thread later = new Thread() { + public void run() { + try { + method.invoke(o, new Object[] { }); + + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.getTargetException().printStackTrace(); + } + } + }; + later.start(); + + } catch (NoSuchMethodException nsme) { + System.err.println("There is no " + name + "() method " + + "in the class " + getClass().getName()); + + } catch (Exception e) { + e.printStackTrace(); + } + } + */ + + + + ////////////////////////////////////////////////////////////// + + // SCREEN GRABASS + + + /** + * Intercepts any relative paths to make them absolute (relative + * to the sketch folder) before passing to save() in PImage. + * (Changed in 0100) + */ + public void save(String filename) { + g.save(savePath(filename)); + } + + + /** + * Grab an image of what's currently in the drawing area and save it + * as a .tif or .tga file. + *

+ * Best used just before endDraw() at the end of your draw(). + * This can only create .tif or .tga images, so if neither extension + * is specified it defaults to writing a tiff and adds a .tif suffix. + */ + public void saveFrame() { + try { + g.save(savePath("screen-" + nf(frameCount, 4) + ".tif")); + } catch (SecurityException se) { + System.err.println("Can't use saveFrame() when running in a browser, " + + "unless using a signed applet."); + } + } + + + /** + * Save the current frame as a .tif or .tga image. + *

+ * The String passed in can contain a series of # signs + * that will be replaced with the screengrab number. + *

+   * i.e. saveFrame("blah-####.tif");
+   *      // saves a numbered tiff image, replacing the
+   *      // #### signs with zeros and the frame number 
+ */ + public void saveFrame(String what) { + try { + g.save(savePath(insertFrame(what))); + } catch (SecurityException se) { + System.err.println("Can't use saveFrame() when running in a browser, " + + "unless using a signed applet."); + } + } + + + /** + * Check a string for #### signs to see if the frame number should be + * inserted. Used for functions like saveFrame() and beginRecord() to + * replace the # marks with the frame number. If only one # is used, + * it will be ignored, under the assumption that it's probably not + * intended to be the frame number. + */ + protected String insertFrame(String what) { + int first = what.indexOf('#'); + int last = what.lastIndexOf('#'); + + if ((first != -1) && (last - first > 0)) { + String prefix = what.substring(0, first); + int count = last - first + 1; + String suffix = what.substring(last + 1); + return prefix + nf(frameCount, count) + suffix; + } + return what; // no change + } + + + + ////////////////////////////////////////////////////////////// + + // CURSOR + + // + + + int cursorType = ARROW; // cursor type + boolean cursorVisible = true; // cursor visibility flag + PImage invisibleCursor; + + + /** + * Set the cursor type + * @param cursorType either ARROW, CROSS, HAND, MOVE, TEXT, WAIT + */ + public void cursor(int cursorType) { + setCursor(Cursor.getPredefinedCursor(cursorType)); + cursorVisible = true; + this.cursorType = cursorType; + } + + + /** + * Replace the cursor with the specified PImage. The x- and y- + * coordinate of the center will be the center of the image. + */ + public void cursor(PImage image) { + cursor(image, image.width/2, image.height/2); + } + + + /** + * Sets the cursor to a predefined symbol, an image, or turns it on if already hidden. + * If you are trying to set an image as the cursor, it is recommended to make the size 16x16 or 32x32 pixels. + * It is not possible to load an image as the cursor if you are exporting your program for the Web. + * The values for parameters x and y must be less than the dimensions of the image. + * =advanced + * Set a custom cursor to an image with a specific hotspot. + * Only works with JDK 1.2 and later. + * Currently seems to be broken on Java 1.4 for Mac OS X + *

+ * Based on code contributed by Amit Pitaru, plus additional + * code to handle Java versions via reflection by Jonathan Feinberg. + * Reflection removed for release 0128 and later. + * @webref environment + * @see PApplet#noCursor() + * @param image any variable of type PImage + * @param hotspotX the horizonal active spot of the cursor + * @param hotspotY the vertical active spot of the cursor + */ + public void cursor(PImage image, int hotspotX, int hotspotY) { + // don't set this as cursor type, instead use cursor_type + // to save the last cursor used in case cursor() is called + //cursor_type = Cursor.CUSTOM_CURSOR; + Image jimage = + createImage(new MemoryImageSource(image.width, image.height, + image.pixels, 0, image.width)); + Point hotspot = new Point(hotspotX, hotspotY); + Toolkit tk = Toolkit.getDefaultToolkit(); + Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor"); + setCursor(cursor); + cursorVisible = true; + } + + + /** + * Show the cursor after noCursor() was called. + * Notice that the program remembers the last set cursor type + */ + public void cursor() { + // maybe should always set here? seems dangerous, since + // it's likely that java will set the cursor to something + // else on its own, and the applet will be stuck b/c bagel + // thinks that the cursor is set to one particular thing + if (!cursorVisible) { + cursorVisible = true; + setCursor(Cursor.getPredefinedCursor(cursorType)); + } + } + + + /** + * Hides the cursor from view. Will not work when running the program in a web browser. + * =advanced + * Hide the cursor by creating a transparent image + * and using it as a custom cursor. + * @webref environment + * @see PApplet#cursor() + * @usage Application + */ + public void noCursor() { + if (!cursorVisible) return; // don't hide if already hidden. + + if (invisibleCursor == null) { + invisibleCursor = new PImage(16, 16, ARGB); + } + // was formerly 16x16, but the 0x0 was added by jdf as a fix + // for macosx, which wasn't honoring the invisible cursor + cursor(invisibleCursor, 8, 8); + cursorVisible = false; + } + + + ////////////////////////////////////////////////////////////// + + + static public void print(byte what) { + System.out.print(what); + System.out.flush(); + } + + static public void print(boolean what) { + System.out.print(what); + System.out.flush(); + } + + static public void print(char what) { + System.out.print(what); + System.out.flush(); + } + + static public void print(int what) { + System.out.print(what); + System.out.flush(); + } + + static public void print(float what) { + System.out.print(what); + System.out.flush(); + } + + static public void print(String what) { + System.out.print(what); + System.out.flush(); + } + + static public void print(Object what) { + if (what == null) { + // special case since this does fuggly things on > 1.1 + System.out.print("null"); + } else { + System.out.println(what.toString()); + } + } + + // + + static public void println() { + System.out.println(); + } + + // + + static public void println(byte what) { + print(what); System.out.println(); + } + + static public void println(boolean what) { + print(what); System.out.println(); + } + + static public void println(char what) { + print(what); System.out.println(); + } + + static public void println(int what) { + print(what); System.out.println(); + } + + static public void println(float what) { + print(what); System.out.println(); + } + + static public void println(String what) { + print(what); System.out.println(); + } + + static public void println(Object what) { + if (what == null) { + // special case since this does fuggly things on > 1.1 + System.out.println("null"); + + } else { + String name = what.getClass().getName(); + if (name.charAt(0) == '[') { + switch (name.charAt(1)) { + case '[': + // don't even mess with multi-dimensional arrays (case '[') + // or anything else that's not int, float, boolean, char + System.out.println(what); + break; + + case 'L': + // print a 1D array of objects as individual elements + Object poo[] = (Object[]) what; + for (int i = 0; i < poo.length; i++) { + if (poo[i] instanceof String) { + System.out.println("[" + i + "] \"" + poo[i] + "\""); + } else { + System.out.println("[" + i + "] " + poo[i]); + } + } + break; + + case 'Z': // boolean + boolean zz[] = (boolean[]) what; + for (int i = 0; i < zz.length; i++) { + System.out.println("[" + i + "] " + zz[i]); + } + break; + + case 'B': // byte + byte bb[] = (byte[]) what; + for (int i = 0; i < bb.length; i++) { + System.out.println("[" + i + "] " + bb[i]); + } + break; + + case 'C': // char + char cc[] = (char[]) what; + for (int i = 0; i < cc.length; i++) { + System.out.println("[" + i + "] '" + cc[i] + "'"); + } + break; + + case 'I': // int + int ii[] = (int[]) what; + for (int i = 0; i < ii.length; i++) { + System.out.println("[" + i + "] " + ii[i]); + } + break; + + case 'F': // float + float ff[] = (float[]) what; + for (int i = 0; i < ff.length; i++) { + System.out.println("[" + i + "] " + ff[i]); + } + break; + + case 'D': // double + double dd[] = (double[]) what; + for (int i = 0; i < dd.length; i++) { + System.out.println("[" + i + "] " + dd[i]); + } + break; + + default: + System.out.println(what); + } + } else { // not an array + System.out.println(what); + } + } + } + + // + + /* + // not very useful, because it only works for public (and protected?) + // fields of a class, not local variables to methods + public void printvar(String name) { + try { + Field field = getClass().getDeclaredField(name); + println(name + " = " + field.get(this)); + } catch (Exception e) { + e.printStackTrace(); + } + } + */ + + + ////////////////////////////////////////////////////////////// + + // MATH + + // lots of convenience methods for math with floats. + // doubles are overkill for processing applets, and casting + // things all the time is annoying, thus the functions below. + + + static public final float abs(float n) { + return (n < 0) ? -n : n; + } + + static public final int abs(int n) { + return (n < 0) ? -n : n; + } + + static public final float sq(float a) { + return a*a; + } + + static public final float sqrt(float a) { + return (float)Math.sqrt(a); + } + + static public final float log(float a) { + return (float)Math.log(a); + } + + static public final float exp(float a) { + return (float)Math.exp(a); + } + + static public final float pow(float a, float b) { + return (float)Math.pow(a, b); + } + + + static public final int max(int a, int b) { + return (a > b) ? a : b; + } + + static public final float max(float a, float b) { + return (a > b) ? a : b; + } + + /* + static public final double max(double a, double b) { + return (a > b) ? a : b; + } + */ + + + static public final int max(int a, int b, int c) { + return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); + } + + static public final float max(float a, float b, float c) { + return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); + } + + + /** + * Find the maximum value in an array. + * Throws an ArrayIndexOutOfBoundsException if the array is length 0. + * @param list the source array + * @return The maximum value + */ + static public final int max(int[] list) { + if (list.length == 0) { + throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); + } + int max = list[0]; + for (int i = 1; i < list.length; i++) { + if (list[i] > max) max = list[i]; + } + return max; + } + + /** + * Find the maximum value in an array. + * Throws an ArrayIndexOutOfBoundsException if the array is length 0. + * @param list the source array + * @return The maximum value + */ + static public final float max(float[] list) { + if (list.length == 0) { + throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); + } + float max = list[0]; + for (int i = 1; i < list.length; i++) { + if (list[i] > max) max = list[i]; + } + return max; + } + + + /** + * Find the maximum value in an array. + * Throws an ArrayIndexOutOfBoundsException if the array is length 0. + * @param list the source array + * @return The maximum value + */ + /* + static public final double max(double[] list) { + if (list.length == 0) { + throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); + } + double max = list[0]; + for (int i = 1; i < list.length; i++) { + if (list[i] > max) max = list[i]; + } + return max; + } + */ + + + static public final int min(int a, int b) { + return (a < b) ? a : b; + } + + static public final float min(float a, float b) { + return (a < b) ? a : b; + } + + /* + static public final double min(double a, double b) { + return (a < b) ? a : b; + } + */ + + + static public final int min(int a, int b, int c) { + return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); + } + + static public final float min(float a, float b, float c) { + return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); + } + + /* + static public final double min(double a, double b, double c) { + return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); + } + */ + + + /** + * Find the minimum value in an array. + * Throws an ArrayIndexOutOfBoundsException if the array is length 0. + * @param list the source array + * @return The minimum value + */ + static public final int min(int[] list) { + if (list.length == 0) { + throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); + } + int min = list[0]; + for (int i = 1; i < list.length; i++) { + if (list[i] < min) min = list[i]; + } + return min; + } + + + /** + * Find the minimum value in an array. + * Throws an ArrayIndexOutOfBoundsException if the array is length 0. + * @param list the source array + * @return The minimum value + */ + static public final float min(float[] list) { + if (list.length == 0) { + throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); + } + float min = list[0]; + for (int i = 1; i < list.length; i++) { + if (list[i] < min) min = list[i]; + } + return min; + } + + + /** + * Find the minimum value in an array. + * Throws an ArrayIndexOutOfBoundsException if the array is length 0. + * @param list the source array + * @return The minimum value + */ + /* + static public final double min(double[] list) { + if (list.length == 0) { + throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); + } + double min = list[0]; + for (int i = 1; i < list.length; i++) { + if (list[i] < min) min = list[i]; + } + return min; + } + */ + + static public final int constrain(int amt, int low, int high) { + return (amt < low) ? low : ((amt > high) ? high : amt); + } + + static public final float constrain(float amt, float low, float high) { + return (amt < low) ? low : ((amt > high) ? high : amt); + } + + + static public final float sin(float angle) { + return (float)Math.sin(angle); + } + + static public final float cos(float angle) { + return (float)Math.cos(angle); + } + + static public final float tan(float angle) { + return (float)Math.tan(angle); + } + + + static public final float asin(float value) { + return (float)Math.asin(value); + } + + static public final float acos(float value) { + return (float)Math.acos(value); + } + + static public final float atan(float value) { + return (float)Math.atan(value); + } + + static public final float atan2(float a, float b) { + return (float)Math.atan2(a, b); + } + + + static public final float degrees(float radians) { + return radians * RAD_TO_DEG; + } + + static public final float radians(float degrees) { + return degrees * DEG_TO_RAD; + } + + + static public final int ceil(float what) { + return (int) Math.ceil(what); + } + + static public final int floor(float what) { + return (int) Math.floor(what); + } + + static public final int round(float what) { + return (int) Math.round(what); + } + + + static public final float mag(float a, float b) { + return (float)Math.sqrt(a*a + b*b); + } + + static public final float mag(float a, float b, float c) { + return (float)Math.sqrt(a*a + b*b + c*c); + } + + + static public final float dist(float x1, float y1, float x2, float y2) { + return sqrt(sq(x2-x1) + sq(y2-y1)); + } + + static public final float dist(float x1, float y1, float z1, + float x2, float y2, float z2) { + return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); + } + + + static public final float lerp(float start, float stop, float amt) { + return start + (stop-start) * amt; + } + + /** + * Normalize a value to exist between 0 and 1 (inclusive). + * Mathematically the opposite of lerp(), figures out what proportion + * a particular value is relative to start and stop coordinates. + */ + static public final float norm(float value, float start, float stop) { + return (value - start) / (stop - start); + } + + /** + * Convenience function to map a variable from one coordinate space + * to another. Equivalent to unlerp() followed by lerp(). + */ + static public final float map(float value, + float istart, float istop, + float ostart, float ostop) { + return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); + } + + + /* + static public final double map(double value, + double istart, double istop, + double ostart, double ostop) { + return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); + } + */ + + + + ////////////////////////////////////////////////////////////// + + // RANDOM NUMBERS + + + Random internalRandom; + + /** + * Return a random number in the range [0, howbig). + *

+ * The number returned will range from zero up to + * (but not including) 'howbig'. + */ + public final float random(float howbig) { + // for some reason (rounding error?) Math.random() * 3 + // can sometimes return '3' (once in ~30 million tries) + // so a check was added to avoid the inclusion of 'howbig' + + // avoid an infinite loop + if (howbig == 0) return 0; + + // internal random number object + if (internalRandom == null) internalRandom = new Random(); + + float value = 0; + do { + //value = (float)Math.random() * howbig; + value = internalRandom.nextFloat() * howbig; + } while (value == howbig); + return value; + } + + + /** + * Return a random number in the range [howsmall, howbig). + *

+ * The number returned will range from 'howsmall' up to + * (but not including 'howbig'. + *

+ * If howsmall is >= howbig, howsmall will be returned, + * meaning that random(5, 5) will return 5 (useful) + * and random(7, 4) will return 7 (not useful.. better idea?) + */ + public final float random(float howsmall, float howbig) { + if (howsmall >= howbig) return howsmall; + float diff = howbig - howsmall; + return random(diff) + howsmall; + } + + + public final void randomSeed(long what) { + // internal random number object + if (internalRandom == null) internalRandom = new Random(); + internalRandom.setSeed(what); + } + + + + ////////////////////////////////////////////////////////////// + + // PERLIN NOISE + + // [toxi 040903] + // octaves and amplitude amount per octave are now user controlled + // via the noiseDetail() function. + + // [toxi 030902] + // cleaned up code and now using bagel's cosine table to speed up + + // [toxi 030901] + // implementation by the german demo group farbrausch + // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip + + static final int PERLIN_YWRAPB = 4; + static final int PERLIN_YWRAP = 1<>= 1; + } + + if (x<0) x=-x; + if (y<0) y=-y; + if (z<0) z=-z; + + int xi=(int)x, yi=(int)y, zi=(int)z; + float xf = (float)(x-xi); + float yf = (float)(y-yi); + float zf = (float)(z-zi); + float rxf, ryf; + + float r=0; + float ampl=0.5f; + + float n1,n2,n3; + + for (int i=0; i=1.0f) { xi++; xf--; } + if (yf>=1.0f) { yi++; yf--; } + if (zf>=1.0f) { zi++; zf--; } + } + return r; + } + + // [toxi 031112] + // now adjusts to the size of the cosLUT used via + // the new variables, defined above + private float noise_fsc(float i) { + // using bagel's cosine table instead + return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]); + } + + // [toxi 040903] + // make perlin noise quality user controlled to allow + // for different levels of detail. lower values will produce + // smoother results as higher octaves are surpressed + + public void noiseDetail(int lod) { + if (lod>0) perlin_octaves=lod; + } + + public void noiseDetail(int lod, float falloff) { + if (lod>0) perlin_octaves=lod; + if (falloff>0) perlin_amp_falloff=falloff; + } + + public void noiseSeed(long what) { + if (perlinRandom == null) perlinRandom = new Random(); + perlinRandom.setSeed(what); + // force table reset after changing the random number seed [0122] + perlin = null; + } + + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + protected String[] loadImageFormats; + + + /** + * Load an image from the data folder or a local directory. + * Supports .gif (including transparency), .tga, and .jpg images. + * In Java 1.3 or later, .png images are + * + * also supported. + *

+ * Generally, loadImage() should only be used during setup, because + * re-loading images inside draw() is likely to cause a significant + * delay while memory is allocated and the thread blocks while waiting + * for the image to load because loading is not asynchronous. + *

+ * To load several images asynchronously, see more information in the + * FAQ about writing your own threaded image loading method. + *

+ * As of 0096, returns null if no image of that name is found, + * rather than an error. + *

+ * Release 0115 also provides support for reading TIFF and RLE-encoded + * Targa (.tga) files written by Processing via save() and saveFrame(). + * Other TIFF and Targa files will probably not load, use a different + * format (gif, jpg and png are safest bets) when creating images with + * another application to use with Processing. + *

+ * Also in release 0115, more image formats (BMP and others) can + * be read when using Java 1.4 and later. Because many people still + * use Java 1.1 and 1.3, these formats are not recommended for + * work that will be posted on the web. To get a list of possible + * image formats for use with Java 1.4 and later, use the following: + * println(javax.imageio.ImageIO.getReaderFormatNames()) + *

+ * Images are loaded via a byte array that is passed to + * Toolkit.createImage(). Unfortunately, we cannot use Applet.getImage() + * because it takes a URL argument, which would be a pain in the a-- + * to make work consistently for online and local sketches. + * Sometimes this causes problems, resulting in issues like + * Bug 279 + * and + * Bug 305. + * In release 0115, everything was instead run through javax.imageio, + * but that turned out to be very slow, see + * Bug 392. + * As a result, starting with 0116, the following happens: + *

    + *
  • TGA and TIFF images are loaded using the internal load methods. + *
  • JPG, GIF, and PNG images are loaded via loadBytes(). + *
  • If the image still isn't loaded, it's passed to javax.imageio. + *
+ * For releases 0116 and later, if you have problems such as those seen + * in Bugs 279 and 305, use Applet.getImage() instead. You'll be stuck + * with the limitations of getImage() (the headache of dealing with + * online/offline use). Set up your own MediaTracker, and pass the resulting + * java.awt.Image to the PImage constructor that takes an AWT image. + */ + public PImage loadImage(String filename) { + return loadImage(filename, null); + } + + + /** + * Loads an image into a variable of type PImage. Four types of images ( .gif, .jpg, .tga, .png) images may be loaded. To load correctly, images must be located in the data directory of the current sketch. In most cases, load all images in setup() to preload them at the start of the program. Loading images inside draw() will reduce the speed of a program. + *

The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch found online can only download files from the same server from which it came. Getting around this restriction requires a signed applet. + *

The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to loadImage(), as shown in the third example on this page. + *

If an image is not loaded successfully, the null value is returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from loadImage() is null.

Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because loadImage() will attempt to interpret the HTML as image data. + * + * =advanced + * Identical to loadImage, but allows you to specify the type of + * image by its extension. Especially useful when downloading from + * CGI scripts. + *

+ * Use 'unknown' as the extension to pass off to the default + * image loader that handles gif, jpg, and png. + * + * @webref image:loading_displaying + * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform. + * @param extension the type of image to load, for example "png", "gif", "jpg" + * + * @see processing.core.PImage + * @see processing.core.PApplet#image(PImage, float, float, float, float) + * @see processing.core.PApplet#imageMode(int) + * @see processing.core.PApplet#background(float, float, float) + */ + public PImage loadImage(String filename, String extension) { + if (extension == null) { + String lower = filename.toLowerCase(); + int dot = filename.lastIndexOf('.'); + if (dot == -1) { + extension = "unknown"; // no extension found + } + extension = lower.substring(dot + 1); + + // check for, and strip any parameters on the url, i.e. + // filename.jpg?blah=blah&something=that + int question = extension.indexOf('?'); + if (question != -1) { + extension = extension.substring(0, question); + } + } + + // just in case. them users will try anything! + extension = extension.toLowerCase(); + + if (extension.equals("tga")) { + try { + return loadImageTGA(filename); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + if (extension.equals("tif") || extension.equals("tiff")) { + byte bytes[] = loadBytes(filename); + return (bytes == null) ? null : PImage.loadTIFF(bytes); + } + + // For jpeg, gif, and png, load them using createImage(), + // because the javax.imageio code was found to be much slower, see + // Bug 392. + try { + if (extension.equals("jpg") || extension.equals("jpeg") || + extension.equals("gif") || extension.equals("png") || + extension.equals("unknown")) { + byte bytes[] = loadBytes(filename); + if (bytes == null) { + return null; + } else { + Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); + PImage image = loadImageMT(awtImage); + if (image.width == -1) { + System.err.println("The file " + filename + + " contains bad image data, or may not be an image."); + } + // if it's a .gif image, test to see if it has transparency + if (extension.equals("gif") || extension.equals("png")) { + image.checkAlpha(); + } + return image; + } + } + } catch (Exception e) { + // show error, but move on to the stuff below, see if it'll work + e.printStackTrace(); + } + + if (loadImageFormats == null) { + loadImageFormats = ImageIO.getReaderFormatNames(); + } + if (loadImageFormats != null) { + for (int i = 0; i < loadImageFormats.length; i++) { + if (extension.equals(loadImageFormats[i])) { + return loadImageIO(filename); + } + } + } + + // failed, could not load image after all those attempts + System.err.println("Could not find a method to load " + filename); + return null; + } + + public PImage requestImage(String filename) { + return requestImage(filename, null); + } + + + /** + * This function load images on a separate thread so that your sketch does not freeze while images load during setup(). While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1. You'll know when the image has loaded properly because its width and height will be greater than 0. Asynchronous image loading (particularly when downloading from a server) can dramatically improve performance.

+ * The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to requestImage(). + * + * @webref image:loading_displaying + * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform + * @param extension the type of image to load, for example "png", "gif", "jpg" + * + * @see processing.core.PApplet#loadImage(String, String) + * @see processing.core.PImage + */ + public PImage requestImage(String filename, String extension) { + PImage vessel = createImage(0, 0, ARGB); + AsyncImageLoader ail = + new AsyncImageLoader(filename, extension, vessel); + ail.start(); + return vessel; + } + + + /** + * By trial and error, four image loading threads seem to work best when + * loading images from online. This is consistent with the number of open + * connections that web browsers will maintain. The variable is made public + * (however no accessor has been added since it's esoteric) if you really + * want to have control over the value used. For instance, when loading local + * files, it might be better to only have a single thread (or two) loading + * images so that you're disk isn't simply jumping around. + */ + public int requestImageMax = 4; + volatile int requestImageCount; + + class AsyncImageLoader extends Thread { + String filename; + String extension; + PImage vessel; + + public AsyncImageLoader(String filename, String extension, PImage vessel) { + this.filename = filename; + this.extension = extension; + this.vessel = vessel; + } + + public void run() { + while (requestImageCount == requestImageMax) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { } + } + requestImageCount++; + + PImage actual = loadImage(filename, extension); + + // An error message should have already printed + if (actual == null) { + vessel.width = -1; + vessel.height = -1; + + } else { + vessel.width = actual.width; + vessel.height = actual.height; + vessel.format = actual.format; + vessel.pixels = actual.pixels; + } + requestImageCount--; + } + } + + + /** + * Load an AWT image synchronously by setting up a MediaTracker for + * a single image, and blocking until it has loaded. + */ + protected PImage loadImageMT(Image awtImage) { + MediaTracker tracker = new MediaTracker(this); + tracker.addImage(awtImage, 0); + try { + tracker.waitForAll(); + } catch (InterruptedException e) { + //e.printStackTrace(); // non-fatal, right? + } + + PImage image = new PImage(awtImage); + image.parent = this; + return image; + } + + + /** + * Use Java 1.4 ImageIO methods to load an image. + */ + protected PImage loadImageIO(String filename) { + InputStream stream = createInput(filename); + if (stream == null) { + System.err.println("The image " + filename + " could not be found."); + return null; + } + + try { + BufferedImage bi = ImageIO.read(stream); + PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); + outgoing.parent = this; + + bi.getRGB(0, 0, outgoing.width, outgoing.height, + outgoing.pixels, 0, outgoing.width); + + // check the alpha for this image + // was gonna call getType() on the image to see if RGB or ARGB, + // but it's not actually useful, since gif images will come through + // as TYPE_BYTE_INDEXED, which means it'll still have to check for + // the transparency. also, would have to iterate through all the other + // types and guess whether alpha was in there, so.. just gonna stick + // with the old method. + outgoing.checkAlpha(); + + // return the image + return outgoing; + + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + + /** + * Targa image loader for RLE-compressed TGA files. + *

+ * Rewritten for 0115 to read/write RLE-encoded targa images. + * For 0125, non-RLE encoded images are now supported, along with + * images whose y-order is reversed (which is standard for TGA files). + */ + protected PImage loadImageTGA(String filename) throws IOException { + InputStream is = createInput(filename); + if (is == null) return null; + + byte header[] = new byte[18]; + int offset = 0; + do { + int count = is.read(header, offset, header.length - offset); + if (count == -1) return null; + offset += count; + } while (offset < 18); + + /* + header[2] image type code + 2 (0x02) - Uncompressed, RGB images. + 3 (0x03) - Uncompressed, black and white images. + 10 (0x0A) - Runlength encoded RGB images. + 11 (0x0B) - Compressed, black and white images. (grayscale?) + + header[16] is the bit depth (8, 24, 32) + + header[17] image descriptor (packed bits) + 0x20 is 32 = origin upper-left + 0x28 is 32 + 8 = origin upper-left + 32 bits + + 7 6 5 4 3 2 1 0 + 128 64 32 16 8 4 2 1 + */ + + int format = 0; + + if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not + (header[16] == 8) && // 8 bits + ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit + format = ALPHA; + + } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not + (header[16] == 24) && // 24 bits + ((header[17] == 0x20) || (header[17] == 0))) { // origin + format = RGB; + + } else if (((header[2] == 2) || (header[2] == 10)) && + (header[16] == 32) && + ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 + format = ARGB; + } + + if (format == 0) { + System.err.println("Unknown .tga file format for " + filename); + //" (" + header[2] + " " + + //(header[16] & 0xff) + " " + + //hex(header[17], 2) + ")"); + return null; + } + + int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); + int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); + PImage outgoing = createImage(w, h, format); + + // where "reversed" means upper-left corner (normal for most of + // the modernized world, but "reversed" for the tga spec) + boolean reversed = (header[17] & 0x20) != 0; + + if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded + if (reversed) { + int index = (h-1) * w; + switch (format) { + case ALPHA: + for (int y = h-1; y >= 0; y--) { + for (int x = 0; x < w; x++) { + outgoing.pixels[index + x] = is.read(); + } + index -= w; + } + break; + case RGB: + for (int y = h-1; y >= 0; y--) { + for (int x = 0; x < w; x++) { + outgoing.pixels[index + x] = + is.read() | (is.read() << 8) | (is.read() << 16) | + 0xff000000; + } + index -= w; + } + break; + case ARGB: + for (int y = h-1; y >= 0; y--) { + for (int x = 0; x < w; x++) { + outgoing.pixels[index + x] = + is.read() | (is.read() << 8) | (is.read() << 16) | + (is.read() << 24); + } + index -= w; + } + } + } else { // not reversed + int count = w * h; + switch (format) { + case ALPHA: + for (int i = 0; i < count; i++) { + outgoing.pixels[i] = is.read(); + } + break; + case RGB: + for (int i = 0; i < count; i++) { + outgoing.pixels[i] = + is.read() | (is.read() << 8) | (is.read() << 16) | + 0xff000000; + } + break; + case ARGB: + for (int i = 0; i < count; i++) { + outgoing.pixels[i] = + is.read() | (is.read() << 8) | (is.read() << 16) | + (is.read() << 24); + } + break; + } + } + + } else { // header[2] is 10 or 11 + int index = 0; + int px[] = outgoing.pixels; + + while (index < px.length) { + int num = is.read(); + boolean isRLE = (num & 0x80) != 0; + if (isRLE) { + num -= 127; // (num & 0x7F) + 1 + int pixel = 0; + switch (format) { + case ALPHA: + pixel = is.read(); + break; + case RGB: + pixel = 0xFF000000 | + is.read() | (is.read() << 8) | (is.read() << 16); + //(is.read() << 16) | (is.read() << 8) | is.read(); + break; + case ARGB: + pixel = is.read() | + (is.read() << 8) | (is.read() << 16) | (is.read() << 24); + break; + } + for (int i = 0; i < num; i++) { + px[index++] = pixel; + if (index == px.length) break; + } + } else { // write up to 127 bytes as uncompressed + num += 1; + switch (format) { + case ALPHA: + for (int i = 0; i < num; i++) { + px[index++] = is.read(); + } + break; + case RGB: + for (int i = 0; i < num; i++) { + px[index++] = 0xFF000000 | + is.read() | (is.read() << 8) | (is.read() << 16); + //(is.read() << 16) | (is.read() << 8) | is.read(); + } + break; + case ARGB: + for (int i = 0; i < num; i++) { + px[index++] = is.read() | //(is.read() << 24) | + (is.read() << 8) | (is.read() << 16) | (is.read() << 24); + //(is.read() << 16) | (is.read() << 8) | is.read(); + } + break; + } + } + } + + if (!reversed) { + int[] temp = new int[w]; + for (int y = 0; y < h/2; y++) { + int z = (h-1) - y; + System.arraycopy(px, y*w, temp, 0, w); + System.arraycopy(px, z*w, px, y*w, w); + System.arraycopy(temp, 0, px, z*w, w); + } + } + } + + return outgoing; + } + + + + ////////////////////////////////////////////////////////////// + + // SHAPE I/O + + + /** + * Loads vector shapes into a variable of type PShape. Currently, only SVG files may be loaded. + * To load correctly, the file must be located in the data directory of the current sketch. + * In most cases, loadShape() should be used inside setup() because loading shapes inside draw() will reduce the speed of a sketch. + *

+ * The filename parameter can also be a URL to a file found online. + * For security reasons, a Processing sketch found online can only download files from the same server from which it came. + * Getting around this restriction requires a signed applet. + *

+ * If a shape is not loaded successfully, the null value is returned and an error message will be printed to the console. + * The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from loadShape() is null. + * + * @webref shape:loading_displaying + * @see PShape + * @see PApplet#shape(PShape) + * @see PApplet#shapeMode(int) + */ + public PShape loadShape(String filename) { + if (filename.toLowerCase().endsWith(".svg")) { + return new PShapeSVG(this, filename); + + } else if (filename.toLowerCase().endsWith(".svgz")) { + try { + InputStream input = new GZIPInputStream(createInput(filename)); + XMLElement xml = new XMLElement(createReader(input)); + return new PShapeSVG(xml); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + + + + ////////////////////////////////////////////////////////////// + + // FONT I/O + + + public PFont loadFont(String filename) { + try { + InputStream input = createInput(filename); + return new PFont(input); + + } catch (Exception e) { + die("Could not load font " + filename + ". " + + "Make sure that the font has been copied " + + "to the data folder of your sketch.", e); + } + return null; + } + + + /** + * Used by PGraphics to remove the requirement for loading a font! + */ + protected PFont createDefaultFont(float size) { +// Font f = new Font("SansSerif", Font.PLAIN, 12); +// println("n: " + f.getName()); +// println("fn: " + f.getFontName()); +// println("ps: " + f.getPSName()); + return createFont("SansSerif", size, true, null); + } + + + public PFont createFont(String name, float size) { + return createFont(name, size, true, null); + } + + + public PFont createFont(String name, float size, boolean smooth) { + return createFont(name, size, smooth, null); + } + + + /** + * Create a .vlw font on the fly from either a font name that's + * installed on the system, or from a .ttf or .otf that's inside + * the data folder of this sketch. + *

+ * Many .otf fonts don't seem to be supported by Java, perhaps because + * they're CFF based? + *

+ * Font names are inconsistent across platforms and Java versions. + * On Mac OS X, Java 1.3 uses the font menu name of the font, + * whereas Java 1.4 uses the PostScript name of the font. Java 1.4 + * on OS X will also accept the font menu name as well. On Windows, + * it appears that only the menu names are used, no matter what + * Java version is in use. Naming system unknown/untested for 1.5. + *

+ * Use 'null' for the charset if you want to dynamically create + * character bitmaps only as they're needed. (Version 1.0.9 and + * earlier would interpret null as all unicode characters.) + */ + public PFont createFont(String name, float size, + boolean smooth, char charset[]) { + String lowerName = name.toLowerCase(); + Font baseFont = null; + + try { + InputStream stream = null; + if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { + stream = createInput(name); + if (stream == null) { + System.err.println("The font \"" + name + "\" " + + "is missing or inaccessible, make sure " + + "the URL is valid or that the file has been " + + "added to your sketch and is readable."); + return null; + } + baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); + + } else { + baseFont = PFont.findFont(name); + } + return new PFont(baseFont.deriveFont(size), smooth, charset, + stream != null); + + } catch (Exception e) { + System.err.println("Problem createFont(" + name + ")"); + e.printStackTrace(); + return null; + } + } + + + + ////////////////////////////////////////////////////////////// + + // FILE/FOLDER SELECTION + + + public File selectedFile; + protected Frame parentFrame; + + + protected void checkParentFrame() { + if (parentFrame == null) { + Component comp = getParent(); + while (comp != null) { + if (comp instanceof Frame) { + parentFrame = (Frame) comp; + break; + } + comp = comp.getParent(); + } + // Who you callin' a hack? + if (parentFrame == null) { + parentFrame = new Frame(); + } + } + } + + + /** + * Open a platform-specific file chooser dialog to select a file for input. + * @return full path to the selected file, or null if no selection. + */ + public String selectInput() { + return selectInput("Select a file..."); + } + + + /** + * Opens a platform-specific file chooser dialog to select a file for input. This function returns the full path to the selected file as a String, or null if no selection. + * + * @webref input:files + * @param prompt message you want the user to see in the file chooser + * @return full path to the selected file, or null if canceled. + * + * @see processing.core.PApplet#selectOutput(String) + * @see processing.core.PApplet#selectFolder(String) + */ + public String selectInput(String prompt) { + return selectFileImpl(prompt, FileDialog.LOAD); + } + + + /** + * Open a platform-specific file save dialog to select a file for output. + * @return full path to the file entered, or null if canceled. + */ + public String selectOutput() { + return selectOutput("Save as..."); + } + + + /** + * Open a platform-specific file save dialog to create of select a file for output. + * This function returns the full path to the selected file as a String, or null if no selection. + * If you select an existing file, that file will be replaced. + * Alternatively, you can navigate to a folder and create a new file to write to. + * + * @param prompt message you want the user to see in the file chooser + * @return full path to the file entered, or null if canceled. + * + * @webref input:files + * @see processing.core.PApplet#selectInput(String) + * @see processing.core.PApplet#selectFolder(String) + */ + public String selectOutput(String prompt) { + return selectFileImpl(prompt, FileDialog.SAVE); + } + + + protected String selectFileImpl(final String prompt, final int mode) { + checkParentFrame(); + + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + FileDialog fileDialog = + new FileDialog(parentFrame, prompt, mode); + fileDialog.setVisible(true); + String directory = fileDialog.getDirectory(); + String filename = fileDialog.getFile(); + selectedFile = + (filename == null) ? null : new File(directory, filename); + } + }); + return (selectedFile == null) ? null : selectedFile.getAbsolutePath(); + + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + + public String selectFolder() { + return selectFolder("Select a folder..."); + } + + + /** + * Opens a platform-specific file chooser dialog to select a folder for input. + * This function returns the full path to the selected folder as a String, or null if no selection. + * + * @webref input:files + * @param prompt message you want the user to see in the file chooser + * @return full path to the selected folder, or null if no selection. + * + * @see processing.core.PApplet#selectOutput(String) + * @see processing.core.PApplet#selectInput(String) + */ + public String selectFolder(final String prompt) { + checkParentFrame(); + + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if (platform == MACOSX) { + FileDialog fileDialog = + new FileDialog(parentFrame, prompt, FileDialog.LOAD); + System.setProperty("apple.awt.fileDialogForDirectories", "true"); + fileDialog.setVisible(true); + System.setProperty("apple.awt.fileDialogForDirectories", "false"); + String filename = fileDialog.getFile(); + selectedFile = (filename == null) ? null : + new File(fileDialog.getDirectory(), fileDialog.getFile()); + } else { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle(prompt); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + + int returned = fileChooser.showOpenDialog(parentFrame); + System.out.println(returned); + if (returned == JFileChooser.CANCEL_OPTION) { + selectedFile = null; + } else { + selectedFile = fileChooser.getSelectedFile(); + } + } + } + }); + return (selectedFile == null) ? null : selectedFile.getAbsolutePath(); + + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + + + ////////////////////////////////////////////////////////////// + + // READERS AND WRITERS + + + /** + * I want to read lines from a file. I have RSI from typing these + * eight lines of code so many times. + */ + public BufferedReader createReader(String filename) { + try { + InputStream is = createInput(filename); + if (is == null) { + System.err.println(filename + " does not exist or could not be read"); + return null; + } + return createReader(is); + + } catch (Exception e) { + if (filename == null) { + System.err.println("Filename passed to reader() was null"); + } else { + System.err.println("Couldn't create a reader for " + filename); + } + } + return null; + } + + + /** + * I want to read lines from a file. And I'm still annoyed. + */ + static public BufferedReader createReader(File file) { + try { + InputStream is = new FileInputStream(file); + if (file.getName().toLowerCase().endsWith(".gz")) { + is = new GZIPInputStream(is); + } + return createReader(is); + + } catch (Exception e) { + if (file == null) { + throw new RuntimeException("File passed to createReader() was null"); + } else { + e.printStackTrace(); + throw new RuntimeException("Couldn't create a reader for " + + file.getAbsolutePath()); + } + } + //return null; + } + + + /** + * I want to read lines from a stream. If I have to type the + * following lines any more I'm gonna send Sun my medical bills. + */ + static public BufferedReader createReader(InputStream input) { + InputStreamReader isr = null; + try { + isr = new InputStreamReader(input, "UTF-8"); + } catch (UnsupportedEncodingException e) { } // not gonna happen + return new BufferedReader(isr); + } + + + /** + * I want to print lines to a file. Why can't I? + */ + public PrintWriter createWriter(String filename) { + return createWriter(saveFile(filename)); + } + + + /** + * I want to print lines to a file. I have RSI from typing these + * eight lines of code so many times. + */ + static public PrintWriter createWriter(File file) { + try { + createPath(file); // make sure in-between folders exist + OutputStream output = new FileOutputStream(file); + if (file.getName().toLowerCase().endsWith(".gz")) { + output = new GZIPOutputStream(output); + } + return createWriter(output); + + } catch (Exception e) { + if (file == null) { + throw new RuntimeException("File passed to createWriter() was null"); + } else { + e.printStackTrace(); + throw new RuntimeException("Couldn't create a writer for " + + file.getAbsolutePath()); + } + } + //return null; + } + + + /** + * I want to print lines to a file. Why am I always explaining myself? + * It's the JavaSoft API engineers who need to explain themselves. + */ + static public PrintWriter createWriter(OutputStream output) { + try { + BufferedOutputStream bos = new BufferedOutputStream(output, 8192); + OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); + return new PrintWriter(osw); + } catch (UnsupportedEncodingException e) { } // not gonna happen + return null; + } + + + ////////////////////////////////////////////////////////////// + + // FILE INPUT + + + /** + * @deprecated As of release 0136, use createInput() instead. + */ + public InputStream openStream(String filename) { + return createInput(filename); + } + + + /** + * This is a method for advanced programmers to open a Java InputStream. The method is useful if you want to use the facilities provided by PApplet to easily open files from the data folder or from a URL, but want an InputStream object so that you can use other Java methods to take more control of how the stream is read. + *

If the requested item doesn't exist, null is returned. + *

In earlier releases, this method was called openStream(). + *

If not online, this will also check to see if the user is asking for a file whose name isn't properly capitalized. If capitalization is different an error will be printed to the console. This helps prevent issues that appear when a sketch is exported to the web, where case sensitivity matters, as opposed to running from inside the Processing Development Environment on Windows or Mac OS, where case sensitivity is preserved but ignored. + *

The filename passed in can be:
+ * - A URL, for instance openStream("http://processing.org/");
+ * - A file in the sketch's data folder
+ * - The full path to a file to be opened locally (when running as an application) + *

+ * If the file ends with .gz, the stream will automatically be gzip decompressed. If you don't want the automatic decompression, use the related function createInputRaw(). + * + * =advanced + * Simplified method to open a Java InputStream. + *

+ * This method is useful if you want to use the facilities provided + * by PApplet to easily open things from the data folder or from a URL, + * but want an InputStream object so that you can use other Java + * methods to take more control of how the stream is read. + *

+ * If the requested item doesn't exist, null is returned. + * (Prior to 0096, die() would be called, killing the applet) + *

+ * For 0096+, the "data" folder is exported intact with subfolders, + * and openStream() properly handles subdirectories from the data folder + *

+ * If not online, this will also check to see if the user is asking + * for a file whose name isn't properly capitalized. This helps prevent + * issues when a sketch is exported to the web, where case sensitivity + * matters, as opposed to Windows and the Mac OS default where + * case sensitivity is preserved but ignored. + *

+ * It is strongly recommended that libraries use this method to open + * data files, so that the loading sequence is handled in the same way + * as functions like loadBytes(), loadImage(), etc. + *

+ * The filename passed in can be: + *

    + *
  • A URL, for instance openStream("http://processing.org/"); + *
  • A file in the sketch's data folder + *
  • Another file to be opened locally (when running as an application) + *
+ * + * @webref input:files + * @see processing.core.PApplet#createOutput(String) + * @see processing.core.PApplet#selectOutput(String) + * @see processing.core.PApplet#selectInput(String) + * + * @param filename the name of the file to use as input + * + */ + public InputStream createInput(String filename) { + InputStream input = createInputRaw(filename); + if ((input != null) && filename.toLowerCase().endsWith(".gz")) { + try { + return new GZIPInputStream(input); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + return input; + } + + + /** + * Call openStream() without automatic gzip decompression. + */ + public InputStream createInputRaw(String filename) { + InputStream stream = null; + + if (filename == null) return null; + + if (filename.length() == 0) { + // an error will be called by the parent function + //System.err.println("The filename passed to openStream() was empty."); + return null; + } + + // safe to check for this as a url first. this will prevent online + // access logs from being spammed with GET /sketchfolder/http://blahblah + if (filename.indexOf(":") != -1) { // at least smells like URL + try { + URL url = new URL(filename); + stream = url.openStream(); + return stream; + + } catch (MalformedURLException mfue) { + // not a url, that's fine + + } catch (FileNotFoundException fnfe) { + // Java 1.5 likes to throw this when URL not available. (fix for 0119) + // http://dev.processing.org/bugs/show_bug.cgi?id=403 + + } catch (IOException e) { + // changed for 0117, shouldn't be throwing exception + e.printStackTrace(); + //System.err.println("Error downloading from URL " + filename); + return null; + //throw new RuntimeException("Error downloading from URL " + filename); + } + } + + // Moved this earlier than the getResourceAsStream() checks, because + // calling getResourceAsStream() on a directory lists its contents. + // http://dev.processing.org/bugs/show_bug.cgi?id=716 + try { + // First see if it's in a data folder. This may fail by throwing + // a SecurityException. If so, this whole block will be skipped. + File file = new File(dataPath(filename)); + if (!file.exists()) { + // next see if it's just in the sketch folder + file = new File(sketchPath, filename); + } + if (file.isDirectory()) { + return null; + } + if (file.exists()) { + try { + // handle case sensitivity check + String filePath = file.getCanonicalPath(); + String filenameActual = new File(filePath).getName(); + // make sure there isn't a subfolder prepended to the name + String filenameShort = new File(filename).getName(); + // if the actual filename is the same, but capitalized + // differently, warn the user. + //if (filenameActual.equalsIgnoreCase(filenameShort) && + //!filenameActual.equals(filenameShort)) { + if (!filenameActual.equals(filenameShort)) { + throw new RuntimeException("This file is named " + + filenameActual + " not " + + filename + ". Rename the file " + + "or change your code."); + } + } catch (IOException e) { } + } + + // if this file is ok, may as well just load it + stream = new FileInputStream(file); + if (stream != null) return stream; + + // have to break these out because a general Exception might + // catch the RuntimeException being thrown above + } catch (IOException ioe) { + } catch (SecurityException se) { } + + // Using getClassLoader() prevents java from converting dots + // to slashes or requiring a slash at the beginning. + // (a slash as a prefix means that it'll load from the root of + // the jar, rather than trying to dig into the package location) + ClassLoader cl = getClass().getClassLoader(); + + // by default, data files are exported to the root path of the jar. + // (not the data folder) so check there first. + stream = cl.getResourceAsStream("data/" + filename); + if (stream != null) { + String cn = stream.getClass().getName(); + // this is an irritation of sun's java plug-in, which will return + // a non-null stream for an object that doesn't exist. like all good + // things, this is probably introduced in java 1.5. awesome! + // http://dev.processing.org/bugs/show_bug.cgi?id=359 + if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { + return stream; + } + } + + // When used with an online script, also need to check without the + // data folder, in case it's not in a subfolder called 'data'. + // http://dev.processing.org/bugs/show_bug.cgi?id=389 + stream = cl.getResourceAsStream(filename); + if (stream != null) { + String cn = stream.getClass().getName(); + if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { + return stream; + } + } + + // Finally, something special for the Internet Explorer users. Turns out + // that we can't get files that are part of the same folder using the + // methods above when using IE, so we have to resort to the old skool + // getDocumentBase() from teh applet dayz. 1996, my brotha. + try { + URL base = getDocumentBase(); + if (base != null) { + URL url = new URL(base, filename); + URLConnection conn = url.openConnection(); + return conn.getInputStream(); +// if (conn instanceof HttpURLConnection) { +// HttpURLConnection httpConnection = (HttpURLConnection) conn; +// // test for 401 result (HTTP only) +// int responseCode = httpConnection.getResponseCode(); +// } + } + } catch (Exception e) { } // IO or NPE or... + + // Now try it with a 'data' subfolder. getting kinda desperate for data... + try { + URL base = getDocumentBase(); + if (base != null) { + URL url = new URL(base, "data/" + filename); + URLConnection conn = url.openConnection(); + return conn.getInputStream(); + } + } catch (Exception e) { } + + try { + // attempt to load from a local file, used when running as + // an application, or as a signed applet + try { // first try to catch any security exceptions + try { + stream = new FileInputStream(dataPath(filename)); + if (stream != null) return stream; + } catch (IOException e2) { } + + try { + stream = new FileInputStream(sketchPath(filename)); + if (stream != null) return stream; + } catch (Exception e) { } // ignored + + try { + stream = new FileInputStream(filename); + if (stream != null) return stream; + } catch (IOException e1) { } + + } catch (SecurityException se) { } // online, whups + + } catch (Exception e) { + //die(e.getMessage(), e); + e.printStackTrace(); + } + + return null; + } + + + static public InputStream createInput(File file) { + if (file == null) { + throw new IllegalArgumentException("File passed to createInput() was null"); + } + try { + InputStream input = new FileInputStream(file); + if (file.getName().toLowerCase().endsWith(".gz")) { + return new GZIPInputStream(input); + } + return input; + + } catch (IOException e) { + System.err.println("Could not createInput() for " + file); + e.printStackTrace(); + return null; + } + } + + + /** + * Reads the contents of a file or url and places it in a byte array. If a file is specified, it must be located in the sketch's "data" directory/folder. + *

The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch found online can only download files from the same server from which it came. Getting around this restriction requires a signed applet. + * + * @webref input:files + * @param filename name of a file in the data folder or a URL. + * + * @see processing.core.PApplet#loadStrings(String) + * @see processing.core.PApplet#saveStrings(String, String[]) + * @see processing.core.PApplet#saveBytes(String, byte[]) + * + */ + public byte[] loadBytes(String filename) { + InputStream is = createInput(filename); + if (is != null) return loadBytes(is); + + System.err.println("The file \"" + filename + "\" " + + "is missing or inaccessible, make sure " + + "the URL is valid or that the file has been " + + "added to your sketch and is readable."); + return null; + } + + + static public byte[] loadBytes(InputStream input) { + try { + BufferedInputStream bis = new BufferedInputStream(input); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + int c = bis.read(); + while (c != -1) { + out.write(c); + c = bis.read(); + } + return out.toByteArray(); + + } catch (IOException e) { + e.printStackTrace(); + //throw new RuntimeException("Couldn't load bytes from stream"); + } + return null; + } + + + static public byte[] loadBytes(File file) { + InputStream is = createInput(file); + return loadBytes(is); + } + + + static public String[] loadStrings(File file) { + InputStream is = createInput(file); + if (is != null) return loadStrings(is); + return null; + } + + + /** + * Reads the contents of a file or url and creates a String array of its individual lines. If a file is specified, it must be located in the sketch's "data" directory/folder. + *

The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch found online can only download files from the same server from which it came. Getting around this restriction requires a signed applet. + *

If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned is null. + *

Starting with Processing release 0134, all files loaded and saved by the Processing API use UTF-8 encoding. In previous releases, the default encoding for your platform was used, which causes problems when files are moved to other platforms. + * + * =advanced + * Load data from a file and shove it into a String array. + *

+ * Exceptions are handled internally, when an error, occurs, an + * exception is printed to the console and 'null' is returned, + * but the program continues running. This is a tradeoff between + * 1) showing the user that there was a problem but 2) not requiring + * that all i/o code is contained in try/catch blocks, for the sake + * of new users (or people who are just trying to get things done + * in a "scripting" fashion. If you want to handle exceptions, + * use Java methods for I/O. + * + * @webref input:files + * @param filename name of the file or url to load + * + * @see processing.core.PApplet#loadBytes(String) + * @see processing.core.PApplet#saveStrings(String, String[]) + * @see processing.core.PApplet#saveBytes(String, byte[]) + */ + public String[] loadStrings(String filename) { + InputStream is = createInput(filename); + if (is != null) return loadStrings(is); + + System.err.println("The file \"" + filename + "\" " + + "is missing or inaccessible, make sure " + + "the URL is valid or that the file has been " + + "added to your sketch and is readable."); + return null; + } + + + static public String[] loadStrings(InputStream input) { + try { + BufferedReader reader = + new BufferedReader(new InputStreamReader(input, "UTF-8")); + + String lines[] = new String[100]; + int lineCount = 0; + String line = null; + while ((line = reader.readLine()) != null) { + if (lineCount == lines.length) { + String temp[] = new String[lineCount << 1]; + System.arraycopy(lines, 0, temp, 0, lineCount); + lines = temp; + } + lines[lineCount++] = line; + } + reader.close(); + + if (lineCount == lines.length) { + return lines; + } + + // resize array to appropriate amount for these lines + String output[] = new String[lineCount]; + System.arraycopy(lines, 0, output, 0, lineCount); + return output; + + } catch (IOException e) { + e.printStackTrace(); + //throw new RuntimeException("Error inside loadStrings()"); + } + return null; + } + + + + ////////////////////////////////////////////////////////////// + + // FILE OUTPUT + + + /** + * Similar to createInput() (formerly openStream), this creates a Java + * OutputStream for a given filename or path. The file will be created in + * the sketch folder, or in the same folder as an exported application. + *

+ * If the path does not exist, intermediate folders will be created. If an + * exception occurs, it will be printed to the console, and null will be + * returned. + *

+ * Future releases may also add support for handling HTTP POST via this + * method (for better symmetry with createInput), however that's maybe a + * little too clever (and then we'd have to add the same features to the + * other file functions like createWriter). Who you callin' bloated? + */ + public OutputStream createOutput(String filename) { + return createOutput(saveFile(filename)); + } + + + static public OutputStream createOutput(File file) { + try { + createPath(file); // make sure the path exists + FileOutputStream fos = new FileOutputStream(file); + if (file.getName().toLowerCase().endsWith(".gz")) { + return new GZIPOutputStream(fos); + } + return fos; + + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + + /** + * Save the contents of a stream to a file in the sketch folder. + * This is basically saveBytes(blah, loadBytes()), but done + * more efficiently (and with less confusing syntax). + */ + public boolean saveStream(String targetFilename, String sourceLocation) { + return saveStream(saveFile(targetFilename), sourceLocation); + } + + + /** + * Identical to the other saveStream(), but writes to a File + * object, for greater control over the file location. + *

+ * Note that unlike other api methods, this will not automatically + * compress or uncompress gzip files. + */ + public boolean saveStream(File targetFile, String sourceLocation) { + return saveStream(targetFile, createInputRaw(sourceLocation)); + } + + + public boolean saveStream(String targetFilename, InputStream sourceStream) { + return saveStream(saveFile(targetFilename), sourceStream); + } + + + static public boolean saveStream(File targetFile, InputStream sourceStream) { + File tempFile = null; + try { + File parentDir = targetFile.getParentFile(); + // make sure that this path actually exists before writing + createPath(targetFile); + tempFile = File.createTempFile(targetFile.getName(), null, parentDir); + + BufferedInputStream bis = new BufferedInputStream(sourceStream, 16384); + FileOutputStream fos = new FileOutputStream(tempFile); + BufferedOutputStream bos = new BufferedOutputStream(fos); + + byte[] buffer = new byte[8192]; + int bytesRead; + while ((bytesRead = bis.read(buffer)) != -1) { + bos.write(buffer, 0, bytesRead); + } + + bos.flush(); + bos.close(); + bos = null; + + if (!tempFile.renameTo(targetFile)) { + System.err.println("Could not rename temporary file " + + tempFile.getAbsolutePath()); + return false; + } + return true; + + } catch (IOException e) { + if (tempFile != null) { + tempFile.delete(); + } + e.printStackTrace(); + return false; + } + } + + + /** + * Saves bytes to a file to inside the sketch folder. + * The filename can be a relative path, i.e. "poo/bytefun.txt" + * would save to a file named "bytefun.txt" to a subfolder + * called 'poo' inside the sketch folder. If the in-between + * subfolders don't exist, they'll be created. + */ + public void saveBytes(String filename, byte buffer[]) { + saveBytes(saveFile(filename), buffer); + } + + + /** + * Saves bytes to a specific File location specified by the user. + */ + static public void saveBytes(File file, byte buffer[]) { + File tempFile = null; + try { + File parentDir = file.getParentFile(); + tempFile = File.createTempFile(file.getName(), null, parentDir); + + /* + String filename = file.getAbsolutePath(); + createPath(filename); + OutputStream output = new FileOutputStream(file); + if (file.getName().toLowerCase().endsWith(".gz")) { + output = new GZIPOutputStream(output); + } + */ + OutputStream output = createOutput(tempFile); + saveBytes(output, buffer); + output.close(); + output = null; + + if (!tempFile.renameTo(file)) { + System.err.println("Could not rename temporary file " + + tempFile.getAbsolutePath()); + } + + } catch (IOException e) { + System.err.println("error saving bytes to " + file); + if (tempFile != null) { + tempFile.delete(); + } + e.printStackTrace(); + } + } + + + /** + * Spews a buffer of bytes to an OutputStream. + */ + static public void saveBytes(OutputStream output, byte buffer[]) { + try { + output.write(buffer); + output.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + // + + public void saveStrings(String filename, String strings[]) { + saveStrings(saveFile(filename), strings); + } + + + static public void saveStrings(File file, String strings[]) { + saveStrings(createOutput(file), strings); + /* + try { + String location = file.getAbsolutePath(); + createPath(location); + OutputStream output = new FileOutputStream(location); + if (file.getName().toLowerCase().endsWith(".gz")) { + output = new GZIPOutputStream(output); + } + saveStrings(output, strings); + output.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + */ + } + + + static public void saveStrings(OutputStream output, String strings[]) { + PrintWriter writer = createWriter(output); + for (int i = 0; i < strings.length; i++) { + writer.println(strings[i]); + } + writer.flush(); + writer.close(); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Prepend the sketch folder path to the filename (or path) that is + * passed in. External libraries should use this function to save to + * the sketch folder. + *

+ * Note that when running as an applet inside a web browser, + * the sketchPath will be set to null, because security restrictions + * prevent applets from accessing that information. + *

+ * This will also cause an error if the sketch is not inited properly, + * meaning that init() was never called on the PApplet when hosted + * my some other main() or by other code. For proper use of init(), + * see the examples in the main description text for PApplet. + */ + public String sketchPath(String where) { + if (sketchPath == null) { + return where; +// throw new RuntimeException("The applet was not inited properly, " + +// "or security restrictions prevented " + +// "it from determining its path."); + } + // isAbsolute() could throw an access exception, but so will writing + // to the local disk using the sketch path, so this is safe here. + // for 0120, added a try/catch anyways. + try { + if (new File(where).isAbsolute()) return where; + } catch (Exception e) { } + + return sketchPath + File.separator + where; + } + + + public File sketchFile(String where) { + return new File(sketchPath(where)); + } + + + /** + * Returns a path inside the applet folder to save to. Like sketchPath(), + * but creates any in-between folders so that things save properly. + *

+ * All saveXxxx() functions use the path to the sketch folder, rather than + * its data folder. Once exported, the data folder will be found inside the + * jar file of the exported application or applet. In this case, it's not + * possible to save data into the jar file, because it will often be running + * from a server, or marked in-use if running from a local file system. + * With this in mind, saving to the data path doesn't make sense anyway. + * If you know you're running locally, and want to save to the data folder, + * use saveXxxx("data/blah.dat"). + */ + public String savePath(String where) { + if (where == null) return null; + String filename = sketchPath(where); + createPath(filename); + return filename; + } + + + /** + * Identical to savePath(), but returns a File object. + */ + public File saveFile(String where) { + return new File(savePath(where)); + } + + + /** + * Return a full path to an item in the data folder. + *

+ * In this method, the data path is defined not as the applet's actual + * data path, but a folder titled "data" in the sketch's working + * directory. When running inside the PDE, this will be the sketch's + * "data" folder. However, when exported (as application or applet), + * sketch's data folder is exported as part of the applications jar file, + * and it's not possible to read/write from the jar file in a generic way. + * If you need to read data from the jar file, you should use other methods + * such as createInput(), createReader(), or loadStrings(). + */ + public String dataPath(String where) { + // isAbsolute() could throw an access exception, but so will writing + // to the local disk using the sketch path, so this is safe here. + if (new File(where).isAbsolute()) return where; + + return sketchPath + File.separator + "data" + File.separator + where; + } + + + /** + * Return a full path to an item in the data folder as a File object. + * See the dataPath() method for more information. + */ + public File dataFile(String where) { + return new File(dataPath(where)); + } + + + /** + * Takes a path and creates any in-between folders if they don't + * already exist. Useful when trying to save to a subfolder that + * may not actually exist. + */ + static public void createPath(String path) { + createPath(new File(path)); + } + + + static public void createPath(File file) { + try { + String parent = file.getParent(); + if (parent != null) { + File unit = new File(parent); + if (!unit.exists()) unit.mkdirs(); + } + } catch (SecurityException se) { + System.err.println("You don't have permissions to create " + + file.getAbsolutePath()); + } + } + + + + ////////////////////////////////////////////////////////////// + + // SORT + + + static public byte[] sort(byte what[]) { + return sort(what, what.length); + } + + + static public byte[] sort(byte[] what, int count) { + byte[] outgoing = new byte[what.length]; + System.arraycopy(what, 0, outgoing, 0, what.length); + Arrays.sort(outgoing, 0, count); + return outgoing; + } + + + static public char[] sort(char what[]) { + return sort(what, what.length); + } + + + static public char[] sort(char[] what, int count) { + char[] outgoing = new char[what.length]; + System.arraycopy(what, 0, outgoing, 0, what.length); + Arrays.sort(outgoing, 0, count); + return outgoing; + } + + + static public int[] sort(int what[]) { + return sort(what, what.length); + } + + + static public int[] sort(int[] what, int count) { + int[] outgoing = new int[what.length]; + System.arraycopy(what, 0, outgoing, 0, what.length); + Arrays.sort(outgoing, 0, count); + return outgoing; + } + + + static public float[] sort(float what[]) { + return sort(what, what.length); + } + + + static public float[] sort(float[] what, int count) { + float[] outgoing = new float[what.length]; + System.arraycopy(what, 0, outgoing, 0, what.length); + Arrays.sort(outgoing, 0, count); + return outgoing; + } + + + static public String[] sort(String what[]) { + return sort(what, what.length); + } + + + static public String[] sort(String[] what, int count) { + String[] outgoing = new String[what.length]; + System.arraycopy(what, 0, outgoing, 0, what.length); + Arrays.sort(outgoing, 0, count); + return outgoing; + } + + + + ////////////////////////////////////////////////////////////// + + // ARRAY UTILITIES + + + /** + * Calls System.arraycopy(), included here so that we can + * avoid people needing to learn about the System object + * before they can just copy an array. + */ + static public void arrayCopy(Object src, int srcPosition, + Object dst, int dstPosition, + int length) { + System.arraycopy(src, srcPosition, dst, dstPosition, length); + } + + + /** + * Convenience method for arraycopy(). + * Identical to arraycopy(src, 0, dst, 0, length); + */ + static public void arrayCopy(Object src, Object dst, int length) { + System.arraycopy(src, 0, dst, 0, length); + } + + + /** + * Shortcut to copy the entire contents of + * the source into the destination array. + * Identical to arraycopy(src, 0, dst, 0, src.length); + */ + static public void arrayCopy(Object src, Object dst) { + System.arraycopy(src, 0, dst, 0, Array.getLength(src)); + } + + // + + /** + * @deprecated Use arrayCopy() instead. + */ + static public void arraycopy(Object src, int srcPosition, + Object dst, int dstPosition, + int length) { + System.arraycopy(src, srcPosition, dst, dstPosition, length); + } + + /** + * @deprecated Use arrayCopy() instead. + */ + static public void arraycopy(Object src, Object dst, int length) { + System.arraycopy(src, 0, dst, 0, length); + } + + /** + * @deprecated Use arrayCopy() instead. + */ + static public void arraycopy(Object src, Object dst) { + System.arraycopy(src, 0, dst, 0, Array.getLength(src)); + } + + // + + static public boolean[] expand(boolean list[]) { + return expand(list, list.length << 1); + } + + static public boolean[] expand(boolean list[], int newSize) { + boolean temp[] = new boolean[newSize]; + System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); + return temp; + } + + + static public byte[] expand(byte list[]) { + return expand(list, list.length << 1); + } + + static public byte[] expand(byte list[], int newSize) { + byte temp[] = new byte[newSize]; + System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); + return temp; + } + + + static public char[] expand(char list[]) { + return expand(list, list.length << 1); + } + + static public char[] expand(char list[], int newSize) { + char temp[] = new char[newSize]; + System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); + return temp; + } + + + static public int[] expand(int list[]) { + return expand(list, list.length << 1); + } + + static public int[] expand(int list[], int newSize) { + int temp[] = new int[newSize]; + System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); + return temp; + } + + + static public float[] expand(float list[]) { + return expand(list, list.length << 1); + } + + static public float[] expand(float list[], int newSize) { + float temp[] = new float[newSize]; + System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); + return temp; + } + + + static public String[] expand(String list[]) { + return expand(list, list.length << 1); + } + + static public String[] expand(String list[], int newSize) { + String temp[] = new String[newSize]; + // in case the new size is smaller than list.length + System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); + return temp; + } + + + static public Object expand(Object array) { + return expand(array, Array.getLength(array) << 1); + } + + static public Object expand(Object list, int newSize) { + Class type = list.getClass().getComponentType(); + Object temp = Array.newInstance(type, newSize); + System.arraycopy(list, 0, temp, 0, + Math.min(Array.getLength(list), newSize)); + return temp; + } + + // + + // contract() has been removed in revision 0124, use subset() instead. + // (expand() is also functionally equivalent) + + // + + static public byte[] append(byte b[], byte value) { + b = expand(b, b.length + 1); + b[b.length-1] = value; + return b; + } + + static public char[] append(char b[], char value) { + b = expand(b, b.length + 1); + b[b.length-1] = value; + return b; + } + + static public int[] append(int b[], int value) { + b = expand(b, b.length + 1); + b[b.length-1] = value; + return b; + } + + static public float[] append(float b[], float value) { + b = expand(b, b.length + 1); + b[b.length-1] = value; + return b; + } + + static public String[] append(String b[], String value) { + b = expand(b, b.length + 1); + b[b.length-1] = value; + return b; + } + + static public Object append(Object b, Object value) { + int length = Array.getLength(b); + b = expand(b, length + 1); + Array.set(b, length, value); + return b; + } + + // + + static public boolean[] shorten(boolean list[]) { + return subset(list, 0, list.length-1); + } + + static public byte[] shorten(byte list[]) { + return subset(list, 0, list.length-1); + } + + static public char[] shorten(char list[]) { + return subset(list, 0, list.length-1); + } + + static public int[] shorten(int list[]) { + return subset(list, 0, list.length-1); + } + + static public float[] shorten(float list[]) { + return subset(list, 0, list.length-1); + } + + static public String[] shorten(String list[]) { + return subset(list, 0, list.length-1); + } + + static public Object shorten(Object list) { + int length = Array.getLength(list); + return subset(list, 0, length - 1); + } + + // + + static final public boolean[] splice(boolean list[], + boolean v, int index) { + boolean outgoing[] = new boolean[list.length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + outgoing[index] = v; + System.arraycopy(list, index, outgoing, index + 1, + list.length - index); + return outgoing; + } + + static final public boolean[] splice(boolean list[], + boolean v[], int index) { + boolean outgoing[] = new boolean[list.length + v.length]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, v.length); + System.arraycopy(list, index, outgoing, index + v.length, + list.length - index); + return outgoing; + } + + + static final public byte[] splice(byte list[], + byte v, int index) { + byte outgoing[] = new byte[list.length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + outgoing[index] = v; + System.arraycopy(list, index, outgoing, index + 1, + list.length - index); + return outgoing; + } + + static final public byte[] splice(byte list[], + byte v[], int index) { + byte outgoing[] = new byte[list.length + v.length]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, v.length); + System.arraycopy(list, index, outgoing, index + v.length, + list.length - index); + return outgoing; + } + + + static final public char[] splice(char list[], + char v, int index) { + char outgoing[] = new char[list.length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + outgoing[index] = v; + System.arraycopy(list, index, outgoing, index + 1, + list.length - index); + return outgoing; + } + + static final public char[] splice(char list[], + char v[], int index) { + char outgoing[] = new char[list.length + v.length]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, v.length); + System.arraycopy(list, index, outgoing, index + v.length, + list.length - index); + return outgoing; + } + + + static final public int[] splice(int list[], + int v, int index) { + int outgoing[] = new int[list.length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + outgoing[index] = v; + System.arraycopy(list, index, outgoing, index + 1, + list.length - index); + return outgoing; + } + + static final public int[] splice(int list[], + int v[], int index) { + int outgoing[] = new int[list.length + v.length]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, v.length); + System.arraycopy(list, index, outgoing, index + v.length, + list.length - index); + return outgoing; + } + + + static final public float[] splice(float list[], + float v, int index) { + float outgoing[] = new float[list.length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + outgoing[index] = v; + System.arraycopy(list, index, outgoing, index + 1, + list.length - index); + return outgoing; + } + + static final public float[] splice(float list[], + float v[], int index) { + float outgoing[] = new float[list.length + v.length]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, v.length); + System.arraycopy(list, index, outgoing, index + v.length, + list.length - index); + return outgoing; + } + + + static final public String[] splice(String list[], + String v, int index) { + String outgoing[] = new String[list.length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + outgoing[index] = v; + System.arraycopy(list, index, outgoing, index + 1, + list.length - index); + return outgoing; + } + + static final public String[] splice(String list[], + String v[], int index) { + String outgoing[] = new String[list.length + v.length]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, v.length); + System.arraycopy(list, index, outgoing, index + v.length, + list.length - index); + return outgoing; + } + + + static final public Object splice(Object list, Object v, int index) { + Object[] outgoing = null; + int length = Array.getLength(list); + + // check whether item being spliced in is an array + if (v.getClass().getName().charAt(0) == '[') { + int vlength = Array.getLength(v); + outgoing = new Object[length + vlength]; + System.arraycopy(list, 0, outgoing, 0, index); + System.arraycopy(v, 0, outgoing, index, vlength); + System.arraycopy(list, index, outgoing, index + vlength, length - index); + + } else { + outgoing = new Object[length + 1]; + System.arraycopy(list, 0, outgoing, 0, index); + Array.set(outgoing, index, v); + System.arraycopy(list, index, outgoing, index + 1, length - index); + } + return outgoing; + } + + // + + static public boolean[] subset(boolean list[], int start) { + return subset(list, start, list.length - start); + } + + static public boolean[] subset(boolean list[], int start, int count) { + boolean output[] = new boolean[count]; + System.arraycopy(list, start, output, 0, count); + return output; + } + + + static public byte[] subset(byte list[], int start) { + return subset(list, start, list.length - start); + } + + static public byte[] subset(byte list[], int start, int count) { + byte output[] = new byte[count]; + System.arraycopy(list, start, output, 0, count); + return output; + } + + + static public char[] subset(char list[], int start) { + return subset(list, start, list.length - start); + } + + static public char[] subset(char list[], int start, int count) { + char output[] = new char[count]; + System.arraycopy(list, start, output, 0, count); + return output; + } + + + static public int[] subset(int list[], int start) { + return subset(list, start, list.length - start); + } + + static public int[] subset(int list[], int start, int count) { + int output[] = new int[count]; + System.arraycopy(list, start, output, 0, count); + return output; + } + + + static public float[] subset(float list[], int start) { + return subset(list, start, list.length - start); + } + + static public float[] subset(float list[], int start, int count) { + float output[] = new float[count]; + System.arraycopy(list, start, output, 0, count); + return output; + } + + + static public String[] subset(String list[], int start) { + return subset(list, start, list.length - start); + } + + static public String[] subset(String list[], int start, int count) { + String output[] = new String[count]; + System.arraycopy(list, start, output, 0, count); + return output; + } + + + static public Object subset(Object list, int start) { + int length = Array.getLength(list); + return subset(list, start, length - start); + } + + static public Object subset(Object list, int start, int count) { + Class type = list.getClass().getComponentType(); + Object outgoing = Array.newInstance(type, count); + System.arraycopy(list, start, outgoing, 0, count); + return outgoing; + } + + // + + static public boolean[] concat(boolean a[], boolean b[]) { + boolean c[] = new boolean[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } + + static public byte[] concat(byte a[], byte b[]) { + byte c[] = new byte[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } + + static public char[] concat(char a[], char b[]) { + char c[] = new char[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } + + static public int[] concat(int a[], int b[]) { + int c[] = new int[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } + + static public float[] concat(float a[], float b[]) { + float c[] = new float[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } + + static public String[] concat(String a[], String b[]) { + String c[] = new String[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } + + static public Object concat(Object a, Object b) { + Class type = a.getClass().getComponentType(); + int alength = Array.getLength(a); + int blength = Array.getLength(b); + Object outgoing = Array.newInstance(type, alength + blength); + System.arraycopy(a, 0, outgoing, 0, alength); + System.arraycopy(b, 0, outgoing, alength, blength); + return outgoing; + } + + // + + static public boolean[] reverse(boolean list[]) { + boolean outgoing[] = new boolean[list.length]; + int length1 = list.length - 1; + for (int i = 0; i < list.length; i++) { + outgoing[i] = list[length1 - i]; + } + return outgoing; + } + + static public byte[] reverse(byte list[]) { + byte outgoing[] = new byte[list.length]; + int length1 = list.length - 1; + for (int i = 0; i < list.length; i++) { + outgoing[i] = list[length1 - i]; + } + return outgoing; + } + + static public char[] reverse(char list[]) { + char outgoing[] = new char[list.length]; + int length1 = list.length - 1; + for (int i = 0; i < list.length; i++) { + outgoing[i] = list[length1 - i]; + } + return outgoing; + } + + static public int[] reverse(int list[]) { + int outgoing[] = new int[list.length]; + int length1 = list.length - 1; + for (int i = 0; i < list.length; i++) { + outgoing[i] = list[length1 - i]; + } + return outgoing; + } + + static public float[] reverse(float list[]) { + float outgoing[] = new float[list.length]; + int length1 = list.length - 1; + for (int i = 0; i < list.length; i++) { + outgoing[i] = list[length1 - i]; + } + return outgoing; + } + + static public String[] reverse(String list[]) { + String outgoing[] = new String[list.length]; + int length1 = list.length - 1; + for (int i = 0; i < list.length; i++) { + outgoing[i] = list[length1 - i]; + } + return outgoing; + } + + static public Object reverse(Object list) { + Class type = list.getClass().getComponentType(); + int length = Array.getLength(list); + Object outgoing = Array.newInstance(type, length); + for (int i = 0; i < length; i++) { + Array.set(outgoing, i, Array.get(list, (length - 1) - i)); + } + return outgoing; + } + + + + ////////////////////////////////////////////////////////////// + + // STRINGS + + + /** + * Remove whitespace characters from the beginning and ending + * of a String. Works like String.trim() but includes the + * unicode nbsp character as well. + */ + static public String trim(String str) { + return str.replace('\u00A0', ' ').trim(); + } + + + /** + * Trim the whitespace from a String array. This returns a new + * array and does not affect the passed-in array. + */ + static public String[] trim(String[] array) { + String[] outgoing = new String[array.length]; + for (int i = 0; i < array.length; i++) { + if (array[i] != null) { + outgoing[i] = array[i].replace('\u00A0', ' ').trim(); + } + } + return outgoing; + } + + + /** + * Join an array of Strings together as a single String, + * separated by the whatever's passed in for the separator. + */ + static public String join(String str[], char separator) { + return join(str, String.valueOf(separator)); + } + + + /** + * Join an array of Strings together as a single String, + * separated by the whatever's passed in for the separator. + *

+ * To use this on numbers, first pass the array to nf() or nfs() + * to get a list of String objects, then use join on that. + *

+   * e.g. String stuff[] = { "apple", "bear", "cat" };
+   *      String list = join(stuff, ", ");
+   *      // list is now "apple, bear, cat"
+ */ + static public String join(String str[], String separator) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < str.length; i++) { + if (i != 0) buffer.append(separator); + buffer.append(str[i]); + } + return buffer.toString(); + } + + + /** + * Split the provided String at wherever whitespace occurs. + * Multiple whitespace (extra spaces or tabs or whatever) + * between items will count as a single break. + *

+ * The whitespace characters are "\t\n\r\f", which are the defaults + * for java.util.StringTokenizer, plus the unicode non-breaking space + * character, which is found commonly on files created by or used + * in conjunction with Mac OS X (character 160, or 0x00A0 in hex). + *

+   * i.e. splitTokens("a b") -> { "a", "b" }
+   *      splitTokens("a    b") -> { "a", "b" }
+   *      splitTokens("a\tb") -> { "a", "b" }
+   *      splitTokens("a \t  b  ") -> { "a", "b" }
+ */ + static public String[] splitTokens(String what) { + return splitTokens(what, WHITESPACE); + } + + + /** + * Splits a string into pieces, using any of the chars in the + * String 'delim' as separator characters. For instance, + * in addition to white space, you might want to treat commas + * as a separator. The delimeter characters won't appear in + * the returned String array. + *
+   * i.e. splitTokens("a, b", " ,") -> { "a", "b" }
+   * 
+ * To include all the whitespace possibilities, use the variable + * WHITESPACE, found in PConstants: + *
+   * i.e. splitTokens("a   | b", WHITESPACE + "|");  ->  { "a", "b" }
+ */ + static public String[] splitTokens(String what, String delim) { + StringTokenizer toker = new StringTokenizer(what, delim); + String pieces[] = new String[toker.countTokens()]; + + int index = 0; + while (toker.hasMoreTokens()) { + pieces[index++] = toker.nextToken(); + } + return pieces; + } + + + /** + * Split a string into pieces along a specific character. + * Most commonly used to break up a String along a space or a tab + * character. + *

+ * This operates differently than the others, where the + * single delimeter is the only breaking point, and consecutive + * delimeters will produce an empty string (""). This way, + * one can split on tab characters, but maintain the column + * alignments (of say an excel file) where there are empty columns. + */ + static public String[] split(String what, char delim) { + // do this so that the exception occurs inside the user's + // program, rather than appearing to be a bug inside split() + if (what == null) return null; + //return split(what, String.valueOf(delim)); // huh + + char chars[] = what.toCharArray(); + int splitCount = 0; //1; + for (int i = 0; i < chars.length; i++) { + if (chars[i] == delim) splitCount++; + } + // make sure that there is something in the input string + //if (chars.length > 0) { + // if the last char is a delimeter, get rid of it.. + //if (chars[chars.length-1] == delim) splitCount--; + // on second thought, i don't agree with this, will disable + //} + if (splitCount == 0) { + String splits[] = new String[1]; + splits[0] = new String(what); + return splits; + } + //int pieceCount = splitCount + 1; + String splits[] = new String[splitCount + 1]; + int splitIndex = 0; + int startIndex = 0; + for (int i = 0; i < chars.length; i++) { + if (chars[i] == delim) { + splits[splitIndex++] = + new String(chars, startIndex, i-startIndex); + startIndex = i + 1; + } + } + //if (startIndex != chars.length) { + splits[splitIndex] = + new String(chars, startIndex, chars.length-startIndex); + //} + return splits; + } + + + /** + * Split a String on a specific delimiter. Unlike Java's String.split() + * method, this does not parse the delimiter as a regexp because it's more + * confusing than necessary, and String.split() is always available for + * those who want regexp. + */ + static public String[] split(String what, String delim) { + ArrayList items = new ArrayList(); + int index; + int offset = 0; + while ((index = what.indexOf(delim, offset)) != -1) { + items.add(what.substring(offset, index)); + offset = index + delim.length(); + } + items.add(what.substring(offset)); + String[] outgoing = new String[items.size()]; + items.toArray(outgoing); + return outgoing; + } + + + static protected HashMap matchPatterns; + + static Pattern matchPattern(String regexp) { + Pattern p = null; + if (matchPatterns == null) { + matchPatterns = new HashMap(); + } else { + p = matchPatterns.get(regexp); + } + if (p == null) { + if (matchPatterns.size() == 10) { + // Just clear out the match patterns here if more than 10 are being + // used. It's not terribly efficient, but changes that you have >10 + // different match patterns are very slim, unless you're doing + // something really tricky (like custom match() methods), in which + // case match() won't be efficient anyway. (And you should just be + // using your own Java code.) The alternative is using a queue here, + // but that's a silly amount of work for negligible benefit. + matchPatterns.clear(); + } + p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); + matchPatterns.put(regexp, p); + } + return p; + } + + + /** + * Match a string with a regular expression, and returns the match as an + * array. The first index is the matching expression, and array elements + * [1] and higher represent each of the groups (sequences found in parens). + * + * This uses multiline matching (Pattern.MULTILINE) and dotall mode + * (Pattern.DOTALL) by default, so that ^ and $ match the beginning and + * end of any lines found in the source, and the . operator will also + * pick up newline characters. + */ + static public String[] match(String what, String regexp) { + Pattern p = matchPattern(regexp); + Matcher m = p.matcher(what); + if (m.find()) { + int count = m.groupCount() + 1; + String[] groups = new String[count]; + for (int i = 0; i < count; i++) { + groups[i] = m.group(i); + } + return groups; + } + return null; + } + + + /** + * Identical to match(), except that it returns an array of all matches in + * the specified String, rather than just the first. + */ + static public String[][] matchAll(String what, String regexp) { + Pattern p = matchPattern(regexp); + Matcher m = p.matcher(what); + ArrayList results = new ArrayList(); + int count = m.groupCount() + 1; + while (m.find()) { + String[] groups = new String[count]; + for (int i = 0; i < count; i++) { + groups[i] = m.group(i); + } + results.add(groups); + } + if (results.isEmpty()) { + return null; + } + String[][] matches = new String[results.size()][count]; + for (int i = 0; i < matches.length; i++) { + matches[i] = (String[]) results.get(i); + } + return matches; + } + + + + ////////////////////////////////////////////////////////////// + + // CASTING FUNCTIONS, INSERTED BY PREPROC + + + /** + * Convert a char to a boolean. 'T', 't', and '1' will become the + * boolean value true, while 'F', 'f', or '0' will become false. + */ + /* + static final public boolean parseBoolean(char what) { + return ((what == 't') || (what == 'T') || (what == '1')); + } + */ + + /** + *

Convert an integer to a boolean. Because of how Java handles upgrading + * numbers, this will also cover byte and char (as they will upgrade to + * an int without any sort of explicit cast).

+ *

The preprocessor will convert boolean(what) to parseBoolean(what).

+ * @return false if 0, true if any other number + */ + static final public boolean parseBoolean(int what) { + return (what != 0); + } + + /* + // removed because this makes no useful sense + static final public boolean parseBoolean(float what) { + return (what != 0); + } + */ + + /** + * Convert the string "true" or "false" to a boolean. + * @return true if 'what' is "true" or "TRUE", false otherwise + */ + static final public boolean parseBoolean(String what) { + return new Boolean(what).booleanValue(); + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + /* + // removed, no need to introduce strange syntax from other languages + static final public boolean[] parseBoolean(char what[]) { + boolean outgoing[] = new boolean[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = + ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); + } + return outgoing; + } + */ + + /** + * Convert a byte array to a boolean array. Each element will be + * evaluated identical to the integer case, where a byte equal + * to zero will return false, and any other value will return true. + * @return array of boolean elements + */ + static final public boolean[] parseBoolean(byte what[]) { + boolean outgoing[] = new boolean[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (what[i] != 0); + } + return outgoing; + } + + /** + * Convert an int array to a boolean array. An int equal + * to zero will return false, and any other value will return true. + * @return array of boolean elements + */ + static final public boolean[] parseBoolean(int what[]) { + boolean outgoing[] = new boolean[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (what[i] != 0); + } + return outgoing; + } + + /* + // removed, not necessary... if necessary, convert to int array first + static final public boolean[] parseBoolean(float what[]) { + boolean outgoing[] = new boolean[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (what[i] != 0); + } + return outgoing; + } + */ + + static final public boolean[] parseBoolean(String what[]) { + boolean outgoing[] = new boolean[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = new Boolean(what[i]).booleanValue(); + } + return outgoing; + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + static final public byte parseByte(boolean what) { + return what ? (byte)1 : 0; + } + + static final public byte parseByte(char what) { + return (byte) what; + } + + static final public byte parseByte(int what) { + return (byte) what; + } + + static final public byte parseByte(float what) { + return (byte) what; + } + + /* + // nixed, no precedent + static final public byte[] parseByte(String what) { // note: array[] + return what.getBytes(); + } + */ + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + static final public byte[] parseByte(boolean what[]) { + byte outgoing[] = new byte[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = what[i] ? (byte)1 : 0; + } + return outgoing; + } + + static final public byte[] parseByte(char what[]) { + byte outgoing[] = new byte[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (byte) what[i]; + } + return outgoing; + } + + static final public byte[] parseByte(int what[]) { + byte outgoing[] = new byte[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (byte) what[i]; + } + return outgoing; + } + + static final public byte[] parseByte(float what[]) { + byte outgoing[] = new byte[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (byte) what[i]; + } + return outgoing; + } + + /* + static final public byte[][] parseByte(String what[]) { // note: array[][] + byte outgoing[][] = new byte[what.length][]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = what[i].getBytes(); + } + return outgoing; + } + */ + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + /* + static final public char parseChar(boolean what) { // 0/1 or T/F ? + return what ? 't' : 'f'; + } + */ + + static final public char parseChar(byte what) { + return (char) (what & 0xff); + } + + static final public char parseChar(int what) { + return (char) what; + } + + /* + static final public char parseChar(float what) { // nonsensical + return (char) what; + } + + static final public char[] parseChar(String what) { // note: array[] + return what.toCharArray(); + } + */ + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + /* + static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? + char outgoing[] = new char[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = what[i] ? 't' : 'f'; + } + return outgoing; + } + */ + + static final public char[] parseChar(byte what[]) { + char outgoing[] = new char[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (char) (what[i] & 0xff); + } + return outgoing; + } + + static final public char[] parseChar(int what[]) { + char outgoing[] = new char[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (char) what[i]; + } + return outgoing; + } + + /* + static final public char[] parseChar(float what[]) { // nonsensical + char outgoing[] = new char[what.length]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = (char) what[i]; + } + return outgoing; + } + + static final public char[][] parseChar(String what[]) { // note: array[][] + char outgoing[][] = new char[what.length][]; + for (int i = 0; i < what.length; i++) { + outgoing[i] = what[i].toCharArray(); + } + return outgoing; + } + */ + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + static final public int parseInt(boolean what) { + return what ? 1 : 0; + } + + /** + * Note that parseInt() will un-sign a signed byte value. + */ + static final public int parseInt(byte what) { + return what & 0xff; + } + + /** + * Note that parseInt('5') is unlike String in the sense that it + * won't return 5, but the ascii value. This is because ((int) someChar) + * returns the ascii value, and parseInt() is just longhand for the cast. + */ + static final public int parseInt(char what) { + return what; + } + + /** + * Same as floor(), or an (int) cast. + */ + static final public int parseInt(float what) { + return (int) what; + } + + /** + * Parse a String into an int value. Returns 0 if the value is bad. + */ + static final public int parseInt(String what) { + return parseInt(what, 0); + } + + /** + * Parse a String to an int, and provide an alternate value that + * should be used when the number is invalid. + */ + static final public int parseInt(String what, int otherwise) { + try { + int offset = what.indexOf('.'); + if (offset == -1) { + return Integer.parseInt(what); + } else { + return Integer.parseInt(what.substring(0, offset)); + } + } catch (NumberFormatException e) { } + return otherwise; + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + static final public int[] parseInt(boolean what[]) { + int list[] = new int[what.length]; + for (int i = 0; i < what.length; i++) { + list[i] = what[i] ? 1 : 0; + } + return list; + } + + static final public int[] parseInt(byte what[]) { // note this unsigns + int list[] = new int[what.length]; + for (int i = 0; i < what.length; i++) { + list[i] = (what[i] & 0xff); + } + return list; + } + + static final public int[] parseInt(char what[]) { + int list[] = new int[what.length]; + for (int i = 0; i < what.length; i++) { + list[i] = what[i]; + } + return list; + } + + static public int[] parseInt(float what[]) { + int inties[] = new int[what.length]; + for (int i = 0; i < what.length; i++) { + inties[i] = (int)what[i]; + } + return inties; + } + + /** + * Make an array of int elements from an array of String objects. + * If the String can't be parsed as a number, it will be set to zero. + * + * String s[] = { "1", "300", "44" }; + * int numbers[] = parseInt(s); + * + * numbers will contain { 1, 300, 44 } + */ + static public int[] parseInt(String what[]) { + return parseInt(what, 0); + } + + /** + * Make an array of int elements from an array of String objects. + * If the String can't be parsed as a number, its entry in the + * array will be set to the value of the "missing" parameter. + * + * String s[] = { "1", "300", "apple", "44" }; + * int numbers[] = parseInt(s, 9999); + * + * numbers will contain { 1, 300, 9999, 44 } + */ + static public int[] parseInt(String what[], int missing) { + int output[] = new int[what.length]; + for (int i = 0; i < what.length; i++) { + try { + output[i] = Integer.parseInt(what[i]); + } catch (NumberFormatException e) { + output[i] = missing; + } + } + return output; + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + /* + static final public float parseFloat(boolean what) { + return what ? 1 : 0; + } + */ + + /** + * Convert an int to a float value. Also handles bytes because of + * Java's rules for upgrading values. + */ + static final public float parseFloat(int what) { // also handles byte + return (float)what; + } + + static final public float parseFloat(String what) { + return parseFloat(what, Float.NaN); + } + + static final public float parseFloat(String what, float otherwise) { + try { + return new Float(what).floatValue(); + } catch (NumberFormatException e) { } + + return otherwise; + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + /* + static final public float[] parseFloat(boolean what[]) { + float floaties[] = new float[what.length]; + for (int i = 0; i < what.length; i++) { + floaties[i] = what[i] ? 1 : 0; + } + return floaties; + } + + static final public float[] parseFloat(char what[]) { + float floaties[] = new float[what.length]; + for (int i = 0; i < what.length; i++) { + floaties[i] = (char) what[i]; + } + return floaties; + } + */ + + static final public float[] parseByte(byte what[]) { + float floaties[] = new float[what.length]; + for (int i = 0; i < what.length; i++) { + floaties[i] = what[i]; + } + return floaties; + } + + static final public float[] parseFloat(int what[]) { + float floaties[] = new float[what.length]; + for (int i = 0; i < what.length; i++) { + floaties[i] = what[i]; + } + return floaties; + } + + static final public float[] parseFloat(String what[]) { + return parseFloat(what, Float.NaN); + } + + static final public float[] parseFloat(String what[], float missing) { + float output[] = new float[what.length]; + for (int i = 0; i < what.length; i++) { + try { + output[i] = new Float(what[i]).floatValue(); + } catch (NumberFormatException e) { + output[i] = missing; + } + } + return output; + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + static final public String str(boolean x) { + return String.valueOf(x); + } + + static final public String str(byte x) { + return String.valueOf(x); + } + + static final public String str(char x) { + return String.valueOf(x); + } + + static final public String str(int x) { + return String.valueOf(x); + } + + static final public String str(float x) { + return String.valueOf(x); + } + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + static final public String[] str(boolean x[]) { + String s[] = new String[x.length]; + for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); + return s; + } + + static final public String[] str(byte x[]) { + String s[] = new String[x.length]; + for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); + return s; + } + + static final public String[] str(char x[]) { + String s[] = new String[x.length]; + for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); + return s; + } + + static final public String[] str(int x[]) { + String s[] = new String[x.length]; + for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); + return s; + } + + static final public String[] str(float x[]) { + String s[] = new String[x.length]; + for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); + return s; + } + + + ////////////////////////////////////////////////////////////// + + // INT NUMBER FORMATTING + + + /** + * Integer number formatter. + */ + static private NumberFormat int_nf; + static private int int_nf_digits; + static private boolean int_nf_commas; + + + static public String[] nf(int num[], int digits) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nf(num[i], digits); + } + return formatted; + } + + + static public String nf(int num, int digits) { + if ((int_nf != null) && + (int_nf_digits == digits) && + !int_nf_commas) { + return int_nf.format(num); + } + + int_nf = NumberFormat.getInstance(); + int_nf.setGroupingUsed(false); // no commas + int_nf_commas = false; + int_nf.setMinimumIntegerDigits(digits); + int_nf_digits = digits; + return int_nf.format(num); + } + + + static public String[] nfc(int num[]) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nfc(num[i]); + } + return formatted; + } + + + static public String nfc(int num) { + if ((int_nf != null) && + (int_nf_digits == 0) && + int_nf_commas) { + return int_nf.format(num); + } + + int_nf = NumberFormat.getInstance(); + int_nf.setGroupingUsed(true); + int_nf_commas = true; + int_nf.setMinimumIntegerDigits(0); + int_nf_digits = 0; + return int_nf.format(num); + } + + + /** + * number format signed (or space) + * Formats a number but leaves a blank space in the front + * when it's positive so that it can be properly aligned with + * numbers that have a negative sign in front of them. + */ + static public String nfs(int num, int digits) { + return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); + } + + static public String[] nfs(int num[], int digits) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nfs(num[i], digits); + } + return formatted; + } + + // + + /** + * number format positive (or plus) + * Formats a number, always placing a - or + sign + * in the front when it's negative or positive. + */ + static public String nfp(int num, int digits) { + return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); + } + + static public String[] nfp(int num[], int digits) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nfp(num[i], digits); + } + return formatted; + } + + + + ////////////////////////////////////////////////////////////// + + // FLOAT NUMBER FORMATTING + + + static private NumberFormat float_nf; + static private int float_nf_left, float_nf_right; + static private boolean float_nf_commas; + + + static public String[] nf(float num[], int left, int right) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nf(num[i], left, right); + } + return formatted; + } + + + static public String nf(float num, int left, int right) { + if ((float_nf != null) && + (float_nf_left == left) && + (float_nf_right == right) && + !float_nf_commas) { + return float_nf.format(num); + } + + float_nf = NumberFormat.getInstance(); + float_nf.setGroupingUsed(false); + float_nf_commas = false; + + if (left != 0) float_nf.setMinimumIntegerDigits(left); + if (right != 0) { + float_nf.setMinimumFractionDigits(right); + float_nf.setMaximumFractionDigits(right); + } + float_nf_left = left; + float_nf_right = right; + return float_nf.format(num); + } + + + static public String[] nfc(float num[], int right) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nfc(num[i], right); + } + return formatted; + } + + + static public String nfc(float num, int right) { + if ((float_nf != null) && + (float_nf_left == 0) && + (float_nf_right == right) && + float_nf_commas) { + return float_nf.format(num); + } + + float_nf = NumberFormat.getInstance(); + float_nf.setGroupingUsed(true); + float_nf_commas = true; + + if (right != 0) { + float_nf.setMinimumFractionDigits(right); + float_nf.setMaximumFractionDigits(right); + } + float_nf_left = 0; + float_nf_right = right; + return float_nf.format(num); + } + + + /** + * Number formatter that takes into account whether the number + * has a sign (positive, negative, etc) in front of it. + */ + static public String[] nfs(float num[], int left, int right) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nfs(num[i], left, right); + } + return formatted; + } + + static public String nfs(float num, int left, int right) { + return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); + } + + + static public String[] nfp(float num[], int left, int right) { + String formatted[] = new String[num.length]; + for (int i = 0; i < formatted.length; i++) { + formatted[i] = nfp(num[i], left, right); + } + return formatted; + } + + static public String nfp(float num, int left, int right) { + return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); + } + + + + ////////////////////////////////////////////////////////////// + + // HEX/BINARY CONVERSION + + + static final public String hex(byte what) { + return hex(what, 2); + } + + static final public String hex(char what) { + return hex(what, 4); + } + + static final public String hex(int what) { + return hex(what, 8); + } + + static final public String hex(int what, int digits) { + String stuff = Integer.toHexString(what).toUpperCase(); + + int length = stuff.length(); + if (length > digits) { + return stuff.substring(length - digits); + + } else if (length < digits) { + return "00000000".substring(8 - (digits-length)) + stuff; + } + return stuff; + } + + static final public int unhex(String what) { + // has to parse as a Long so that it'll work for numbers bigger than 2^31 + return (int) (Long.parseLong(what, 16)); + } + + // + + /** + * Returns a String that contains the binary value of a byte. + * The returned value will always have 8 digits. + */ + static final public String binary(byte what) { + return binary(what, 8); + } + + /** + * Returns a String that contains the binary value of a char. + * The returned value will always have 16 digits because chars + * are two bytes long. + */ + static final public String binary(char what) { + return binary(what, 16); + } + + /** + * Returns a String that contains the binary value of an int. + * The length depends on the size of the number itself. + * An int can be up to 32 binary digits, but that seems like + * overkill for almost any situation, so this function just + * auto-size. If you want a specific number of digits (like all 32) + * use binary(int what, int digits) to specify how many digits. + */ + static final public String binary(int what) { + return Integer.toBinaryString(what); + //return binary(what, 32); + } + + /** + * Returns a String that contains the binary value of an int. + * The digits parameter determines how many digits will be used. + */ + static final public String binary(int what, int digits) { + String stuff = Integer.toBinaryString(what); + + int length = stuff.length(); + if (length > digits) { + return stuff.substring(length - digits); + + } else if (length < digits) { + int offset = 32 - (digits-length); + return "00000000000000000000000000000000".substring(offset) + stuff; + } + return stuff; + } + + + /** + * Unpack a binary String into an int. + * i.e. unbinary("00001000") would return 8. + */ + static final public int unbinary(String what) { + return Integer.parseInt(what, 2); + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR FUNCTIONS + + // moved here so that they can work without + // the graphics actually being instantiated (outside setup) + + + public final int color(int gray) { + if (g == null) { + if (gray > 255) gray = 255; else if (gray < 0) gray = 0; + return 0xff000000 | (gray << 16) | (gray << 8) | gray; + } + return g.color(gray); + } + + + public final int color(float fgray) { + if (g == null) { + int gray = (int) fgray; + if (gray > 255) gray = 255; else if (gray < 0) gray = 0; + return 0xff000000 | (gray << 16) | (gray << 8) | gray; + } + return g.color(fgray); + } + + + /** + * As of 0116 this also takes color(#FF8800, alpha) + * + * @param gray number specifying value between white and black + */ + public final int color(int gray, int alpha) { + if (g == null) { + if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; + if (gray > 255) { + // then assume this is actually a #FF8800 + return (alpha << 24) | (gray & 0xFFFFFF); + } else { + //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; + return (alpha << 24) | (gray << 16) | (gray << 8) | gray; + } + } + return g.color(gray, alpha); + } + + + public final int color(float fgray, float falpha) { + if (g == null) { + int gray = (int) fgray; + int alpha = (int) falpha; + if (gray > 255) gray = 255; else if (gray < 0) gray = 0; + if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; + return 0xff000000 | (gray << 16) | (gray << 8) | gray; + } + return g.color(fgray, falpha); + } + + + public final int color(int x, int y, int z) { + if (g == null) { + if (x > 255) x = 255; else if (x < 0) x = 0; + if (y > 255) y = 255; else if (y < 0) y = 0; + if (z > 255) z = 255; else if (z < 0) z = 0; + + return 0xff000000 | (x << 16) | (y << 8) | z; + } + return g.color(x, y, z); + } + + + public final int color(float x, float y, float z) { + if (g == null) { + if (x > 255) x = 255; else if (x < 0) x = 0; + if (y > 255) y = 255; else if (y < 0) y = 0; + if (z > 255) z = 255; else if (z < 0) z = 0; + + return 0xff000000 | ((int)x << 16) | ((int)y << 8) | (int)z; + } + return g.color(x, y, z); + } + + + public final int color(int x, int y, int z, int a) { + if (g == null) { + if (a > 255) a = 255; else if (a < 0) a = 0; + if (x > 255) x = 255; else if (x < 0) x = 0; + if (y > 255) y = 255; else if (y < 0) y = 0; + if (z > 255) z = 255; else if (z < 0) z = 0; + + return (a << 24) | (x << 16) | (y << 8) | z; + } + return g.color(x, y, z, a); + } + + /** + * Creates colors for storing in variables of the color datatype. The parameters are interpreted as RGB or HSB values depending on the current colorMode(). The default mode is RGB values from 0 to 255 and therefore, the function call color(255, 204, 0) will return a bright yellow color. More about how colors are stored can be found in the reference for the color datatype. + * + * @webref color:creating_reading + * @param x red or hue values relative to the current color range + * @param y green or saturation values relative to the current color range + * @param z blue or brightness values relative to the current color range + * @param a alpha relative to current color range + * + * @see processing.core.PApplet#colorMode(int) + * @ref color_datatype + */ + public final int color(float x, float y, float z, float a) { + if (g == null) { + if (a > 255) a = 255; else if (a < 0) a = 0; + if (x > 255) x = 255; else if (x < 0) x = 0; + if (y > 255) y = 255; else if (y < 0) y = 0; + if (z > 255) z = 255; else if (z < 0) z = 0; + + return ((int)a << 24) | ((int)x << 16) | ((int)y << 8) | (int)z; + } + return g.color(x, y, z, a); + } + + + + ////////////////////////////////////////////////////////////// + + // MAIN + + + /** + * Set this sketch to communicate its state back to the PDE. + *

+ * This uses the stderr stream to write positions of the window + * (so that it will be saved by the PDE for the next run) and + * notify on quit. See more notes in the Worker class. + */ + public void setupExternalMessages() { + + frame.addComponentListener(new ComponentAdapter() { + public void componentMoved(ComponentEvent e) { + Point where = ((Frame) e.getSource()).getLocation(); + System.err.println(PApplet.EXTERNAL_MOVE + " " + + where.x + " " + where.y); + System.err.flush(); // doesn't seem to help or hurt + } + }); + + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { +// System.err.println(PApplet.EXTERNAL_QUIT); +// System.err.flush(); // important +// System.exit(0); + exit(); // don't quit, need to just shut everything down (0133) + } + }); + } + + + /** + * Set up a listener that will fire proper component resize events + * in cases where frame.setResizable(true) is called. + */ + public void setupFrameResizeListener() { + frame.addComponentListener(new ComponentAdapter() { + + public void componentResized(ComponentEvent e) { + // Ignore bad resize events fired during setup to fix + // http://dev.processing.org/bugs/show_bug.cgi?id=341 + // This should also fix the blank screen on Linux bug + // http://dev.processing.org/bugs/show_bug.cgi?id=282 + if (frame.isResizable()) { + // might be multiple resize calls before visible (i.e. first + // when pack() is called, then when it's resized for use). + // ignore them because it's not the user resizing things. + Frame farm = (Frame) e.getComponent(); + if (farm.isVisible()) { + Insets insets = farm.getInsets(); + Dimension windowSize = farm.getSize(); + int usableW = windowSize.width - insets.left - insets.right; + int usableH = windowSize.height - insets.top - insets.bottom; + + // the ComponentListener in PApplet will handle calling size() + setBounds(insets.left, insets.top, usableW, usableH); + } + } + } + }); + } + + + /** + * GIF image of the Processing logo. + */ + static public final byte[] ICON_IMAGE = { + 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, + 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, + 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, + 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, + 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, + 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, + 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, + -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, + 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, + 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, + 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, + 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 + }; + + + /** + * main() method for running this class from the command line. + *

+ * The options shown here are not yet finalized and will be + * changing over the next several releases. + *

+ * The simplest way to turn and applet into an application is to + * add the following code to your program: + *

static public void main(String args[]) {
+   *   PApplet.main(new String[] { "YourSketchName" });
+   * }
+ * This will properly launch your applet from a double-clickable + * .jar or from the command line. + *
+   * Parameters useful for launching or also used by the PDE:
+   *
+   * --location=x,y        upper-lefthand corner of where the applet
+   *                       should appear on screen. if not used,
+   *                       the default is to center on the main screen.
+   *
+   * --present             put the applet into full screen presentation
+   *                       mode. requires java 1.4 or later.
+   *
+   * --exclusive           use full screen exclusive mode when presenting.
+   *                       disables new windows or interaction with other
+   *                       monitors, this is like a "game" mode.
+   *
+   * --hide-stop           use to hide the stop button in situations where
+   *                       you don't want to allow users to exit. also
+   *                       see the FAQ on information for capturing the ESC
+   *                       key when running in presentation mode.
+   *
+   * --stop-color=#xxxxxx  color of the 'stop' text used to quit an
+   *                       sketch when it's in present mode.
+   *
+   * --bgcolor=#xxxxxx     background color of the window.
+   *
+   * --sketch-path         location of where to save files from functions
+   *                       like saveStrings() or saveFrame(). defaults to
+   *                       the folder that the java application was
+   *                       launched from, which means if this isn't set by
+   *                       the pde, everything goes into the same folder
+   *                       as processing.exe.
+   *
+   * --display=n           set what display should be used by this applet.
+   *                       displays are numbered starting from 1.
+   *
+   * Parameters used by Processing when running via the PDE
+   *
+   * --external            set when the applet is being used by the PDE
+   *
+   * --editor-location=x,y position of the upper-lefthand corner of the
+   *                       editor window, for placement of applet window
+   * 
+ */ + static public void runSketch(String args[], final PApplet constructedApplet) { + // Disable abyssmally slow Sun renderer on OS X 10.5. + if (platform == MACOSX) { + // Only run this on OS X otherwise it can cause a permissions error. + // http://dev.processing.org/bugs/show_bug.cgi?id=976 + System.setProperty("apple.awt.graphics.UseQuartz", + String.valueOf(useQuartz)); + } + + // This doesn't do anything. +// if (platform == WINDOWS) { +// // For now, disable the D3D renderer on Java 6u10 because +// // it causes problems with Present mode. +// // http://dev.processing.org/bugs/show_bug.cgi?id=1009 +// System.setProperty("sun.java2d.d3d", "false"); +// } + + if (args.length < 1) { + System.err.println("Usage: PApplet "); + System.err.println("For additional options, " + + "see the Javadoc for PApplet"); + System.exit(1); + } + + boolean external = false; + int[] location = null; + int[] editorLocation = null; + + String name = null; + boolean present = false; + boolean exclusive = false; + Color backgroundColor = Color.BLACK; + Color stopColor = Color.GRAY; + GraphicsDevice displayDevice = null; + boolean hideStop = false; + + String param = null, value = null; + + // try to get the user folder. if running under java web start, + // this may cause a security exception if the code is not signed. + // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 + String folder = null; + try { + folder = System.getProperty("user.dir"); + } catch (Exception e) { } + + int argIndex = 0; + while (argIndex < args.length) { + int equals = args[argIndex].indexOf('='); + if (equals != -1) { + param = args[argIndex].substring(0, equals); + value = args[argIndex].substring(equals + 1); + + if (param.equals(ARGS_EDITOR_LOCATION)) { + external = true; + editorLocation = parseInt(split(value, ',')); + + } else if (param.equals(ARGS_DISPLAY)) { + int deviceIndex = Integer.parseInt(value) - 1; + + //DisplayMode dm = device.getDisplayMode(); + //if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) { + + GraphicsEnvironment environment = + GraphicsEnvironment.getLocalGraphicsEnvironment(); + GraphicsDevice devices[] = environment.getScreenDevices(); + if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { + displayDevice = devices[deviceIndex]; + } else { + System.err.println("Display " + value + " does not exist, " + + "using the default display instead."); + } + + } else if (param.equals(ARGS_BGCOLOR)) { + if (value.charAt(0) == '#') value = value.substring(1); + backgroundColor = new Color(Integer.parseInt(value, 16)); + + } else if (param.equals(ARGS_STOP_COLOR)) { + if (value.charAt(0) == '#') value = value.substring(1); + stopColor = new Color(Integer.parseInt(value, 16)); + + } else if (param.equals(ARGS_SKETCH_FOLDER)) { + folder = value; + + } else if (param.equals(ARGS_LOCATION)) { + location = parseInt(split(value, ',')); + } + + } else { + if (args[argIndex].equals(ARGS_PRESENT)) { + present = true; + + } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { + exclusive = true; + + } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { + hideStop = true; + + } else if (args[argIndex].equals(ARGS_EXTERNAL)) { + external = true; + + } else { + name = args[argIndex]; + break; + } + } + argIndex++; + } + + // Set this property before getting into any GUI init code + //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); + // This )*)(*@#$ Apple crap don't work no matter where you put it + // (static method of the class, at the top of main, wherever) + + if (displayDevice == null) { + GraphicsEnvironment environment = + GraphicsEnvironment.getLocalGraphicsEnvironment(); + displayDevice = environment.getDefaultScreenDevice(); + } + + Frame frame = new Frame(displayDevice.getDefaultConfiguration()); + /* + Frame frame = null; + if (displayDevice != null) { + frame = new Frame(displayDevice.getDefaultConfiguration()); + } else { + frame = new Frame(); + } + */ + //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + + // remove the grow box by default + // users who want it back can call frame.setResizable(true) + //frame.setResizable(false); + // moved later (issue #467) + + // Set the trimmings around the image + Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); + frame.setIconImage(image); + frame.setTitle(name); + + final PApplet applet; + if (constructedApplet != null) { + applet = constructedApplet; + } else { + try { + Class c = Thread.currentThread().getContextClassLoader().loadClass(name); + applet = (PApplet) c.newInstance(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + // these are needed before init/start + applet.frame = frame; + applet.sketchPath = folder; + applet.args = PApplet.subset(args, 1); + applet.external = external; + + // Need to save the window bounds at full screen, + // because pack() will cause the bounds to go to zero. + // http://dev.processing.org/bugs/show_bug.cgi?id=923 + Rectangle fullScreenRect = null; + + // For 0149, moving this code (up to the pack() method) before init(). + // For OpenGL (and perhaps other renderers in the future), a peer is + // needed before a GLDrawable can be created. So pack() needs to be + // called on the Frame before applet.init(), which itself calls size(), + // and launches the Thread that will kick off setup(). + // http://dev.processing.org/bugs/show_bug.cgi?id=891 + // http://dev.processing.org/bugs/show_bug.cgi?id=908 + if (present) { + frame.setUndecorated(true); + frame.setBackground(backgroundColor); + if (exclusive) { + displayDevice.setFullScreenWindow(frame); + frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); + fullScreenRect = frame.getBounds(); + } else { + DisplayMode mode = displayDevice.getDisplayMode(); + fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight()); + frame.setBounds(fullScreenRect); + frame.setVisible(true); + } + } + frame.setLayout(null); + frame.add(applet); + if (present) { + frame.invalidate(); + } else { + frame.pack(); + } + // insufficient, places the 100x100 sketches offset strangely + //frame.validate(); + + // disabling resize has to happen after pack() to avoid apparent Apple bug + // http://code.google.com/p/processing/issues/detail?id=467 + frame.setResizable(false); + + applet.init(); + + // Wait until the applet has figured out its width. + // In a static mode app, this will be after setup() has completed, + // and the empty draw() has set "finished" to true. + // TODO make sure this won't hang if the applet has an exception. + while (applet.defaultSize && !applet.finished) { + //System.out.println("default size"); + try { + Thread.sleep(5); + + } catch (InterruptedException e) { + //System.out.println("interrupt"); + } + } + //println("not default size " + applet.width + " " + applet.height); + //println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")"); + + if (present) { + // After the pack(), the screen bounds are gonna be 0s + frame.setBounds(fullScreenRect); + applet.setBounds((fullScreenRect.width - applet.width) / 2, + (fullScreenRect.height - applet.height) / 2, + applet.width, applet.height); + + if (!hideStop) { + Label label = new Label("stop"); + label.setForeground(stopColor); + label.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + System.exit(0); + } + }); + frame.add(label); + + Dimension labelSize = label.getPreferredSize(); + // sometimes shows up truncated on mac + //System.out.println("label width is " + labelSize.width); + labelSize = new Dimension(100, labelSize.height); + label.setSize(labelSize); + label.setLocation(20, fullScreenRect.height - labelSize.height - 20); + } + + // not always running externally when in present mode + if (external) { + applet.setupExternalMessages(); + } + + } else { // if not presenting + // can't do pack earlier cuz present mode don't like it + // (can't go full screen with a frame after calling pack) + // frame.pack(); // get insets. get more. + Insets insets = frame.getInsets(); + + int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + + insets.left + insets.right; + int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + + insets.top + insets.bottom; + +System.out.println("frame.setSize(" + windowW + ", " + windowH + ")"); + frame.setSize(windowW, windowH); + + if (location != null) { + // a specific location was received from PdeRuntime + // (applet has been run more than once, user placed window) + frame.setLocation(location[0], location[1]); + + } else if (external) { + int locationX = editorLocation[0] - 20; + int locationY = editorLocation[1]; + + if (locationX - windowW > 10) { + // if it fits to the left of the window + frame.setLocation(locationX - windowW, locationY); + + } else { // doesn't fit + // if it fits inside the editor window, + // offset slightly from upper lefthand corner + // so that it's plunked inside the text area + locationX = editorLocation[0] + 66; + locationY = editorLocation[1] + 66; + + if ((locationX + windowW > applet.screenWidth - 33) || + (locationY + windowH > applet.screenHeight - 33)) { + // otherwise center on screen + locationX = (applet.screenWidth - windowW) / 2; + locationY = (applet.screenHeight - windowH) / 2; + } + frame.setLocation(locationX, locationY); + } + } else { // just center on screen + frame.setLocation((applet.screenWidth - applet.width) / 2, + (applet.screenHeight - applet.height) / 2); + } + Point frameLoc = frame.getLocation(); + if (frameLoc.y < 0) { + // Windows actually allows you to place frames where they can't be + // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 + frame.setLocation(frameLoc.x, 30); + } + + if (backgroundColor == Color.black) { //BLACK) { + // this means no bg color unless specified + backgroundColor = SystemColor.control; + } + frame.setBackground(backgroundColor); + + int usableWindowH = windowH - insets.top - insets.bottom; + applet.setBounds((windowW - applet.width)/2, + insets.top + (usableWindowH - applet.height)/2, + applet.width, applet.height); + + if (external) { + applet.setupExternalMessages(); + + } else { // !external + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } + + // handle frame resizing events + applet.setupFrameResizeListener(); + + // all set for rockin + if (applet.displayable()) { + frame.setVisible(true); + } + } + + // Disabling for 0185, because it causes an assertion failure on OS X + // http://code.google.com/p/processing/issues/detail?id=258 + // (Although this doesn't seem to be the one that was causing problems.) + //applet.requestFocus(); // ask for keydowns + } + + public static void main(final String[] args) { + runSketch(args, null); + } + + /** + * These methods provide a means for running an already-constructed + * sketch. In particular, it makes it easy to launch a sketch in + * Jython: + * + *
class MySketch(PApplet):
+   *     pass
+   *
+   *MySketch().runSketch();
+ */ + protected void runSketch(final String[] args) { + final String[] argsWithSketchName = new String[args.length + 1]; + System.arraycopy(args, 0, argsWithSketchName, 0, args.length); + final String className = this.getClass().getSimpleName(); + final String cleanedClass = + className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); + argsWithSketchName[args.length] = cleanedClass; + runSketch(argsWithSketchName, this); + } + + protected void runSketch() { + runSketch(new String[0]); + } + + ////////////////////////////////////////////////////////////// + + + /** + * Begin recording to a new renderer of the specified type, using the width + * and height of the main drawing surface. + */ + public PGraphics beginRecord(String renderer, String filename) { + filename = insertFrame(filename); + PGraphics rec = createGraphics(width, height, renderer, filename); + beginRecord(rec); + return rec; + } + + + /** + * Begin recording (echoing) commands to the specified PGraphics object. + */ + public void beginRecord(PGraphics recorder) { + this.recorder = recorder; + recorder.beginDraw(); + } + + + public void endRecord() { + if (recorder != null) { + recorder.endDraw(); + recorder.dispose(); + recorder = null; + } + } + + + /** + * Begin recording raw shape data to a renderer of the specified type, + * using the width and height of the main drawing surface. + * + * If hashmarks (###) are found in the filename, they'll be replaced + * by the current frame number (frameCount). + */ + public PGraphics beginRaw(String renderer, String filename) { + filename = insertFrame(filename); + PGraphics rec = createGraphics(width, height, renderer, filename); + g.beginRaw(rec); + return rec; + } + + + /** + * Begin recording raw shape data to the specified renderer. + * + * This simply echoes to g.beginRaw(), but since is placed here (rather than + * generated by preproc.pl) for clarity and so that it doesn't echo the + * command should beginRecord() be in use. + */ + public void beginRaw(PGraphics rawGraphics) { + g.beginRaw(rawGraphics); + } + + + /** + * Stop recording raw shape data to the specified renderer. + * + * This simply echoes to g.beginRaw(), but since is placed here (rather than + * generated by preproc.pl) for clarity and so that it doesn't echo the + * command should beginRecord() be in use. + */ + public void endRaw() { + g.endRaw(); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Loads the pixel data for the display window into the pixels[] array. This function must always be called before reading from or writing to pixels[]. + *

Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change. + * =advanced + * Override the g.pixels[] function to set the pixels[] array + * that's part of the PApplet object. Allows the use of + * pixels[] in the code, rather than g.pixels[]. + * + * @webref image:pixels + * @see processing.core.PApplet#pixels + * @see processing.core.PApplet#updatePixels() + */ + public void loadPixels() { + g.loadPixels(); + pixels = g.pixels; + } + + /** + * Updates the display window with the data in the pixels[] array. Use in conjunction with loadPixels(). If you're only reading pixels from the array, there's no need to call updatePixels() unless there are changes. + *

Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change. + *

Currently, none of the renderers use the additional parameters to updatePixels(), however this may be implemented in the future. + * + * @webref image:pixels + * + * @see processing.core.PApplet#loadPixels() + * @see processing.core.PApplet#updatePixels() + * + */ + public void updatePixels() { + g.updatePixels(); + } + + + public void updatePixels(int x1, int y1, int x2, int y2) { + g.updatePixels(x1, y1, x2, y2); + } + + + ////////////////////////////////////////////////////////////// + + // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! + // This includes the Javadoc comments, which are automatically copied from + // the PImage and PGraphics source code files. + + // public functions for processing.core + + + public void flush() { + if (recorder != null) recorder.flush(); + g.flush(); + } + + + /** + * Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be implemented in a consistent manner across renderers. Many options will often graduate to standard features instead of hints over time. + *

hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's control panel, however not all cards make this available. This hint must be called immediately after the size() command because it resets the renderer, obliterating any settings and anything drawn (and like size(), re-running the code that came before it again). + *

hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in earlier releases, where smooth() and noSmooth() could be used to enable and disable smoothing, though the quality was inferior. + *

hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are installed, rather than the bitmapped version from a .vlw file. This is useful with the JAVA2D renderer setting, as it will improve font rendering speed. This is not enabled by default, because it can be misleading while testing because the type will look great on your machine (because you have the font installed) but lousy on others' machines if the identical font is unavailable. This option can only be set per-sketch, and must be called before any use of textFont(). + *

hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on top of everything at will. When depth testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, any 3D drawing that happens later in draw() will ignore existing shapes on the screen. + *

hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and lines in P3D and OPENGL. This can slow performance considerably, and the algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT). + *

hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the OPENGL renderer setting by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT). + *

As of release 0149, unhint() has been removed in favor of adding additional ENABLE/DISABLE constants to reset the default behavior. This prevents the double negatives, and also reinforces which hints can be enabled or disabled. + * + * @webref rendering + * @param which name of the hint to be enabled or disabled + * + * @see processing.core.PGraphics + * @see processing.core.PApplet#createGraphics(int, int, String, String) + * @see processing.core.PApplet#size(int, int) + */ + public void hint(int which) { + if (recorder != null) recorder.hint(which); + g.hint(which); + } + + + /** + * Start a new shape of type POLYGON + */ + public void beginShape() { + if (recorder != null) recorder.beginShape(); + g.beginShape(); + } + + + /** + * Start a new shape. + *

+ * Differences between beginShape() and line() and point() methods. + *

+ * beginShape() is intended to be more flexible at the expense of being + * a little more complicated to use. it handles more complicated shapes + * that can consist of many connected lines (so you get joins) or lines + * mixed with curves. + *

+ * The line() and point() command are for the far more common cases + * (particularly for our audience) that simply need to draw a line + * or a point on the screen. + *

+ * From the code side of things, line() may or may not call beginShape() + * to do the drawing. In the beta code, they do, but in the alpha code, + * they did not. they might be implemented one way or the other depending + * on tradeoffs of runtime efficiency vs. implementation efficiency &mdash + * meaning the speed that things run at vs. the speed it takes me to write + * the code and maintain it. for beta, the latter is most important so + * that's how things are implemented. + */ + public void beginShape(int kind) { + if (recorder != null) recorder.beginShape(kind); + g.beginShape(kind); + } + + + /** + * Sets whether the upcoming vertex is part of an edge. + * Equivalent to glEdgeFlag(), for people familiar with OpenGL. + */ + public void edge(boolean edge) { + if (recorder != null) recorder.edge(edge); + g.edge(edge); + } + + + /** + * Sets the current normal vector. Only applies with 3D rendering + * and inside a beginShape/endShape block. + *

+ * This is for drawing three dimensional shapes and surfaces, + * allowing you to specify a vector perpendicular to the surface + * of the shape, which determines how lighting affects it. + *

+ * For the most part, PGraphics3D will attempt to automatically + * assign normals to shapes, but since that's imperfect, + * this is a better option when you want more control. + *

+ * For people familiar with OpenGL, this function is basically + * identical to glNormal3f(). + */ + public void normal(float nx, float ny, float nz) { + if (recorder != null) recorder.normal(nx, ny, nz); + g.normal(nx, ny, nz); + } + + + /** + * Set texture mode to either to use coordinates based on the IMAGE + * (more intuitive for new users) or NORMALIZED (better for advanced chaps) + */ + public void textureMode(int mode) { + if (recorder != null) recorder.textureMode(mode); + g.textureMode(mode); + } + + + /** + * Set texture image for current shape. + * Needs to be called between @see beginShape and @see endShape + * + * @param image reference to a PImage object + */ + public void texture(PImage image) { + if (recorder != null) recorder.texture(image); + g.texture(image); + } + + + public void vertex(float x, float y) { + if (recorder != null) recorder.vertex(x, y); + g.vertex(x, y); + } + + + public void vertex(float x, float y, float z) { + if (recorder != null) recorder.vertex(x, y, z); + g.vertex(x, y, z); + } + + + /** + * Used by renderer subclasses or PShape to efficiently pass in already + * formatted vertex information. + * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT + */ + public void vertex(float[] v) { + if (recorder != null) recorder.vertex(v); + g.vertex(v); + } + + + public void vertex(float x, float y, float u, float v) { + if (recorder != null) recorder.vertex(x, y, u, v); + g.vertex(x, y, u, v); + } + + + public void vertex(float x, float y, float z, float u, float v) { + if (recorder != null) recorder.vertex(x, y, z, u, v); + g.vertex(x, y, z, u, v); + } + + + /** This feature is in testing, do not use or rely upon its implementation */ + public void breakShape() { + if (recorder != null) recorder.breakShape(); + g.breakShape(); + } + + + public void endShape() { + if (recorder != null) recorder.endShape(); + g.endShape(); + } + + + public void endShape(int mode) { + if (recorder != null) recorder.endShape(mode); + g.endShape(mode); + } + + + public void bezierVertex(float x2, float y2, + float x3, float y3, + float x4, float y4) { + if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); + g.bezierVertex(x2, y2, x3, y3, x4, y4); + } + + + public void bezierVertex(float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); + g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); + } + + + public void curveVertex(float x, float y) { + if (recorder != null) recorder.curveVertex(x, y); + g.curveVertex(x, y); + } + + + public void curveVertex(float x, float y, float z) { + if (recorder != null) recorder.curveVertex(x, y, z); + g.curveVertex(x, y, z); + } + + + public void point(float x, float y) { + if (recorder != null) recorder.point(x, y); + g.point(x, y); + } + + + /** + * Draws a point, a coordinate in space at the dimension of one pixel. + * The first parameter is the horizontal value for the point, the second + * value is the vertical value for the point, and the optional third value + * is the depth value. Drawing this shape in 3D using the z + * parameter requires the P3D or OPENGL parameter in combination with + * size as shown in the above example. + *

Due to what appears to be a bug in Apple's Java implementation, + * the point() and set() methods are extremely slow in some circumstances + * when used with the default renderer. Using P2D or P3D will fix the + * problem. Grouping many calls to point() or set() together can also + * help. (Bug 1094) + * + * @webref shape:2d_primitives + * @param x x-coordinate of the point + * @param y y-coordinate of the point + * @param z z-coordinate of the point + * + * @see PGraphics#beginShape() + */ + public void point(float x, float y, float z) { + if (recorder != null) recorder.point(x, y, z); + g.point(x, y, z); + } + + + public void line(float x1, float y1, float x2, float y2) { + if (recorder != null) recorder.line(x1, y1, x2, y2); + g.line(x1, y1, x2, y2); + } + + + /** + * Draws a line (a direct path between two points) to the screen. + * The version of line() with four parameters draws the line in 2D. + * To color a line, use the stroke() function. A line cannot be + * filled, therefore the fill() method will not affect the color + * of a line. 2D lines are drawn with a width of one pixel by default, + * but this can be changed with the strokeWeight() function. + * The version with six parameters allows the line to be placed anywhere + * within XYZ space. Drawing this shape in 3D using the z parameter + * requires the P3D or OPENGL parameter in combination with size as shown + * in the above example. + * + * @webref shape:2d_primitives + * @param x1 x-coordinate of the first point + * @param y1 y-coordinate of the first point + * @param z1 z-coordinate of the first point + * @param x2 x-coordinate of the second point + * @param y2 y-coordinate of the second point + * @param z2 z-coordinate of the second point + * + * @see PGraphics#strokeWeight(float) + * @see PGraphics#strokeJoin(int) + * @see PGraphics#strokeCap(int) + * @see PGraphics#beginShape() + */ + public void line(float x1, float y1, float z1, + float x2, float y2, float z2) { + if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); + g.line(x1, y1, z1, x2, y2, z2); + } + + + /** + * A triangle is a plane created by connecting three points. The first two + * arguments specify the first point, the middle two arguments specify + * the second point, and the last two arguments specify the third point. + * + * @webref shape:2d_primitives + * @param x1 x-coordinate of the first point + * @param y1 y-coordinate of the first point + * @param x2 x-coordinate of the second point + * @param y2 y-coordinate of the second point + * @param x3 x-coordinate of the third point + * @param y3 y-coordinate of the third point + * + * @see PApplet#beginShape() + */ + public void triangle(float x1, float y1, float x2, float y2, + float x3, float y3) { + if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); + g.triangle(x1, y1, x2, y2, x3, y3); + } + + + /** + * A quad is a quadrilateral, a four sided polygon. It is similar to + * a rectangle, but the angles between its edges are not constrained + * ninety degrees. The first pair of parameters (x1,y1) sets the + * first vertex and the subsequent pairs should proceed clockwise or + * counter-clockwise around the defined shape. + * + * @webref shape:2d_primitives + * @param x1 x-coordinate of the first corner + * @param y1 y-coordinate of the first corner + * @param x2 x-coordinate of the second corner + * @param y2 y-coordinate of the second corner + * @param x3 x-coordinate of the third corner + * @param y3 y-coordinate of the third corner + * @param x4 x-coordinate of the fourth corner + * @param y4 y-coordinate of the fourth corner + * + */ + public void quad(float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4) { + if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); + g.quad(x1, y1, x2, y2, x3, y3, x4, y4); + } + + + public void rectMode(int mode) { + if (recorder != null) recorder.rectMode(mode); + g.rectMode(mode); + } + + + /** + * Draws a rectangle to the screen. A rectangle is a four-sided shape with + * every angle at ninety degrees. The first two parameters set the location, + * the third sets the width, and the fourth sets the height. The origin is + * changed with the rectMode() function. + * + * @webref shape:2d_primitives + * @param a x-coordinate of the rectangle + * @param b y-coordinate of the rectangle + * @param c width of the rectangle + * @param d height of the rectangle + * + * @see PGraphics#rectMode(int) + * @see PGraphics#quad(float, float, float, float, float, float, float, float) + */ + public void rect(float a, float b, float c, float d) { + if (recorder != null) recorder.rect(a, b, c, d); + g.rect(a, b, c, d); + } + + + public void rect(float a, float b, float c, float d, float hr, float vr) { + if (recorder != null) recorder.rect(a, b, c, d, hr, vr); + g.rect(a, b, c, d, hr, vr); + } + + + public void rect(float a, float b, float c, float d, + float tl, float tr, float bl, float br) { + if (recorder != null) recorder.rect(a, b, c, d, tl, tr, bl, br); + g.rect(a, b, c, d, tl, tr, bl, br); + } + + + /** + * The origin of the ellipse is modified by the ellipseMode() + * function. The default configuration is ellipseMode(CENTER), + * which specifies the location of the ellipse as the center of the shape. + * The RADIUS mode is the same, but the width and height parameters to + * ellipse() specify the radius of the ellipse, rather than the + * diameter. The CORNER mode draws the shape from the upper-left corner + * of its bounding box. The CORNERS mode uses the four parameters to + * ellipse() to set two opposing corners of the ellipse's bounding + * box. The parameter must be written in "ALL CAPS" because Processing + * syntax is case sensitive. + * + * @webref shape:attributes + * + * @param mode Either CENTER, RADIUS, CORNER, or CORNERS. + * @see PApplet#ellipse(float, float, float, float) + */ + public void ellipseMode(int mode) { + if (recorder != null) recorder.ellipseMode(mode); + g.ellipseMode(mode); + } + + + /** + * Draws an ellipse (oval) in the display window. An ellipse with an equal + * width and height is a circle. The first two parameters set + * the location, the third sets the width, and the fourth sets the height. + * The origin may be changed with the ellipseMode() function. + * + * @webref shape:2d_primitives + * @param a x-coordinate of the ellipse + * @param b y-coordinate of the ellipse + * @param c width of the ellipse + * @param d height of the ellipse + * + * @see PApplet#ellipseMode(int) + */ + public void ellipse(float a, float b, float c, float d) { + if (recorder != null) recorder.ellipse(a, b, c, d); + g.ellipse(a, b, c, d); + } + + + /** + * Draws an arc in the display window. + * Arcs are drawn along the outer edge of an ellipse defined by the + * x, y, width and height parameters. + * The origin or the arc's ellipse may be changed with the + * ellipseMode() function. + * The start and stop parameters specify the angles + * at which to draw the arc. + * + * @webref shape:2d_primitives + * @param a x-coordinate of the arc's ellipse + * @param b y-coordinate of the arc's ellipse + * @param c width of the arc's ellipse + * @param d height of the arc's ellipse + * @param start angle to start the arc, specified in radians + * @param stop angle to stop the arc, specified in radians + * + * @see PGraphics#ellipseMode(int) + * @see PGraphics#ellipse(float, float, float, float) + */ + public void arc(float a, float b, float c, float d, + float start, float stop) { + if (recorder != null) recorder.arc(a, b, c, d, start, stop); + g.arc(a, b, c, d, start, stop); + } + + + /** + * @param size dimension of the box in all dimensions, creates a cube + */ + public void box(float size) { + if (recorder != null) recorder.box(size); + g.box(size); + } + + + /** + * A box is an extruded rectangle. A box with equal dimension + * on all sides is a cube. + * + * @webref shape:3d_primitives + * @param w dimension of the box in the x-dimension + * @param h dimension of the box in the y-dimension + * @param d dimension of the box in the z-dimension + * + * @see PApplet#sphere(float) + */ + public void box(float w, float h, float d) { + if (recorder != null) recorder.box(w, h, d); + g.box(w, h, d); + } + + + /** + * @param res number of segments (minimum 3) used per full circle revolution + */ + public void sphereDetail(int res) { + if (recorder != null) recorder.sphereDetail(res); + g.sphereDetail(res); + } + + + /** + * Controls the detail used to render a sphere by adjusting the number of + * vertices of the sphere mesh. The default resolution is 30, which creates + * a fairly detailed sphere definition with vertices every 360/30 = 12 + * degrees. If you're going to render a great number of spheres per frame, + * it is advised to reduce the level of detail using this function. + * The setting stays active until sphereDetail() is called again with + * a new parameter and so should not be called prior to every + * sphere() statement, unless you wish to render spheres with + * different settings, e.g. using less detail for smaller spheres or ones + * further away from the camera. To control the detail of the horizontal + * and vertical resolution independently, use the version of the functions + * with two parameters. + * + * =advanced + * Code for sphereDetail() submitted by toxi [031031]. + * Code for enhanced u/v version from davbol [080801]. + * + * @webref shape:3d_primitives + * @param ures number of segments used horizontally (longitudinally) + * per full circle revolution + * @param vres number of segments used vertically (latitudinally) + * from top to bottom + * + * @see PGraphics#sphere(float) + */ + /** + * Set the detail level for approximating a sphere. The ures and vres params + * control the horizontal and vertical resolution. + * + */ + public void sphereDetail(int ures, int vres) { + if (recorder != null) recorder.sphereDetail(ures, vres); + g.sphereDetail(ures, vres); + } + + + /** + * Draw a sphere with radius r centered at coordinate 0, 0, 0. + * A sphere is a hollow ball made from tessellated triangles. + * =advanced + *

+ * Implementation notes: + *

+ * cache all the points of the sphere in a static array + * top and bottom are just a bunch of triangles that land + * in the center point + *

+ * sphere is a series of concentric circles who radii vary + * along the shape, based on, er.. cos or something + *

+   * [toxi 031031] new sphere code. removed all multiplies with
+   * radius, as scale() will take care of that anyway
+   *
+   * [toxi 031223] updated sphere code (removed modulos)
+   * and introduced sphereAt(x,y,z,r)
+   * to avoid additional translate()'s on the user/sketch side
+   *
+   * [davbol 080801] now using separate sphereDetailU/V
+   * 
+ * + * @webref shape:3d_primitives + * @param r the radius of the sphere + */ + public void sphere(float r) { + if (recorder != null) recorder.sphere(r); + g.sphere(r); + } + + + /** + * Evalutes quadratic bezier at point t for points a, b, c, d. + * The parameter t varies between 0 and 1. The a and d parameters are the + * on-curve points, b and c are the control points. To make a two-dimensional + * curve, call this function once with the x coordinates and a second time + * with the y coordinates to get the location of a bezier curve at t. + * + * =advanced + * For instance, to convert the following example:
+   * stroke(255, 102, 0);
+   * line(85, 20, 10, 10);
+   * line(90, 90, 15, 80);
+   * stroke(0, 0, 0);
+   * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+   *
+   * // draw it in gray, using 10 steps instead of the default 20
+   * // this is a slower way to do it, but useful if you need
+   * // to do things with the coordinates at each step
+   * stroke(128);
+   * beginShape(LINE_STRIP);
+   * for (int i = 0; i <= 10; i++) {
+   *   float t = i / 10.0f;
+   *   float x = bezierPoint(85, 10, 90, 15, t);
+   *   float y = bezierPoint(20, 10, 90, 80, t);
+   *   vertex(x, y);
+   * }
+   * endShape();
+ * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of first control point + * @param c coordinate of second control point + * @param d coordinate of second point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#bezierVertex(float, float, float, float, float, float) + * @see PGraphics#curvePoint(float, float, float, float, float) + */ + public float bezierPoint(float a, float b, float c, float d, float t) { + return g.bezierPoint(a, b, c, d, t); + } + + + /** + * Calculates the tangent of a point on a Bezier curve. There is a good + * definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent + * + * =advanced + * Code submitted by Dave Bollinger (davol) for release 0136. + * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of first control point + * @param c coordinate of second control point + * @param d coordinate of second point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#bezierVertex(float, float, float, float, float, float) + * @see PGraphics#curvePoint(float, float, float, float, float) + */ + public float bezierTangent(float a, float b, float c, float d, float t) { + return g.bezierTangent(a, b, c, d, t); + } + + + /** + * Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the P3D or OPENGL renderer as the default (JAVA2D) renderer does not use this information. + * + * @webref shape:curves + * @param detail resolution of the curves + * + * @see PApplet#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PApplet#curveVertex(float, float) + * @see PApplet#curveTightness(float) + */ + public void bezierDetail(int detail) { + if (recorder != null) recorder.bezierDetail(detail); + g.bezierDetail(detail); + } + + + /** + * Draws a Bezier curve on the screen. These curves are defined by a series + * of anchor and control points. The first two parameters specify the first + * anchor point and the last two parameters specify the other anchor point. + * The middle parameters specify the control points which define the shape + * of the curve. Bezier curves were developed by French engineer Pierre + * Bezier. Using the 3D version of requires rendering with P3D or OPENGL + * (see the Environment reference for more information). + * + * =advanced + * Draw a cubic bezier curve. The first and last points are + * the on-curve points. The middle two are the 'control' points, + * or 'handles' in an application like Illustrator. + *

+ * Identical to typing: + *

beginShape();
+   * vertex(x1, y1);
+   * bezierVertex(x2, y2, x3, y3, x4, y4);
+   * endShape();
+   * 
+ * In Postscript-speak, this would be: + *
moveto(x1, y1);
+   * curveto(x2, y2, x3, y3, x4, y4);
+ * If you were to try and continue that curve like so: + *
curveto(x5, y5, x6, y6, x7, y7);
+ * This would be done in processing by adding these statements: + *
bezierVertex(x5, y5, x6, y6, x7, y7)
+   * 
+ * To draw a quadratic (instead of cubic) curve, + * use the control point twice by doubling it: + *
bezier(x1, y1, cx, cy, cx, cy, x2, y2);
+ * + * @webref shape:curves + * @param x1 coordinates for the first anchor point + * @param y1 coordinates for the first anchor point + * @param z1 coordinates for the first anchor point + * @param x2 coordinates for the first control point + * @param y2 coordinates for the first control point + * @param z2 coordinates for the first control point + * @param x3 coordinates for the second control point + * @param y3 coordinates for the second control point + * @param z3 coordinates for the second control point + * @param x4 coordinates for the second anchor point + * @param y4 coordinates for the second anchor point + * @param z4 coordinates for the second anchor point + * + * @see PGraphics#bezierVertex(float, float, float, float, float, float) + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + */ + public void bezier(float x1, float y1, + float x2, float y2, + float x3, float y3, + float x4, float y4) { + if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); + g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); + } + + + public void bezier(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); + g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); + } + + + /** + * Evalutes the Catmull-Rom curve at point t for points a, b, c, d. The + * parameter t varies between 0 and 1, a and d are points on the curve, + * and b and c are the control points. This can be done once with the x + * coordinates and a second time with the y coordinates to get the + * location of a curve at t. + * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of second point on the curve + * @param c coordinate of third point on the curve + * @param d coordinate of fourth point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#bezierPoint(float, float, float, float, float) + */ + public float curvePoint(float a, float b, float c, float d, float t) { + return g.curvePoint(a, b, c, d, t); + } + + + /** + * Calculates the tangent of a point on a Catmull-Rom curve. There is a good definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent. + * + * =advanced + * Code thanks to Dave Bollinger (Bug #715) + * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of first control point + * @param c coordinate of second control point + * @param d coordinate of second point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#curvePoint(float, float, float, float, float) + * @see PGraphics#bezierTangent(float, float, float, float, float) + */ + public float curveTangent(float a, float b, float c, float d, float t) { + return g.curveTangent(a, b, c, d, t); + } + + + /** + * Sets the resolution at which curves display. The default value is 20. + * This function is only useful when using the P3D or OPENGL renderer as + * the default (JAVA2D) renderer does not use this information. + * + * @webref shape:curves + * @param detail resolution of the curves + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#curveTightness(float) + */ + public void curveDetail(int detail) { + if (recorder != null) recorder.curveDetail(detail); + g.curveDetail(detail); + } + + + /** + * Modifies the quality of forms created with curve() and + *curveVertex(). The parameter squishy determines how the + * curve fits to the vertex points. The value 0.0 is the default value for + * squishy (this value defines the curves to be Catmull-Rom splines) + * and the value 1.0 connects all the points with straight lines. + * Values within the range -5.0 and 5.0 will deform the curves but + * will leave them recognizable and as values increase in magnitude, + * they will continue to deform. + * + * @webref shape:curves + * @param tightness amount of deformation from the original vertices + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * + */ + public void curveTightness(float tightness) { + if (recorder != null) recorder.curveTightness(tightness); + g.curveTightness(tightness); + } + + + /** + * Draws a curved line on the screen. The first and second parameters + * specify the beginning control point and the last two parameters specify + * the ending control point. The middle parameters specify the start and + * stop of the curve. Longer curves can be created by putting a series of + * curve() functions together or using curveVertex(). + * An additional function called curveTightness() provides control + * for the visual quality of the curve. The curve() function is an + * implementation of Catmull-Rom splines. Using the 3D version of requires + * rendering with P3D or OPENGL (see the Environment reference for more + * information). + * + * =advanced + * As of revision 0070, this function no longer doubles the first + * and last points. The curves are a bit more boring, but it's more + * mathematically correct, and properly mirrored in curvePoint(). + *

+ * Identical to typing out:

+   * beginShape();
+   * curveVertex(x1, y1);
+   * curveVertex(x2, y2);
+   * curveVertex(x3, y3);
+   * curveVertex(x4, y4);
+   * endShape();
+   * 
+ * + * @webref shape:curves + * @param x1 coordinates for the beginning control point + * @param y1 coordinates for the beginning control point + * @param z1 coordinates for the beginning control point + * @param x2 coordinates for the first point + * @param y2 coordinates for the first point + * @param z2 coordinates for the first point + * @param x3 coordinates for the second point + * @param y3 coordinates for the second point + * @param z3 coordinates for the second point + * @param x4 coordinates for the ending control point + * @param y4 coordinates for the ending control point + * @param z4 coordinates for the ending control point + * + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#curveTightness(float) + * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) + */ + public void curve(float x1, float y1, + float x2, float y2, + float x3, float y3, + float x4, float y4) { + if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); + g.curve(x1, y1, x2, y2, x3, y3, x4, y4); + } + + + public void curve(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); + g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); + } + + + /** + * If true in PImage, use bilinear interpolation for copy() + * operations. When inherited by PGraphics, also controls shapes. + */ + public void smooth() { + if (recorder != null) recorder.smooth(); + g.smooth(); + } + + + /** + * Disable smoothing. See smooth(). + */ + public void noSmooth() { + if (recorder != null) recorder.noSmooth(); + g.noSmooth(); + } + + + /** + * Modifies the location from which images draw. The default mode is + * imageMode(CORNER), which specifies the location to be the + * upper-left corner and uses the fourth and fifth parameters of + * image() to set the image's width and height. The syntax + * imageMode(CORNERS) uses the second and third parameters of + * image() to set the location of one corner of the image and + * uses the fourth and fifth parameters to set the opposite corner. + * Use imageMode(CENTER) to draw images centered at the given + * x and y position. + *

The parameter to imageMode() must be written in + * ALL CAPS because Processing syntax is case sensitive. + * + * @webref image:loading_displaying + * @param mode Either CORNER, CORNERS, or CENTER + * + * @see processing.core.PApplet#loadImage(String, String) + * @see processing.core.PImage + * @see processing.core.PApplet#image(PImage, float, float, float, float) + * @see processing.core.PGraphics#background(float, float, float, float) + */ + public void imageMode(int mode) { + if (recorder != null) recorder.imageMode(mode); + g.imageMode(mode); + } + + + public void image(PImage image, float x, float y) { + if (recorder != null) recorder.image(image, x, y); + g.image(image, x, y); + } + + + /** + * Displays images to the screen. The images must be in the sketch's "data" + * directory to load correctly. Select "Add file..." from the "Sketch" menu + * to add the image. Processing currently works with GIF, JPEG, and Targa + * images. The color of an image may be modified with the tint() + * function and if a GIF has transparency, it will maintain its transparency. + * The img parameter specifies the image to display and the x + * and y parameters define the location of the image from its + * upper-left corner. The image is displayed at its original size unless + * the width and height parameters specify a different size. + * The imageMode() function changes the way the parameters work. + * A call to imageMode(CORNERS) will change the width and height + * parameters to define the x and y values of the opposite corner of the + * image. + * + * =advanced + * Starting with release 0124, when using the default (JAVA2D) renderer, + * smooth() will also improve image quality of resized images. + * + * @webref image:loading_displaying + * @param image the image to display + * @param x x-coordinate of the image + * @param y y-coordinate of the image + * @param c width to display the image + * @param d height to display the image + * + * @see processing.core.PApplet#loadImage(String, String) + * @see processing.core.PImage + * @see processing.core.PGraphics#imageMode(int) + * @see processing.core.PGraphics#tint(float) + * @see processing.core.PGraphics#background(float, float, float, float) + * @see processing.core.PGraphics#alpha(int) + */ + public void image(PImage image, float x, float y, float c, float d) { + if (recorder != null) recorder.image(image, x, y, c, d); + g.image(image, x, y, c, d); + } + + + /** + * Draw an image(), also specifying u/v coordinates. + * In this method, the u, v coordinates are always based on image space + * location, regardless of the current textureMode(). + */ + public void image(PImage image, + float a, float b, float c, float d, + int u1, int v1, int u2, int v2) { + if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2); + g.image(image, a, b, c, d, u1, v1, u2, v2); + } + + + /** + * Modifies the location from which shapes draw. + * The default mode is shapeMode(CORNER), which specifies the + * location to be the upper left corner of the shape and uses the third + * and fourth parameters of shape() to specify the width and height. + * The syntax shapeMode(CORNERS) uses the first and second parameters + * of shape() to set the location of one corner and uses the third + * and fourth parameters to set the opposite corner. + * The syntax shapeMode(CENTER) draws the shape from its center point + * and uses the third and forth parameters of shape() to specify the + * width and height. + * The parameter must be written in "ALL CAPS" because Processing syntax + * is case sensitive. + * + * @param mode One of CORNER, CORNERS, CENTER + * + * @webref shape:loading_displaying + * @see PGraphics#shape(PShape) + * @see PGraphics#rectMode(int) + */ + public void shapeMode(int mode) { + if (recorder != null) recorder.shapeMode(mode); + g.shapeMode(mode); + } + + + public void shape(PShape shape) { + if (recorder != null) recorder.shape(shape); + g.shape(shape); + } + + + /** + * Convenience method to draw at a particular location. + */ + public void shape(PShape shape, float x, float y) { + if (recorder != null) recorder.shape(shape, x, y); + g.shape(shape, x, y); + } + + + /** + * Displays shapes to the screen. The shapes must be in the sketch's "data" + * directory to load correctly. Select "Add file..." from the "Sketch" menu + * to add the shape. + * Processing currently works with SVG shapes only. + * The sh parameter specifies the shape to display and the x + * and y parameters define the location of the shape from its + * upper-left corner. + * The shape is displayed at its original size unless the width + * and height parameters specify a different size. + * The shapeMode() function changes the way the parameters work. + * A call to shapeMode(CORNERS), for example, will change the width + * and height parameters to define the x and y values of the opposite corner + * of the shape. + *

+ * Note complex shapes may draw awkwardly with P2D, P3D, and OPENGL. Those + * renderers do not yet support shapes that have holes or complicated breaks. + * + * @param shape + * @param x x-coordinate of the shape + * @param y y-coordinate of the shape + * @param c width to display the shape + * @param d height to display the shape + * + * @webref shape:loading_displaying + * @see PShape + * @see PGraphics#loadShape(String) + * @see PGraphics#shapeMode(int) + */ + public void shape(PShape shape, float x, float y, float c, float d) { + if (recorder != null) recorder.shape(shape, x, y, c, d); + g.shape(shape, x, y, c, d); + } + + + /** + * Sets the alignment of the text to one of LEFT, CENTER, or RIGHT. + * This will also reset the vertical text alignment to BASELINE. + */ + public void textAlign(int align) { + if (recorder != null) recorder.textAlign(align); + g.textAlign(align); + } + + + /** + * Sets the horizontal and vertical alignment of the text. The horizontal + * alignment can be one of LEFT, CENTER, or RIGHT. The vertical alignment + * can be TOP, BOTTOM, CENTER, or the BASELINE (the default). + */ + public void textAlign(int alignX, int alignY) { + if (recorder != null) recorder.textAlign(alignX, alignY); + g.textAlign(alignX, alignY); + } + + + /** + * Returns the ascent of the current font at the current size. + * This is a method, rather than a variable inside the PGraphics object + * because it requires calculation. + */ + public float textAscent() { + return g.textAscent(); + } + + + /** + * Returns the descent of the current font at the current size. + * This is a method, rather than a variable inside the PGraphics object + * because it requires calculation. + */ + public float textDescent() { + return g.textDescent(); + } + + + /** + * Sets the current font. The font's size will be the "natural" + * size of this font (the size that was set when using "Create Font"). + * The leading will also be reset. + */ + public void textFont(PFont which) { + if (recorder != null) recorder.textFont(which); + g.textFont(which); + } + + + /** + * Useful function to set the font and size at the same time. + */ + public void textFont(PFont which, float size) { + if (recorder != null) recorder.textFont(which, size); + g.textFont(which, size); + } + + + /** + * Set the text leading to a specific value. If using a custom + * value for the text leading, you'll have to call textLeading() + * again after any calls to textSize(). + */ + public void textLeading(float leading) { + if (recorder != null) recorder.textLeading(leading); + g.textLeading(leading); + } + + + /** + * Sets the text rendering/placement to be either SCREEN (direct + * to the screen, exact coordinates, only use the font's original size) + * or MODEL (the default, where text is manipulated by translate() and + * can have a textSize). The text size cannot be set when using + * textMode(SCREEN), because it uses the pixels directly from the font. + */ + public void textMode(int mode) { + if (recorder != null) recorder.textMode(mode); + g.textMode(mode); + } + + + /** + * Sets the text size, also resets the value for the leading. + */ + public void textSize(float size) { + if (recorder != null) recorder.textSize(size); + g.textSize(size); + } + + + public float textWidth(char c) { + return g.textWidth(c); + } + + + /** + * Return the width of a line of text. If the text has multiple + * lines, this returns the length of the longest line. + */ + public float textWidth(String str) { + return g.textWidth(str); + } + + + /** + * TODO not sure if this stays... + */ + public float textWidth(char[] chars, int start, int length) { + return g.textWidth(chars, start, length); + } + + + /** + * Write text where we just left off. + */ + public void text(char c) { + if (recorder != null) recorder.text(c); + g.text(c); + } + + + /** + * Draw a single character on screen. + * Extremely slow when used with textMode(SCREEN) and Java 2D, + * because loadPixels has to be called first and updatePixels last. + */ + public void text(char c, float x, float y) { + if (recorder != null) recorder.text(c, x, y); + g.text(c, x, y); + } + + + /** + * Draw a single character on screen (with a z coordinate) + */ + public void text(char c, float x, float y, float z) { + if (recorder != null) recorder.text(c, x, y, z); + g.text(c, x, y, z); + } + + + /** + * Write text where we just left off. + */ + public void text(String str) { + if (recorder != null) recorder.text(str); + g.text(str); + } + + + /** + * Draw a chunk of text. + * Newlines that are \n (Unix newline or linefeed char, ascii 10) + * are honored, but \r (carriage return, Windows and Mac OS) are + * ignored. + */ + public void text(String str, float x, float y) { + if (recorder != null) recorder.text(str, x, y); + g.text(str, x, y); + } + + + /** + * Method to draw text from an array of chars. This method will usually be + * more efficient than drawing from a String object, because the String will + * not be converted to a char array before drawing. + */ + public void text(char[] chars, int start, int stop, float x, float y) { + if (recorder != null) recorder.text(chars, start, stop, x, y); + g.text(chars, start, stop, x, y); + } + + + /** + * Same as above but with a z coordinate. + */ + public void text(String str, float x, float y, float z) { + if (recorder != null) recorder.text(str, x, y, z); + g.text(str, x, y, z); + } + + + public void text(char[] chars, int start, int stop, + float x, float y, float z) { + if (recorder != null) recorder.text(chars, start, stop, x, y, z); + g.text(chars, start, stop, x, y, z); + } + + + /** + * Draw text in a box that is constrained to a particular size. + * The current rectMode() determines what the coordinates mean + * (whether x1/y1/x2/y2 or x/y/w/h). + *

+ * Note that the x,y coords of the start of the box + * will align with the *ascent* of the text, not the baseline, + * as is the case for the other text() functions. + *

+ * Newlines that are \n (Unix newline or linefeed char, ascii 10) + * are honored, and \r (carriage return, Windows and Mac OS) are + * ignored. + */ + public void text(String str, float x1, float y1, float x2, float y2) { + if (recorder != null) recorder.text(str, x1, y1, x2, y2); + g.text(str, x1, y1, x2, y2); + } + + + public void text(String s, float x1, float y1, float x2, float y2, float z) { + if (recorder != null) recorder.text(s, x1, y1, x2, y2, z); + g.text(s, x1, y1, x2, y2, z); + } + + + public void text(int num, float x, float y) { + if (recorder != null) recorder.text(num, x, y); + g.text(num, x, y); + } + + + public void text(int num, float x, float y, float z) { + if (recorder != null) recorder.text(num, x, y, z); + g.text(num, x, y, z); + } + + + /** + * This does a basic number formatting, to avoid the + * generally ugly appearance of printing floats. + * Users who want more control should use their own nf() cmmand, + * or if they want the long, ugly version of float, + * use String.valueOf() to convert the float to a String first. + */ + public void text(float num, float x, float y) { + if (recorder != null) recorder.text(num, x, y); + g.text(num, x, y); + } + + + public void text(float num, float x, float y, float z) { + if (recorder != null) recorder.text(num, x, y, z); + g.text(num, x, y, z); + } + + + /** + * Push a copy of the current transformation matrix onto the stack. + */ + public void pushMatrix() { + if (recorder != null) recorder.pushMatrix(); + g.pushMatrix(); + } + + + /** + * Replace the current transformation matrix with the top of the stack. + */ + public void popMatrix() { + if (recorder != null) recorder.popMatrix(); + g.popMatrix(); + } + + + /** + * Translate in X and Y. + */ + public void translate(float tx, float ty) { + if (recorder != null) recorder.translate(tx, ty); + g.translate(tx, ty); + } + + + /** + * Translate in X, Y, and Z. + */ + public void translate(float tx, float ty, float tz) { + if (recorder != null) recorder.translate(tx, ty, tz); + g.translate(tx, ty, tz); + } + + + /** + * Two dimensional rotation. + * + * Same as rotateZ (this is identical to a 3D rotation along the z-axis) + * but included for clarity. It'd be weird for people drawing 2D graphics + * to be using rotateZ. And they might kick our a-- for the confusion. + * + * Additional background. + */ + public void rotate(float angle) { + if (recorder != null) recorder.rotate(angle); + g.rotate(angle); + } + + + /** + * Rotate around the X axis. + */ + public void rotateX(float angle) { + if (recorder != null) recorder.rotateX(angle); + g.rotateX(angle); + } + + + /** + * Rotate around the Y axis. + */ + public void rotateY(float angle) { + if (recorder != null) recorder.rotateY(angle); + g.rotateY(angle); + } + + + /** + * Rotate around the Z axis. + * + * The functions rotate() and rotateZ() are identical, it's just that it make + * sense to have rotate() and then rotateX() and rotateY() when using 3D; + * nor does it make sense to use a function called rotateZ() if you're only + * doing things in 2D. so we just decided to have them both be the same. + */ + public void rotateZ(float angle) { + if (recorder != null) recorder.rotateZ(angle); + g.rotateZ(angle); + } + + + /** + * Rotate about a vector in space. Same as the glRotatef() function. + */ + public void rotate(float angle, float vx, float vy, float vz) { + if (recorder != null) recorder.rotate(angle, vx, vy, vz); + g.rotate(angle, vx, vy, vz); + } + + + /** + * Scale in all dimensions. + */ + public void scale(float s) { + if (recorder != null) recorder.scale(s); + g.scale(s); + } + + + /** + * Scale in X and Y. Equivalent to scale(sx, sy, 1). + * + * Not recommended for use in 3D, because the z-dimension is just + * scaled by 1, since there's no way to know what else to scale it by. + */ + public void scale(float sx, float sy) { + if (recorder != null) recorder.scale(sx, sy); + g.scale(sx, sy); + } + + + /** + * Scale in X, Y, and Z. + */ + public void scale(float x, float y, float z) { + if (recorder != null) recorder.scale(x, y, z); + g.scale(x, y, z); + } + + + /** + * Shear along X axis + */ + public void shearX(float angle) { + if (recorder != null) recorder.shearX(angle); + g.shearX(angle); + } + + + /** + * Shear along Y axis + */ + public void shearY(float angle) { + if (recorder != null) recorder.shearY(angle); + g.shearY(angle); + } + + + /** + * Set the current transformation matrix to identity. + */ + public void resetMatrix() { + if (recorder != null) recorder.resetMatrix(); + g.resetMatrix(); + } + + + public void applyMatrix(PMatrix source) { + if (recorder != null) recorder.applyMatrix(source); + g.applyMatrix(source); + } + + + public void applyMatrix(PMatrix2D source) { + if (recorder != null) recorder.applyMatrix(source); + g.applyMatrix(source); + } + + + /** + * Apply a 3x2 affine transformation matrix. + */ + public void applyMatrix(float n00, float n01, float n02, + float n10, float n11, float n12) { + if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); + g.applyMatrix(n00, n01, n02, n10, n11, n12); + } + + + public void applyMatrix(PMatrix3D source) { + if (recorder != null) recorder.applyMatrix(source); + g.applyMatrix(source); + } + + + /** + * Apply a 4x4 transformation matrix. + */ + public void applyMatrix(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); + g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); + } + + + public PMatrix getMatrix() { + return g.getMatrix(); + } + + + /** + * Copy the current transformation matrix into the specified target. + * Pass in null to create a new matrix. + */ + public PMatrix2D getMatrix(PMatrix2D target) { + return g.getMatrix(target); + } + + + /** + * Copy the current transformation matrix into the specified target. + * Pass in null to create a new matrix. + */ + public PMatrix3D getMatrix(PMatrix3D target) { + return g.getMatrix(target); + } + + + /** + * Set the current transformation matrix to the contents of another. + */ + public void setMatrix(PMatrix source) { + if (recorder != null) recorder.setMatrix(source); + g.setMatrix(source); + } + + + /** + * Set the current transformation to the contents of the specified source. + */ + public void setMatrix(PMatrix2D source) { + if (recorder != null) recorder.setMatrix(source); + g.setMatrix(source); + } + + + /** + * Set the current transformation to the contents of the specified source. + */ + public void setMatrix(PMatrix3D source) { + if (recorder != null) recorder.setMatrix(source); + g.setMatrix(source); + } + + + /** + * Print the current model (or "transformation") matrix. + */ + public void printMatrix() { + if (recorder != null) recorder.printMatrix(); + g.printMatrix(); + } + + + public void beginCamera() { + if (recorder != null) recorder.beginCamera(); + g.beginCamera(); + } + + + public void endCamera() { + if (recorder != null) recorder.endCamera(); + g.endCamera(); + } + + + public void camera() { + if (recorder != null) recorder.camera(); + g.camera(); + } + + + public void camera(float eyeX, float eyeY, float eyeZ, + float centerX, float centerY, float centerZ, + float upX, float upY, float upZ) { + if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); + g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); + } + + + public void printCamera() { + if (recorder != null) recorder.printCamera(); + g.printCamera(); + } + + + public void ortho() { + if (recorder != null) recorder.ortho(); + g.ortho(); + } + + + public void ortho(float left, float right, + float bottom, float top, + float near, float far) { + if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); + g.ortho(left, right, bottom, top, near, far); + } + + + public void perspective() { + if (recorder != null) recorder.perspective(); + g.perspective(); + } + + + public void perspective(float fovy, float aspect, float zNear, float zFar) { + if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); + g.perspective(fovy, aspect, zNear, zFar); + } + + + public void frustum(float left, float right, + float bottom, float top, + float near, float far) { + if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); + g.frustum(left, right, bottom, top, near, far); + } + + + public void printProjection() { + if (recorder != null) recorder.printProjection(); + g.printProjection(); + } + + + /** + * Given an x and y coordinate, returns the x position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenX(float x, float y) { + return g.screenX(x, y); + } + + + /** + * Given an x and y coordinate, returns the y position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenY(float x, float y) { + return g.screenY(x, y); + } + + + /** + * Maps a three dimensional point to its placement on-screen. + *

+ * Given an (x, y, z) coordinate, returns the x position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenX(float x, float y, float z) { + return g.screenX(x, y, z); + } + + + /** + * Maps a three dimensional point to its placement on-screen. + *

+ * Given an (x, y, z) coordinate, returns the y position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenY(float x, float y, float z) { + return g.screenY(x, y, z); + } + + + /** + * Maps a three dimensional point to its placement on-screen. + *

+ * Given an (x, y, z) coordinate, returns its z value. + * This value can be used to determine if an (x, y, z) coordinate + * is in front or in back of another (x, y, z) coordinate. + * The units are based on how the zbuffer is set up, and don't + * relate to anything "real". They're only useful for in + * comparison to another value obtained from screenZ(), + * or directly out of the zbuffer[]. + */ + public float screenZ(float x, float y, float z) { + return g.screenZ(x, y, z); + } + + + /** + * Returns the model space x value for an x, y, z coordinate. + *

+ * This will give you a coordinate after it has been transformed + * by translate(), rotate(), and camera(), but not yet transformed + * by the projection matrix. For instance, his can be useful for + * figuring out how points in 3D space relate to the edge + * coordinates of a shape. + */ + public float modelX(float x, float y, float z) { + return g.modelX(x, y, z); + } + + + /** + * Returns the model space y value for an x, y, z coordinate. + */ + public float modelY(float x, float y, float z) { + return g.modelY(x, y, z); + } + + + /** + * Returns the model space z value for an x, y, z coordinate. + */ + public float modelZ(float x, float y, float z) { + return g.modelZ(x, y, z); + } + + + public void pushStyle() { + if (recorder != null) recorder.pushStyle(); + g.pushStyle(); + } + + + public void popStyle() { + if (recorder != null) recorder.popStyle(); + g.popStyle(); + } + + + public void style(PStyle s) { + if (recorder != null) recorder.style(s); + g.style(s); + } + + + public void strokeWeight(float weight) { + if (recorder != null) recorder.strokeWeight(weight); + g.strokeWeight(weight); + } + + + public void strokeJoin(int join) { + if (recorder != null) recorder.strokeJoin(join); + g.strokeJoin(join); + } + + + public void strokeCap(int cap) { + if (recorder != null) recorder.strokeCap(cap); + g.strokeCap(cap); + } + + + /** + * Disables drawing the stroke (outline). If both noStroke() and + * noFill() are called, no shapes will be drawn to the screen. + * + * @webref color:setting + * + * @see PGraphics#stroke(float, float, float, float) + */ + public void noStroke() { + if (recorder != null) recorder.noStroke(); + g.noStroke(); + } + + + /** + * Set the tint to either a grayscale or ARGB value. + * See notes attached to the fill() function. + * @param rgb color value in hexadecimal notation + * (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype + */ + public void stroke(int rgb) { + if (recorder != null) recorder.stroke(rgb); + g.stroke(rgb); + } + + + public void stroke(int rgb, float alpha) { + if (recorder != null) recorder.stroke(rgb, alpha); + g.stroke(rgb, alpha); + } + + + /** + * + * @param gray specifies a value between white and black + */ + public void stroke(float gray) { + if (recorder != null) recorder.stroke(gray); + g.stroke(gray); + } + + + public void stroke(float gray, float alpha) { + if (recorder != null) recorder.stroke(gray, alpha); + g.stroke(gray, alpha); + } + + + public void stroke(float x, float y, float z) { + if (recorder != null) recorder.stroke(x, y, z); + g.stroke(x, y, z); + } + + + /** + * Sets the color used to draw lines and borders around shapes. This color + * is either specified in terms of the RGB or HSB color depending on the + * current colorMode() (the default color space is RGB, with each + * value in the range from 0 to 255). + *

When using hexadecimal notation to specify a color, use "#" or + * "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six + * digits to specify a color (the way colors are specified in HTML and CSS). + * When using the hexadecimal notation starting with "0x", the hexadecimal + * value must be specified with eight characters; the first two characters + * define the alpha component and the remainder the red, green, and blue + * components. + *

The value for the parameter "gray" must be less than or equal + * to the current maximum value as specified by colorMode(). + * The default maximum value is 255. + * + * @webref color:setting + * @param alpha opacity of the stroke + * @param x red or hue value (depending on the current color mode) + * @param y green or saturation value (depending on the current color mode) + * @param z blue or brightness value (depending on the current color mode) + */ + public void stroke(float x, float y, float z, float a) { + if (recorder != null) recorder.stroke(x, y, z, a); + g.stroke(x, y, z, a); + } + + + /** + * Removes the current fill value for displaying images and reverts to displaying images with their original hues. + * + * @webref image:loading_displaying + * @see processing.core.PGraphics#tint(float, float, float, float) + * @see processing.core.PGraphics#image(PImage, float, float, float, float) + */ + public void noTint() { + if (recorder != null) recorder.noTint(); + g.noTint(); + } + + + /** + * Set the tint to either a grayscale or ARGB value. + */ + public void tint(int rgb) { + if (recorder != null) recorder.tint(rgb); + g.tint(rgb); + } + + + /** + * @param rgb color value in hexadecimal notation + * (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype + * @param alpha opacity of the image + */ + public void tint(int rgb, float alpha) { + if (recorder != null) recorder.tint(rgb, alpha); + g.tint(rgb, alpha); + } + + + /** + * @param gray any valid number + */ + public void tint(float gray) { + if (recorder != null) recorder.tint(gray); + g.tint(gray); + } + + + public void tint(float gray, float alpha) { + if (recorder != null) recorder.tint(gray, alpha); + g.tint(gray, alpha); + } + + + public void tint(float x, float y, float z) { + if (recorder != null) recorder.tint(x, y, z); + g.tint(x, y, z); + } + + + /** + * Sets the fill value for displaying images. Images can be tinted to + * specified colors or made transparent by setting the alpha. + *

To make an image transparent, but not change it's color, + * use white as the tint color and specify an alpha value. For instance, + * tint(255, 128) will make an image 50% transparent (unless + * colorMode() has been used). + * + *

When using hexadecimal notation to specify a color, use "#" or + * "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six + * digits to specify a color (the way colors are specified in HTML and CSS). + * When using the hexadecimal notation starting with "0x", the hexadecimal + * value must be specified with eight characters; the first two characters + * define the alpha component and the remainder the red, green, and blue + * components. + *

The value for the parameter "gray" must be less than or equal + * to the current maximum value as specified by colorMode(). + * The default maximum value is 255. + *

The tint() method is also used to control the coloring of + * textures in 3D. + * + * @webref image:loading_displaying + * @param x red or hue value + * @param y green or saturation value + * @param z blue or brightness value + * + * @see processing.core.PGraphics#noTint() + * @see processing.core.PGraphics#image(PImage, float, float, float, float) + */ + public void tint(float x, float y, float z, float a) { + if (recorder != null) recorder.tint(x, y, z, a); + g.tint(x, y, z, a); + } + + + /** + * Disables filling geometry. If both noStroke() and noFill() + * are called, no shapes will be drawn to the screen. + * + * @webref color:setting + * + * @see PGraphics#fill(float, float, float, float) + * + */ + public void noFill() { + if (recorder != null) recorder.noFill(); + g.noFill(); + } + + + /** + * Set the fill to either a grayscale value or an ARGB int. + * @param rgb color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype + */ + public void fill(int rgb) { + if (recorder != null) recorder.fill(rgb); + g.fill(rgb); + } + + + public void fill(int rgb, float alpha) { + if (recorder != null) recorder.fill(rgb, alpha); + g.fill(rgb, alpha); + } + + + /** + * @param gray number specifying value between white and black + */ + public void fill(float gray) { + if (recorder != null) recorder.fill(gray); + g.fill(gray); + } + + + public void fill(float gray, float alpha) { + if (recorder != null) recorder.fill(gray, alpha); + g.fill(gray, alpha); + } + + + public void fill(float x, float y, float z) { + if (recorder != null) recorder.fill(x, y, z); + g.fill(x, y, z); + } + + + /** + * Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all subsequent shapes will be filled with orange. This color is either specified in terms of the RGB or HSB color depending on the current colorMode() (the default color space is RGB, with each value in the range from 0 to 255). + *

When using hexadecimal notation to specify a color, use "#" or "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six digits to specify a color (the way colors are specified in HTML and CSS). When using the hexadecimal notation starting with "0x", the hexadecimal value must be specified with eight characters; the first two characters define the alpha component and the remainder the red, green, and blue components. + *

The value for the parameter "gray" must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. + *

To change the color of an image (or a texture), use tint(). + * + * @webref color:setting + * @param x red or hue value + * @param y green or saturation value + * @param z blue or brightness value + * @param alpha opacity of the fill + * + * @see PGraphics#noFill() + * @see PGraphics#stroke(float) + * @see PGraphics#tint(float) + * @see PGraphics#background(float, float, float, float) + * @see PGraphics#colorMode(int, float, float, float, float) + */ + public void fill(float x, float y, float z, float a) { + if (recorder != null) recorder.fill(x, y, z, a); + g.fill(x, y, z, a); + } + + + public void ambient(int rgb) { + if (recorder != null) recorder.ambient(rgb); + g.ambient(rgb); + } + + + public void ambient(float gray) { + if (recorder != null) recorder.ambient(gray); + g.ambient(gray); + } + + + public void ambient(float x, float y, float z) { + if (recorder != null) recorder.ambient(x, y, z); + g.ambient(x, y, z); + } + + + public void specular(int rgb) { + if (recorder != null) recorder.specular(rgb); + g.specular(rgb); + } + + + public void specular(float gray) { + if (recorder != null) recorder.specular(gray); + g.specular(gray); + } + + + public void specular(float x, float y, float z) { + if (recorder != null) recorder.specular(x, y, z); + g.specular(x, y, z); + } + + + public void shininess(float shine) { + if (recorder != null) recorder.shininess(shine); + g.shininess(shine); + } + + + public void emissive(int rgb) { + if (recorder != null) recorder.emissive(rgb); + g.emissive(rgb); + } + + + public void emissive(float gray) { + if (recorder != null) recorder.emissive(gray); + g.emissive(gray); + } + + + public void emissive(float x, float y, float z) { + if (recorder != null) recorder.emissive(x, y, z); + g.emissive(x, y, z); + } + + + public void lights() { + if (recorder != null) recorder.lights(); + g.lights(); + } + + + public void noLights() { + if (recorder != null) recorder.noLights(); + g.noLights(); + } + + + public void ambientLight(float red, float green, float blue) { + if (recorder != null) recorder.ambientLight(red, green, blue); + g.ambientLight(red, green, blue); + } + + + public void ambientLight(float red, float green, float blue, + float x, float y, float z) { + if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z); + g.ambientLight(red, green, blue, x, y, z); + } + + + public void directionalLight(float red, float green, float blue, + float nx, float ny, float nz) { + if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz); + g.directionalLight(red, green, blue, nx, ny, nz); + } + + + public void pointLight(float red, float green, float blue, + float x, float y, float z) { + if (recorder != null) recorder.pointLight(red, green, blue, x, y, z); + g.pointLight(red, green, blue, x, y, z); + } + + + public void spotLight(float red, float green, float blue, + float x, float y, float z, + float nx, float ny, float nz, + float angle, float concentration) { + if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); + g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); + } + + + public void lightFalloff(float constant, float linear, float quadratic) { + if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); + g.lightFalloff(constant, linear, quadratic); + } + + + public void lightSpecular(float x, float y, float z) { + if (recorder != null) recorder.lightSpecular(x, y, z); + g.lightSpecular(x, y, z); + } + + + /** + * Set the background to a gray or ARGB color. + *

+ * For the main drawing surface, the alpha value will be ignored. However, + * alpha can be used on PGraphics objects from createGraphics(). This is + * the only way to set all the pixels partially transparent, for instance. + *

+ * Note that background() should be called before any transformations occur, + * because some implementations may require the current transformation matrix + * to be identity before drawing. + * + * @param rgb color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00)
or any value of the color datatype + */ + public void background(int rgb) { + if (recorder != null) recorder.background(rgb); + g.background(rgb); + } + + + /** + * See notes about alpha in background(x, y, z, a). + */ + public void background(int rgb, float alpha) { + if (recorder != null) recorder.background(rgb, alpha); + g.background(rgb, alpha); + } + + + /** + * Set the background to a grayscale value, based on the + * current colorMode. + */ + public void background(float gray) { + if (recorder != null) recorder.background(gray); + g.background(gray); + } + + + /** + * See notes about alpha in background(x, y, z, a). + * @param gray specifies a value between white and black + * @param alpha opacity of the background + */ + public void background(float gray, float alpha) { + if (recorder != null) recorder.background(gray, alpha); + g.background(gray, alpha); + } + + + /** + * Set the background to an r, g, b or h, s, b value, + * based on the current colorMode. + */ + public void background(float x, float y, float z) { + if (recorder != null) recorder.background(x, y, z); + g.background(x, y, z); + } + + + /** + * The background() function sets the color used for the background of the Processing window. The default background is light gray. In the draw() function, the background color is used to clear the display window at the beginning of each frame. + *

An image can also be used as the background for a sketch, however its width and height must be the same size as the sketch window. To resize an image 'b' to the size of the sketch window, use b.resize(width, height). + *

Images used as background will ignore the current tint() setting. + *

It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with createGraphics. + * + * =advanced + *

Clear the background with a color that includes an alpha value. This can + * only be used with objects created by createGraphics(), because the main + * drawing surface cannot be set transparent.

+ *

It might be tempting to use this function to partially clear the screen + * on each frame, however that's not how this function works. When calling + * background(), the pixels will be replaced with pixels that have that level + * of transparency. To do a semi-transparent overlay, use fill() with alpha + * and draw a rectangle.

+ * + * @webref color:setting + * @param x red or hue value (depending on the current color mode) + * @param y green or saturation value (depending on the current color mode) + * @param z blue or brightness value (depending on the current color mode) + * + * @see PGraphics#stroke(float) + * @see PGraphics#fill(float) + * @see PGraphics#tint(float) + * @see PGraphics#colorMode(int) + */ + public void background(float x, float y, float z, float a) { + if (recorder != null) recorder.background(x, y, z, a); + g.background(x, y, z, a); + } + + + /** + * Takes an RGB or ARGB image and sets it as the background. + * The width and height of the image must be the same size as the sketch. + * Use image.resize(width, height) to make short work of such a task. + *

+ * Note that even if the image is set as RGB, the high 8 bits of each pixel + * should be set opaque (0xFF000000), because the image data will be copied + * directly to the screen, and non-opaque background images may have strange + * behavior. Using image.filter(OPAQUE) will handle this easily. + *

+ * When using 3D, this will also clear the zbuffer (if it exists). + */ + public void background(PImage image) { + if (recorder != null) recorder.background(image); + g.background(image); + } + + + /** + * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness + * @param max range for all color elements + */ + public void colorMode(int mode) { + if (recorder != null) recorder.colorMode(mode); + g.colorMode(mode); + } + + + public void colorMode(int mode, float max) { + if (recorder != null) recorder.colorMode(mode, max); + g.colorMode(mode, max); + } + + + /** + * Set the colorMode and the maximum values for (r, g, b) + * or (h, s, b). + *

+ * Note that this doesn't set the maximum for the alpha value, + * which might be confusing if for instance you switched to + *

colorMode(HSB, 360, 100, 100);
+ * because the alpha values were still between 0 and 255. + */ + public void colorMode(int mode, float maxX, float maxY, float maxZ) { + if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ); + g.colorMode(mode, maxX, maxY, maxZ); + } + + + /** + * Changes the way Processing interprets color data. By default, the parameters for fill(), stroke(), background(), and color() are defined by values between 0 and 255 using the RGB color model. The colorMode() function is used to change the numerical range used for specifying colors and to switch color systems. For example, calling colorMode(RGB, 1.0) will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the parameters range1, range2, range3, and range 4. + * + * @webref color:setting + * @param maxX range for the red or hue depending on the current color mode + * @param maxY range for the green or saturation depending on the current color mode + * @param maxZ range for the blue or brightness depending on the current color mode + * @param maxA range for the alpha + * + * @see PGraphics#background(float) + * @see PGraphics#fill(float) + * @see PGraphics#stroke(float) + */ + public void colorMode(int mode, + float maxX, float maxY, float maxZ, float maxA) { + if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA); + g.colorMode(mode, maxX, maxY, maxZ, maxA); + } + + + /** + * Extracts the alpha value from a color. + * + * @webref color:creating_reading + * @param what any value of the color datatype + */ + public final float alpha(int what) { + return g.alpha(what); + } + + + /** + * Extracts the red value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.

The red() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use the >> (right shift) operator with a bit mask. For example, the following two lines of code are equivalent:
float r1 = red(myColor);
float r2 = myColor >> 16 & 0xFF;
+ * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + * @ref rightshift + */ + public final float red(int what) { + return g.red(what); + } + + + /** + * Extracts the green value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.

The green() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use the >> (right shift) operator with a bit mask. For example, the following two lines of code are equivalent:
float r1 = green(myColor);
float r2 = myColor >> 8 & 0xFF;
+ * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + * @ref rightshift + */ + public final float green(int what) { + return g.green(what); + } + + + /** + * Extracts the blue value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.

The blue() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use a bit mask to remove the other color components. For example, the following two lines of code are equivalent:
float r1 = blue(myColor);
float r2 = myColor & 0xFF;
+ * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + */ + public final float blue(int what) { + return g.blue(what); + } + + + /** + * Extracts the hue value from a color. + * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + */ + public final float hue(int what) { + return g.hue(what); + } + + + /** + * Extracts the saturation value from a color. + * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#brightness(int) + */ + public final float saturation(int what) { + return g.saturation(what); + } + + + /** + * Extracts the brightness value from a color. + * + * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + */ + public final float brightness(int what) { + return g.brightness(what); + } + + + /** + * Calculates a color or colors between two color at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. + * + * @webref color:creating_reading + * @param c1 interpolate from this color + * @param c2 interpolate to this color + * @param amt between 0.0 and 1.0 + * + * @see PGraphics#blendColor(int, int, int) + * @see PGraphics#color(float, float, float, float) + */ + public int lerpColor(int c1, int c2, float amt) { + return g.lerpColor(c1, c2, amt); + } + + + /** + * Interpolate between two colors. Like lerp(), but for the + * individual color components of a color supplied as an int value. + */ + static public int lerpColor(int c1, int c2, float amt, int mode) { + return PGraphics.lerpColor(c1, c2, amt, mode); + } + + + /** + * Return true if this renderer should be drawn to the screen. Defaults to + * returning true, since nearly all renderers are on-screen beasts. But can + * be overridden for subclasses like PDF so that a window doesn't open up. + *

+ * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, + * what to call this? + */ + public boolean displayable() { + return g.displayable(); + } + + + /** + * Store data of some kind for a renderer that requires extra metadata of + * some kind. Usually this is a renderer-specific representation of the + * image data, for instance a BufferedImage with tint() settings applied for + * PGraphicsJava2D, or resized image data and OpenGL texture indices for + * PGraphicsOpenGL. + */ + public void setCache(Object parent, Object storage) { + if (recorder != null) recorder.setCache(parent, storage); + g.setCache(parent, storage); + } + + + /** + * Get cache storage data for the specified renderer. Because each renderer + * will cache data in different formats, it's necessary to store cache data + * keyed by the renderer object. Otherwise, attempting to draw the same + * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. + * @param parent The PGraphics object (or any object, really) associated + * @return data stored for the specified parent + */ + public Object getCache(Object parent) { + return g.getCache(parent); + } + + + /** + * Remove information associated with this renderer from the cache, if any. + * @param parent The PGraphics object whose cache data should be removed + */ + public void removeCache(Object parent) { + if (recorder != null) recorder.removeCache(parent); + g.removeCache(parent); + } + + + /** + * Returns an ARGB "color" type (a packed 32 bit int with the color. + * If the coordinate is outside the image, zero is returned + * (black, but completely transparent). + *

+ * If the image is in RGB format (i.e. on a PVideo object), + * the value will get its high bits set, just to avoid cases where + * they haven't been set already. + *

+ * If the image is in ALPHA format, this returns a white with its + * alpha value set. + *

+ * This function is included primarily for beginners. It is quite + * slow because it has to check to see if the x, y that was provided + * is inside the bounds, and then has to check to see what image + * type it is. If you want things to be more efficient, access the + * pixels[] array directly. + */ + public int get(int x, int y) { + return g.get(x, y); + } + + + /** + * Reads the color of any pixel or grabs a group of pixels. If no parameters are specified, the entire image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display window by specifing an additional width and height parameter. If the pixel requested is outside of the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. Even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB. + *

Getting the color of a single pixel with get(x, y) is easy, but not as fast as grabbing the data directly from pixels[]. The equivalent statement to "get(x, y)" using pixels[] is "pixels[y*width+x]". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values. + *

As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Reads the color of any pixel or grabs a rectangle of pixels + * @param x x-coordinate of the pixel + * @param y y-coordinate of the pixel + * @param w width of pixel rectangle to get + * @param h height of pixel rectangle to get + * + * @see processing.core.PImage#set(int, int, int) + * @see processing.core.PImage#pixels + * @see processing.core.PImage#copy(PImage, int, int, int, int, int, int, int, int) + */ + public PImage get(int x, int y, int w, int h) { + return g.get(x, y, w, h); + } + + + /** + * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). + */ + public PImage get() { + return g.get(); + } + + + /** + * Changes the color of any pixel or writes an image directly into the display window. The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). When setting an image, the x and y parameters define the coordinates for the upper-left corner of the image. + *

Setting the color of a single pixel with set(x, y) is easy, but not as fast as putting the data directly into pixels[]. The equivalent statement to "set(x, y, #000000)" using pixels[] is "pixels[y*width+x] = #000000". You must call loadPixels() to load the display window data into the pixels[] array before setting the values and calling updatePixels() to update the window with any changes. + *

As of release 1.0, this function ignores imageMode(). + *

Due to what appears to be a bug in Apple's Java implementation, the point() and set() methods are extremely slow in some circumstances when used with the default renderer. Using P2D or P3D will fix the problem. Grouping many calls to point() or set() together can also help. (Bug 1094) + * =advanced + *

As of release 0149, this function ignores imageMode(). + * + * @webref image:pixels + * @param x x-coordinate of the pixel + * @param y y-coordinate of the pixel + * @param c any value of the color datatype + */ + public void set(int x, int y, int c) { + if (recorder != null) recorder.set(x, y, c); + g.set(x, y, c); + } + + + /** + * Efficient method of drawing an image's pixels directly to this surface. + * No variations are employed, meaning that any scale, tint, or imageMode + * settings will be ignored. + */ + public void set(int x, int y, PImage src) { + if (recorder != null) recorder.set(x, y, src); + g.set(x, y, src); + } + + + /** + * Set alpha channel for an image. Black colors in the source + * image will make the destination image completely transparent, + * and white will make things fully opaque. Gray values will + * be in-between steps. + *

+ * Strictly speaking the "blue" value from the source image is + * used as the alpha color. For a fully grayscale image, this + * is correct, but for a color image it's not 100% accurate. + * For a more accurate conversion, first use filter(GRAY) + * which will make the image into a "correct" grayscale by + * performing a proper luminance-based conversion. + * + * @param maskArray any array of Integer numbers used as the alpha channel, needs to be same length as the image's pixel array + */ + public void mask(int maskArray[]) { + if (recorder != null) recorder.mask(maskArray); + g.mask(maskArray); + } + + + /** + * Masks part of an image from displaying by loading another image and using it as an alpha channel. + * This mask image should only contain grayscale data, but only the blue color channel is used. + * The mask image needs to be the same size as the image to which it is applied. + * In addition to using a mask image, an integer array containing the alpha channel data can be specified directly. + * This method is useful for creating dynamically generated alpha masks. + * This array must be of the same length as the target image's pixels array and should contain only grayscale data of values between 0-255. + * @webref + * @brief Masks part of the image from displaying + * @param maskImg any PImage object used as the alpha channel for "img", needs to be same size as "img" + */ + public void mask(PImage maskImg) { + if (recorder != null) recorder.mask(maskImg); + g.mask(maskImg); + } + + + public void filter(int kind) { + if (recorder != null) recorder.filter(kind); + g.filter(kind); + } + + + /** + * Filters an image as defined by one of the following modes:

THRESHOLD - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0(white). If no level is specified, 0.5 is used.

GRAY - converts any colors in the image to grayscale equivalents

INVERT - sets each pixel to its inverse value

POSTERIZE - limits each channel of the image to the number of colors specified as the level parameter

BLUR - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1.

OPAQUE - sets the alpha channel to entirely opaque.

ERODE - reduces the light areas with the amount defined by the level parameter.

DILATE - increases the light areas with the amount defined by the level parameter + * =advanced + * Method to apply a variety of basic filters to this image. + *

+ *

    + *
  • filter(BLUR) provides a basic blur. + *
  • filter(GRAY) converts the image to grayscale based on luminance. + *
  • filter(INVERT) will invert the color components in the image. + *
  • filter(OPAQUE) set all the high bits in the image to opaque + *
  • filter(THRESHOLD) converts the image to black and white. + *
  • filter(DILATE) grow white/light areas + *
  • filter(ERODE) shrink white/light areas + *
+ * Luminance conversion code contributed by + * toxi + *

+ * Gaussian blur code contributed by + * Mario Klingemann + * + * @webref + * @brief Converts the image to grayscale or black and white + * @param kind Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE + * @param param in the range from 0 to 1 + */ + public void filter(int kind, float param) { + if (recorder != null) recorder.filter(kind, param); + g.filter(kind, param); + } + + + /** + * Copy things from one area of this image + * to another area in the same image. + */ + public void copy(int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh) { + if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); + g.copy(sx, sy, sw, sh, dx, dy, dw, dh); + } + + + /** + * Copies a region of pixels from one image into another. If the source and destination regions aren't the same size, it will automatically resize source pixels to fit the specified target region. No alpha information is used in the process, however if the source image has an alpha channel set, it will be copied as well. + *

As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Copies the entire image + * @param sx X coordinate of the source's upper left corner + * @param sy Y coordinate of the source's upper left corner + * @param sw source image width + * @param sh source image height + * @param dx X coordinate of the destination's upper left corner + * @param dy Y coordinate of the destination's upper left corner + * @param dw destination image width + * @param dh destination image height + * @param src an image variable referring to the source image. + * + * @see processing.core.PGraphics#alpha(int) + * @see processing.core.PImage#blend(PImage, int, int, int, int, int, int, int, int, int) + */ + public void copy(PImage src, + int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh) { + if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); + g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); + } + + + /** + * Blend two colors based on a particular mode. + *

    + *
  • REPLACE - destination colour equals colour of source pixel: C = A. + * Sometimes called "Normal" or "Copy" in other software. + * + *
  • BLEND - linear interpolation of colours: + * C = A*factor + B + * + *
  • ADD - additive blending with white clip: + * C = min(A*factor + B, 255). + * Clipped to 0..255, Photoshop calls this "Linear Burn", + * and Director calls it "Add Pin". + * + *
  • SUBTRACT - substractive blend with black clip: + * C = max(B - A*factor, 0). + * Clipped to 0..255, Photoshop calls this "Linear Dodge", + * and Director calls it "Subtract Pin". + * + *
  • DARKEST - only the darkest colour succeeds: + * C = min(A*factor, B). + * Illustrator calls this "Darken". + * + *
  • LIGHTEST - only the lightest colour succeeds: + * C = max(A*factor, B). + * Illustrator calls this "Lighten". + * + *
  • DIFFERENCE - subtract colors from underlying image. + * + *
  • EXCLUSION - similar to DIFFERENCE, but less extreme. + * + *
  • MULTIPLY - Multiply the colors, result will always be darker. + * + *
  • SCREEN - Opposite multiply, uses inverse values of the colors. + * + *
  • OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, + * and screens light values. + * + *
  • HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. + * + *
  • SOFT_LIGHT - Mix of DARKEST and LIGHTEST. + * Works like OVERLAY, but not as harsh. + * + *
  • DODGE - Lightens light tones and increases contrast, ignores darks. + * Called "Color Dodge" in Illustrator and Photoshop. + * + *
  • BURN - Darker areas are applied, increasing contrast, ignores lights. + * Called "Color Burn" in Illustrator and Photoshop. + *
+ *

A useful reference for blending modes and their algorithms can be + * found in the SVG + * specification.

+ *

It is important to note that Processing uses "fast" code, not + * necessarily "correct" code. No biggie, most software does. A nitpicker + * can find numerous "off by 1 division" problems in the blend code where + * >>8 or >>7 is used when strictly speaking + * /255.0 or /127.0 should have been used.

+ *

For instance, exclusion (not intended for real-time use) reads + * r1 + r2 - ((2 * r1 * r2) / 255) because 255 == 1.0 + * not 256 == 1.0. In other words, (255*255)>>8 is not + * the same as (255*255)/255. But for real-time use the shifts + * are preferrable, and the difference is insignificant for applications + * built with Processing.

+ */ + static public int blendColor(int c1, int c2, int mode) { + return PGraphics.blendColor(c1, c2, mode); + } + + + /** + * Blends one area of this image to another area. + * + * @see processing.core.PImage#blendColor(int,int,int) + */ + public void blend(int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh, int mode) { + if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); + g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); + } + + + /** + * Blends a region of pixels into the image specified by the img parameter. These copies utilize full alpha channel support and a choice of the following modes to blend the colors of source pixels (A) with the ones of pixels in the destination image (B):

+ * BLEND - linear interpolation of colours: C = A*factor + B

+ * ADD - additive blending with white clip: C = min(A*factor + B, 255)

+ * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0)

+ * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)

+ * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)

+ * DIFFERENCE - subtract colors from underlying image.

+ * EXCLUSION - similar to DIFFERENCE, but less extreme.

+ * MULTIPLY - Multiply the colors, result will always be darker.

+ * SCREEN - Opposite multiply, uses inverse values of the colors.

+ * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values.

+ * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.

+ * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh.

+ * DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop.

+ * BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop.

+ * All modes use the alpha information (highest byte) of source image pixels as the blending factor. If the source and destination regions are different sizes, the image will be automatically resized to match the destination size. If the srcImg parameter is not used, the display window is used as the source image.

+ * As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Copies a pixel or rectangle of pixels using different blending modes + * @param src an image variable referring to the source image + * @param sx X coordinate of the source's upper left corner + * @param sy Y coordinate of the source's upper left corner + * @param sw source image width + * @param sh source image height + * @param dx X coordinate of the destinations's upper left corner + * @param dy Y coordinate of the destinations's upper left corner + * @param dw destination image width + * @param dh destination image height + * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN + * + * @see processing.core.PGraphics#alpha(int) + * @see processing.core.PGraphics#copy(PImage, int, int, int, int, int, int, int, int) + * @see processing.core.PImage#blendColor(int,int,int) + */ + public void blend(PImage src, + int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh, int mode) { + if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); + g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); + } +} diff --git a/support/Processing_core_src/processing/core/PConstants.java b/support/Processing_core_src/processing/core/PConstants.java new file mode 100644 index 0000000..f1eae58 --- /dev/null +++ b/support/Processing_core_src/processing/core/PConstants.java @@ -0,0 +1,504 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-08 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.Cursor; +import java.awt.event.KeyEvent; + + +/** + * Numbers shared throughout processing.core. + *

+ * An attempt is made to keep the constants as short/non-verbose + * as possible. For instance, the constant is TIFF instead of + * FILE_TYPE_TIFF. We'll do this as long as we can get away with it. + * + * @usage Web & Application + */ +public interface PConstants { + + static public final int X = 0; // model coords xyz (formerly MX/MY/MZ) + static public final int Y = 1; + static public final int Z = 2; + + static public final int R = 3; // actual rgb, after lighting + static public final int G = 4; // fill stored here, transform in place + static public final int B = 5; // TODO don't do that anymore (?) + static public final int A = 6; + + static public final int U = 7; // texture + static public final int V = 8; + + static public final int NX = 9; // normal + static public final int NY = 10; + static public final int NZ = 11; + + static public final int EDGE = 12; + + + // stroke + + /** stroke argb values */ + static public final int SR = 13; + static public final int SG = 14; + static public final int SB = 15; + static public final int SA = 16; + + /** stroke weight */ + static public final int SW = 17; + + + // transformations (2D and 3D) + + static public final int TX = 18; // transformed xyzw + static public final int TY = 19; + static public final int TZ = 20; + + static public final int VX = 21; // view space coords + static public final int VY = 22; + static public final int VZ = 23; + static public final int VW = 24; + + + // material properties + + // Ambient color (usually to be kept the same as diffuse) + // fill(_) sets both ambient and diffuse. + static public final int AR = 25; + static public final int AG = 26; + static public final int AB = 27; + + // Diffuse is shared with fill. + static public final int DR = 3; // TODO needs to not be shared, this is a material property + static public final int DG = 4; + static public final int DB = 5; + static public final int DA = 6; + + // specular (by default kept white) + static public final int SPR = 28; + static public final int SPG = 29; + static public final int SPB = 30; + + static public final int SHINE = 31; + + // emissive (by default kept black) + static public final int ER = 32; + static public final int EG = 33; + static public final int EB = 34; + + // has this vertex been lit yet + static public final int BEEN_LIT = 35; + + static public final int VERTEX_FIELD_COUNT = 36; + + + // renderers known to processing.core + + static final String P2D = "processing.core.PGraphics2D"; + static final String P3D = "processing.core.PGraphics3D"; + static final String JAVA2D = "processing.core.PGraphicsJava2D"; + static final String OPENGL = "processing.opengl.PGraphicsOpenGL"; + static final String PDF = "processing.pdf.PGraphicsPDF"; + static final String DXF = "processing.dxf.RawDXF"; + + + // platform IDs for PApplet.platform + + static final int OTHER = 0; + static final int WINDOWS = 1; + static final int MACOSX = 2; + static final int LINUX = 3; + + static final String[] platformNames = { + "other", "windows", "macosx", "linux" + }; + + + static final float EPSILON = 0.0001f; + + + // max/min values for numbers + + /** + * Same as Float.MAX_VALUE, but included for parity with MIN_VALUE, + * and to avoid teaching static methods on the first day. + */ + static final float MAX_FLOAT = Float.MAX_VALUE; + /** + * Note that Float.MIN_VALUE is the smallest positive value + * for a floating point number, not actually the minimum (negative) value + * for a float. This constant equals 0xFF7FFFFF, the smallest (farthest + * negative) value a float can have before it hits NaN. + */ + static final float MIN_FLOAT = -Float.MAX_VALUE; + /** Largest possible (positive) integer value */ + static final int MAX_INT = Integer.MAX_VALUE; + /** Smallest possible (negative) integer value */ + static final int MIN_INT = Integer.MIN_VALUE; + + + // useful goodness + + /** + * PI is a mathematical constant with the value 3.14159265358979323846. + * It is the ratio of the circumference of a circle to its diameter. + * It is useful in combination with the trigonometric functions sin() and cos(). + * + * @webref constants + * @see processing.core.PConstants#HALF_PI + * @see processing.core.PConstants#TWO_PI + * @see processing.core.PConstants#QUARTER_PI + * + */ + static final float PI = (float) Math.PI; + /** + * HALF_PI is a mathematical constant with the value 1.57079632679489661923. + * It is half the ratio of the circumference of a circle to its diameter. + * It is useful in combination with the trigonometric functions sin() and cos(). + * + * @webref constants + * @see processing.core.PConstants#PI + * @see processing.core.PConstants#TWO_PI + * @see processing.core.PConstants#QUARTER_PI + */ + static final float HALF_PI = PI / 2.0f; + static final float THIRD_PI = PI / 3.0f; + /** + * QUARTER_PI is a mathematical constant with the value 0.7853982. + * It is one quarter the ratio of the circumference of a circle to its diameter. + * It is useful in combination with the trigonometric functions sin() and cos(). + * + * @webref constants + * @see processing.core.PConstants#PI + * @see processing.core.PConstants#TWO_PI + * @see processing.core.PConstants#HALF_PI + */ + static final float QUARTER_PI = PI / 4.0f; + /** + * TWO_PI is a mathematical constant with the value 6.28318530717958647693. + * It is twice the ratio of the circumference of a circle to its diameter. + * It is useful in combination with the trigonometric functions sin() and cos(). + * + * @webref constants + * @see processing.core.PConstants#PI + * @see processing.core.PConstants#HALF_PI + * @see processing.core.PConstants#QUARTER_PI + */ + static final float TWO_PI = PI * 2.0f; + + static final float DEG_TO_RAD = PI/180.0f; + static final float RAD_TO_DEG = 180.0f/PI; + + + // angle modes + + //static final int RADIANS = 0; + //static final int DEGREES = 1; + + + // used by split, all the standard whitespace chars + // (also includes unicode nbsp, that little bostage) + + static final String WHITESPACE = " \t\n\r\f\u00A0"; + + + // for colors and/or images + + static final int RGB = 1; // image & color + static final int ARGB = 2; // image + static final int HSB = 3; // color + static final int ALPHA = 4; // image + static final int CMYK = 5; // image & color (someday) + + + // image file types + + static final int TIFF = 0; + static final int TARGA = 1; + static final int JPEG = 2; + static final int GIF = 3; + + + // filter/convert types + + static final int BLUR = 11; + static final int GRAY = 12; + static final int INVERT = 13; + static final int OPAQUE = 14; + static final int POSTERIZE = 15; + static final int THRESHOLD = 16; + static final int ERODE = 17; + static final int DILATE = 18; + + + // blend mode keyword definitions + // @see processing.core.PImage#blendColor(int,int,int) + + public final static int REPLACE = 0; + public final static int BLEND = 1 << 0; + public final static int ADD = 1 << 1; + public final static int SUBTRACT = 1 << 2; + public final static int LIGHTEST = 1 << 3; + public final static int DARKEST = 1 << 4; + public final static int DIFFERENCE = 1 << 5; + public final static int EXCLUSION = 1 << 6; + public final static int MULTIPLY = 1 << 7; + public final static int SCREEN = 1 << 8; + public final static int OVERLAY = 1 << 9; + public final static int HARD_LIGHT = 1 << 10; + public final static int SOFT_LIGHT = 1 << 11; + public final static int DODGE = 1 << 12; + public final static int BURN = 1 << 13; + + // colour component bitmasks + + public static final int ALPHA_MASK = 0xff000000; + public static final int RED_MASK = 0x00ff0000; + public static final int GREEN_MASK = 0x0000ff00; + public static final int BLUE_MASK = 0x000000ff; + + + // for messages + + static final int CHATTER = 0; + static final int COMPLAINT = 1; + static final int PROBLEM = 2; + + + // types of projection matrices + + static final int CUSTOM = 0; // user-specified fanciness + static final int ORTHOGRAPHIC = 2; // 2D isometric projection + static final int PERSPECTIVE = 3; // perspective matrix + + + // shapes + + // the low four bits set the variety, + // higher bits set the specific shape type + + //static final int GROUP = (1 << 2); + + static final int POINT = 2; // shared with light (!) + static final int POINTS = 2; + + static final int LINE = 4; + static final int LINES = 4; + + static final int TRIANGLE = 8; + static final int TRIANGLES = 9; + static final int TRIANGLE_STRIP = 10; + static final int TRIANGLE_FAN = 11; + + static final int QUAD = 16; + static final int QUADS = 16; + static final int QUAD_STRIP = 17; + + static final int POLYGON = 20; + static final int PATH = 21; + + static final int RECT = 30; + static final int ELLIPSE = 31; + static final int ARC = 32; + + static final int SPHERE = 40; + static final int BOX = 41; + + + // shape closing modes + + static final int OPEN = 1; + static final int CLOSE = 2; + + + // shape drawing modes + + /** Draw mode convention to use (x, y) to (width, height) */ + static final int CORNER = 0; + /** Draw mode convention to use (x1, y1) to (x2, y2) coordinates */ + static final int CORNERS = 1; + /** Draw mode from the center, and using the radius */ + static final int RADIUS = 2; + /** @deprecated Use RADIUS instead. */ + static final int CENTER_RADIUS = 2; + /** + * Draw from the center, using second pair of values as the diameter. + * Formerly called CENTER_DIAMETER in alpha releases. + */ + static final int CENTER = 3; + /** + * Synonym for the CENTER constant. Draw from the center, + * using second pair of values as the diameter. + */ + static final int DIAMETER = 3; + /** @deprecated Use DIAMETER instead. */ + static final int CENTER_DIAMETER = 3; + + + // vertically alignment modes for text + + /** Default vertical alignment for text placement */ + static final int BASELINE = 0; + /** Align text to the top */ + static final int TOP = 101; + /** Align text from the bottom, using the baseline. */ + static final int BOTTOM = 102; + + + // uv texture orientation modes + + /** texture coordinates in 0..1 range */ + static final int NORMAL = 1; + /** @deprecated use NORMAL instead */ + static final int NORMALIZED = 1; + /** texture coordinates based on image width/height */ + static final int IMAGE = 2; + + + // text placement modes + + /** + * textMode(MODEL) is the default, meaning that characters + * will be affected by transformations like any other shapes. + *

+ * Changed value in 0093 to not interfere with LEFT, CENTER, and RIGHT. + */ + static final int MODEL = 4; + + /** + * textMode(SHAPE) draws text using the the glyph outlines of + * individual characters rather than as textures. If the outlines are + * not available, then textMode(SHAPE) will be ignored and textMode(MODEL) + * will be used instead. For this reason, be sure to call textMode() + * after calling textFont(). + *

+ * Currently, textMode(SHAPE) is only supported by OPENGL mode. + * It also requires Java 1.2 or higher (OPENGL requires 1.4 anyway) + */ + static final int SHAPE = 5; + + + // text alignment modes + // are inherited from LEFT, CENTER, RIGHT + + + // stroke modes + + static final int SQUARE = 1 << 0; // called 'butt' in the svg spec + static final int ROUND = 1 << 1; + static final int PROJECT = 1 << 2; // called 'square' in the svg spec + static final int MITER = 1 << 3; + static final int BEVEL = 1 << 5; + + + // lighting + + static final int AMBIENT = 0; + static final int DIRECTIONAL = 1; + //static final int POINT = 2; // shared with shape feature + static final int SPOT = 3; + + + // key constants + + // only including the most-used of these guys + // if people need more esoteric keys, they can learn about + // the esoteric java KeyEvent api and of virtual keys + + // both key and keyCode will equal these values + // for 0125, these were changed to 'char' values, because they + // can be upgraded to ints automatically by Java, but having them + // as ints prevented split(blah, TAB) from working + static final char BACKSPACE = 8; + static final char TAB = 9; + static final char ENTER = 10; + static final char RETURN = 13; + static final char ESC = 27; + static final char DELETE = 127; + + // i.e. if ((key == CODED) && (keyCode == UP)) + static final int CODED = 0xffff; + + // key will be CODED and keyCode will be this value + static final int UP = KeyEvent.VK_UP; + static final int DOWN = KeyEvent.VK_DOWN; + static final int LEFT = KeyEvent.VK_LEFT; + static final int RIGHT = KeyEvent.VK_RIGHT; + + // key will be CODED and keyCode will be this value + static final int ALT = KeyEvent.VK_ALT; + static final int CONTROL = KeyEvent.VK_CONTROL; + static final int SHIFT = KeyEvent.VK_SHIFT; + + + // cursor types + + static final int ARROW = Cursor.DEFAULT_CURSOR; + static final int CROSS = Cursor.CROSSHAIR_CURSOR; + static final int HAND = Cursor.HAND_CURSOR; + static final int MOVE = Cursor.MOVE_CURSOR; + static final int TEXT = Cursor.TEXT_CURSOR; + static final int WAIT = Cursor.WAIT_CURSOR; + + + // hints - hint values are positive for the alternate version, + // negative of the same value returns to the normal/default state + + static final int DISABLE_OPENGL_2X_SMOOTH = 1; + static final int ENABLE_OPENGL_2X_SMOOTH = -1; + static final int ENABLE_OPENGL_4X_SMOOTH = 2; + + static final int ENABLE_NATIVE_FONTS = 3; + + static final int DISABLE_DEPTH_TEST = 4; + static final int ENABLE_DEPTH_TEST = -4; + + static final int ENABLE_DEPTH_SORT = 5; + static final int DISABLE_DEPTH_SORT = -5; + + static final int DISABLE_OPENGL_ERROR_REPORT = 6; + static final int ENABLE_OPENGL_ERROR_REPORT = -6; + + static final int ENABLE_ACCURATE_TEXTURES = 7; + static final int DISABLE_ACCURATE_TEXTURES = -7; + + static final int HINT_COUNT = 10; + + + // error messages + + static final String ERROR_BACKGROUND_IMAGE_SIZE = + "background image must be the same size as your application"; + static final String ERROR_BACKGROUND_IMAGE_FORMAT = + "background images should be RGB or ARGB"; + + static final String ERROR_TEXTFONT_NULL_PFONT = + "A null PFont was passed to textFont()"; + + static final String ERROR_PUSHMATRIX_OVERFLOW = + "Too many calls to pushMatrix()."; + static final String ERROR_PUSHMATRIX_UNDERFLOW = + "Too many calls to popMatrix(), and not enough to pushMatrix()."; +} diff --git a/support/Processing_core_src/processing/core/PFont.java b/support/Processing_core_src/processing/core/PFont.java new file mode 100644 index 0000000..e08e650 --- /dev/null +++ b/support/Processing_core_src/processing/core/PFont.java @@ -0,0 +1,884 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-10 Ben Fry & Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of version 2.01 of the GNU Lesser General + Public License as published by the Free Software Foundation. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.*; +import java.awt.image.*; +import java.io.*; +import java.util.Arrays; +import java.util.HashMap; + + +/** + * Grayscale bitmap font class used by Processing. + *

+ * Awful (and by that, I mean awesome) ASCII (non-)art for how this works: + *

+ *   |
+ *   |                   height is the full used height of the image
+ *   |
+ *   |   ..XX..       }
+ *   |   ..XX..       }
+ *   |   ......       }
+ *   |   XXXX..       }  topExtent (top y is baseline - topExtent)
+ *   |   ..XX..       }
+ *   |   ..XX..       }  dotted areas are where the image data
+ *   |   ..XX..       }  is actually located for the character
+ *   +---XXXXXX----   }  (it extends to the right and down
+ *   |                   for power of two texture sizes)
+ *   ^^^^ leftExtent (amount to move over before drawing the image
+ *
+ *   ^^^^^^^^^^^^^^ setWidth (width displaced by char)
+ * 
+ */ +public class PFont implements PConstants { + + /** Number of character glyphs in this font. */ + protected int glyphCount; + + /** + * Actual glyph data. The length of this array won't necessarily be the + * same size as glyphCount, in cases where lazy font loading is in use. + */ + protected Glyph[] glyphs; + + /** + * Name of the font as seen by Java when it was created. + * If the font is available, the native version will be used. + */ + protected String name; + + /** + * Postscript name of the font that this bitmap was created from. + */ + protected String psname; + + /** + * The original size of the font when it was first created + */ + protected int size; + + /** true if smoothing was enabled for this font, used for native impl */ + protected boolean smooth; + + /** + * The ascent of the font. If the 'd' character is present in this PFont, + * this value is replaced with its pixel height, because the values returned + * by FontMetrics.getAscent() seem to be terrible. + */ + protected int ascent; + + /** + * The descent of the font. If the 'p' character is present in this PFont, + * this value is replaced with its lowest pixel height, because the values + * returned by FontMetrics.getDescent() are gross. + */ + protected int descent; + + /** + * A more efficient array lookup for straight ASCII characters. For Unicode + * characters, a QuickSort-style search is used. + */ + protected int[] ascii; + + /** + * True if this font is set to load dynamically. This is the default when + * createFont() method is called without a character set. Bitmap versions of + * characters are only created when prompted by an index() call. + */ + protected boolean lazy; + + /** + * Native Java version of the font. If possible, this allows the + * PGraphics subclass to just use Java's font rendering stuff + * in situations where that's faster. + */ + protected Font font; + + /** True if this font was loaded from a stream, rather than from the OS. */ + protected boolean stream; + + /** + * True if we've already tried to find the native AWT version of this font. + */ + protected boolean fontSearched; + + /** + * Array of the native system fonts. Used to lookup native fonts by their + * PostScript name. This is a workaround for a several year old Apple Java + * bug that they can't be bothered to fix. + */ + static protected Font[] fonts; + static protected HashMap fontDifferent; + + + // objects to handle creation of font characters only as they're needed + BufferedImage lazyImage; + Graphics2D lazyGraphics; + FontMetrics lazyMetrics; + int[] lazySamples; + + + public PFont() { } // for subclasses + + + /** + * Create a new Processing font from a native font, but don't create all the + * characters at once, instead wait until they're used to include them. + * @param font + * @param smooth + */ + public PFont(Font font, boolean smooth) { + this(font, smooth, null); + } + + + /** + * Create a new image-based font on the fly. If charset is set to null, + * the characters will only be created as bitmaps when they're drawn. + * + * @param font the font object to create from + * @param charset array of all unicode chars that should be included + * @param smooth true to enable smoothing/anti-aliasing + */ + public PFont(Font font, boolean smooth, char charset[]) { + // save this so that we can use the native version + this.font = font; + this.smooth = smooth; + + name = font.getName(); + psname = font.getPSName(); + size = font.getSize(); + + // no, i'm not interested in getting off the couch + //lazy = true; + // not sure what else to do here + //mbox2 = 0; + + int initialCount = 10; + glyphs = new Glyph[initialCount]; + + ascii = new int[128]; + Arrays.fill(ascii, -1); + + int mbox3 = size * 3; + + lazyImage = new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB); + lazyGraphics = (Graphics2D) lazyImage.getGraphics(); + lazyGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + smooth ? + RenderingHints.VALUE_ANTIALIAS_ON : + RenderingHints.VALUE_ANTIALIAS_OFF); + // adding this for post-1.0.9 + lazyGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + smooth ? + RenderingHints.VALUE_TEXT_ANTIALIAS_ON : + RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); + + lazyGraphics.setFont(font); + lazyMetrics = lazyGraphics.getFontMetrics(); + lazySamples = new int[mbox3 * mbox3]; + + // These values are terrible/unusable. Verified again for Processing 1.1. + // They vary widely per-platform and per-font, so instead we'll use the + // calculate-by-hand method of measuring pixels in characters. + //ascent = lazyMetrics.getAscent(); + //descent = lazyMetrics.getDescent(); + + if (charset == null) { + lazy = true; + + } else { + // charset needs to be sorted to make index lookup run more quickly + // http://dev.processing.org/bugs/show_bug.cgi?id=494 + Arrays.sort(charset); + + glyphs = new Glyph[charset.length]; + + glyphCount = 0; + for (char c : charset) { + if (font.canDisplay(c)) { + Glyph glyf = new Glyph(c); + if (glyf.value < 128) { + ascii[glyf.value] = glyphCount; + } + glyphs[glyphCount++] = glyf; + } + } + + // shorten the array if necessary + if (glyphCount != charset.length) { + glyphs = (Glyph[]) PApplet.subset(glyphs, 0, glyphCount); + } + + // foreign font, so just make ascent the max topExtent + // for > 1.0.9, not doing this anymore. + // instead using getAscent() and getDescent() values for these cases. +// if ((ascent == 0) && (descent == 0)) { +// //for (int i = 0; i < charCount; i++) { +// for (Glyph glyph : glyphs) { +// char cc = (char) glyph.value; +// //char cc = (char) glyphs[i].value; +// if (Character.isWhitespace(cc) || +// (cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) { +// continue; +// } +// if (glyph.topExtent > ascent) { +// ascent = glyph.topExtent; +// } +// int d = -glyph.topExtent + glyph.height; +// if (d > descent) { +// descent = d; +// } +// } +// } + } + + // If not already created, just create these two characters to calculate + // the ascent and descent values for the font. This was tested to only + // require 5-10 ms on a 2.4 GHz MacBook Pro. + // In versions 1.0.9 and earlier, fonts that could not display d or p + // used the max up/down values as calculated by looking through the font. + // That's no longer valid with the auto-generating fonts, so we'll just + // use getAscent() and getDescent() in such (minor) cases. + if (ascent == 0) { + if (font.canDisplay('d')) { + new Glyph('d'); + } else { + ascent = lazyMetrics.getAscent(); + } + } + if (descent == 0) { + if (font.canDisplay('p')) { + new Glyph('p'); + } else { + descent = lazyMetrics.getDescent(); + } + } + } + + + /** + * Adds an additional parameter that indicates the font came from a file, + * not a built-in OS font. + */ + public PFont(Font font, boolean smooth, char charset[], boolean stream) { + this(font, smooth, charset); + this.stream = stream; + } + + + public PFont(InputStream input) throws IOException { + DataInputStream is = new DataInputStream(input); + + // number of character images stored in this font + glyphCount = is.readInt(); + + // used to be the bitCount, but now used for version number. + // version 8 is any font before 69, so 9 is anything from 83+ + // 9 was buggy so gonna increment to 10. + int version = is.readInt(); + + // this was formerly ignored, now it's the actual font size + //mbox = is.readInt(); + size = is.readInt(); + + // this was formerly mboxY, the one that was used + // this will make new fonts downward compatible + is.readInt(); // ignore the other mbox attribute + + ascent = is.readInt(); // formerly baseHt (zero/ignored) + descent = is.readInt(); // formerly ignored struct padding + + // allocate enough space for the character info + glyphs = new Glyph[glyphCount]; + + ascii = new int[128]; + Arrays.fill(ascii, -1); + + // read the information about the individual characters + for (int i = 0; i < glyphCount; i++) { + Glyph glyph = new Glyph(is); + // cache locations of the ascii charset + if (glyph.value < 128) { + ascii[glyph.value] = i; + } + glyphs[i] = glyph; + } + + // not a roman font, so throw an error and ask to re-build. + // that way can avoid a bunch of error checking hacks in here. + if ((ascent == 0) && (descent == 0)) { + throw new RuntimeException("Please use \"Create Font\" to " + + "re-create this font."); + } + + for (Glyph glyph : glyphs) { + glyph.readBitmap(is); + } + + if (version >= 10) { // includes the font name at the end of the file + name = is.readUTF(); + psname = is.readUTF(); + } + if (version == 11) { + smooth = is.readBoolean(); + } + } + + + /** + * Write this PFont to an OutputStream. + *

+ * This is used by the Create Font tool, or whatever anyone else dreams + * up for messing with fonts themselves. + *

+ * It is assumed that the calling class will handle closing + * the stream when finished. + */ + public void save(OutputStream output) throws IOException { + DataOutputStream os = new DataOutputStream(output); + + os.writeInt(glyphCount); + + if ((name == null) || (psname == null)) { + name = ""; + psname = ""; + } + + os.writeInt(11); // formerly numBits, now used for version number + os.writeInt(size); // formerly mboxX (was 64, now 48) + os.writeInt(0); // formerly mboxY, now ignored + os.writeInt(ascent); // formerly baseHt (was ignored) + os.writeInt(descent); // formerly struct padding for c version + + for (int i = 0; i < glyphCount; i++) { + glyphs[i].writeHeader(os); + } + + for (int i = 0; i < glyphCount; i++) { + glyphs[i].writeBitmap(os); + } + + // version 11 + os.writeUTF(name); + os.writeUTF(psname); + os.writeBoolean(smooth); + + os.flush(); + } + + + /** + * Create a new glyph, and add the character to the current font. + * @param c character to create an image for. + */ + protected void addGlyph(char c) { + Glyph glyph = new Glyph(c); + + if (glyphCount == glyphs.length) { + glyphs = (Glyph[]) PApplet.expand(glyphs); + } + if (glyphCount == 0) { + glyphs[glyphCount] = glyph; + if (glyph.value < 128) { + ascii[glyph.value] = 0; + } + + } else if (glyphs[glyphCount-1].value < glyph.value) { + glyphs[glyphCount] = glyph; + if (glyph.value < 128) { + ascii[glyph.value] = glyphCount; + } + + } else { + for (int i = 0; i < glyphCount; i++) { + if (glyphs[i].value > c) { + for (int j = glyphCount; j > i; --j) { + glyphs[j] = glyphs[j-1]; + if (glyphs[j].value < 128) { + ascii[glyphs[j].value] = j; + } + } + glyphs[i] = glyph; + // cache locations of the ascii charset + if (c < 128) ascii[c] = i; + break; + } + } + } + glyphCount++; + } + + + public String getName() { + return name; + } + + + public String getPostScriptName() { + return psname; + } + + + /** + * Set the native complement of this font. + */ + public void setFont(Font font) { + this.font = font; + } + + + /** + * Return the native java.awt.Font associated with this PFont (if any). + */ + public Font getFont() { +// if (font == null && !fontSearched) { +// font = findFont(); +// } + return font; + } + + + public boolean isStream() { + return stream; + } + + + /** + * Attempt to find the native version of this font. + * (Public so that it can be used by OpenGL or other renderers.) + */ + public Font findFont() { + if (font == null) { + if (!fontSearched) { + // this font may or may not be installed + font = new Font(name, Font.PLAIN, size); + // if the ps name matches, then we're in fine shape + if (!font.getPSName().equals(psname)) { + // on osx java 1.4 (not 1.3.. ugh), you can specify the ps name + // of the font, so try that in case this .vlw font was created on pc + // and the name is different, but the ps name is found on the + // java 1.4 mac that's currently running this sketch. + font = new Font(psname, Font.PLAIN, size); + } + // check again, and if still bad, screw em + if (!font.getPSName().equals(psname)) { + font = null; + } + fontSearched = true; + } + } + return font; + } + + + public Glyph getGlyph(char c) { + int index = index(c); + return (index == -1) ? null : glyphs[index]; + } + + + /** + * Get index for the character. + * @return index into arrays or -1 if not found + */ + protected int index(char c) { + if (lazy) { + int index = indexActual(c); + if (index != -1) { + return index; + } + if (font.canDisplay(c)) { + // create the glyph + addGlyph(c); + // now where did i put that? + return indexActual(c); + + } else { + return -1; + } + + } else { + return indexActual(c); + } + } + + + protected int indexActual(char c) { + // degenerate case, but the find function will have trouble + // if there are somehow zero chars in the lookup + //if (value.length == 0) return -1; + if (glyphCount == 0) return -1; + + // quicker lookup for the ascii fellers + if (c < 128) return ascii[c]; + + // some other unicode char, hunt it out + //return index_hunt(c, 0, value.length-1); + return indexHunt(c, 0, glyphCount-1); + } + + + protected int indexHunt(int c, int start, int stop) { + int pivot = (start + stop) / 2; + + // if this is the char, then return it + if (c == glyphs[pivot].value) return pivot; + + // char doesn't exist, otherwise would have been the pivot + //if (start == stop) return -1; + if (start >= stop) return -1; + + // if it's in the lower half, continue searching that + if (c < glyphs[pivot].value) return indexHunt(c, start, pivot-1); + + // if it's in the upper half, continue there + return indexHunt(c, pivot+1, stop); + } + + + /** + * Currently un-implemented for .vlw fonts, + * but honored for layout in case subclasses use it. + */ + public float kern(char a, char b) { + return 0; + } + + + /** + * Returns the ascent of this font from the baseline. + * The value is based on a font of size 1. + */ + public float ascent() { + return ((float) ascent / (float) size); + } + + + /** + * Returns how far this font descends from the baseline. + * The value is based on a font size of 1. + */ + public float descent() { + return ((float) descent / (float) size); + } + + + /** + * Width of this character for a font of size 1. + */ + public float width(char c) { + if (c == 32) return width('i'); + + int cc = index(c); + if (cc == -1) return 0; + + return ((float) glyphs[cc].setWidth / (float) size); + } + + + ////////////////////////////////////////////////////////////// + + + static final char[] EXTRA_CHARS = { + 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, + 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, + 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, + 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, + 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, + 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, + 0x00B0, 0x00B1, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00BA, + 0x00BB, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, + 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, + 0x00CE, 0x00CF, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, + 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DF, + 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, + 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, + 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, + 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FF, 0x0102, 0x0103, + 0x0104, 0x0105, 0x0106, 0x0107, 0x010C, 0x010D, 0x010E, 0x010F, + 0x0110, 0x0111, 0x0118, 0x0119, 0x011A, 0x011B, 0x0131, 0x0139, + 0x013A, 0x013D, 0x013E, 0x0141, 0x0142, 0x0143, 0x0144, 0x0147, + 0x0148, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0158, + 0x0159, 0x015A, 0x015B, 0x015E, 0x015F, 0x0160, 0x0161, 0x0162, + 0x0163, 0x0164, 0x0165, 0x016E, 0x016F, 0x0170, 0x0171, 0x0178, + 0x0179, 0x017A, 0x017B, 0x017C, 0x017D, 0x017E, 0x0192, 0x02C6, + 0x02C7, 0x02D8, 0x02D9, 0x02DA, 0x02DB, 0x02DC, 0x02DD, 0x03A9, + 0x03C0, 0x2013, 0x2014, 0x2018, 0x2019, 0x201A, 0x201C, 0x201D, + 0x201E, 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203A, + 0x2044, 0x20AC, 0x2122, 0x2202, 0x2206, 0x220F, 0x2211, 0x221A, + 0x221E, 0x222B, 0x2248, 0x2260, 0x2264, 0x2265, 0x25CA, 0xF8FF, + 0xFB01, 0xFB02 + }; + + + /** + * The default Processing character set. + *

+ * This is the union of the Mac Roman and Windows ANSI (CP1250) + * character sets. ISO 8859-1 Latin 1 is Unicode characters 0x80 -> 0xFF, + * and would seem a good standard, but in practice, most P5 users would + * rather have characters that they expect from their platform's fonts. + *

+ * This is more of an interim solution until a much better + * font solution can be determined. (i.e. create fonts on + * the fly from some sort of vector format). + *

+ * Not that I expect that to happen. + */ + static public char[] CHARSET; + static { + CHARSET = new char[126-33+1 + EXTRA_CHARS.length]; + int index = 0; + for (int i = 33; i <= 126; i++) { + CHARSET[index++] = (char)i; + } + for (int i = 0; i < EXTRA_CHARS.length; i++) { + CHARSET[index++] = EXTRA_CHARS[i]; + } + }; + + + /** + * Get a list of the fonts installed on the system that can be used + * by Java. Not all fonts can be used in Java, in fact it's mostly + * only TrueType fonts. OpenType fonts with CFF data such as Adobe's + * OpenType fonts seem to have trouble (even though they're sort of + * TrueType fonts as well, or may have a .ttf extension). Regular + * PostScript fonts seem to work OK, however. + *

+ * Not recommended for use in applets, but this is implemented + * in PFont because the Java methods to access this information + * have changed between 1.1 and 1.4, and the 1.4 method is + * typical of the sort of undergraduate-level over-abstraction + * that the seems to have made its way into the Java API after 1.1. + */ + static public String[] list() { + loadFonts(); + String list[] = new String[fonts.length]; + for (int i = 0; i < list.length; i++) { + list[i] = fonts[i].getName(); + } + return list; + } + + + static public void loadFonts() { + if (fonts == null) { + GraphicsEnvironment ge = + GraphicsEnvironment.getLocalGraphicsEnvironment(); + fonts = ge.getAllFonts(); + if (PApplet.platform == PConstants.MACOSX) { + fontDifferent = new HashMap(); + for (Font font : fonts) { + // getName() returns the PostScript name on OS X 10.6 w/ Java 6. + fontDifferent.put(font.getName(), font); + //fontDifferent.put(font.getPSName(), font); + } + } + } + } + + + /** + * Starting with Java 1.5, Apple broke the ability to specify most fonts. + * This bug was filed years ago as #4769141 at bugreporter.apple.com. More: + * Bug 407. + */ + static public Font findFont(String name) { + loadFonts(); + if (PApplet.platform == PConstants.MACOSX) { + Font maybe = fontDifferent.get(name); + if (maybe != null) { + return maybe; + } +// for (int i = 0; i < fonts.length; i++) { +// if (name.equals(fonts[i].getName())) { +// return fonts[i]; +// } +// } + } + return new Font(name, Font.PLAIN, 1); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * A single character, and its visage. + */ + public class Glyph { + PImage image; + int value; + int height; + int width; + int setWidth; + int topExtent; + int leftExtent; + + + protected Glyph() { + // used when reading from a stream or for subclasses + } + + + protected Glyph(DataInputStream is) throws IOException { + readHeader(is); + } + + + protected void readHeader(DataInputStream is) throws IOException { + value = is.readInt(); + height = is.readInt(); + width = is.readInt(); + setWidth = is.readInt(); + topExtent = is.readInt(); + leftExtent = is.readInt(); + + // pointer from a struct in the c version, ignored + is.readInt(); + + // the values for getAscent() and getDescent() from FontMetrics + // seem to be way too large.. perhaps they're the max? + // as such, use a more traditional marker for ascent/descent + if (value == 'd') { + if (ascent == 0) ascent = topExtent; + } + if (value == 'p') { + if (descent == 0) descent = -topExtent + height; + } + } + + + protected void writeHeader(DataOutputStream os) throws IOException { + os.writeInt(value); + os.writeInt(height); + os.writeInt(width); + os.writeInt(setWidth); + os.writeInt(topExtent); + os.writeInt(leftExtent); + os.writeInt(0); // padding + } + + + protected void readBitmap(DataInputStream is) throws IOException { + image = new PImage(width, height, ALPHA); + int bitmapSize = width * height; + + byte[] temp = new byte[bitmapSize]; + is.readFully(temp); + + // convert the bitmap to an alpha channel + int w = width; + int h = height; + int[] pixels = image.pixels; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + pixels[y * width + x] = temp[y*w + x] & 0xff; +// System.out.print((image.pixels[y*64+x] > 128) ? "*" : "."); + } +// System.out.println(); + } +// System.out.println(); + } + + + protected void writeBitmap(DataOutputStream os) throws IOException { + int[] pixels = image.pixels; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + os.write(pixels[y * width + x] & 0xff); + } + } + } + + + protected Glyph(char c) { + int mbox3 = size * 3; + lazyGraphics.setColor(Color.white); + lazyGraphics.fillRect(0, 0, mbox3, mbox3); + lazyGraphics.setColor(Color.black); + lazyGraphics.drawString(String.valueOf(c), size, size * 2); + + WritableRaster raster = lazyImage.getRaster(); + raster.getDataElements(0, 0, mbox3, mbox3, lazySamples); + + int minX = 1000, maxX = 0; + int minY = 1000, maxY = 0; + boolean pixelFound = false; + + for (int y = 0; y < mbox3; y++) { + for (int x = 0; x < mbox3; x++) { + int sample = lazySamples[y * mbox3 + x] & 0xff; + if (sample != 255) { + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + pixelFound = true; + } + } + } + + if (!pixelFound) { + minX = minY = 0; + maxX = maxY = 0; + // this will create a 1 pixel white (clear) character.. + // maybe better to set one to -1 so nothing is added? + } + + value = c; + height = (maxY - minY) + 1; + width = (maxX - minX) + 1; + setWidth = lazyMetrics.charWidth(c); + + // offset from vertical location of baseline + // of where the char was drawn (size*2) + topExtent = size*2 - minY; + + // offset from left of where coord was drawn + leftExtent = minX - size; + + image = new PImage(width, height, ALPHA); + int[] pixels = image.pixels; + for (int y = minY; y <= maxY; y++) { + for (int x = minX; x <= maxX; x++) { + int val = 255 - (lazySamples[y * mbox3 + x] & 0xff); + int pindex = (y - minY) * width + (x - minX); + pixels[pindex] = val; + } + } + + // replace the ascent/descent values with something.. err, decent. + if (value == 'd') { + if (ascent == 0) ascent = topExtent; + } + if (value == 'p') { + if (descent == 0) descent = -topExtent + height; + } + } + } +} diff --git a/support/Processing_core_src/processing/core/PGraphics.java b/support/Processing_core_src/processing/core/PGraphics.java new file mode 100644 index 0000000..b9738c8 --- /dev/null +++ b/support/Processing_core_src/processing/core/PGraphics.java @@ -0,0 +1,5863 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-09 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.*; +import java.util.HashMap; + + +/** + * Main graphics and rendering context, as well as the base API implementation for processing "core". + * Use this class if you need to draw into an off-screen graphics buffer. + * A PGraphics object can be constructed with the createGraphics() function. + * The beginDraw() and endDraw() methods (see above example) are necessary to set up the buffer and to finalize it. + * The fields and methods for this class are extensive; + * for a complete list visit the developer's reference: http://dev.processing.org/reference/core/ + * =advanced + * Main graphics and rendering context, as well as the base API implementation. + * + *

Subclassing and initializing PGraphics objects

+ * Starting in release 0149, subclasses of PGraphics are handled differently. + * The constructor for subclasses takes no parameters, instead a series of + * functions are called by the hosting PApplet to specify its attributes. + *
    + *
  • setParent(PApplet) - is called to specify the parent PApplet. + *
  • setPrimary(boolean) - called with true if this PGraphics will be the + * primary drawing surface used by the sketch, or false if not. + *
  • setPath(String) - called when the renderer needs a filename or output + * path, such as with the PDF or DXF renderers. + *
  • setSize(int, int) - this is called last, at which point it's safe for + * the renderer to complete its initialization routine. + *
+ * The functions were broken out because of the growing number of parameters + * such as these that might be used by a renderer, yet with the exception of + * setSize(), it's not clear which will be necessary. So while the size could + * be passed in to the constructor instead of a setSize() function, a function + * would still be needed that would notify the renderer that it was time to + * finish its initialization. Thus, setSize() simply does both. + * + *

Know your rights: public vs. private methods

+ * Methods that are protected are often subclassed by other renderers, however + * they are not set 'public' because they shouldn't be part of the user-facing + * public API accessible from PApplet. That is, we don't want sketches calling + * textModeCheck() or vertexTexture() directly. + * + *

Handling warnings and exceptions

+ * Methods that are unavailable generally show a warning, unless their lack of + * availability will soon cause another exception. For instance, if a method + * like getMatrix() returns null because it is unavailable, an exception will + * be thrown stating that the method is unavailable, rather than waiting for + * the NullPointerException that will occur when the sketch tries to use that + * method. As of release 0149, warnings will only be shown once, and exceptions + * have been changed to warnings where possible. + * + *

Using xxxxImpl() for subclassing smoothness

+ * The xxxImpl() methods are generally renderer-specific handling for some + * subset if tasks for a particular function (vague enough for you?) For + * instance, imageImpl() handles drawing an image whose x/y/w/h and u/v coords + * have been specified, and screen placement (independent of imageMode) has + * been determined. There's no point in all renderers implementing the + * if (imageMode == BLAH) placement/sizing logic, so that's handled + * by PGraphics, which then calls imageImpl() once all that is figured out. + * + *

His brother PImage

+ * PGraphics subclasses PImage so that it can be drawn and manipulated in a + * similar fashion. As such, many methods are inherited from PGraphics, + * though many are unavailable: for instance, resize() is not likely to be + * implemented; the same goes for mask(), depending on the situation. + * + *

What's in PGraphics, what ain't

+ * For the benefit of subclasses, as much as possible has been placed inside + * PGraphics. For instance, bezier interpolation code and implementations of + * the strokeCap() method (that simply sets the strokeCap variable) are + * handled here. Features that will vary widely between renderers are located + * inside the subclasses themselves. For instance, all matrix handling code + * is per-renderer: Java 2D uses its own AffineTransform, P2D uses a PMatrix2D, + * and PGraphics3D needs to keep continually update forward and reverse + * transformations. A proper (future) OpenGL implementation will have all its + * matrix madness handled by the card. Lighting also falls under this + * category, however the base material property settings (emissive, specular, + * et al.) are handled in PGraphics because they use the standard colorMode() + * logic. Subclasses should override methods like emissiveFromCalc(), which + * is a point where a valid color has been defined internally, and can be + * applied in some manner based on the calcXxxx values. + * + *

What's in the PGraphics documentation, what ain't

+ * Some things are noted here, some things are not. For public API, always + * refer to the reference + * on Processing.org for proper explanations. No attempt has been made to + * keep the javadoc up to date or complete. It's an enormous task for + * which we simply do not have the time. That is, it's not something that + * to be done once—it's a matter of keeping the multiple references + * synchronized (to say nothing of the translation issues), while targeting + * them for their separate audiences. Ouch. + * + * We're working right now on synchronizing the two references, so the website reference + * is generated from the javadoc comments. Yay. + * + * @webref rendering + * @instanceName graphics any object of the type PGraphics + * @usage Web & Application + * @see processing.core.PApplet#createGraphics(int, int, String) + */ +public class PGraphics extends PImage implements PConstants { + + // ........................................................ + + // width and height are already inherited from PImage + + + /// width minus one (useful for many calculations) + protected int width1; + + /// height minus one (useful for many calculations) + protected int height1; + + /// width * height (useful for many calculations) + public int pixelCount; + + /// true if smoothing is enabled (read-only) + public boolean smooth = false; + + // ........................................................ + + /// true if defaults() has been called a first time + protected boolean settingsInited; + + /// set to a PGraphics object being used inside a beginRaw/endRaw() block + protected PGraphics raw; + + // ........................................................ + + /** path to the file being saved for this renderer (if any) */ + protected String path; + + /** + * true if this is the main drawing surface for a particular sketch. + * This would be set to false for an offscreen buffer or if it were + * created any other way than size(). When this is set, the listeners + * are also added to the sketch. + */ + protected boolean primarySurface; + + // ........................................................ + + /** + * Array of hint[] items. These are hacks to get around various + * temporary workarounds inside the environment. + *

+ * Note that this array cannot be static, as a hint() may result in a + * runtime change specific to a renderer. For instance, calling + * hint(DISABLE_DEPTH_TEST) has to call glDisable() right away on an + * instance of PGraphicsOpenGL. + *

+ * The hints[] array is allocated early on because it might + * be used inside beginDraw(), allocate(), etc. + */ + protected boolean[] hints = new boolean[HINT_COUNT]; + + + //////////////////////////////////////////////////////////// + + // STYLE PROPERTIES + + // Also inherits imageMode() and smooth() (among others) from PImage. + + /** The current colorMode */ + public int colorMode; // = RGB; + + /** Max value for red (or hue) set by colorMode */ + public float colorModeX; // = 255; + + /** Max value for green (or saturation) set by colorMode */ + public float colorModeY; // = 255; + + /** Max value for blue (or value) set by colorMode */ + public float colorModeZ; // = 255; + + /** Max value for alpha set by colorMode */ + public float colorModeA; // = 255; + + /** True if colors are not in the range 0..1 */ + boolean colorModeScale; // = true; + + /** True if colorMode(RGB, 255) */ + boolean colorModeDefault; // = true; + + // ........................................................ + + // Tint color for images + + /** + * True if tint() is enabled (read-only). + * + * Using tint/tintColor seems a better option for naming than + * tintEnabled/tint because the latter seems ugly, even though + * g.tint as the actual color seems a little more intuitive, + * it's just that g.tintEnabled is even more unintuitive. + * Same goes for fill and stroke, et al. + */ + public boolean tint; + + /** tint that was last set (read-only) */ + public int tintColor; + + protected boolean tintAlpha; + protected float tintR, tintG, tintB, tintA; + protected int tintRi, tintGi, tintBi, tintAi; + + // ........................................................ + + // Fill color + + /** true if fill() is enabled, (read-only) */ + public boolean fill; + + /** fill that was last set (read-only) */ + public int fillColor = 0xffFFFFFF; + + protected boolean fillAlpha; + protected float fillR, fillG, fillB, fillA; + protected int fillRi, fillGi, fillBi, fillAi; + + // ........................................................ + + // Stroke color + + /** true if stroke() is enabled, (read-only) */ + public boolean stroke; + + /** stroke that was last set (read-only) */ + public int strokeColor = 0xff000000; + + protected boolean strokeAlpha; + protected float strokeR, strokeG, strokeB, strokeA; + protected int strokeRi, strokeGi, strokeBi, strokeAi; + + // ........................................................ + + // Additional stroke properties + + static protected final float DEFAULT_STROKE_WEIGHT = 1; + static protected final int DEFAULT_STROKE_JOIN = MITER; + static protected final int DEFAULT_STROKE_CAP = ROUND; + + /** + * Last value set by strokeWeight() (read-only). This has a default + * setting, rather than fighting with renderers about whether that + * renderer supports thick lines. + */ + public float strokeWeight = DEFAULT_STROKE_WEIGHT; + + /** + * Set by strokeJoin() (read-only). This has a default setting + * so that strokeJoin() need not be called by defaults, + * because subclasses may not implement it (i.e. PGraphicsGL) + */ + public int strokeJoin = DEFAULT_STROKE_JOIN; + + /** + * Set by strokeCap() (read-only). This has a default setting + * so that strokeCap() need not be called by defaults, + * because subclasses may not implement it (i.e. PGraphicsGL) + */ + public int strokeCap = DEFAULT_STROKE_CAP; + + // ........................................................ + + // Shape placement properties + + // imageMode() is inherited from PImage + + /** The current rect mode (read-only) */ + public int rectMode; + + /** The current ellipse mode (read-only) */ + public int ellipseMode; + + /** The current shape alignment mode (read-only) */ + public int shapeMode; + + /** The current image alignment (read-only) */ + public int imageMode = CORNER; + + // ........................................................ + + // Text and font properties + + /** The current text font (read-only) */ + public PFont textFont; + + /** The current text align (read-only) */ + public int textAlign = LEFT; + + /** The current vertical text alignment (read-only) */ + public int textAlignY = BASELINE; + + /** The current text mode (read-only) */ + public int textMode = MODEL; + + /** The current text size (read-only) */ + public float textSize; + + /** The current text leading (read-only) */ + public float textLeading; + + // ........................................................ + + // Material properties + +// PMaterial material; +// PMaterial[] materialStack; +// int materialStackPointer; + + public float ambientR, ambientG, ambientB; + public float specularR, specularG, specularB; + public float emissiveR, emissiveG, emissiveB; + public float shininess; + + + // Style stack + + static final int STYLE_STACK_DEPTH = 64; + PStyle[] styleStack = new PStyle[STYLE_STACK_DEPTH]; + int styleStackDepth; + + + //////////////////////////////////////////////////////////// + + + /** Last background color that was set, zero if an image */ + public int backgroundColor = 0xffCCCCCC; + + protected boolean backgroundAlpha; + protected float backgroundR, backgroundG, backgroundB, backgroundA; + protected int backgroundRi, backgroundGi, backgroundBi, backgroundAi; + + // ........................................................ + + /** + * Current model-view matrix transformation of the form m[row][column], + * which is a "column vector" (as opposed to "row vector") matrix. + */ +// PMatrix matrix; +// public float m00, m01, m02, m03; +// public float m10, m11, m12, m13; +// public float m20, m21, m22, m23; +// public float m30, m31, m32, m33; + +// static final int MATRIX_STACK_DEPTH = 32; +// float[][] matrixStack = new float[MATRIX_STACK_DEPTH][16]; +// float[][] matrixInvStack = new float[MATRIX_STACK_DEPTH][16]; +// int matrixStackDepth; + + static final int MATRIX_STACK_DEPTH = 32; + + // ........................................................ + + /** + * Java AWT Image object associated with this renderer. For P2D and P3D, + * this will be associated with their MemoryImageSource. For PGraphicsJava2D, + * it will be the offscreen drawing buffer. + */ + public Image image; + + // ........................................................ + + // internal color for setting/calculating + protected float calcR, calcG, calcB, calcA; + protected int calcRi, calcGi, calcBi, calcAi; + protected int calcColor; + protected boolean calcAlpha; + + /** The last RGB value converted to HSB */ + int cacheHsbKey; + /** Result of the last conversion to HSB */ + float[] cacheHsbValue = new float[3]; + + // ........................................................ + + /** + * Type of shape passed to beginShape(), + * zero if no shape is currently being drawn. + */ + protected int shape; + + // vertices + static final int DEFAULT_VERTICES = 512; + protected float vertices[][] = + new float[DEFAULT_VERTICES][VERTEX_FIELD_COUNT]; + protected int vertexCount; // total number of vertices + + // ........................................................ + + protected boolean bezierInited = false; + public int bezierDetail = 20; + + // used by both curve and bezier, so just init here + protected PMatrix3D bezierBasisMatrix = + new PMatrix3D(-1, 3, -3, 1, + 3, -6, 3, 0, + -3, 3, 0, 0, + 1, 0, 0, 0); + + //protected PMatrix3D bezierForwardMatrix; + protected PMatrix3D bezierDrawMatrix; + + // ........................................................ + + protected boolean curveInited = false; + protected int curveDetail = 20; + public float curveTightness = 0; + // catmull-rom basis matrix, perhaps with optional s parameter + protected PMatrix3D curveBasisMatrix; + protected PMatrix3D curveDrawMatrix; + + protected PMatrix3D bezierBasisInverse; + protected PMatrix3D curveToBezierMatrix; + + // ........................................................ + + // spline vertices + + protected float curveVertices[][]; + protected int curveVertexCount; + + // ........................................................ + + // precalculate sin/cos lookup tables [toxi] + // circle resolution is determined from the actual used radii + // passed to ellipse() method. this will automatically take any + // scale transformations into account too + + // [toxi 031031] + // changed table's precision to 0.5 degree steps + // introduced new vars for more flexible code + static final protected float sinLUT[]; + static final protected float cosLUT[]; + static final protected float SINCOS_PRECISION = 0.5f; + static final protected int SINCOS_LENGTH = (int) (360f / SINCOS_PRECISION); + static { + sinLUT = new float[SINCOS_LENGTH]; + cosLUT = new float[SINCOS_LENGTH]; + for (int i = 0; i < SINCOS_LENGTH; i++) { + sinLUT[i] = (float) Math.sin(i * DEG_TO_RAD * SINCOS_PRECISION); + cosLUT[i] = (float) Math.cos(i * DEG_TO_RAD * SINCOS_PRECISION); + } + } + + // ........................................................ + + /** The current font if a Java version of it is installed */ + //protected Font textFontNative; + + /** Metrics for the current native Java font */ + //protected FontMetrics textFontNativeMetrics; + + /** Last text position, because text often mixed on lines together */ + protected float textX, textY, textZ; + + /** + * Internal buffer used by the text() functions + * because the String object is slow + */ + protected char[] textBuffer = new char[8 * 1024]; + protected char[] textWidthBuffer = new char[8 * 1024]; + + protected int textBreakCount; + protected int[] textBreakStart; + protected int[] textBreakStop; + + // ........................................................ + + public boolean edge = true; + + // ........................................................ + + /// normal calculated per triangle + static protected final int NORMAL_MODE_AUTO = 0; + /// one normal manually specified per shape + static protected final int NORMAL_MODE_SHAPE = 1; + /// normals specified for each shape vertex + static protected final int NORMAL_MODE_VERTEX = 2; + + /// Current mode for normals, one of AUTO, SHAPE, or VERTEX + protected int normalMode; + + /// Keep track of how many calls to normal, to determine the mode. + //protected int normalCount; + + /** Current normal vector. */ + public float normalX, normalY, normalZ; + + // ........................................................ + + /** + * Sets whether texture coordinates passed to + * vertex() calls will be based on coordinates that are + * based on the IMAGE or NORMALIZED. + */ + public int textureMode; + + /** + * Current horizontal coordinate for texture, will always + * be between 0 and 1, even if using textureMode(IMAGE). + */ + public float textureU; + + /** Current vertical coordinate for texture, see above. */ + public float textureV; + + /** Current image being used as a texture */ + public PImage textureImage; + + // ........................................................ + + // [toxi031031] new & faster sphere code w/ support flexibile resolutions + // will be set by sphereDetail() or 1st call to sphere() + float sphereX[], sphereY[], sphereZ[]; + + /// Number of U steps (aka "theta") around longitudinally spanning 2*pi + public int sphereDetailU = 0; + /// Number of V steps (aka "phi") along latitudinally top-to-bottom spanning pi + public int sphereDetailV = 0; + + + ////////////////////////////////////////////////////////////// + + // INTERNAL + + + /** + * Constructor for the PGraphics object. Use this to ensure that + * the defaults get set properly. In a subclass, use this(w, h) + * as the first line of a subclass' constructor to properly set + * the internal fields and defaults. + * + */ + public PGraphics() { + } + + + public void setParent(PApplet parent) { // ignore + this.parent = parent; + } + + + /** + * Set (or unset) this as the main drawing surface. Meaning that it can + * safely be set to opaque (and given a default gray background), or anything + * else that goes along with that. + */ + public void setPrimary(boolean primary) { // ignore + this.primarySurface = primary; + + // base images must be opaque (for performance and general + // headache reasons.. argh, a semi-transparent opengl surface?) + // use createGraphics() if you want a transparent surface. + if (primarySurface) { + format = RGB; + } + } + + + public void setPath(String path) { // ignore + this.path = path; + } + + + /** + * The final step in setting up a renderer, set its size of this renderer. + * This was formerly handled by the constructor, but instead it's been broken + * out so that setParent/setPrimary/setPath can be handled differently. + * + * Important that this is ignored by preproc.pl because otherwise it will + * override setSize() in PApplet/Applet/Component, which will 1) not call + * super.setSize(), and 2) will cause the renderer to be resized from the + * event thread (EDT), causing a nasty crash as it collides with the + * animation thread. + */ + public void setSize(int w, int h) { // ignore + width = w; + height = h; + width1 = width - 1; + height1 = height - 1; + + allocate(); + reapplySettings(); + } + + + /** + * Allocate memory for this renderer. Generally will need to be implemented + * for all renderers. + */ + protected void allocate() { } + + + /** + * Handle any takedown for this graphics context. + *

+ * This is called when a sketch is shut down and this renderer was + * specified using the size() command, or inside endRecord() and + * endRaw(), in order to shut things off. + */ + public void dispose() { // ignore + } + + + + ////////////////////////////////////////////////////////////// + + // FRAME + + + /** + * Some renderers have requirements re: when they are ready to draw. + */ + public boolean canDraw() { // ignore + return true; + } + + + /** + * Sets the default properties for a PGraphics object. It should be called before anything is drawn into the object. + * =advanced + *

+ * When creating your own PGraphics, you should call this before + * drawing anything. + * + * @webref + * @brief Sets up the rendering context + */ + public void beginDraw() { // ignore + } + + + /** + * Finalizes the rendering of a PGraphics object so that it can be shown on screen. + * =advanced + *

+ * When creating your own PGraphics, you should call this when + * you're finished drawing. + * + * @webref + * @brief Finalizes the renderering context + */ + public void endDraw() { // ignore + } + + + public void flush() { + // no-op, mostly for P3D to write sorted stuff + } + + + protected void checkSettings() { + if (!settingsInited) defaultSettings(); + } + + + /** + * Set engine's default values. This has to be called by PApplet, + * somewhere inside setup() or draw() because it talks to the + * graphics buffer, meaning that for subclasses like OpenGL, there + * needs to be a valid graphics context to mess with otherwise + * you'll get some good crashing action. + * + * This is currently called by checkSettings(), during beginDraw(). + */ + protected void defaultSettings() { // ignore +// System.out.println("PGraphics.defaultSettings() " + width + " " + height); + + noSmooth(); // 0149 + + colorMode(RGB, 255); + fill(255); + stroke(0); + + // as of 0178, no longer relying on local versions of the variables + // being set, because subclasses may need to take extra action. + strokeWeight(DEFAULT_STROKE_WEIGHT); + strokeJoin(DEFAULT_STROKE_JOIN); + strokeCap(DEFAULT_STROKE_CAP); + + // init shape stuff + shape = 0; + + // init matrices (must do before lights) + //matrixStackDepth = 0; + + rectMode(CORNER); + ellipseMode(DIAMETER); + + // no current font + textFont = null; + textSize = 12; + textLeading = 14; + textAlign = LEFT; + textMode = MODEL; + + // if this fella is associated with an applet, then clear its background. + // if it's been created by someone else through createGraphics, + // they have to call background() themselves, otherwise everything gets + // a gray background (when just a transparent surface or an empty pdf + // is what's desired). + // this background() call is for the Java 2D and OpenGL renderers. + if (primarySurface) { + //System.out.println("main drawing surface bg " + getClass().getName()); + background(backgroundColor); + } + + settingsInited = true; + // defaultSettings() overlaps reapplySettings(), don't do both + //reapplySettings = false; + } + + + /** + * Re-apply current settings. Some methods, such as textFont(), require that + * their methods be called (rather than simply setting the textFont variable) + * because they affect the graphics context, or they require parameters from + * the context (e.g. getting native fonts for text). + * + * This will only be called from an allocate(), which is only called from + * size(), which is safely called from inside beginDraw(). And it cannot be + * called before defaultSettings(), so we should be safe. + */ + protected void reapplySettings() { +// System.out.println("attempting reapplySettings()"); + if (!settingsInited) return; // if this is the initial setup, no need to reapply + +// System.out.println(" doing reapplySettings"); +// new Exception().printStackTrace(System.out); + + colorMode(colorMode, colorModeX, colorModeY, colorModeZ); + if (fill) { +// PApplet.println(" fill " + PApplet.hex(fillColor)); + fill(fillColor); + } else { + noFill(); + } + if (stroke) { + stroke(strokeColor); + + // The if() statements should be handled inside the functions, + // otherwise an actual reset/revert won't work properly. + //if (strokeWeight != DEFAULT_STROKE_WEIGHT) { + strokeWeight(strokeWeight); + //} +// if (strokeCap != DEFAULT_STROKE_CAP) { + strokeCap(strokeCap); +// } +// if (strokeJoin != DEFAULT_STROKE_JOIN) { + strokeJoin(strokeJoin); +// } + } else { + noStroke(); + } + if (tint) { + tint(tintColor); + } else { + noTint(); + } + if (smooth) { + smooth(); + } else { + // Don't bother setting this, cuz it'll anger P3D. + noSmooth(); + } + if (textFont != null) { +// System.out.println(" textFont in reapply is " + textFont); + // textFont() resets the leading, so save it in case it's changed + float saveLeading = textLeading; + textFont(textFont, textSize); + textLeading(saveLeading); + } + textMode(textMode); + textAlign(textAlign, textAlignY); + background(backgroundColor); + + //reapplySettings = false; + } + + + ////////////////////////////////////////////////////////////// + + // HINTS + + /** + * Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be implemented in a consistent manner across renderers. Many options will often graduate to standard features instead of hints over time. + *

hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's control panel, however not all cards make this available. This hint must be called immediately after the size() command because it resets the renderer, obliterating any settings and anything drawn (and like size(), re-running the code that came before it again). + *

hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in earlier releases, where smooth() and noSmooth() could be used to enable and disable smoothing, though the quality was inferior. + *

hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are installed, rather than the bitmapped version from a .vlw file. This is useful with the JAVA2D renderer setting, as it will improve font rendering speed. This is not enabled by default, because it can be misleading while testing because the type will look great on your machine (because you have the font installed) but lousy on others' machines if the identical font is unavailable. This option can only be set per-sketch, and must be called before any use of textFont(). + *

hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on top of everything at will. When depth testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, any 3D drawing that happens later in draw() will ignore existing shapes on the screen. + *

hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and lines in P3D and OPENGL. This can slow performance considerably, and the algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT). + *

hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the OPENGL renderer setting by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT). + *

As of release 0149, unhint() has been removed in favor of adding additional ENABLE/DISABLE constants to reset the default behavior. This prevents the double negatives, and also reinforces which hints can be enabled or disabled. + * + * @webref rendering + * @param which name of the hint to be enabled or disabled + * + * @see processing.core.PGraphics + * @see processing.core.PApplet#createGraphics(int, int, String, String) + * @see processing.core.PApplet#size(int, int) + */ + public void hint(int which) { + if (which > 0) { + hints[which] = true; + } else { + hints[-which] = false; + } + } + + + + ////////////////////////////////////////////////////////////// + + // VERTEX SHAPES + + /** + * Start a new shape of type POLYGON + */ + public void beginShape() { + beginShape(POLYGON); + } + + + /** + * Start a new shape. + *

+ * Differences between beginShape() and line() and point() methods. + *

+ * beginShape() is intended to be more flexible at the expense of being + * a little more complicated to use. it handles more complicated shapes + * that can consist of many connected lines (so you get joins) or lines + * mixed with curves. + *

+ * The line() and point() command are for the far more common cases + * (particularly for our audience) that simply need to draw a line + * or a point on the screen. + *

+ * From the code side of things, line() may or may not call beginShape() + * to do the drawing. In the beta code, they do, but in the alpha code, + * they did not. they might be implemented one way or the other depending + * on tradeoffs of runtime efficiency vs. implementation efficiency &mdash + * meaning the speed that things run at vs. the speed it takes me to write + * the code and maintain it. for beta, the latter is most important so + * that's how things are implemented. + */ + public void beginShape(int kind) { + shape = kind; + } + + + /** + * Sets whether the upcoming vertex is part of an edge. + * Equivalent to glEdgeFlag(), for people familiar with OpenGL. + */ + public void edge(boolean edge) { + this.edge = edge; + } + + + /** + * Sets the current normal vector. Only applies with 3D rendering + * and inside a beginShape/endShape block. + *

+ * This is for drawing three dimensional shapes and surfaces, + * allowing you to specify a vector perpendicular to the surface + * of the shape, which determines how lighting affects it. + *

+ * For the most part, PGraphics3D will attempt to automatically + * assign normals to shapes, but since that's imperfect, + * this is a better option when you want more control. + *

+ * For people familiar with OpenGL, this function is basically + * identical to glNormal3f(). + */ + public void normal(float nx, float ny, float nz) { + normalX = nx; + normalY = ny; + normalZ = nz; + + // if drawing a shape and the normal hasn't been set yet, + // then we need to set the normals for each vertex so far + if (shape != 0) { + if (normalMode == NORMAL_MODE_AUTO) { + // either they set the normals, or they don't [0149] +// for (int i = vertex_start; i < vertexCount; i++) { +// vertices[i][NX] = normalX; +// vertices[i][NY] = normalY; +// vertices[i][NZ] = normalZ; +// } + // One normal per begin/end shape + normalMode = NORMAL_MODE_SHAPE; + + } else if (normalMode == NORMAL_MODE_SHAPE) { + // a separate normal for each vertex + normalMode = NORMAL_MODE_VERTEX; + } + } + } + + + /** + * Set texture mode to either to use coordinates based on the IMAGE + * (more intuitive for new users) or NORMALIZED (better for advanced chaps) + */ + public void textureMode(int mode) { + this.textureMode = mode; + } + + + /** + * Set texture image for current shape. + * Needs to be called between @see beginShape and @see endShape + * + * @param image reference to a PImage object + */ + public void texture(PImage image) { + textureImage = image; + } + + + protected void vertexCheck() { + if (vertexCount == vertices.length) { + float temp[][] = new float[vertexCount << 1][VERTEX_FIELD_COUNT]; + System.arraycopy(vertices, 0, temp, 0, vertexCount); + vertices = temp; + } + } + + + public void vertex(float x, float y) { + vertexCheck(); + float[] vertex = vertices[vertexCount]; + + curveVertexCount = 0; + + vertex[X] = x; + vertex[Y] = y; + + vertex[EDGE] = edge ? 1 : 0; + +// if (fill) { +// vertex[R] = fillR; +// vertex[G] = fillG; +// vertex[B] = fillB; +// vertex[A] = fillA; +// } + if (fill || textureImage != null) { + if (textureImage == null) { + vertex[R] = fillR; + vertex[G] = fillG; + vertex[B] = fillB; + vertex[A] = fillA; + } else { + if (tint) { + vertex[R] = tintR; + vertex[G] = tintG; + vertex[B] = tintB; + vertex[A] = tintA; + } else { + vertex[R] = 1; + vertex[G] = 1; + vertex[B] = 1; + vertex[A] = 1; + } + } + } + + if (stroke) { + vertex[SR] = strokeR; + vertex[SG] = strokeG; + vertex[SB] = strokeB; + vertex[SA] = strokeA; + vertex[SW] = strokeWeight; + } + + if (textureImage != null) { + vertex[U] = textureU; + vertex[V] = textureV; + } + + vertexCount++; + } + + + public void vertex(float x, float y, float z) { + vertexCheck(); + float[] vertex = vertices[vertexCount]; + + // only do this if we're using an irregular (POLYGON) shape that + // will go through the triangulator. otherwise it'll do thinks like + // disappear in mathematically odd ways + // http://dev.processing.org/bugs/show_bug.cgi?id=444 + if (shape == POLYGON) { + if (vertexCount > 0) { + float pvertex[] = vertices[vertexCount-1]; + if ((Math.abs(pvertex[X] - x) < EPSILON) && + (Math.abs(pvertex[Y] - y) < EPSILON) && + (Math.abs(pvertex[Z] - z) < EPSILON)) { + // this vertex is identical, don't add it, + // because it will anger the triangulator + return; + } + } + } + + // User called vertex(), so that invalidates anything queued up for curve + // vertices. If this is internally called by curveVertexSegment, + // then curveVertexCount will be saved and restored. + curveVertexCount = 0; + + vertex[X] = x; + vertex[Y] = y; + vertex[Z] = z; + + vertex[EDGE] = edge ? 1 : 0; + + if (fill || textureImage != null) { + if (textureImage == null) { + vertex[R] = fillR; + vertex[G] = fillG; + vertex[B] = fillB; + vertex[A] = fillA; + } else { + if (tint) { + vertex[R] = tintR; + vertex[G] = tintG; + vertex[B] = tintB; + vertex[A] = tintA; + } else { + vertex[R] = 1; + vertex[G] = 1; + vertex[B] = 1; + vertex[A] = 1; + } + } + + vertex[AR] = ambientR; + vertex[AG] = ambientG; + vertex[AB] = ambientB; + + vertex[SPR] = specularR; + vertex[SPG] = specularG; + vertex[SPB] = specularB; + //vertex[SPA] = specularA; + + vertex[SHINE] = shininess; + + vertex[ER] = emissiveR; + vertex[EG] = emissiveG; + vertex[EB] = emissiveB; + } + + if (stroke) { + vertex[SR] = strokeR; + vertex[SG] = strokeG; + vertex[SB] = strokeB; + vertex[SA] = strokeA; + vertex[SW] = strokeWeight; + } + + if (textureImage != null) { + vertex[U] = textureU; + vertex[V] = textureV; + } + + vertex[NX] = normalX; + vertex[NY] = normalY; + vertex[NZ] = normalZ; + + vertex[BEEN_LIT] = 0; + + vertexCount++; + } + + + /** + * Used by renderer subclasses or PShape to efficiently pass in already + * formatted vertex information. + * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT + */ + public void vertex(float[] v) { + vertexCheck(); + curveVertexCount = 0; + float[] vertex = vertices[vertexCount]; + System.arraycopy(v, 0, vertex, 0, VERTEX_FIELD_COUNT); + vertexCount++; + } + + + public void vertex(float x, float y, float u, float v) { + vertexTexture(u, v); + vertex(x, y); + } + + + public void vertex(float x, float y, float z, float u, float v) { + vertexTexture(u, v); + vertex(x, y, z); + } + + + /** + * Internal method to copy all style information for the given vertex. + * Can be overridden by subclasses to handle only properties pertinent to + * that renderer. (e.g. no need to copy the emissive color in P2D) + */ +// protected void vertexStyle() { +// } + + + /** + * Set (U, V) coords for the next vertex in the current shape. + * This is ugly as its own function, and will (almost?) always be + * coincident with a call to vertex. As of beta, this was moved to + * the protected method you see here, and called from an optional + * param of and overloaded vertex(). + *

+ * The parameters depend on the current textureMode. When using + * textureMode(IMAGE), the coordinates will be relative to the size + * of the image texture, when used with textureMode(NORMAL), + * they'll be in the range 0..1. + *

+ * Used by both PGraphics2D (for images) and PGraphics3D. + */ + protected void vertexTexture(float u, float v) { + if (textureImage == null) { + throw new RuntimeException("You must first call texture() before " + + "using u and v coordinates with vertex()"); + } + if (textureMode == IMAGE) { + u /= (float) textureImage.width; + v /= (float) textureImage.height; + } + + textureU = u; + textureV = v; + + if (textureU < 0) textureU = 0; + else if (textureU > 1) textureU = 1; + + if (textureV < 0) textureV = 0; + else if (textureV > 1) textureV = 1; + } + + + /** This feature is in testing, do not use or rely upon its implementation */ + public void breakShape() { + showWarning("This renderer cannot currently handle concave shapes, " + + "or shapes with holes."); + } + + + public void endShape() { + endShape(OPEN); + } + + + public void endShape(int mode) { + } + + + + ////////////////////////////////////////////////////////////// + + // CURVE/BEZIER VERTEX HANDLING + + + protected void bezierVertexCheck() { + if (shape == 0 || shape != POLYGON) { + throw new RuntimeException("beginShape() or beginShape(POLYGON) " + + "must be used before bezierVertex()"); + } + if (vertexCount == 0) { + throw new RuntimeException("vertex() must be used at least once" + + "before bezierVertex()"); + } + } + + + public void bezierVertex(float x2, float y2, + float x3, float y3, + float x4, float y4) { + bezierInitCheck(); + bezierVertexCheck(); + PMatrix3D draw = bezierDrawMatrix; + + float[] prev = vertices[vertexCount-1]; + float x1 = prev[X]; + float y1 = prev[Y]; + + float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4; + float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4; + float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4; + + float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4; + float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4; + float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4; + + for (int j = 0; j < bezierDetail; j++) { + x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3; + y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3; + vertex(x1, y1); + } + } + + + public void bezierVertex(float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + bezierInitCheck(); + bezierVertexCheck(); + PMatrix3D draw = bezierDrawMatrix; + + float[] prev = vertices[vertexCount-1]; + float x1 = prev[X]; + float y1 = prev[Y]; + float z1 = prev[Z]; + + float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4; + float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4; + float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4; + + float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4; + float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4; + float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4; + + float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4; + float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4; + float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4; + + for (int j = 0; j < bezierDetail; j++) { + x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3; + y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3; + z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3; + vertex(x1, y1, z1); + } + } + + + /** + * Perform initialization specific to curveVertex(), and handle standard + * error modes. Can be overridden by subclasses that need the flexibility. + */ + protected void curveVertexCheck() { + if (shape != POLYGON) { + throw new RuntimeException("You must use beginShape() or " + + "beginShape(POLYGON) before curveVertex()"); + } + // to improve code init time, allocate on first use. + if (curveVertices == null) { + curveVertices = new float[128][3]; + } + + if (curveVertexCount == curveVertices.length) { + // Can't use PApplet.expand() cuz it doesn't do the copy properly + float[][] temp = new float[curveVertexCount << 1][3]; + System.arraycopy(curveVertices, 0, temp, 0, curveVertexCount); + curveVertices = temp; + } + curveInitCheck(); + } + + + public void curveVertex(float x, float y) { + curveVertexCheck(); + float[] vertex = curveVertices[curveVertexCount]; + vertex[X] = x; + vertex[Y] = y; + curveVertexCount++; + + // draw a segment if there are enough points + if (curveVertexCount > 3) { + curveVertexSegment(curveVertices[curveVertexCount-4][X], + curveVertices[curveVertexCount-4][Y], + curveVertices[curveVertexCount-3][X], + curveVertices[curveVertexCount-3][Y], + curveVertices[curveVertexCount-2][X], + curveVertices[curveVertexCount-2][Y], + curveVertices[curveVertexCount-1][X], + curveVertices[curveVertexCount-1][Y]); + } + } + + + public void curveVertex(float x, float y, float z) { + curveVertexCheck(); + float[] vertex = curveVertices[curveVertexCount]; + vertex[X] = x; + vertex[Y] = y; + vertex[Z] = z; + curveVertexCount++; + + // draw a segment if there are enough points + if (curveVertexCount > 3) { + curveVertexSegment(curveVertices[curveVertexCount-4][X], + curveVertices[curveVertexCount-4][Y], + curveVertices[curveVertexCount-4][Z], + curveVertices[curveVertexCount-3][X], + curveVertices[curveVertexCount-3][Y], + curveVertices[curveVertexCount-3][Z], + curveVertices[curveVertexCount-2][X], + curveVertices[curveVertexCount-2][Y], + curveVertices[curveVertexCount-2][Z], + curveVertices[curveVertexCount-1][X], + curveVertices[curveVertexCount-1][Y], + curveVertices[curveVertexCount-1][Z]); + } + } + + + /** + * Handle emitting a specific segment of Catmull-Rom curve. This can be + * overridden by subclasses that need more efficient rendering options. + */ + protected void curveVertexSegment(float x1, float y1, + float x2, float y2, + float x3, float y3, + float x4, float y4) { + float x0 = x2; + float y0 = y2; + + PMatrix3D draw = curveDrawMatrix; + + float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4; + float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4; + float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4; + + float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4; + float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4; + float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4; + + // vertex() will reset splineVertexCount, so save it + int savedCount = curveVertexCount; + + vertex(x0, y0); + for (int j = 0; j < curveDetail; j++) { + x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; + y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; + vertex(x0, y0); + } + curveVertexCount = savedCount; + } + + + /** + * Handle emitting a specific segment of Catmull-Rom curve. This can be + * overridden by subclasses that need more efficient rendering options. + */ + protected void curveVertexSegment(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + float x0 = x2; + float y0 = y2; + float z0 = z2; + + PMatrix3D draw = curveDrawMatrix; + + float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4; + float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4; + float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4; + + float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4; + float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4; + float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4; + + // vertex() will reset splineVertexCount, so save it + int savedCount = curveVertexCount; + + float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4; + float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4; + float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4; + + vertex(x0, y0, z0); + for (int j = 0; j < curveDetail; j++) { + x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; + y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; + z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3; + vertex(x0, y0, z0); + } + curveVertexCount = savedCount; + } + + + + ////////////////////////////////////////////////////////////// + + // SIMPLE SHAPES WITH ANALOGUES IN beginShape() + + + public void point(float x, float y) { + beginShape(POINTS); + vertex(x, y); + endShape(); + } + + + /** + * Draws a point, a coordinate in space at the dimension of one pixel. + * The first parameter is the horizontal value for the point, the second + * value is the vertical value for the point, and the optional third value + * is the depth value. Drawing this shape in 3D using the z + * parameter requires the P3D or OPENGL parameter in combination with + * size as shown in the above example. + *

Due to what appears to be a bug in Apple's Java implementation, + * the point() and set() methods are extremely slow in some circumstances + * when used with the default renderer. Using P2D or P3D will fix the + * problem. Grouping many calls to point() or set() together can also + * help. (Bug 1094) + * + * @webref shape:2d_primitives + * @param x x-coordinate of the point + * @param y y-coordinate of the point + * @param z z-coordinate of the point + * + * @see PGraphics#beginShape() + */ + public void point(float x, float y, float z) { + beginShape(POINTS); + vertex(x, y, z); + endShape(); + } + + + public void line(float x1, float y1, float x2, float y2) { + beginShape(LINES); + vertex(x1, y1); + vertex(x2, y2); + endShape(); + } + + + + /** + * Draws a line (a direct path between two points) to the screen. + * The version of line() with four parameters draws the line in 2D. + * To color a line, use the stroke() function. A line cannot be + * filled, therefore the fill() method will not affect the color + * of a line. 2D lines are drawn with a width of one pixel by default, + * but this can be changed with the strokeWeight() function. + * The version with six parameters allows the line to be placed anywhere + * within XYZ space. Drawing this shape in 3D using the z parameter + * requires the P3D or OPENGL parameter in combination with size as shown + * in the above example. + * + * @webref shape:2d_primitives + * @param x1 x-coordinate of the first point + * @param y1 y-coordinate of the first point + * @param z1 z-coordinate of the first point + * @param x2 x-coordinate of the second point + * @param y2 y-coordinate of the second point + * @param z2 z-coordinate of the second point + * + * @see PGraphics#strokeWeight(float) + * @see PGraphics#strokeJoin(int) + * @see PGraphics#strokeCap(int) + * @see PGraphics#beginShape() + */ + public void line(float x1, float y1, float z1, + float x2, float y2, float z2) { + beginShape(LINES); + vertex(x1, y1, z1); + vertex(x2, y2, z2); + endShape(); + } + + + /** + * A triangle is a plane created by connecting three points. The first two + * arguments specify the first point, the middle two arguments specify + * the second point, and the last two arguments specify the third point. + * + * @webref shape:2d_primitives + * @param x1 x-coordinate of the first point + * @param y1 y-coordinate of the first point + * @param x2 x-coordinate of the second point + * @param y2 y-coordinate of the second point + * @param x3 x-coordinate of the third point + * @param y3 y-coordinate of the third point + * + * @see PApplet#beginShape() + */ + public void triangle(float x1, float y1, float x2, float y2, + float x3, float y3) { + beginShape(TRIANGLES); + vertex(x1, y1); + vertex(x2, y2); + vertex(x3, y3); + endShape(); + } + + + /** + * A quad is a quadrilateral, a four sided polygon. It is similar to + * a rectangle, but the angles between its edges are not constrained + * ninety degrees. The first pair of parameters (x1,y1) sets the + * first vertex and the subsequent pairs should proceed clockwise or + * counter-clockwise around the defined shape. + * + * @webref shape:2d_primitives + * @param x1 x-coordinate of the first corner + * @param y1 y-coordinate of the first corner + * @param x2 x-coordinate of the second corner + * @param y2 y-coordinate of the second corner + * @param x3 x-coordinate of the third corner + * @param y3 y-coordinate of the third corner + * @param x4 x-coordinate of the fourth corner + * @param y4 y-coordinate of the fourth corner + * + */ + public void quad(float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4) { + beginShape(QUADS); + vertex(x1, y1); + vertex(x2, y2); + vertex(x3, y3); + vertex(x4, y4); + endShape(); + } + + + + ////////////////////////////////////////////////////////////// + + // RECT + + + public void rectMode(int mode) { + rectMode = mode; + } + + + /** + * Draws a rectangle to the screen. A rectangle is a four-sided shape with + * every angle at ninety degrees. The first two parameters set the location, + * the third sets the width, and the fourth sets the height. The origin is + * changed with the rectMode() function. + * + * @webref shape:2d_primitives + * @param a x-coordinate of the rectangle + * @param b y-coordinate of the rectangle + * @param c width of the rectangle + * @param d height of the rectangle + * + * @see PGraphics#rectMode(int) + * @see PGraphics#quad(float, float, float, float, float, float, float, float) + */ + public void rect(float a, float b, float c, float d) { + float hradius, vradius; + switch (rectMode) { + case CORNERS: + break; + case CORNER: + c += a; d += b; + break; + case RADIUS: + hradius = c; + vradius = d; + c = a + hradius; + d = b + vradius; + a -= hradius; + b -= vradius; + break; + case CENTER: + hradius = c / 2.0f; + vradius = d / 2.0f; + c = a + hradius; + d = b + vradius; + a -= hradius; + b -= vradius; + } + + if (a > c) { + float temp = a; a = c; c = temp; + } + + if (b > d) { + float temp = b; b = d; d = temp; + } + + rectImpl(a, b, c, d); + } + + + protected void rectImpl(float x1, float y1, float x2, float y2) { + quad(x1, y1, x2, y1, x2, y2, x1, y2); + } + + + // Still need to do a lot of work here to make it behave across renderers + // (e.g. not all renderers use the vertices array) + // Also seems to be some issues on quality here (too dense) + // http://code.google.com/p/processing/issues/detail?id=265 + private void quadraticVertex(float cpx, float cpy, float x, float y) { + float[] prev = vertices[vertexCount - 1]; + float prevX = prev[X]; + float prevY = prev[Y]; + float cp1x = prevX + 2.0f/3.0f*(cpx - prevX); + float cp1y = prevY + 2.0f/3.0f*(cpy - prevY); + float cp2x = cp1x + (x - prevX)/3.0f; + float cp2y = cp1y + (y - prevY)/3.0f; + bezierVertex(cp1x, cp1y, cp2x, cp2y, x, y); + } + + + public void rect(float a, float b, float c, float d, float hr, float vr) { + float hradius, vradius; + switch (rectMode) { + case CORNERS: + break; + case CORNER: + c += a; d += b; + break; + case RADIUS: + hradius = c; + vradius = d; + c = a + hradius; + d = b + vradius; + a -= hradius; + b -= vradius; + break; + case CENTER: + hradius = c / 2.0f; + vradius = d / 2.0f; + c = a + hradius; + d = b + vradius; + a -= hradius; + b -= vradius; + } + + if (a > c) { + float temp = a; a = c; c = temp; + } + + if (b > d) { + float temp = b; b = d; d = temp; + } + + rectImpl(a, b, c, d, hr, vr); + } + + + protected void rectImpl(float x1, float y1, float x2, float y2, float hr, float vr) { + beginShape(); +// vertex(x1+hr, y1); + vertex(x2-hr, y1); + quadraticVertex(x2, y1, x2, y1+vr); + vertex(x2, y2-vr); + quadraticVertex(x2, y2, x2-hr, y2); + vertex(x1+hr, y2); + quadraticVertex(x1, y2, x1, y2-vr); + vertex(x1, y1+vr); + quadraticVertex(x1, y1, x1+hr, y1); +// endShape(); + endShape(CLOSE); + } + + + public void rect(float a, float b, float c, float d, + float tl, float tr, float bl, float br) { + float hradius, vradius; + switch (rectMode) { + case CORNERS: + break; + case CORNER: + c += a; d += b; + break; + case RADIUS: + hradius = c; + vradius = d; + c = a + hradius; + d = b + vradius; + a -= hradius; + b -= vradius; + break; + case CENTER: + hradius = c / 2.0f; + vradius = d / 2.0f; + c = a + hradius; + d = b + vradius; + a -= hradius; + b -= vradius; + } + + if (a > c) { + float temp = a; a = c; c = temp; + } + + if (b > d) { + float temp = b; b = d; d = temp; + } + + rectImpl(a, b, c, d, tl, tr, bl, br); + } + + + protected void rectImpl(float x1, float y1, float x2, float y2, + float tl, float tr, float bl, float br) { + beginShape(); +// vertex(x1+tl, y1); + if (tr != 0) { + vertex(x2-tr, y1); + quadraticVertex(x2, y1, x2, y1+tr); + } else { + vertex(x2, y1); + } + if (br != 0) { + vertex(x2, y2-br); + quadraticVertex(x2, y2, x2-br, y2); + } else { + vertex(x2, y2); + } + if (bl != 0) { + vertex(x1+bl, y2); + quadraticVertex(x1, y2, x1, y2-bl); + } else { + vertex(x1, y2); + } + if (tl != 0) { + vertex(x1, y1+tl); + quadraticVertex(x1, y1, x1+tl, y1); + } else { + vertex(x1, y1); + } +// endShape(); + endShape(CLOSE); + } + + + + ////////////////////////////////////////////////////////////// + + // ELLIPSE AND ARC + + + /** + * The origin of the ellipse is modified by the ellipseMode() + * function. The default configuration is ellipseMode(CENTER), + * which specifies the location of the ellipse as the center of the shape. + * The RADIUS mode is the same, but the width and height parameters to + * ellipse() specify the radius of the ellipse, rather than the + * diameter. The CORNER mode draws the shape from the upper-left corner + * of its bounding box. The CORNERS mode uses the four parameters to + * ellipse() to set two opposing corners of the ellipse's bounding + * box. The parameter must be written in "ALL CAPS" because Processing + * syntax is case sensitive. + * + * @webref shape:attributes + * + * @param mode Either CENTER, RADIUS, CORNER, or CORNERS. + * @see PApplet#ellipse(float, float, float, float) + */ + public void ellipseMode(int mode) { + ellipseMode = mode; + } + + + /** + * Draws an ellipse (oval) in the display window. An ellipse with an equal + * width and height is a circle. The first two parameters set + * the location, the third sets the width, and the fourth sets the height. + * The origin may be changed with the ellipseMode() function. + * + * @webref shape:2d_primitives + * @param a x-coordinate of the ellipse + * @param b y-coordinate of the ellipse + * @param c width of the ellipse + * @param d height of the ellipse + * + * @see PApplet#ellipseMode(int) + */ + public void ellipse(float a, float b, float c, float d) { + float x = a; + float y = b; + float w = c; + float h = d; + + if (ellipseMode == CORNERS) { + w = c - a; + h = d - b; + + } else if (ellipseMode == RADIUS) { + x = a - c; + y = b - d; + w = c * 2; + h = d * 2; + + } else if (ellipseMode == DIAMETER) { + x = a - c/2f; + y = b - d/2f; + } + + if (w < 0) { // undo negative width + x += w; + w = -w; + } + + if (h < 0) { // undo negative height + y += h; + h = -h; + } + + ellipseImpl(x, y, w, h); + } + + + protected void ellipseImpl(float x, float y, float w, float h) { + } + + + /** + * Draws an arc in the display window. + * Arcs are drawn along the outer edge of an ellipse defined by the + * x, y, width and height parameters. + * The origin or the arc's ellipse may be changed with the + * ellipseMode() function. + * The start and stop parameters specify the angles + * at which to draw the arc. + * + * @webref shape:2d_primitives + * @param a x-coordinate of the arc's ellipse + * @param b y-coordinate of the arc's ellipse + * @param c width of the arc's ellipse + * @param d height of the arc's ellipse + * @param start angle to start the arc, specified in radians + * @param stop angle to stop the arc, specified in radians + * + * @see PGraphics#ellipseMode(int) + * @see PGraphics#ellipse(float, float, float, float) + */ + public void arc(float a, float b, float c, float d, + float start, float stop) { + float x = a; + float y = b; + float w = c; + float h = d; + + if (ellipseMode == CORNERS) { + w = c - a; + h = d - b; + + } else if (ellipseMode == RADIUS) { + x = a - c; + y = b - d; + w = c * 2; + h = d * 2; + + } else if (ellipseMode == CENTER) { + x = a - c/2f; + y = b - d/2f; + } + + // make sure this loop will exit before starting while + if (Float.isInfinite(start) || Float.isInfinite(stop)) return; +// while (stop < start) stop += TWO_PI; + if (stop < start) return; // why bother + + // make sure that we're starting at a useful point + while (start < 0) { + start += TWO_PI; + stop += TWO_PI; + } + + if (stop - start > TWO_PI) { + start = 0; + stop = TWO_PI; + } + + arcImpl(x, y, w, h, start, stop); + } + + + /** + * Start and stop are in radians, converted by the parent function. + * Note that the radians can be greater (or less) than TWO_PI. + * This is so that an arc can be drawn that crosses zero mark, + * and the user will still collect $200. + */ + protected void arcImpl(float x, float y, float w, float h, + float start, float stop) { + } + + + + ////////////////////////////////////////////////////////////// + + // BOX + + + /** + * @param size dimension of the box in all dimensions, creates a cube + */ + public void box(float size) { + box(size, size, size); + } + + + /** + * A box is an extruded rectangle. A box with equal dimension + * on all sides is a cube. + * + * @webref shape:3d_primitives + * @param w dimension of the box in the x-dimension + * @param h dimension of the box in the y-dimension + * @param d dimension of the box in the z-dimension + * + * @see PApplet#sphere(float) + */ + public void box(float w, float h, float d) { + float x1 = -w/2f; float x2 = w/2f; + float y1 = -h/2f; float y2 = h/2f; + float z1 = -d/2f; float z2 = d/2f; + + // TODO not the least bit efficient, it even redraws lines + // along the vertices. ugly ugly ugly! + + beginShape(QUADS); + + // front + normal(0, 0, 1); + vertex(x1, y1, z1); + vertex(x2, y1, z1); + vertex(x2, y2, z1); + vertex(x1, y2, z1); + + // right + normal(1, 0, 0); + vertex(x2, y1, z1); + vertex(x2, y1, z2); + vertex(x2, y2, z2); + vertex(x2, y2, z1); + + // back + normal(0, 0, -1); + vertex(x2, y1, z2); + vertex(x1, y1, z2); + vertex(x1, y2, z2); + vertex(x2, y2, z2); + + // left + normal(-1, 0, 0); + vertex(x1, y1, z2); + vertex(x1, y1, z1); + vertex(x1, y2, z1); + vertex(x1, y2, z2); + + // top + normal(0, 1, 0); + vertex(x1, y1, z2); + vertex(x2, y1, z2); + vertex(x2, y1, z1); + vertex(x1, y1, z1); + + // bottom + normal(0, -1, 0); + vertex(x1, y2, z1); + vertex(x2, y2, z1); + vertex(x2, y2, z2); + vertex(x1, y2, z2); + + endShape(); + } + + + + ////////////////////////////////////////////////////////////// + + // SPHERE + + + /** + * @param res number of segments (minimum 3) used per full circle revolution + */ + public void sphereDetail(int res) { + sphereDetail(res, res); + } + + + /** + * Controls the detail used to render a sphere by adjusting the number of + * vertices of the sphere mesh. The default resolution is 30, which creates + * a fairly detailed sphere definition with vertices every 360/30 = 12 + * degrees. If you're going to render a great number of spheres per frame, + * it is advised to reduce the level of detail using this function. + * The setting stays active until sphereDetail() is called again with + * a new parameter and so should not be called prior to every + * sphere() statement, unless you wish to render spheres with + * different settings, e.g. using less detail for smaller spheres or ones + * further away from the camera. To control the detail of the horizontal + * and vertical resolution independently, use the version of the functions + * with two parameters. + * + * =advanced + * Code for sphereDetail() submitted by toxi [031031]. + * Code for enhanced u/v version from davbol [080801]. + * + * @webref shape:3d_primitives + * @param ures number of segments used horizontally (longitudinally) + * per full circle revolution + * @param vres number of segments used vertically (latitudinally) + * from top to bottom + * + * @see PGraphics#sphere(float) + */ + /** + * Set the detail level for approximating a sphere. The ures and vres params + * control the horizontal and vertical resolution. + * + */ + public void sphereDetail(int ures, int vres) { + if (ures < 3) ures = 3; // force a minimum res + if (vres < 2) vres = 2; // force a minimum res + if ((ures == sphereDetailU) && (vres == sphereDetailV)) return; + + float delta = (float)SINCOS_LENGTH/ures; + float[] cx = new float[ures]; + float[] cz = new float[ures]; + // calc unit circle in XZ plane + for (int i = 0; i < ures; i++) { + cx[i] = cosLUT[(int) (i*delta) % SINCOS_LENGTH]; + cz[i] = sinLUT[(int) (i*delta) % SINCOS_LENGTH]; + } + // computing vertexlist + // vertexlist starts at south pole + int vertCount = ures * (vres-1) + 2; + int currVert = 0; + + // re-init arrays to store vertices + sphereX = new float[vertCount]; + sphereY = new float[vertCount]; + sphereZ = new float[vertCount]; + + float angle_step = (SINCOS_LENGTH*0.5f)/vres; + float angle = angle_step; + + // step along Y axis + for (int i = 1; i < vres; i++) { + float curradius = sinLUT[(int) angle % SINCOS_LENGTH]; + float currY = -cosLUT[(int) angle % SINCOS_LENGTH]; + for (int j = 0; j < ures; j++) { + sphereX[currVert] = cx[j] * curradius; + sphereY[currVert] = currY; + sphereZ[currVert++] = cz[j] * curradius; + } + angle += angle_step; + } + sphereDetailU = ures; + sphereDetailV = vres; + } + + + /** + * Draw a sphere with radius r centered at coordinate 0, 0, 0. + * A sphere is a hollow ball made from tessellated triangles. + * =advanced + *

+ * Implementation notes: + *

+ * cache all the points of the sphere in a static array + * top and bottom are just a bunch of triangles that land + * in the center point + *

+ * sphere is a series of concentric circles who radii vary + * along the shape, based on, er.. cos or something + *

+   * [toxi 031031] new sphere code. removed all multiplies with
+   * radius, as scale() will take care of that anyway
+   *
+   * [toxi 031223] updated sphere code (removed modulos)
+   * and introduced sphereAt(x,y,z,r)
+   * to avoid additional translate()'s on the user/sketch side
+   *
+   * [davbol 080801] now using separate sphereDetailU/V
+   * 
+ * + * @webref shape:3d_primitives + * @param r the radius of the sphere + */ + public void sphere(float r) { + if ((sphereDetailU < 3) || (sphereDetailV < 2)) { + sphereDetail(30); + } + + pushMatrix(); + scale(r); + edge(false); + + // 1st ring from south pole + beginShape(TRIANGLE_STRIP); + for (int i = 0; i < sphereDetailU; i++) { + normal(0, -1, 0); + vertex(0, -1, 0); + normal(sphereX[i], sphereY[i], sphereZ[i]); + vertex(sphereX[i], sphereY[i], sphereZ[i]); + } + //normal(0, -1, 0); + vertex(0, -1, 0); + normal(sphereX[0], sphereY[0], sphereZ[0]); + vertex(sphereX[0], sphereY[0], sphereZ[0]); + endShape(); + + int v1,v11,v2; + + // middle rings + int voff = 0; + for (int i = 2; i < sphereDetailV; i++) { + v1 = v11 = voff; + voff += sphereDetailU; + v2 = voff; + beginShape(TRIANGLE_STRIP); + for (int j = 0; j < sphereDetailU; j++) { + normal(sphereX[v1], sphereY[v1], sphereZ[v1]); + vertex(sphereX[v1], sphereY[v1], sphereZ[v1++]); + normal(sphereX[v2], sphereY[v2], sphereZ[v2]); + vertex(sphereX[v2], sphereY[v2], sphereZ[v2++]); + } + // close each ring + v1 = v11; + v2 = voff; + normal(sphereX[v1], sphereY[v1], sphereZ[v1]); + vertex(sphereX[v1], sphereY[v1], sphereZ[v1]); + normal(sphereX[v2], sphereY[v2], sphereZ[v2]); + vertex(sphereX[v2], sphereY[v2], sphereZ[v2]); + endShape(); + } + + // add the northern cap + beginShape(TRIANGLE_STRIP); + for (int i = 0; i < sphereDetailU; i++) { + v2 = voff + i; + normal(sphereX[v2], sphereY[v2], sphereZ[v2]); + vertex(sphereX[v2], sphereY[v2], sphereZ[v2]); + normal(0, 1, 0); + vertex(0, 1, 0); + } + normal(sphereX[voff], sphereY[voff], sphereZ[voff]); + vertex(sphereX[voff], sphereY[voff], sphereZ[voff]); + normal(0, 1, 0); + vertex(0, 1, 0); + endShape(); + + edge(true); + popMatrix(); + } + + + + ////////////////////////////////////////////////////////////// + + // BEZIER + + /** + * Evaluates the Bezier at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b and c are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a bezier curve at t. + */ + + /** + * Evalutes quadratic bezier at point t for points a, b, c, d. + * The parameter t varies between 0 and 1. The a and d parameters are the + * on-curve points, b and c are the control points. To make a two-dimensional + * curve, call this function once with the x coordinates and a second time + * with the y coordinates to get the location of a bezier curve at t. + * + * =advanced + * For instance, to convert the following example:
+   * stroke(255, 102, 0);
+   * line(85, 20, 10, 10);
+   * line(90, 90, 15, 80);
+   * stroke(0, 0, 0);
+   * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+   *
+   * // draw it in gray, using 10 steps instead of the default 20
+   * // this is a slower way to do it, but useful if you need
+   * // to do things with the coordinates at each step
+   * stroke(128);
+   * beginShape(LINE_STRIP);
+   * for (int i = 0; i <= 10; i++) {
+   *   float t = i / 10.0f;
+   *   float x = bezierPoint(85, 10, 90, 15, t);
+   *   float y = bezierPoint(20, 10, 90, 80, t);
+   *   vertex(x, y);
+   * }
+   * endShape();
+ * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of first control point + * @param c coordinate of second control point + * @param d coordinate of second point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#bezierVertex(float, float, float, float, float, float) + * @see PGraphics#curvePoint(float, float, float, float, float) + */ + public float bezierPoint(float a, float b, float c, float d, float t) { + float t1 = 1.0f - t; + return a*t1*t1*t1 + 3*b*t*t1*t1 + 3*c*t*t*t1 + d*t*t*t; + } + + + /** + * Calculates the tangent of a point on a Bezier curve. There is a good + * definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent + * + * =advanced + * Code submitted by Dave Bollinger (davol) for release 0136. + * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of first control point + * @param c coordinate of second control point + * @param d coordinate of second point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#bezierVertex(float, float, float, float, float, float) + * @see PGraphics#curvePoint(float, float, float, float, float) + */ + public float bezierTangent(float a, float b, float c, float d, float t) { + return (3*t*t * (-a+3*b-3*c+d) + + 6*t * (a-2*b+c) + + 3 * (-a+b)); + } + + + protected void bezierInitCheck() { + if (!bezierInited) { + bezierInit(); + } + } + + + protected void bezierInit() { + // overkill to be broken out, but better parity with the curve stuff below + bezierDetail(bezierDetail); + bezierInited = true; + } + + + /** + * Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the P3D or OPENGL renderer as the default (JAVA2D) renderer does not use this information. + * + * @webref shape:curves + * @param detail resolution of the curves + * + * @see PApplet#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PApplet#curveVertex(float, float) + * @see PApplet#curveTightness(float) + */ + public void bezierDetail(int detail) { + bezierDetail = detail; + + if (bezierDrawMatrix == null) { + bezierDrawMatrix = new PMatrix3D(); + } + + // setup matrix for forward differencing to speed up drawing + splineForward(detail, bezierDrawMatrix); + + // multiply the basis and forward diff matrices together + // saves much time since this needn't be done for each curve + //mult_spline_matrix(bezierForwardMatrix, bezier_basis, bezierDrawMatrix, 4); + //bezierDrawMatrix.set(bezierForwardMatrix); + bezierDrawMatrix.apply(bezierBasisMatrix); + } + + + /** + * Draws a Bezier curve on the screen. These curves are defined by a series + * of anchor and control points. The first two parameters specify the first + * anchor point and the last two parameters specify the other anchor point. + * The middle parameters specify the control points which define the shape + * of the curve. Bezier curves were developed by French engineer Pierre + * Bezier. Using the 3D version of requires rendering with P3D or OPENGL + * (see the Environment reference for more information). + * + * =advanced + * Draw a cubic bezier curve. The first and last points are + * the on-curve points. The middle two are the 'control' points, + * or 'handles' in an application like Illustrator. + *

+ * Identical to typing: + *

beginShape();
+   * vertex(x1, y1);
+   * bezierVertex(x2, y2, x3, y3, x4, y4);
+   * endShape();
+   * 
+ * In Postscript-speak, this would be: + *
moveto(x1, y1);
+   * curveto(x2, y2, x3, y3, x4, y4);
+ * If you were to try and continue that curve like so: + *
curveto(x5, y5, x6, y6, x7, y7);
+ * This would be done in processing by adding these statements: + *
bezierVertex(x5, y5, x6, y6, x7, y7)
+   * 
+ * To draw a quadratic (instead of cubic) curve, + * use the control point twice by doubling it: + *
bezier(x1, y1, cx, cy, cx, cy, x2, y2);
+ * + * @webref shape:curves + * @param x1 coordinates for the first anchor point + * @param y1 coordinates for the first anchor point + * @param z1 coordinates for the first anchor point + * @param x2 coordinates for the first control point + * @param y2 coordinates for the first control point + * @param z2 coordinates for the first control point + * @param x3 coordinates for the second control point + * @param y3 coordinates for the second control point + * @param z3 coordinates for the second control point + * @param x4 coordinates for the second anchor point + * @param y4 coordinates for the second anchor point + * @param z4 coordinates for the second anchor point + * + * @see PGraphics#bezierVertex(float, float, float, float, float, float) + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + */ + public void bezier(float x1, float y1, + float x2, float y2, + float x3, float y3, + float x4, float y4) { + beginShape(); + vertex(x1, y1); + bezierVertex(x2, y2, x3, y3, x4, y4); + endShape(); + } + + + public void bezier(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + beginShape(); + vertex(x1, y1, z1); + bezierVertex(x2, y2, z2, + x3, y3, z3, + x4, y4, z4); + endShape(); + } + + + + ////////////////////////////////////////////////////////////// + + // CATMULL-ROM CURVE + + + /** + * Evalutes the Catmull-Rom curve at point t for points a, b, c, d. The + * parameter t varies between 0 and 1, a and d are points on the curve, + * and b and c are the control points. This can be done once with the x + * coordinates and a second time with the y coordinates to get the + * location of a curve at t. + * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of second point on the curve + * @param c coordinate of third point on the curve + * @param d coordinate of fourth point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#bezierPoint(float, float, float, float, float) + */ + public float curvePoint(float a, float b, float c, float d, float t) { + curveInitCheck(); + + float tt = t * t; + float ttt = t * tt; + PMatrix3D cb = curveBasisMatrix; + + // not optimized (and probably need not be) + return (a * (ttt*cb.m00 + tt*cb.m10 + t*cb.m20 + cb.m30) + + b * (ttt*cb.m01 + tt*cb.m11 + t*cb.m21 + cb.m31) + + c * (ttt*cb.m02 + tt*cb.m12 + t*cb.m22 + cb.m32) + + d * (ttt*cb.m03 + tt*cb.m13 + t*cb.m23 + cb.m33)); + } + + + /** + * Calculates the tangent of a point on a Catmull-Rom curve. There is a good definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent. + * + * =advanced + * Code thanks to Dave Bollinger (Bug #715) + * + * @webref shape:curves + * @param a coordinate of first point on the curve + * @param b coordinate of first control point + * @param c coordinate of second control point + * @param d coordinate of second point on the curve + * @param t value between 0 and 1 + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#curvePoint(float, float, float, float, float) + * @see PGraphics#bezierTangent(float, float, float, float, float) + */ + public float curveTangent(float a, float b, float c, float d, float t) { + curveInitCheck(); + + float tt3 = t * t * 3; + float t2 = t * 2; + PMatrix3D cb = curveBasisMatrix; + + // not optimized (and probably need not be) + return (a * (tt3*cb.m00 + t2*cb.m10 + cb.m20) + + b * (tt3*cb.m01 + t2*cb.m11 + cb.m21) + + c * (tt3*cb.m02 + t2*cb.m12 + cb.m22) + + d * (tt3*cb.m03 + t2*cb.m13 + cb.m23) ); + } + + + /** + * Sets the resolution at which curves display. The default value is 20. + * This function is only useful when using the P3D or OPENGL renderer as + * the default (JAVA2D) renderer does not use this information. + * + * @webref shape:curves + * @param detail resolution of the curves + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#curveTightness(float) + */ + public void curveDetail(int detail) { + curveDetail = detail; + curveInit(); + } + + + /** + * Modifies the quality of forms created with curve() and + *curveVertex(). The parameter squishy determines how the + * curve fits to the vertex points. The value 0.0 is the default value for + * squishy (this value defines the curves to be Catmull-Rom splines) + * and the value 1.0 connects all the points with straight lines. + * Values within the range -5.0 and 5.0 will deform the curves but + * will leave them recognizable and as values increase in magnitude, + * they will continue to deform. + * + * @webref shape:curves + * @param tightness amount of deformation from the original vertices + * + * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) + * @see PGraphics#curveVertex(float, float) + * + */ + public void curveTightness(float tightness) { + curveTightness = tightness; + curveInit(); + } + + + protected void curveInitCheck() { + if (!curveInited) { + curveInit(); + } + } + + + /** + * Set the number of segments to use when drawing a Catmull-Rom + * curve, and setting the s parameter, which defines how tightly + * the curve fits to each vertex. Catmull-Rom curves are actually + * a subset of this curve type where the s is set to zero. + *

+ * (This function is not optimized, since it's not expected to + * be called all that often. there are many juicy and obvious + * opimizations in here, but it's probably better to keep the + * code more readable) + */ + protected void curveInit() { + // allocate only if/when used to save startup time + if (curveDrawMatrix == null) { + curveBasisMatrix = new PMatrix3D(); + curveDrawMatrix = new PMatrix3D(); + curveInited = true; + } + + float s = curveTightness; + curveBasisMatrix.set((s-1)/2f, (s+3)/2f, (-3-s)/2f, (1-s)/2f, + (1-s), (-5-s)/2f, (s+2), (s-1)/2f, + (s-1)/2f, 0, (1-s)/2f, 0, + 0, 1, 0, 0); + + //setup_spline_forward(segments, curveForwardMatrix); + splineForward(curveDetail, curveDrawMatrix); + + if (bezierBasisInverse == null) { + bezierBasisInverse = bezierBasisMatrix.get(); + bezierBasisInverse.invert(); + curveToBezierMatrix = new PMatrix3D(); + } + + // TODO only needed for PGraphicsJava2D? if so, move it there + // actually, it's generally useful for other renderers, so keep it + // or hide the implementation elsewhere. + curveToBezierMatrix.set(curveBasisMatrix); + curveToBezierMatrix.preApply(bezierBasisInverse); + + // multiply the basis and forward diff matrices together + // saves much time since this needn't be done for each curve + curveDrawMatrix.apply(curveBasisMatrix); + } + + + /** + * Draws a curved line on the screen. The first and second parameters + * specify the beginning control point and the last two parameters specify + * the ending control point. The middle parameters specify the start and + * stop of the curve. Longer curves can be created by putting a series of + * curve() functions together or using curveVertex(). + * An additional function called curveTightness() provides control + * for the visual quality of the curve. The curve() function is an + * implementation of Catmull-Rom splines. Using the 3D version of requires + * rendering with P3D or OPENGL (see the Environment reference for more + * information). + * + * =advanced + * As of revision 0070, this function no longer doubles the first + * and last points. The curves are a bit more boring, but it's more + * mathematically correct, and properly mirrored in curvePoint(). + *

+ * Identical to typing out:

+   * beginShape();
+   * curveVertex(x1, y1);
+   * curveVertex(x2, y2);
+   * curveVertex(x3, y3);
+   * curveVertex(x4, y4);
+   * endShape();
+   * 
+ * + * @webref shape:curves + * @param x1 coordinates for the beginning control point + * @param y1 coordinates for the beginning control point + * @param z1 coordinates for the beginning control point + * @param x2 coordinates for the first point + * @param y2 coordinates for the first point + * @param z2 coordinates for the first point + * @param x3 coordinates for the second point + * @param y3 coordinates for the second point + * @param z3 coordinates for the second point + * @param x4 coordinates for the ending control point + * @param y4 coordinates for the ending control point + * @param z4 coordinates for the ending control point + * + * @see PGraphics#curveVertex(float, float) + * @see PGraphics#curveTightness(float) + * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) + */ + public void curve(float x1, float y1, + float x2, float y2, + float x3, float y3, + float x4, float y4) { + beginShape(); + curveVertex(x1, y1); + curveVertex(x2, y2); + curveVertex(x3, y3); + curveVertex(x4, y4); + endShape(); + } + + + public void curve(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + beginShape(); + curveVertex(x1, y1, z1); + curveVertex(x2, y2, z2); + curveVertex(x3, y3, z3); + curveVertex(x4, y4, z4); + endShape(); + } + + + + ////////////////////////////////////////////////////////////// + + // SPLINE UTILITY FUNCTIONS (used by both Bezier and Catmull-Rom) + + + /** + * Setup forward-differencing matrix to be used for speedy + * curve rendering. It's based on using a specific number + * of curve segments and just doing incremental adds for each + * vertex of the segment, rather than running the mathematically + * expensive cubic equation. + * @param segments number of curve segments to use when drawing + * @param matrix target object for the new matrix + */ + protected void splineForward(int segments, PMatrix3D matrix) { + float f = 1.0f / segments; + float ff = f * f; + float fff = ff * f; + + matrix.set(0, 0, 0, 1, + fff, ff, f, 0, + 6*fff, 2*ff, 0, 0, + 6*fff, 0, 0, 0); + } + + + + ////////////////////////////////////////////////////////////// + + // SMOOTHING + + + /** + * If true in PImage, use bilinear interpolation for copy() + * operations. When inherited by PGraphics, also controls shapes. + */ + public void smooth() { + smooth = true; + } + + + /** + * Disable smoothing. See smooth(). + */ + public void noSmooth() { + smooth = false; + } + + + + ////////////////////////////////////////////////////////////// + + // IMAGE + + + /** + * Modifies the location from which images draw. The default mode is + * imageMode(CORNER), which specifies the location to be the + * upper-left corner and uses the fourth and fifth parameters of + * image() to set the image's width and height. The syntax + * imageMode(CORNERS) uses the second and third parameters of + * image() to set the location of one corner of the image and + * uses the fourth and fifth parameters to set the opposite corner. + * Use imageMode(CENTER) to draw images centered at the given + * x and y position. + *

The parameter to imageMode() must be written in + * ALL CAPS because Processing syntax is case sensitive. + * + * @webref image:loading_displaying + * @param mode Either CORNER, CORNERS, or CENTER + * + * @see processing.core.PApplet#loadImage(String, String) + * @see processing.core.PImage + * @see processing.core.PApplet#image(PImage, float, float, float, float) + * @see processing.core.PGraphics#background(float, float, float, float) + */ + public void imageMode(int mode) { + if ((mode == CORNER) || (mode == CORNERS) || (mode == CENTER)) { + imageMode = mode; + } else { + String msg = + "imageMode() only works with CORNER, CORNERS, or CENTER"; + throw new RuntimeException(msg); + } + } + + + public void image(PImage image, float x, float y) { + // Starting in release 0144, image errors are simply ignored. + // loadImageAsync() sets width and height to -1 when loading fails. + if (image.width == -1 || image.height == -1) return; + + if (imageMode == CORNER || imageMode == CORNERS) { + imageImpl(image, + x, y, x+image.width, y+image.height, + 0, 0, image.width, image.height); + + } else if (imageMode == CENTER) { + float x1 = x - image.width/2; + float y1 = y - image.height/2; + imageImpl(image, + x1, y1, x1+image.width, y1+image.height, + 0, 0, image.width, image.height); + } + } + + + /** + * Displays images to the screen. The images must be in the sketch's "data" + * directory to load correctly. Select "Add file..." from the "Sketch" menu + * to add the image. Processing currently works with GIF, JPEG, and Targa + * images. The color of an image may be modified with the tint() + * function and if a GIF has transparency, it will maintain its transparency. + * The img parameter specifies the image to display and the x + * and y parameters define the location of the image from its + * upper-left corner. The image is displayed at its original size unless + * the width and height parameters specify a different size. + * The imageMode() function changes the way the parameters work. + * A call to imageMode(CORNERS) will change the width and height + * parameters to define the x and y values of the opposite corner of the + * image. + * + * =advanced + * Starting with release 0124, when using the default (JAVA2D) renderer, + * smooth() will also improve image quality of resized images. + * + * @webref image:loading_displaying + * @param image the image to display + * @param x x-coordinate of the image + * @param y y-coordinate of the image + * @param c width to display the image + * @param d height to display the image + * + * @see processing.core.PApplet#loadImage(String, String) + * @see processing.core.PImage + * @see processing.core.PGraphics#imageMode(int) + * @see processing.core.PGraphics#tint(float) + * @see processing.core.PGraphics#background(float, float, float, float) + * @see processing.core.PGraphics#alpha(int) + */ + public void image(PImage image, float x, float y, float c, float d) { + image(image, x, y, c, d, 0, 0, image.width, image.height); + } + + + /** + * Draw an image(), also specifying u/v coordinates. + * In this method, the u, v coordinates are always based on image space + * location, regardless of the current textureMode(). + */ + public void image(PImage image, + float a, float b, float c, float d, + int u1, int v1, int u2, int v2) { + // Starting in release 0144, image errors are simply ignored. + // loadImageAsync() sets width and height to -1 when loading fails. + if (image.width == -1 || image.height == -1) return; + + if (imageMode == CORNER) { + if (c < 0) { // reset a negative width + a += c; c = -c; + } + if (d < 0) { // reset a negative height + b += d; d = -d; + } + + imageImpl(image, + a, b, a + c, b + d, + u1, v1, u2, v2); + + } else if (imageMode == CORNERS) { + if (c < a) { // reverse because x2 < x1 + float temp = a; a = c; c = temp; + } + if (d < b) { // reverse because y2 < y1 + float temp = b; b = d; d = temp; + } + + imageImpl(image, + a, b, c, d, + u1, v1, u2, v2); + + } else if (imageMode == CENTER) { + // c and d are width/height + if (c < 0) c = -c; + if (d < 0) d = -d; + float x1 = a - c/2; + float y1 = b - d/2; + + imageImpl(image, + x1, y1, x1 + c, y1 + d, + u1, v1, u2, v2); + } + } + + + /** + * Expects x1, y1, x2, y2 coordinates where (x2 >= x1) and (y2 >= y1). + * If tint() has been called, the image will be colored. + *

+ * The default implementation draws an image as a textured quad. + * The (u, v) coordinates are in image space (they're ints, after all..) + */ + protected void imageImpl(PImage image, + float x1, float y1, float x2, float y2, + int u1, int v1, int u2, int v2) { + boolean savedStroke = stroke; +// boolean savedFill = fill; + int savedTextureMode = textureMode; + + stroke = false; +// fill = true; + textureMode = IMAGE; + +// float savedFillR = fillR; +// float savedFillG = fillG; +// float savedFillB = fillB; +// float savedFillA = fillA; +// +// if (tint) { +// fillR = tintR; +// fillG = tintG; +// fillB = tintB; +// fillA = tintA; +// +// } else { +// fillR = 1; +// fillG = 1; +// fillB = 1; +// fillA = 1; +// } + + beginShape(QUADS); + texture(image); + vertex(x1, y1, u1, v1); + vertex(x1, y2, u1, v2); + vertex(x2, y2, u2, v2); + vertex(x2, y1, u2, v1); + endShape(); + + stroke = savedStroke; +// fill = savedFill; + textureMode = savedTextureMode; + +// fillR = savedFillR; +// fillG = savedFillG; +// fillB = savedFillB; +// fillA = savedFillA; + } + + + + ////////////////////////////////////////////////////////////// + + // SHAPE + + + /** + * Modifies the location from which shapes draw. + * The default mode is shapeMode(CORNER), which specifies the + * location to be the upper left corner of the shape and uses the third + * and fourth parameters of shape() to specify the width and height. + * The syntax shapeMode(CORNERS) uses the first and second parameters + * of shape() to set the location of one corner and uses the third + * and fourth parameters to set the opposite corner. + * The syntax shapeMode(CENTER) draws the shape from its center point + * and uses the third and forth parameters of shape() to specify the + * width and height. + * The parameter must be written in "ALL CAPS" because Processing syntax + * is case sensitive. + * + * @param mode One of CORNER, CORNERS, CENTER + * + * @webref shape:loading_displaying + * @see PGraphics#shape(PShape) + * @see PGraphics#rectMode(int) + */ + public void shapeMode(int mode) { + this.shapeMode = mode; + } + + + public void shape(PShape shape) { + if (shape.isVisible()) { // don't do expensive matrix ops if invisible + if (shapeMode == CENTER) { + pushMatrix(); + translate(-shape.getWidth()/2, -shape.getHeight()/2); + } + + shape.draw(this); // needs to handle recorder too + + if (shapeMode == CENTER) { + popMatrix(); + } + } + } + + + /** + * Convenience method to draw at a particular location. + */ + public void shape(PShape shape, float x, float y) { + if (shape.isVisible()) { // don't do expensive matrix ops if invisible + pushMatrix(); + + if (shapeMode == CENTER) { + translate(x - shape.getWidth()/2, y - shape.getHeight()/2); + + } else if ((shapeMode == CORNER) || (shapeMode == CORNERS)) { + translate(x, y); + } + shape.draw(this); + + popMatrix(); + } + } + + + /** + * Displays shapes to the screen. The shapes must be in the sketch's "data" + * directory to load correctly. Select "Add file..." from the "Sketch" menu + * to add the shape. + * Processing currently works with SVG shapes only. + * The sh parameter specifies the shape to display and the x + * and y parameters define the location of the shape from its + * upper-left corner. + * The shape is displayed at its original size unless the width + * and height parameters specify a different size. + * The shapeMode() function changes the way the parameters work. + * A call to shapeMode(CORNERS), for example, will change the width + * and height parameters to define the x and y values of the opposite corner + * of the shape. + *

+ * Note complex shapes may draw awkwardly with P2D, P3D, and OPENGL. Those + * renderers do not yet support shapes that have holes or complicated breaks. + * + * @param shape + * @param x x-coordinate of the shape + * @param y y-coordinate of the shape + * @param c width to display the shape + * @param d height to display the shape + * + * @webref shape:loading_displaying + * @see PShape + * @see PGraphics#loadShape(String) + * @see PGraphics#shapeMode(int) + */ + public void shape(PShape shape, float x, float y, float c, float d) { + if (shape.isVisible()) { // don't do expensive matrix ops if invisible + pushMatrix(); + + if (shapeMode == CENTER) { + // x and y are center, c and d refer to a diameter + translate(x - c/2f, y - d/2f); + scale(c / shape.getWidth(), d / shape.getHeight()); + + } else if (shapeMode == CORNER) { + translate(x, y); + scale(c / shape.getWidth(), d / shape.getHeight()); + + } else if (shapeMode == CORNERS) { + // c and d are x2/y2, make them into width/height + c -= x; + d -= y; + // then same as above + translate(x, y); + scale(c / shape.getWidth(), d / shape.getHeight()); + } + shape.draw(this); + + popMatrix(); + } + } + + + + ////////////////////////////////////////////////////////////// + + // TEXT/FONTS + + + /** + * Sets the alignment of the text to one of LEFT, CENTER, or RIGHT. + * This will also reset the vertical text alignment to BASELINE. + */ + public void textAlign(int align) { + textAlign(align, BASELINE); + } + + + /** + * Sets the horizontal and vertical alignment of the text. The horizontal + * alignment can be one of LEFT, CENTER, or RIGHT. The vertical alignment + * can be TOP, BOTTOM, CENTER, or the BASELINE (the default). + */ + public void textAlign(int alignX, int alignY) { + textAlign = alignX; + textAlignY = alignY; + } + + + /** + * Returns the ascent of the current font at the current size. + * This is a method, rather than a variable inside the PGraphics object + * because it requires calculation. + */ + public float textAscent() { + if (textFont == null) { + defaultFontOrDeath("textAscent"); + } + return textFont.ascent() * ((textMode == SCREEN) ? textFont.size : textSize); + } + + + /** + * Returns the descent of the current font at the current size. + * This is a method, rather than a variable inside the PGraphics object + * because it requires calculation. + */ + public float textDescent() { + if (textFont == null) { + defaultFontOrDeath("textDescent"); + } + return textFont.descent() * ((textMode == SCREEN) ? textFont.size : textSize); + } + + + /** + * Sets the current font. The font's size will be the "natural" + * size of this font (the size that was set when using "Create Font"). + * The leading will also be reset. + */ + public void textFont(PFont which) { + if (which != null) { + textFont = which; + if (hints[ENABLE_NATIVE_FONTS]) { + //if (which.font == null) { + which.findFont(); + //} + } + /* + textFontNative = which.font; + + //textFontNativeMetrics = null; + // changed for rev 0104 for textMode(SHAPE) in opengl + if (textFontNative != null) { + // TODO need a better way to handle this. could use reflection to get + // rid of the warning, but that'd be a little silly. supporting this is + // an artifact of supporting java 1.1, otherwise we'd use getLineMetrics, + // as recommended by the @deprecated flag. + textFontNativeMetrics = + Toolkit.getDefaultToolkit().getFontMetrics(textFontNative); + // The following is what needs to be done, however we need to be able + // to get the actual graphics context where the drawing is happening. + // For instance, parent.getGraphics() doesn't work for OpenGL since + // an OpenGL drawing surface is an embedded component. +// if (parent != null) { +// textFontNativeMetrics = parent.getGraphics().getFontMetrics(textFontNative); +// } + + // float w = font.getStringBounds(text, g2.getFontRenderContext()).getWidth(); + } + */ + textSize(which.size); + + } else { + throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT); + } + } + + + /** + * Useful function to set the font and size at the same time. + */ + public void textFont(PFont which, float size) { + textFont(which); + textSize(size); + } + + + /** + * Set the text leading to a specific value. If using a custom + * value for the text leading, you'll have to call textLeading() + * again after any calls to textSize(). + */ + public void textLeading(float leading) { + textLeading = leading; + } + + + /** + * Sets the text rendering/placement to be either SCREEN (direct + * to the screen, exact coordinates, only use the font's original size) + * or MODEL (the default, where text is manipulated by translate() and + * can have a textSize). The text size cannot be set when using + * textMode(SCREEN), because it uses the pixels directly from the font. + */ + public void textMode(int mode) { + // CENTER and MODEL overlap (they're both 3) + if ((mode == LEFT) || (mode == RIGHT)) { + showWarning("Since Processing beta, textMode() is now textAlign()."); + return; + } +// if ((mode != SCREEN) && (mode != MODEL)) { +// showError("Only textMode(SCREEN) and textMode(MODEL) " + +// "are available with this renderer."); +// } + + if (textModeCheck(mode)) { + textMode = mode; + } else { + String modeStr = String.valueOf(mode); + switch (mode) { + case SCREEN: modeStr = "SCREEN"; break; + case MODEL: modeStr = "MODEL"; break; + case SHAPE: modeStr = "SHAPE"; break; + } + showWarning("textMode(" + modeStr + ") is not supported by this renderer."); + } + + // reset the font to its natural size + // (helps with width calculations and all that) + //if (textMode == SCREEN) { + //textSize(textFont.size); + //} + + //} else { + //throw new RuntimeException("use textFont() before textMode()"); + //} + } + + + protected boolean textModeCheck(int mode) { + return true; + } + + + /** + * Sets the text size, also resets the value for the leading. + */ + public void textSize(float size) { + if (textFont == null) { + defaultFontOrDeath("textSize", size); + } + textSize = size; + textLeading = (textAscent() + textDescent()) * 1.275f; + } + + + // ........................................................ + + + public float textWidth(char c) { + textWidthBuffer[0] = c; + return textWidthImpl(textWidthBuffer, 0, 1); + } + + + /** + * Return the width of a line of text. If the text has multiple + * lines, this returns the length of the longest line. + */ + public float textWidth(String str) { + if (textFont == null) { + defaultFontOrDeath("textWidth"); + } + + int length = str.length(); + if (length > textWidthBuffer.length) { + textWidthBuffer = new char[length + 10]; + } + str.getChars(0, length, textWidthBuffer, 0); + + float wide = 0; + int index = 0; + int start = 0; + + while (index < length) { + if (textWidthBuffer[index] == '\n') { + wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index)); + start = index+1; + } + index++; + } + if (start < length) { + wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index)); + } + return wide; + } + + + /** + * TODO not sure if this stays... + */ + public float textWidth(char[] chars, int start, int length) { + return textWidthImpl(chars, start, start + length); + } + + + /** + * Implementation of returning the text width of + * the chars [start, stop) in the buffer. + * Unlike the previous version that was inside PFont, this will + * return the size not of a 1 pixel font, but the actual current size. + */ + protected float textWidthImpl(char buffer[], int start, int stop) { + float wide = 0; + for (int i = start; i < stop; i++) { + // could add kerning here, but it just ain't implemented + wide += textFont.width(buffer[i]) * textSize; + } + return wide; + } + + + // ........................................................ + + + /** + * Write text where we just left off. + */ + public void text(char c) { + text(c, textX, textY, textZ); + } + + + /** + * Draw a single character on screen. + * Extremely slow when used with textMode(SCREEN) and Java 2D, + * because loadPixels has to be called first and updatePixels last. + */ + public void text(char c, float x, float y) { + if (textFont == null) { + defaultFontOrDeath("text"); + } + + if (textMode == SCREEN) loadPixels(); + + if (textAlignY == CENTER) { + y += textAscent() / 2; + } else if (textAlignY == TOP) { + y += textAscent(); + } else if (textAlignY == BOTTOM) { + y -= textDescent(); + //} else if (textAlignY == BASELINE) { + // do nothing + } + + textBuffer[0] = c; + textLineAlignImpl(textBuffer, 0, 1, x, y); + + if (textMode == SCREEN) updatePixels(); + } + + + /** + * Draw a single character on screen (with a z coordinate) + */ + public void text(char c, float x, float y, float z) { +// if ((z != 0) && (textMode == SCREEN)) { +// String msg = "textMode(SCREEN) cannot have a z coordinate"; +// throw new RuntimeException(msg); +// } + + if (z != 0) translate(0, 0, z); // slowness, badness + + text(c, x, y); + textZ = z; + + if (z != 0) translate(0, 0, -z); + } + + + /** + * Write text where we just left off. + */ + public void text(String str) { + text(str, textX, textY, textZ); + } + + + /** + * Draw a chunk of text. + * Newlines that are \n (Unix newline or linefeed char, ascii 10) + * are honored, but \r (carriage return, Windows and Mac OS) are + * ignored. + */ + public void text(String str, float x, float y) { + if (textFont == null) { + defaultFontOrDeath("text"); + } + + if (textMode == SCREEN) loadPixels(); + + int length = str.length(); + if (length > textBuffer.length) { + textBuffer = new char[length + 10]; + } + str.getChars(0, length, textBuffer, 0); + text(textBuffer, 0, length, x, y); + } + + + /** + * Method to draw text from an array of chars. This method will usually be + * more efficient than drawing from a String object, because the String will + * not be converted to a char array before drawing. + */ + public void text(char[] chars, int start, int stop, float x, float y) { + // If multiple lines, sum the height of the additional lines + float high = 0; //-textAscent(); + for (int i = start; i < stop; i++) { + if (chars[i] == '\n') { + high += textLeading; + } + } + if (textAlignY == CENTER) { + // for a single line, this adds half the textAscent to y + // for multiple lines, subtract half the additional height + //y += (textAscent() - textDescent() - high)/2; + y += (textAscent() - high)/2; + } else if (textAlignY == TOP) { + // for a single line, need to add textAscent to y + // for multiple lines, no different + y += textAscent(); + } else if (textAlignY == BOTTOM) { + // for a single line, this is just offset by the descent + // for multiple lines, subtract leading for each line + y -= textDescent() + high; + //} else if (textAlignY == BASELINE) { + // do nothing + } + +// int start = 0; + int index = 0; + while (index < stop) { //length) { + if (chars[index] == '\n') { + textLineAlignImpl(chars, start, index, x, y); + start = index + 1; + y += textLeading; + } + index++; + } + if (start < stop) { //length) { + textLineAlignImpl(chars, start, index, x, y); + } + if (textMode == SCREEN) updatePixels(); + } + + + /** + * Same as above but with a z coordinate. + */ + public void text(String str, float x, float y, float z) { + if (z != 0) translate(0, 0, z); // slow! + + text(str, x, y); + textZ = z; + + if (z != 0) translate(0, 0, -z); // inaccurate! + } + + + public void text(char[] chars, int start, int stop, + float x, float y, float z) { + if (z != 0) translate(0, 0, z); // slow! + + text(chars, start, stop, x, y); + textZ = z; + + if (z != 0) translate(0, 0, -z); // inaccurate! + } + + + /** + * Draw text in a box that is constrained to a particular size. + * The current rectMode() determines what the coordinates mean + * (whether x1/y1/x2/y2 or x/y/w/h). + *

+ * Note that the x,y coords of the start of the box + * will align with the *ascent* of the text, not the baseline, + * as is the case for the other text() functions. + *

+ * Newlines that are \n (Unix newline or linefeed char, ascii 10) + * are honored, and \r (carriage return, Windows and Mac OS) are + * ignored. + */ + public void text(String str, float x1, float y1, float x2, float y2) { + if (textFont == null) { + defaultFontOrDeath("text"); + } + + if (textMode == SCREEN) loadPixels(); + + float hradius, vradius; + switch (rectMode) { + case CORNER: + x2 += x1; y2 += y1; + break; + case RADIUS: + hradius = x2; + vradius = y2; + x2 = x1 + hradius; + y2 = y1 + vradius; + x1 -= hradius; + y1 -= vradius; + break; + case CENTER: + hradius = x2 / 2.0f; + vradius = y2 / 2.0f; + x2 = x1 + hradius; + y2 = y1 + vradius; + x1 -= hradius; + y1 -= vradius; + } + if (x2 < x1) { + float temp = x1; x1 = x2; x2 = temp; + } + if (y2 < y1) { + float temp = y1; y1 = y2; y2 = temp; + } + +// float currentY = y1; + float boxWidth = x2 - x1; + +// // ala illustrator, the text itself must fit inside the box +// currentY += textAscent(); //ascent() * textSize; +// // if the box is already too small, tell em to f off +// if (currentY > y2) return; + + float spaceWidth = textWidth(' '); + + if (textBreakStart == null) { + textBreakStart = new int[20]; + textBreakStop = new int[20]; + } + textBreakCount = 0; + + int length = str.length(); + if (length + 1 > textBuffer.length) { + textBuffer = new char[length + 1]; + } + str.getChars(0, length, textBuffer, 0); + // add a fake newline to simplify calculations + textBuffer[length++] = '\n'; + + int sentenceStart = 0; + for (int i = 0; i < length; i++) { + if (textBuffer[i] == '\n') { +// currentY = textSentence(textBuffer, sentenceStart, i, +// lineX, boxWidth, currentY, y2, spaceWidth); + boolean legit = + textSentence(textBuffer, sentenceStart, i, boxWidth, spaceWidth); + if (!legit) break; +// if (Float.isNaN(currentY)) break; // word too big (or error) +// if (currentY > y2) break; // past the box + sentenceStart = i + 1; + } + } + + // lineX is the position where the text starts, which is adjusted + // to left/center/right based on the current textAlign + float lineX = x1; //boxX1; + if (textAlign == CENTER) { + lineX = lineX + boxWidth/2f; + } else if (textAlign == RIGHT) { + lineX = x2; //boxX2; + } + + float boxHeight = y2 - y1; + //int lineFitCount = 1 + PApplet.floor((boxHeight - textAscent()) / textLeading); + // incorporate textAscent() for the top (baseline will be y1 + ascent) + // and textDescent() for the bottom, so that lower parts of letters aren't + // outside the box. [0151] + float topAndBottom = textAscent() + textDescent(); + int lineFitCount = 1 + PApplet.floor((boxHeight - topAndBottom) / textLeading); + int lineCount = Math.min(textBreakCount, lineFitCount); + + if (textAlignY == CENTER) { + float lineHigh = topAndBottom + textLeading * (lineCount - 1); + float y = y1 + textAscent() + (boxHeight - lineHigh) / 2; + for (int i = 0; i < lineCount; i++) { + textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y); + y += textLeading; + } + + } else if (textAlignY == BOTTOM) { + float y = y2 - textDescent() - textLeading * (lineCount - 1); + for (int i = 0; i < lineCount; i++) { + textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y); + y += textLeading; + } + + } else { // TOP or BASELINE just go to the default + float y = y1 + textAscent(); + for (int i = 0; i < lineCount; i++) { + textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y); + y += textLeading; + } + } + + if (textMode == SCREEN) updatePixels(); + } + + + /** + * Emit a sentence of text, defined as a chunk of text without any newlines. + * @param stop non-inclusive, the end of the text in question + */ + protected boolean textSentence(char[] buffer, int start, int stop, + float boxWidth, float spaceWidth) { + float runningX = 0; + + // Keep track of this separately from index, since we'll need to back up + // from index when breaking words that are too long to fit. + int lineStart = start; + int wordStart = start; + int index = start; + while (index <= stop) { + // boundary of a word or end of this sentence + if ((buffer[index] == ' ') || (index == stop)) { + float wordWidth = textWidthImpl(buffer, wordStart, index); + + if (runningX + wordWidth > boxWidth) { + if (runningX != 0) { + // Next word is too big, output the current line and advance + index = wordStart; + textSentenceBreak(lineStart, index); + // Eat whitespace because multiple spaces don't count for s* + // when they're at the end of a line. + while ((index < stop) && (buffer[index] == ' ')) { + index++; + } + } else { // (runningX == 0) + // If this is the first word on the line, and its width is greater + // than the width of the text box, then break the word where at the + // max width, and send the rest of the word to the next line. + do { + index--; + if (index == wordStart) { + // Not a single char will fit on this line. screw 'em. + //System.out.println("screw you"); + return false; //Float.NaN; + } + wordWidth = textWidthImpl(buffer, wordStart, index); + } while (wordWidth > boxWidth); + + //textLineImpl(buffer, lineStart, index, x, y); + textSentenceBreak(lineStart, index); + } + lineStart = index; + wordStart = index; + runningX = 0; + + } else if (index == stop) { + // last line in the block, time to unload + //textLineImpl(buffer, lineStart, index, x, y); + textSentenceBreak(lineStart, index); +// y += textLeading; + index++; + + } else { // this word will fit, just add it to the line + runningX += wordWidth + spaceWidth; + wordStart = index + 1; // move on to the next word + index++; + } + } else { // not a space or the last character + index++; // this is just another letter + } + } +// return y; + return true; + } + + + protected void textSentenceBreak(int start, int stop) { + if (textBreakCount == textBreakStart.length) { + textBreakStart = PApplet.expand(textBreakStart); + textBreakStop = PApplet.expand(textBreakStop); + } + textBreakStart[textBreakCount] = start; + textBreakStop[textBreakCount] = stop; + textBreakCount++; + } + + + public void text(String s, float x1, float y1, float x2, float y2, float z) { + if (z != 0) translate(0, 0, z); // slowness, badness + + text(s, x1, y1, x2, y2); + textZ = z; + + if (z != 0) translate(0, 0, -z); // TEMPORARY HACK! SLOW! + } + + + public void text(int num, float x, float y) { + text(String.valueOf(num), x, y); + } + + + public void text(int num, float x, float y, float z) { + text(String.valueOf(num), x, y, z); + } + + + /** + * This does a basic number formatting, to avoid the + * generally ugly appearance of printing floats. + * Users who want more control should use their own nf() cmmand, + * or if they want the long, ugly version of float, + * use String.valueOf() to convert the float to a String first. + */ + public void text(float num, float x, float y) { + text(PApplet.nfs(num, 0, 3), x, y); + } + + + public void text(float num, float x, float y, float z) { + text(PApplet.nfs(num, 0, 3), x, y, z); + } + + + + ////////////////////////////////////////////////////////////// + + // TEXT IMPL + + // These are most likely to be overridden by subclasses, since the other + // (public) functions handle generic features like setting alignment. + + + /** + * Handles placement of a text line, then calls textLineImpl + * to actually render at the specific point. + */ + protected void textLineAlignImpl(char buffer[], int start, int stop, + float x, float y) { + if (textAlign == CENTER) { + x -= textWidthImpl(buffer, start, stop) / 2f; + + } else if (textAlign == RIGHT) { + x -= textWidthImpl(buffer, start, stop); + } + + textLineImpl(buffer, start, stop, x, y); + } + + + /** + * Implementation of actual drawing for a line of text. + */ + protected void textLineImpl(char buffer[], int start, int stop, + float x, float y) { + for (int index = start; index < stop; index++) { + textCharImpl(buffer[index], x, y); + + // this doesn't account for kerning + x += textWidth(buffer[index]); + } + textX = x; + textY = y; + textZ = 0; // this will get set by the caller if non-zero + } + + + protected void textCharImpl(char ch, float x, float y) { //, float z) { + PFont.Glyph glyph = textFont.getGlyph(ch); + if (glyph != null) { + if (textMode == MODEL) { + float high = glyph.height / (float) textFont.size; + float bwidth = glyph.width / (float) textFont.size; + float lextent = glyph.leftExtent / (float) textFont.size; + float textent = glyph.topExtent / (float) textFont.size; + + float x1 = x + lextent * textSize; + float y1 = y - textent * textSize; + float x2 = x1 + bwidth * textSize; + float y2 = y1 + high * textSize; + + textCharModelImpl(glyph.image, + x1, y1, x2, y2, + glyph.width, glyph.height); + + } else if (textMode == SCREEN) { + int xx = (int) x + glyph.leftExtent; + int yy = (int) y - glyph.topExtent; + + int w0 = glyph.width; + int h0 = glyph.height; + + textCharScreenImpl(glyph.image, xx, yy, w0, h0); + } + } + } + + + protected void textCharModelImpl(PImage glyph, + float x1, float y1, //float z1, + float x2, float y2, //float z2, + int u2, int v2) { + boolean savedTint = tint; + int savedTintColor = tintColor; + float savedTintR = tintR; + float savedTintG = tintG; + float savedTintB = tintB; + float savedTintA = tintA; + boolean savedTintAlpha = tintAlpha; + + tint = true; + tintColor = fillColor; + tintR = fillR; + tintG = fillG; + tintB = fillB; + tintA = fillA; + tintAlpha = fillAlpha; + + imageImpl(glyph, x1, y1, x2, y2, 0, 0, u2, v2); + + tint = savedTint; + tintColor = savedTintColor; + tintR = savedTintR; + tintG = savedTintG; + tintB = savedTintB; + tintA = savedTintA; + tintAlpha = savedTintAlpha; + } + + + protected void textCharScreenImpl(PImage glyph, + int xx, int yy, + int w0, int h0) { + int x0 = 0; + int y0 = 0; + + if ((xx >= width) || (yy >= height) || + (xx + w0 < 0) || (yy + h0 < 0)) return; + + if (xx < 0) { + x0 -= xx; + w0 += xx; + xx = 0; + } + if (yy < 0) { + y0 -= yy; + h0 += yy; + yy = 0; + } + if (xx + w0 > width) { + w0 -= ((xx + w0) - width); + } + if (yy + h0 > height) { + h0 -= ((yy + h0) - height); + } + + int fr = fillRi; + int fg = fillGi; + int fb = fillBi; + int fa = fillAi; + + int pixels1[] = glyph.pixels; //images[glyph].pixels; + + // TODO this can be optimized a bit + for (int row = y0; row < y0 + h0; row++) { + for (int col = x0; col < x0 + w0; col++) { + //int a1 = (fa * pixels1[row * textFont.twidth + col]) >> 8; + int a1 = (fa * pixels1[row * glyph.width + col]) >> 8; + int a2 = a1 ^ 0xff; + //int p1 = pixels1[row * glyph.width + col]; + int p2 = pixels[(yy + row-y0)*width + (xx+col-x0)]; + + pixels[(yy + row-y0)*width + xx+col-x0] = + (0xff000000 | + (((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) | + (( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) | + (( a1 * fb + a2 * ( p2 & 0xff)) >> 8)); + } + } + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX STACK + + + /** + * Push a copy of the current transformation matrix onto the stack. + */ + public void pushMatrix() { + showMethodWarning("pushMatrix"); + } + + + /** + * Replace the current transformation matrix with the top of the stack. + */ + public void popMatrix() { + showMethodWarning("popMatrix"); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX TRANSFORMATIONS + + + /** + * Translate in X and Y. + */ + public void translate(float tx, float ty) { + showMissingWarning("translate"); + } + + + /** + * Translate in X, Y, and Z. + */ + public void translate(float tx, float ty, float tz) { + showMissingWarning("translate"); + } + + + /** + * Two dimensional rotation. + * + * Same as rotateZ (this is identical to a 3D rotation along the z-axis) + * but included for clarity. It'd be weird for people drawing 2D graphics + * to be using rotateZ. And they might kick our a-- for the confusion. + * + * Additional background. + */ + public void rotate(float angle) { + showMissingWarning("rotate"); + } + + + /** + * Rotate around the X axis. + */ + public void rotateX(float angle) { + showMethodWarning("rotateX"); + } + + + /** + * Rotate around the Y axis. + */ + public void rotateY(float angle) { + showMethodWarning("rotateY"); + } + + + /** + * Rotate around the Z axis. + * + * The functions rotate() and rotateZ() are identical, it's just that it make + * sense to have rotate() and then rotateX() and rotateY() when using 3D; + * nor does it make sense to use a function called rotateZ() if you're only + * doing things in 2D. so we just decided to have them both be the same. + */ + public void rotateZ(float angle) { + showMethodWarning("rotateZ"); + } + + + /** + * Rotate about a vector in space. Same as the glRotatef() function. + */ + public void rotate(float angle, float vx, float vy, float vz) { + showMissingWarning("rotate"); + } + + + /** + * Scale in all dimensions. + */ + public void scale(float s) { + showMissingWarning("scale"); + } + + + /** + * Scale in X and Y. Equivalent to scale(sx, sy, 1). + * + * Not recommended for use in 3D, because the z-dimension is just + * scaled by 1, since there's no way to know what else to scale it by. + */ + public void scale(float sx, float sy) { + showMissingWarning("scale"); + } + + + /** + * Scale in X, Y, and Z. + */ + public void scale(float x, float y, float z) { + showMissingWarning("scale"); + } + + + /** + * Shear along X axis + */ + public void shearX(float angle) { + showMissingWarning("shearX"); + } + + + /** + * Shear along Y axis + */ + public void shearY(float angle) { + showMissingWarning("shearY"); + } + + + ////////////////////////////////////////////////////////////// + + // MATRIX FULL MONTY + + + /** + * Set the current transformation matrix to identity. + */ + public void resetMatrix() { + showMethodWarning("resetMatrix"); + } + + + public void applyMatrix(PMatrix source) { + if (source instanceof PMatrix2D) { + applyMatrix((PMatrix2D) source); + } else if (source instanceof PMatrix3D) { + applyMatrix((PMatrix3D) source); + } + } + + + public void applyMatrix(PMatrix2D source) { + applyMatrix(source.m00, source.m01, source.m02, + source.m10, source.m11, source.m12); + } + + + /** + * Apply a 3x2 affine transformation matrix. + */ + public void applyMatrix(float n00, float n01, float n02, + float n10, float n11, float n12) { + showMissingWarning("applyMatrix"); + } + + + public void applyMatrix(PMatrix3D source) { + applyMatrix(source.m00, source.m01, source.m02, source.m03, + source.m10, source.m11, source.m12, source.m13, + source.m20, source.m21, source.m22, source.m23, + source.m30, source.m31, source.m32, source.m33); + } + + + /** + * Apply a 4x4 transformation matrix. + */ + public void applyMatrix(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + showMissingWarning("applyMatrix"); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX GET/SET/PRINT + + + public PMatrix getMatrix() { + showMissingWarning("getMatrix"); + return null; + } + + + /** + * Copy the current transformation matrix into the specified target. + * Pass in null to create a new matrix. + */ + public PMatrix2D getMatrix(PMatrix2D target) { + showMissingWarning("getMatrix"); + return null; + } + + + /** + * Copy the current transformation matrix into the specified target. + * Pass in null to create a new matrix. + */ + public PMatrix3D getMatrix(PMatrix3D target) { + showMissingWarning("getMatrix"); + return null; + } + + + /** + * Set the current transformation matrix to the contents of another. + */ + public void setMatrix(PMatrix source) { + if (source instanceof PMatrix2D) { + setMatrix((PMatrix2D) source); + } else if (source instanceof PMatrix3D) { + setMatrix((PMatrix3D) source); + } + } + + + /** + * Set the current transformation to the contents of the specified source. + */ + public void setMatrix(PMatrix2D source) { + showMissingWarning("setMatrix"); + } + + + /** + * Set the current transformation to the contents of the specified source. + */ + public void setMatrix(PMatrix3D source) { + showMissingWarning("setMatrix"); + } + + + /** + * Print the current model (or "transformation") matrix. + */ + public void printMatrix() { + showMethodWarning("printMatrix"); + } + + + + ////////////////////////////////////////////////////////////// + + // CAMERA + + + public void beginCamera() { + showMethodWarning("beginCamera"); + } + + + public void endCamera() { + showMethodWarning("endCamera"); + } + + + public void camera() { + showMissingWarning("camera"); + } + + + public void camera(float eyeX, float eyeY, float eyeZ, + float centerX, float centerY, float centerZ, + float upX, float upY, float upZ) { + showMissingWarning("camera"); + } + + + public void printCamera() { + showMethodWarning("printCamera"); + } + + + + ////////////////////////////////////////////////////////////// + + // PROJECTION + + + public void ortho() { + showMissingWarning("ortho"); + } + + + public void ortho(float left, float right, + float bottom, float top, + float near, float far) { + showMissingWarning("ortho"); + } + + + public void perspective() { + showMissingWarning("perspective"); + } + + + public void perspective(float fovy, float aspect, float zNear, float zFar) { + showMissingWarning("perspective"); + } + + + public void frustum(float left, float right, + float bottom, float top, + float near, float far) { + showMethodWarning("frustum"); + } + + + public void printProjection() { + showMethodWarning("printCamera"); + } + + + + ////////////////////////////////////////////////////////////// + + // SCREEN TRANSFORMS + + + /** + * Given an x and y coordinate, returns the x position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenX(float x, float y) { + showMissingWarning("screenX"); + return 0; + } + + + /** + * Given an x and y coordinate, returns the y position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenY(float x, float y) { + showMissingWarning("screenY"); + return 0; + } + + + /** + * Maps a three dimensional point to its placement on-screen. + *

+ * Given an (x, y, z) coordinate, returns the x position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenX(float x, float y, float z) { + showMissingWarning("screenX"); + return 0; + } + + + /** + * Maps a three dimensional point to its placement on-screen. + *

+ * Given an (x, y, z) coordinate, returns the y position of where + * that point would be placed on screen, once affected by translate(), + * scale(), or any other transformations. + */ + public float screenY(float x, float y, float z) { + showMissingWarning("screenY"); + return 0; + } + + + /** + * Maps a three dimensional point to its placement on-screen. + *

+ * Given an (x, y, z) coordinate, returns its z value. + * This value can be used to determine if an (x, y, z) coordinate + * is in front or in back of another (x, y, z) coordinate. + * The units are based on how the zbuffer is set up, and don't + * relate to anything "real". They're only useful for in + * comparison to another value obtained from screenZ(), + * or directly out of the zbuffer[]. + */ + public float screenZ(float x, float y, float z) { + showMissingWarning("screenZ"); + return 0; + } + + + /** + * Returns the model space x value for an x, y, z coordinate. + *

+ * This will give you a coordinate after it has been transformed + * by translate(), rotate(), and camera(), but not yet transformed + * by the projection matrix. For instance, his can be useful for + * figuring out how points in 3D space relate to the edge + * coordinates of a shape. + */ + public float modelX(float x, float y, float z) { + showMissingWarning("modelX"); + return 0; + } + + + /** + * Returns the model space y value for an x, y, z coordinate. + */ + public float modelY(float x, float y, float z) { + showMissingWarning("modelY"); + return 0; + } + + + /** + * Returns the model space z value for an x, y, z coordinate. + */ + public float modelZ(float x, float y, float z) { + showMissingWarning("modelZ"); + return 0; + } + + + + ////////////////////////////////////////////////////////////// + + // STYLE + + + public void pushStyle() { + if (styleStackDepth == styleStack.length) { + styleStack = (PStyle[]) PApplet.expand(styleStack); + } + if (styleStack[styleStackDepth] == null) { + styleStack[styleStackDepth] = new PStyle(); + } + PStyle s = styleStack[styleStackDepth++]; + getStyle(s); + } + + + public void popStyle() { + if (styleStackDepth == 0) { + throw new RuntimeException("Too many popStyle() without enough pushStyle()"); + } + styleStackDepth--; + style(styleStack[styleStackDepth]); + } + + + public void style(PStyle s) { + // if (s.smooth) { + // smooth(); + // } else { + // noSmooth(); + // } + + imageMode(s.imageMode); + rectMode(s.rectMode); + ellipseMode(s.ellipseMode); + shapeMode(s.shapeMode); + + if (s.tint) { + tint(s.tintColor); + } else { + noTint(); + } + if (s.fill) { + fill(s.fillColor); + } else { + noFill(); + } + if (s.stroke) { + stroke(s.strokeColor); + } else { + noStroke(); + } + strokeWeight(s.strokeWeight); + strokeCap(s.strokeCap); + strokeJoin(s.strokeJoin); + + // Set the colorMode() for the material properties. + // TODO this is really inefficient, need to just have a material() method, + // but this has the least impact to the API. + colorMode(RGB, 1); + ambient(s.ambientR, s.ambientG, s.ambientB); + emissive(s.emissiveR, s.emissiveG, s.emissiveB); + specular(s.specularR, s.specularG, s.specularB); + shininess(s.shininess); + + /* + s.ambientR = ambientR; + s.ambientG = ambientG; + s.ambientB = ambientB; + s.specularR = specularR; + s.specularG = specularG; + s.specularB = specularB; + s.emissiveR = emissiveR; + s.emissiveG = emissiveG; + s.emissiveB = emissiveB; + s.shininess = shininess; + */ + // material(s.ambientR, s.ambientG, s.ambientB, + // s.emissiveR, s.emissiveG, s.emissiveB, + // s.specularR, s.specularG, s.specularB, + // s.shininess); + + // Set this after the material properties. + colorMode(s.colorMode, + s.colorModeX, s.colorModeY, s.colorModeZ, s.colorModeA); + + // This is a bit asymmetric, since there's no way to do "noFont()", + // and a null textFont will produce an error (since usually that means that + // the font couldn't load properly). So in some cases, the font won't be + // 'cleared' to null, even though that's technically correct. + if (s.textFont != null) { + textFont(s.textFont, s.textSize); + textLeading(s.textLeading); + } + // These don't require a font to be set. + textAlign(s.textAlign, s.textAlignY); + textMode(s.textMode); + } + + + public PStyle getStyle() { // ignore + return getStyle(null); + } + + + public PStyle getStyle(PStyle s) { // ignore + if (s == null) { + s = new PStyle(); + } + + s.imageMode = imageMode; + s.rectMode = rectMode; + s.ellipseMode = ellipseMode; + s.shapeMode = shapeMode; + + s.colorMode = colorMode; + s.colorModeX = colorModeX; + s.colorModeY = colorModeY; + s.colorModeZ = colorModeZ; + s.colorModeA = colorModeA; + + s.tint = tint; + s.tintColor = tintColor; + s.fill = fill; + s.fillColor = fillColor; + s.stroke = stroke; + s.strokeColor = strokeColor; + s.strokeWeight = strokeWeight; + s.strokeCap = strokeCap; + s.strokeJoin = strokeJoin; + + s.ambientR = ambientR; + s.ambientG = ambientG; + s.ambientB = ambientB; + s.specularR = specularR; + s.specularG = specularG; + s.specularB = specularB; + s.emissiveR = emissiveR; + s.emissiveG = emissiveG; + s.emissiveB = emissiveB; + s.shininess = shininess; + + s.textFont = textFont; + s.textAlign = textAlign; + s.textAlignY = textAlignY; + s.textMode = textMode; + s.textSize = textSize; + s.textLeading = textLeading; + + return s; + } + + + + ////////////////////////////////////////////////////////////// + + // STROKE CAP/JOIN/WEIGHT + + + public void strokeWeight(float weight) { + strokeWeight = weight; + } + + + public void strokeJoin(int join) { + strokeJoin = join; + } + + + public void strokeCap(int cap) { + strokeCap = cap; + } + + + + ////////////////////////////////////////////////////////////// + + // STROKE COLOR + + + /** + * Disables drawing the stroke (outline). If both noStroke() and + * noFill() are called, no shapes will be drawn to the screen. + * + * @webref color:setting + * + * @see PGraphics#stroke(float, float, float, float) + */ + public void noStroke() { + stroke = false; + } + + + /** + * Set the tint to either a grayscale or ARGB value. + * See notes attached to the fill() function. + * @param rgb color value in hexadecimal notation + * (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype + */ + public void stroke(int rgb) { + colorCalc(rgb); + strokeFromCalc(); + } + + + public void stroke(int rgb, float alpha) { + colorCalc(rgb, alpha); + strokeFromCalc(); + } + + + /** + * + * @param gray specifies a value between white and black + */ + public void stroke(float gray) { + colorCalc(gray); + strokeFromCalc(); + } + + + public void stroke(float gray, float alpha) { + colorCalc(gray, alpha); + strokeFromCalc(); + } + + + public void stroke(float x, float y, float z) { + colorCalc(x, y, z); + strokeFromCalc(); + } + + + /** + * Sets the color used to draw lines and borders around shapes. This color + * is either specified in terms of the RGB or HSB color depending on the + * current colorMode() (the default color space is RGB, with each + * value in the range from 0 to 255). + *

When using hexadecimal notation to specify a color, use "#" or + * "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six + * digits to specify a color (the way colors are specified in HTML and CSS). + * When using the hexadecimal notation starting with "0x", the hexadecimal + * value must be specified with eight characters; the first two characters + * define the alpha component and the remainder the red, green, and blue + * components. + *

The value for the parameter "gray" must be less than or equal + * to the current maximum value as specified by colorMode(). + * The default maximum value is 255. + * + * @webref color:setting + * @param alpha opacity of the stroke + * @param x red or hue value (depending on the current color mode) + * @param y green or saturation value (depending on the current color mode) + * @param z blue or brightness value (depending on the current color mode) + */ + public void stroke(float x, float y, float z, float a) { + colorCalc(x, y, z, a); + strokeFromCalc(); + } + + + protected void strokeFromCalc() { + stroke = true; + strokeR = calcR; + strokeG = calcG; + strokeB = calcB; + strokeA = calcA; + strokeRi = calcRi; + strokeGi = calcGi; + strokeBi = calcBi; + strokeAi = calcAi; + strokeColor = calcColor; + strokeAlpha = calcAlpha; + } + + + + ////////////////////////////////////////////////////////////// + + // TINT COLOR + + + /** + * Removes the current fill value for displaying images and reverts to displaying images with their original hues. + * + * @webref image:loading_displaying + * @see processing.core.PGraphics#tint(float, float, float, float) + * @see processing.core.PGraphics#image(PImage, float, float, float, float) + */ + public void noTint() { + tint = false; + } + + + /** + * Set the tint to either a grayscale or ARGB value. + */ + public void tint(int rgb) { + colorCalc(rgb); + tintFromCalc(); + } + + + /** + * @param rgb color value in hexadecimal notation + * (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype + * @param alpha opacity of the image + */ + public void tint(int rgb, float alpha) { + colorCalc(rgb, alpha); + tintFromCalc(); + } + + + /** + * @param gray any valid number + */ + public void tint(float gray) { + colorCalc(gray); + tintFromCalc(); + } + + + public void tint(float gray, float alpha) { + colorCalc(gray, alpha); + tintFromCalc(); + } + + + public void tint(float x, float y, float z) { + colorCalc(x, y, z); + tintFromCalc(); + } + + + /** + * Sets the fill value for displaying images. Images can be tinted to + * specified colors or made transparent by setting the alpha. + *

To make an image transparent, but not change it's color, + * use white as the tint color and specify an alpha value. For instance, + * tint(255, 128) will make an image 50% transparent (unless + * colorMode() has been used). + * + *

When using hexadecimal notation to specify a color, use "#" or + * "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six + * digits to specify a color (the way colors are specified in HTML and CSS). + * When using the hexadecimal notation starting with "0x", the hexadecimal + * value must be specified with eight characters; the first two characters + * define the alpha component and the remainder the red, green, and blue + * components. + *

The value for the parameter "gray" must be less than or equal + * to the current maximum value as specified by colorMode(). + * The default maximum value is 255. + *

The tint() method is also used to control the coloring of + * textures in 3D. + * + * @webref image:loading_displaying + * @param x red or hue value + * @param y green or saturation value + * @param z blue or brightness value + * + * @see processing.core.PGraphics#noTint() + * @see processing.core.PGraphics#image(PImage, float, float, float, float) + */ + public void tint(float x, float y, float z, float a) { + colorCalc(x, y, z, a); + tintFromCalc(); + } + + + protected void tintFromCalc() { + tint = true; + tintR = calcR; + tintG = calcG; + tintB = calcB; + tintA = calcA; + tintRi = calcRi; + tintGi = calcGi; + tintBi = calcBi; + tintAi = calcAi; + tintColor = calcColor; + tintAlpha = calcAlpha; + } + + + + ////////////////////////////////////////////////////////////// + + // FILL COLOR + + + /** + * Disables filling geometry. If both noStroke() and noFill() + * are called, no shapes will be drawn to the screen. + * + * @webref color:setting + * + * @see PGraphics#fill(float, float, float, float) + * + */ + public void noFill() { + fill = false; + } + + + /** + * Set the fill to either a grayscale value or an ARGB int. + * @param rgb color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype + */ + public void fill(int rgb) { + colorCalc(rgb); + fillFromCalc(); + } + + + public void fill(int rgb, float alpha) { + colorCalc(rgb, alpha); + fillFromCalc(); + } + + + /** + * @param gray number specifying value between white and black + */ + public void fill(float gray) { + colorCalc(gray); + fillFromCalc(); + } + + + public void fill(float gray, float alpha) { + colorCalc(gray, alpha); + fillFromCalc(); + } + + + public void fill(float x, float y, float z) { + colorCalc(x, y, z); + fillFromCalc(); + } + + + /** + * Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all subsequent shapes will be filled with orange. This color is either specified in terms of the RGB or HSB color depending on the current colorMode() (the default color space is RGB, with each value in the range from 0 to 255). + *

When using hexadecimal notation to specify a color, use "#" or "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six digits to specify a color (the way colors are specified in HTML and CSS). When using the hexadecimal notation starting with "0x", the hexadecimal value must be specified with eight characters; the first two characters define the alpha component and the remainder the red, green, and blue components. + *

The value for the parameter "gray" must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. + *

To change the color of an image (or a texture), use tint(). + * + * @webref color:setting + * @param x red or hue value + * @param y green or saturation value + * @param z blue or brightness value + * @param alpha opacity of the fill + * + * @see PGraphics#noFill() + * @see PGraphics#stroke(float) + * @see PGraphics#tint(float) + * @see PGraphics#background(float, float, float, float) + * @see PGraphics#colorMode(int, float, float, float, float) + */ + public void fill(float x, float y, float z, float a) { + colorCalc(x, y, z, a); + fillFromCalc(); + } + + + protected void fillFromCalc() { + fill = true; + fillR = calcR; + fillG = calcG; + fillB = calcB; + fillA = calcA; + fillRi = calcRi; + fillGi = calcGi; + fillBi = calcBi; + fillAi = calcAi; + fillColor = calcColor; + fillAlpha = calcAlpha; + } + + + + ////////////////////////////////////////////////////////////// + + // MATERIAL PROPERTIES + + + public void ambient(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// ambient((float) rgb); +// +// } else { +// colorCalcARGB(rgb, colorModeA); +// ambientFromCalc(); +// } + colorCalc(rgb); + ambientFromCalc(); + } + + + public void ambient(float gray) { + colorCalc(gray); + ambientFromCalc(); + } + + + public void ambient(float x, float y, float z) { + colorCalc(x, y, z); + ambientFromCalc(); + } + + + protected void ambientFromCalc() { + ambientR = calcR; + ambientG = calcG; + ambientB = calcB; + } + + + public void specular(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// specular((float) rgb); +// +// } else { +// colorCalcARGB(rgb, colorModeA); +// specularFromCalc(); +// } + colorCalc(rgb); + specularFromCalc(); + } + + + public void specular(float gray) { + colorCalc(gray); + specularFromCalc(); + } + + + public void specular(float x, float y, float z) { + colorCalc(x, y, z); + specularFromCalc(); + } + + + protected void specularFromCalc() { + specularR = calcR; + specularG = calcG; + specularB = calcB; + } + + + public void shininess(float shine) { + shininess = shine; + } + + + public void emissive(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// emissive((float) rgb); +// +// } else { +// colorCalcARGB(rgb, colorModeA); +// emissiveFromCalc(); +// } + colorCalc(rgb); + emissiveFromCalc(); + } + + + public void emissive(float gray) { + colorCalc(gray); + emissiveFromCalc(); + } + + + public void emissive(float x, float y, float z) { + colorCalc(x, y, z); + emissiveFromCalc(); + } + + + protected void emissiveFromCalc() { + emissiveR = calcR; + emissiveG = calcG; + emissiveB = calcB; + } + + + + ////////////////////////////////////////////////////////////// + + // LIGHTS + + // The details of lighting are very implementation-specific, so this base + // class does not handle any details of settings lights. It does however + // display warning messages that the functions are not available. + + + public void lights() { + showMethodWarning("lights"); + } + + public void noLights() { + showMethodWarning("noLights"); + } + + public void ambientLight(float red, float green, float blue) { + showMethodWarning("ambientLight"); + } + + public void ambientLight(float red, float green, float blue, + float x, float y, float z) { + showMethodWarning("ambientLight"); + } + + public void directionalLight(float red, float green, float blue, + float nx, float ny, float nz) { + showMethodWarning("directionalLight"); + } + + public void pointLight(float red, float green, float blue, + float x, float y, float z) { + showMethodWarning("pointLight"); + } + + public void spotLight(float red, float green, float blue, + float x, float y, float z, + float nx, float ny, float nz, + float angle, float concentration) { + showMethodWarning("spotLight"); + } + + public void lightFalloff(float constant, float linear, float quadratic) { + showMethodWarning("lightFalloff"); + } + + public void lightSpecular(float x, float y, float z) { + showMethodWarning("lightSpecular"); + } + + + + ////////////////////////////////////////////////////////////// + + // BACKGROUND + + + /** + * Set the background to a gray or ARGB color. + *

+ * For the main drawing surface, the alpha value will be ignored. However, + * alpha can be used on PGraphics objects from createGraphics(). This is + * the only way to set all the pixels partially transparent, for instance. + *

+ * Note that background() should be called before any transformations occur, + * because some implementations may require the current transformation matrix + * to be identity before drawing. + * + * @param rgb color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00)
or any value of the color datatype + */ + public void background(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// background((float) rgb); +// +// } else { +// if (format == RGB) { +// rgb |= 0xff000000; // ignore alpha for main drawing surface +// } +// colorCalcARGB(rgb, colorModeA); +// backgroundFromCalc(); +// backgroundImpl(); +// } + colorCalc(rgb); + backgroundFromCalc(); + } + + + /** + * See notes about alpha in background(x, y, z, a). + */ + public void background(int rgb, float alpha) { +// if (format == RGB) { +// background(rgb); // ignore alpha for main drawing surface +// +// } else { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// background((float) rgb, alpha); +// +// } else { +// colorCalcARGB(rgb, alpha); +// backgroundFromCalc(); +// backgroundImpl(); +// } +// } + colorCalc(rgb, alpha); + backgroundFromCalc(); + } + + + /** + * Set the background to a grayscale value, based on the + * current colorMode. + */ + public void background(float gray) { + colorCalc(gray); + backgroundFromCalc(); +// backgroundImpl(); + } + + + /** + * See notes about alpha in background(x, y, z, a). + * @param gray specifies a value between white and black + * @param alpha opacity of the background + */ + public void background(float gray, float alpha) { + if (format == RGB) { + background(gray); // ignore alpha for main drawing surface + + } else { + colorCalc(gray, alpha); + backgroundFromCalc(); +// backgroundImpl(); + } + } + + + /** + * Set the background to an r, g, b or h, s, b value, + * based on the current colorMode. + */ + public void background(float x, float y, float z) { + colorCalc(x, y, z); + backgroundFromCalc(); +// backgroundImpl(); + } + + + /** + * The background() function sets the color used for the background of the Processing window. The default background is light gray. In the draw() function, the background color is used to clear the display window at the beginning of each frame. + *

An image can also be used as the background for a sketch, however its width and height must be the same size as the sketch window. To resize an image 'b' to the size of the sketch window, use b.resize(width, height). + *

Images used as background will ignore the current tint() setting. + *

It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with createGraphics. + * + * =advanced + *

Clear the background with a color that includes an alpha value. This can + * only be used with objects created by createGraphics(), because the main + * drawing surface cannot be set transparent.

+ *

It might be tempting to use this function to partially clear the screen + * on each frame, however that's not how this function works. When calling + * background(), the pixels will be replaced with pixels that have that level + * of transparency. To do a semi-transparent overlay, use fill() with alpha + * and draw a rectangle.

+ * + * @webref color:setting + * @param x red or hue value (depending on the current color mode) + * @param y green or saturation value (depending on the current color mode) + * @param z blue or brightness value (depending on the current color mode) + * + * @see PGraphics#stroke(float) + * @see PGraphics#fill(float) + * @see PGraphics#tint(float) + * @see PGraphics#colorMode(int) + */ + public void background(float x, float y, float z, float a) { +// if (format == RGB) { +// background(x, y, z); // don't allow people to set alpha +// +// } else { +// colorCalc(x, y, z, a); +// backgroundFromCalc(); +// backgroundImpl(); +// } + colorCalc(x, y, z, a); + backgroundFromCalc(); + } + + + protected void backgroundFromCalc() { + backgroundR = calcR; + backgroundG = calcG; + backgroundB = calcB; + backgroundA = (format == RGB) ? colorModeA : calcA; + backgroundRi = calcRi; + backgroundGi = calcGi; + backgroundBi = calcBi; + backgroundAi = (format == RGB) ? 255 : calcAi; + backgroundAlpha = (format == RGB) ? false : calcAlpha; + backgroundColor = calcColor; + + backgroundImpl(); + } + + + /** + * Takes an RGB or ARGB image and sets it as the background. + * The width and height of the image must be the same size as the sketch. + * Use image.resize(width, height) to make short work of such a task. + *

+ * Note that even if the image is set as RGB, the high 8 bits of each pixel + * should be set opaque (0xFF000000), because the image data will be copied + * directly to the screen, and non-opaque background images may have strange + * behavior. Using image.filter(OPAQUE) will handle this easily. + *

+ * When using 3D, this will also clear the zbuffer (if it exists). + */ + public void background(PImage image) { + if ((image.width != width) || (image.height != height)) { + throw new RuntimeException(ERROR_BACKGROUND_IMAGE_SIZE); + } + if ((image.format != RGB) && (image.format != ARGB)) { + throw new RuntimeException(ERROR_BACKGROUND_IMAGE_FORMAT); + } + backgroundColor = 0; // just zero it out for images + backgroundImpl(image); + } + + + /** + * Actually set the background image. This is separated from the error + * handling and other semantic goofiness that is shared across renderers. + */ + protected void backgroundImpl(PImage image) { + // blit image to the screen + set(0, 0, image); + } + + + /** + * Actual implementation of clearing the background, now that the + * internal variables for background color have been set. Called by the + * backgroundFromCalc() method, which is what all the other background() + * methods call once the work is done. + */ + protected void backgroundImpl() { + pushStyle(); + pushMatrix(); + resetMatrix(); + fill(backgroundColor); + rect(0, 0, width, height); + popMatrix(); + popStyle(); + } + + + /** + * Callback to handle clearing the background when begin/endRaw is in use. + * Handled as separate function for OpenGL (or other) subclasses that + * override backgroundImpl() but still needs this to work properly. + */ +// protected void backgroundRawImpl() { +// if (raw != null) { +// raw.colorMode(RGB, 1); +// raw.noStroke(); +// raw.fill(backgroundR, backgroundG, backgroundB); +// raw.beginShape(TRIANGLES); +// +// raw.vertex(0, 0); +// raw.vertex(width, 0); +// raw.vertex(0, height); +// +// raw.vertex(width, 0); +// raw.vertex(width, height); +// raw.vertex(0, height); +// +// raw.endShape(); +// } +// } + + + + ////////////////////////////////////////////////////////////// + + // COLOR MODE + + + /** + * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness + * @param max range for all color elements + */ + public void colorMode(int mode) { + colorMode(mode, colorModeX, colorModeY, colorModeZ, colorModeA); + } + + + public void colorMode(int mode, float max) { + colorMode(mode, max, max, max, max); + } + + + /** + * Set the colorMode and the maximum values for (r, g, b) + * or (h, s, b). + *

+ * Note that this doesn't set the maximum for the alpha value, + * which might be confusing if for instance you switched to + *

colorMode(HSB, 360, 100, 100);
+ * because the alpha values were still between 0 and 255. + */ + public void colorMode(int mode, float maxX, float maxY, float maxZ) { + colorMode(mode, maxX, maxY, maxZ, colorModeA); + } + + + /** + * Changes the way Processing interprets color data. By default, the parameters for fill(), stroke(), background(), and color() are defined by values between 0 and 255 using the RGB color model. The colorMode() function is used to change the numerical range used for specifying colors and to switch color systems. For example, calling colorMode(RGB, 1.0) will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the parameters range1, range2, range3, and range 4. + * + * @webref color:setting + * @param maxX range for the red or hue depending on the current color mode + * @param maxY range for the green or saturation depending on the current color mode + * @param maxZ range for the blue or brightness depending on the current color mode + * @param maxA range for the alpha + * + * @see PGraphics#background(float) + * @see PGraphics#fill(float) + * @see PGraphics#stroke(float) + */ + public void colorMode(int mode, + float maxX, float maxY, float maxZ, float maxA) { + colorMode = mode; + + colorModeX = maxX; // still needs to be set for hsb + colorModeY = maxY; + colorModeZ = maxZ; + colorModeA = maxA; + + // if color max values are all 1, then no need to scale + colorModeScale = + ((maxA != 1) || (maxX != maxY) || (maxY != maxZ) || (maxZ != maxA)); + + // if color is rgb/0..255 this will make it easier for the + // red() green() etc functions + colorModeDefault = (colorMode == RGB) && + (colorModeA == 255) && (colorModeX == 255) && + (colorModeY == 255) && (colorModeZ == 255); + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR CALCULATIONS + + // Given input values for coloring, these functions will fill the calcXxxx + // variables with values that have been properly filtered through the + // current colorMode settings. + + // Renderers that need to subclass any drawing properties such as fill or + // stroke will usally want to override methods like fillFromCalc (or the + // same for stroke, ambient, etc.) That way the color calcuations are + // covered by this based PGraphics class, leaving only a single function + // to override/implement in the subclass. + + + /** + * Set the fill to either a grayscale value or an ARGB int. + *

+ * The problem with this code is that it has to detect between these two + * situations automatically. This is done by checking to see if the high bits + * (the alpha for 0xAA000000) is set, and if not, whether the color value + * that follows is less than colorModeX (first param passed to colorMode). + *

+ * This auto-detect would break in the following situation: + *

size(256, 256);
+   * for (int i = 0; i < 256; i++) {
+   *   color c = color(0, 0, 0, i);
+   *   stroke(c);
+   *   line(i, 0, i, 256);
+   * }
+ * ...on the first time through the loop, where (i == 0), since the color + * itself is zero (black) then it would appear indistinguishable from code + * that reads "fill(0)". The solution is to use the four parameter versions + * of stroke or fill to more directly specify the desired result. + */ + protected void colorCalc(int rgb) { + if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { + colorCalc((float) rgb); + + } else { + colorCalcARGB(rgb, colorModeA); + } + } + + + protected void colorCalc(int rgb, float alpha) { + if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above + colorCalc((float) rgb, alpha); + + } else { + colorCalcARGB(rgb, alpha); + } + } + + + protected void colorCalc(float gray) { + colorCalc(gray, colorModeA); + } + + + protected void colorCalc(float gray, float alpha) { + if (gray > colorModeX) gray = colorModeX; + if (alpha > colorModeA) alpha = colorModeA; + + if (gray < 0) gray = 0; + if (alpha < 0) alpha = 0; + + calcR = colorModeScale ? (gray / colorModeX) : gray; + calcG = calcR; + calcB = calcR; + calcA = colorModeScale ? (alpha / colorModeA) : alpha; + + calcRi = (int)(calcR*255); calcGi = (int)(calcG*255); + calcBi = (int)(calcB*255); calcAi = (int)(calcA*255); + calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi; + calcAlpha = (calcAi != 255); + } + + + protected void colorCalc(float x, float y, float z) { + colorCalc(x, y, z, colorModeA); + } + + + protected void colorCalc(float x, float y, float z, float a) { + if (x > colorModeX) x = colorModeX; + if (y > colorModeY) y = colorModeY; + if (z > colorModeZ) z = colorModeZ; + if (a > colorModeA) a = colorModeA; + + if (x < 0) x = 0; + if (y < 0) y = 0; + if (z < 0) z = 0; + if (a < 0) a = 0; + + switch (colorMode) { + case RGB: + if (colorModeScale) { + calcR = x / colorModeX; + calcG = y / colorModeY; + calcB = z / colorModeZ; + calcA = a / colorModeA; + } else { + calcR = x; calcG = y; calcB = z; calcA = a; + } + break; + + case HSB: + x /= colorModeX; // h + y /= colorModeY; // s + z /= colorModeZ; // b + + calcA = colorModeScale ? (a/colorModeA) : a; + + if (y == 0) { // saturation == 0 + calcR = calcG = calcB = z; + + } else { + float which = (x - (int)x) * 6.0f; + float f = which - (int)which; + float p = z * (1.0f - y); + float q = z * (1.0f - y * f); + float t = z * (1.0f - (y * (1.0f - f))); + + switch ((int)which) { + case 0: calcR = z; calcG = t; calcB = p; break; + case 1: calcR = q; calcG = z; calcB = p; break; + case 2: calcR = p; calcG = z; calcB = t; break; + case 3: calcR = p; calcG = q; calcB = z; break; + case 4: calcR = t; calcG = p; calcB = z; break; + case 5: calcR = z; calcG = p; calcB = q; break; + } + } + break; + } + calcRi = (int)(255*calcR); calcGi = (int)(255*calcG); + calcBi = (int)(255*calcB); calcAi = (int)(255*calcA); + calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi; + calcAlpha = (calcAi != 255); + } + + + /** + * Unpacks AARRGGBB color for direct use with colorCalc. + *

+ * Handled here with its own function since this is indepenent + * of the color mode. + *

+ * Strangely the old version of this code ignored the alpha + * value. not sure if that was a bug or what. + *

+ * Note, no need for a bounds check since it's a 32 bit number. + */ + protected void colorCalcARGB(int argb, float alpha) { + if (alpha == colorModeA) { + calcAi = (argb >> 24) & 0xff; + calcColor = argb; + } else { + calcAi = (int) (((argb >> 24) & 0xff) * (alpha / colorModeA)); + calcColor = (calcAi << 24) | (argb & 0xFFFFFF); + } + calcRi = (argb >> 16) & 0xff; + calcGi = (argb >> 8) & 0xff; + calcBi = argb & 0xff; + calcA = (float)calcAi / 255.0f; + calcR = (float)calcRi / 255.0f; + calcG = (float)calcGi / 255.0f; + calcB = (float)calcBi / 255.0f; + calcAlpha = (calcAi != 255); + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE STUFFING + + // The 'color' primitive type in Processing syntax is in fact a 32-bit int. + // These functions handle stuffing color values into a 32-bit cage based + // on the current colorMode settings. + + // These functions are really slow (because they take the current colorMode + // into account), but they're easy to use. Advanced users can write their + // own bit shifting operations to setup 'color' data types. + + + public final int color(int gray) { // ignore + if (((gray & 0xff000000) == 0) && (gray <= colorModeX)) { + if (colorModeDefault) { + // bounds checking to make sure the numbers aren't to high or low + if (gray > 255) gray = 255; else if (gray < 0) gray = 0; + return 0xff000000 | (gray << 16) | (gray << 8) | gray; + } else { + colorCalc(gray); + } + } else { + colorCalcARGB(gray, colorModeA); + } + return calcColor; + } + + + public final int color(float gray) { // ignore + colorCalc(gray); + return calcColor; + } + + + /** + * @param gray can be packed ARGB or a gray in this case + */ + public final int color(int gray, int alpha) { // ignore + if (colorModeDefault) { + // bounds checking to make sure the numbers aren't to high or low + if (gray > 255) gray = 255; else if (gray < 0) gray = 0; + if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; + + return ((alpha & 0xff) << 24) | (gray << 16) | (gray << 8) | gray; + } + colorCalc(gray, alpha); + return calcColor; + } + + + /** + * @param rgb can be packed ARGB or a gray in this case + */ + public final int color(int rgb, float alpha) { // ignore + if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { + colorCalc(rgb, alpha); + } else { + colorCalcARGB(rgb, alpha); + } + return calcColor; + } + + + public final int color(float gray, float alpha) { // ignore + colorCalc(gray, alpha); + return calcColor; + } + + + public final int color(int x, int y, int z) { // ignore + if (colorModeDefault) { + // bounds checking to make sure the numbers aren't to high or low + if (x > 255) x = 255; else if (x < 0) x = 0; + if (y > 255) y = 255; else if (y < 0) y = 0; + if (z > 255) z = 255; else if (z < 0) z = 0; + + return 0xff000000 | (x << 16) | (y << 8) | z; + } + colorCalc(x, y, z); + return calcColor; + } + + + public final int color(float x, float y, float z) { // ignore + colorCalc(x, y, z); + return calcColor; + } + + + public final int color(int x, int y, int z, int a) { // ignore + if (colorModeDefault) { + // bounds checking to make sure the numbers aren't to high or low + if (a > 255) a = 255; else if (a < 0) a = 0; + if (x > 255) x = 255; else if (x < 0) x = 0; + if (y > 255) y = 255; else if (y < 0) y = 0; + if (z > 255) z = 255; else if (z < 0) z = 0; + + return (a << 24) | (x << 16) | (y << 8) | z; + } + colorCalc(x, y, z, a); + return calcColor; + } + + + public final int color(float x, float y, float z, float a) { // ignore + colorCalc(x, y, z, a); + return calcColor; + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE EXTRACTION + + // Vee have veys of making the colors talk. + + + /** + * Extracts the alpha value from a color. + * + * @webref color:creating_reading + * @param what any value of the color datatype + */ + public final float alpha(int what) { + float c = (what >> 24) & 0xff; + if (colorModeA == 255) return c; + return (c / 255.0f) * colorModeA; + } + + + /** + * Extracts the red value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.

The red() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use the >> (right shift) operator with a bit mask. For example, the following two lines of code are equivalent:

float r1 = red(myColor);
float r2 = myColor >> 16 & 0xFF;
+ * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + * @ref rightshift + */ + public final float red(int what) { + float c = (what >> 16) & 0xff; + if (colorModeDefault) return c; + return (c / 255.0f) * colorModeX; + } + + + /** + * Extracts the green value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.

The green() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use the >> (right shift) operator with a bit mask. For example, the following two lines of code are equivalent:
float r1 = green(myColor);
float r2 = myColor >> 8 & 0xFF;
+ * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + * @ref rightshift + */ + public final float green(int what) { + float c = (what >> 8) & 0xff; + if (colorModeDefault) return c; + return (c / 255.0f) * colorModeY; + } + + + /** + * Extracts the blue value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.

The blue() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use a bit mask to remove the other color components. For example, the following two lines of code are equivalent:
float r1 = blue(myColor);
float r2 = myColor & 0xFF;
+ * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + */ + public final float blue(int what) { + float c = (what) & 0xff; + if (colorModeDefault) return c; + return (c / 255.0f) * colorModeZ; + } + + + /** + * Extracts the hue value from a color. + * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#saturation(int) + * @see PGraphics#brightness(int) + */ + public final float hue(int what) { + if (what != cacheHsbKey) { + Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff, + what & 0xff, cacheHsbValue); + cacheHsbKey = what; + } + return cacheHsbValue[0] * colorModeX; + } + + + /** + * Extracts the saturation value from a color. + * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#brightness(int) + */ + public final float saturation(int what) { + if (what != cacheHsbKey) { + Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff, + what & 0xff, cacheHsbValue); + cacheHsbKey = what; + } + return cacheHsbValue[1] * colorModeY; + } + + + /** + * Extracts the brightness value from a color. + * + * + * @webref color:creating_reading + * @param what any value of the color datatype + * + * @see PGraphics#red(int) + * @see PGraphics#green(int) + * @see PGraphics#blue(int) + * @see PGraphics#hue(int) + * @see PGraphics#saturation(int) + */ + public final float brightness(int what) { + if (what != cacheHsbKey) { + Color.RGBtoHSB((what >> 16) & 0xff, (what >> 8) & 0xff, + what & 0xff, cacheHsbValue); + cacheHsbKey = what; + } + return cacheHsbValue[2] * colorModeZ; + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE INTERPOLATION + + // Against our better judgement. + + + /** + * Calculates a color or colors between two color at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. + * + * @webref color:creating_reading + * @param c1 interpolate from this color + * @param c2 interpolate to this color + * @param amt between 0.0 and 1.0 + * + * @see PGraphics#blendColor(int, int, int) + * @see PGraphics#color(float, float, float, float) + */ + public int lerpColor(int c1, int c2, float amt) { + return lerpColor(c1, c2, amt, colorMode); + } + + static float[] lerpColorHSB1; + static float[] lerpColorHSB2; + + /** + * Interpolate between two colors. Like lerp(), but for the + * individual color components of a color supplied as an int value. + */ + static public int lerpColor(int c1, int c2, float amt, int mode) { + if (mode == RGB) { + float a1 = ((c1 >> 24) & 0xff); + float r1 = (c1 >> 16) & 0xff; + float g1 = (c1 >> 8) & 0xff; + float b1 = c1 & 0xff; + float a2 = (c2 >> 24) & 0xff; + float r2 = (c2 >> 16) & 0xff; + float g2 = (c2 >> 8) & 0xff; + float b2 = c2 & 0xff; + + return (((int) (a1 + (a2-a1)*amt) << 24) | + ((int) (r1 + (r2-r1)*amt) << 16) | + ((int) (g1 + (g2-g1)*amt) << 8) | + ((int) (b1 + (b2-b1)*amt))); + + } else if (mode == HSB) { + if (lerpColorHSB1 == null) { + lerpColorHSB1 = new float[3]; + lerpColorHSB2 = new float[3]; + } + + float a1 = (c1 >> 24) & 0xff; + float a2 = (c2 >> 24) & 0xff; + int alfa = ((int) (a1 + (a2-a1)*amt)) << 24; + + Color.RGBtoHSB((c1 >> 16) & 0xff, (c1 >> 8) & 0xff, c1 & 0xff, + lerpColorHSB1); + Color.RGBtoHSB((c2 >> 16) & 0xff, (c2 >> 8) & 0xff, c2 & 0xff, + lerpColorHSB2); + + /* If mode is HSB, this will take the shortest path around the + * color wheel to find the new color. For instance, red to blue + * will go red violet blue (backwards in hue space) rather than + * cycling through ROYGBIV. + */ + // Disabling rollover (wasn't working anyway) for 0126. + // Otherwise it makes full spectrum scale impossible for + // those who might want it...in spite of how despicable + // a full spectrum scale might be. + // roll around when 0.9 to 0.1 + // more than 0.5 away means that it should roll in the other direction + /* + float h1 = lerpColorHSB1[0]; + float h2 = lerpColorHSB2[0]; + if (Math.abs(h1 - h2) > 0.5f) { + if (h1 > h2) { + // i.e. h1 is 0.7, h2 is 0.1 + h2 += 1; + } else { + // i.e. h1 is 0.1, h2 is 0.7 + h1 += 1; + } + } + float ho = (PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt)) % 1.0f; + */ + float ho = PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt); + float so = PApplet.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt); + float bo = PApplet.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt); + + return alfa | (Color.HSBtoRGB(ho, so, bo) & 0xFFFFFF); + } + return 0; + } + + + + ////////////////////////////////////////////////////////////// + + // BEGINRAW/ENDRAW + + + /** + * Record individual lines and triangles by echoing them to another renderer. + */ + public void beginRaw(PGraphics rawGraphics) { // ignore + this.raw = rawGraphics; + rawGraphics.beginDraw(); + } + + + public void endRaw() { // ignore + if (raw != null) { + // for 3D, need to flush any geometry that's been stored for sorting + // (particularly if the ENABLE_DEPTH_SORT hint is set) + flush(); + + // just like beginDraw, this will have to be called because + // endDraw() will be happening outside of draw() + raw.endDraw(); + raw.dispose(); + raw = null; + } + } + + + + ////////////////////////////////////////////////////////////// + + // WARNINGS and EXCEPTIONS + + + static protected HashMap warnings; + + + /** + * Show a renderer error, and keep track of it so that it's only shown once. + * @param msg the error message (which will be stored for later comparison) + */ + static public void showWarning(String msg) { // ignore + if (warnings == null) { + warnings = new HashMap(); + } + if (!warnings.containsKey(msg)) { + System.err.println(msg); + warnings.put(msg, new Object()); + } + } + + + /** + * Display a warning that the specified method is only available with 3D. + * @param method The method name (no parentheses) + */ + static protected void showDepthWarning(String method) { + showWarning(method + "() can only be used with a renderer that " + + "supports 3D, such as P3D or OPENGL."); + } + + + /** + * Display a warning that the specified method that takes x, y, z parameters + * can only be used with x and y parameters in this renderer. + * @param method The method name (no parentheses) + */ + static protected void showDepthWarningXYZ(String method) { + showWarning(method + "() with x, y, and z coordinates " + + "can only be used with a renderer that " + + "supports 3D, such as P3D or OPENGL. " + + "Use a version without a z-coordinate instead."); + } + + + /** + * Display a warning that the specified method is simply unavailable. + */ + static protected void showMethodWarning(String method) { + showWarning(method + "() is not available with this renderer."); + } + + + /** + * Error that a particular variation of a method is unavailable (even though + * other variations are). For instance, if vertex(x, y, u, v) is not + * available, but vertex(x, y) is just fine. + */ + static protected void showVariationWarning(String str) { + showWarning(str + " is not available with this renderer."); + } + + + /** + * Display a warning that the specified method is not implemented, meaning + * that it could be either a completely missing function, although other + * variations of it may still work properly. + */ + static protected void showMissingWarning(String method) { + showWarning(method + "(), or this particular variation of it, " + + "is not available with this renderer."); + } + + + /** + * Show an renderer-related exception that halts the program. Currently just + * wraps the message as a RuntimeException and throws it, but might do + * something more specific might be used in the future. + */ + static public void showException(String msg) { // ignore + throw new RuntimeException(msg); + } + + + /** + * Same as below, but defaults to a 12 point font, just as MacWrite intended. + */ + protected void defaultFontOrDeath(String method) { + defaultFontOrDeath(method, 12); + } + + + /** + * First try to create a default font, but if that's not possible, throw + * an exception that halts the program because textFont() has not been used + * prior to the specified method. + */ + protected void defaultFontOrDeath(String method, float size) { + if (parent != null) { + textFont = parent.createDefaultFont(size); + } else { + throw new RuntimeException("Use textFont() before " + method + "()"); + } + } + + + + ////////////////////////////////////////////////////////////// + + // RENDERER SUPPORT QUERIES + + + /** + * Return true if this renderer should be drawn to the screen. Defaults to + * returning true, since nearly all renderers are on-screen beasts. But can + * be overridden for subclasses like PDF so that a window doesn't open up. + *

+ * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, + * what to call this? + */ + public boolean displayable() { + return true; + } + + + /** + * Return true if this renderer supports 2D drawing. Defaults to true. + */ + public boolean is2D() { + return true; + } + + + /** + * Return true if this renderer supports 2D drawing. Defaults to true. + */ + public boolean is3D() { + return false; + } +} diff --git a/support/Processing_core_src/processing/core/PGraphics2D.java b/support/Processing_core_src/processing/core/PGraphics2D.java new file mode 100644 index 0000000..0c0bfa7 --- /dev/null +++ b/support/Processing_core_src/processing/core/PGraphics2D.java @@ -0,0 +1,2144 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2006-08 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.Toolkit; +import java.awt.image.DirectColorModel; +import java.awt.image.MemoryImageSource; +import java.util.Arrays; + + +/** + * Subclass of PGraphics that handles fast 2D rendering using a + * MemoryImageSource. The renderer found in this class is not as accurate as + * PGraphicsJava2D, but offers certain speed tradeoffs, particular when + * messing with the pixels array, or displaying image or video data. + */ +public class PGraphics2D extends PGraphics { + + PMatrix2D ctm = new PMatrix2D(); + + //PPolygon polygon; // general polygon to use for shape + PPolygon fpolygon; // used to fill polys for tri or quad strips + PPolygon spolygon; // stroke/line polygon + float svertices[][]; // temp vertices used for stroking end of poly + + PPolygon tpolygon; + int[] vertexOrder; + + PLine line; + + float[][] matrixStack = new float[MATRIX_STACK_DEPTH][6]; + int matrixStackDepth; + + DirectColorModel cm; + MemoryImageSource mis; + + + ////////////////////////////////////////////////////////////// + + + public PGraphics2D() { } + + + //public void setParent(PApplet parent) + + + //public void setPrimary(boolean primary) + + + //public void setPath(String path) + + + //public void setSize(int iwidth, int iheight) + + + protected void allocate() { + pixelCount = width * height; + pixels = new int[pixelCount]; + + if (primarySurface) { + cm = new DirectColorModel(32, 0x00ff0000, 0x0000ff00, 0x000000ff);; + mis = new MemoryImageSource(width, height, pixels, 0, width); + mis.setFullBufferUpdates(true); + mis.setAnimated(true); + image = Toolkit.getDefaultToolkit().createImage(mis); + } + } + + + //public void dispose() + + + + ////////////////////////////////////////////////////////////// + + + public boolean canDraw() { + return true; + } + + + public void beginDraw() { + // need to call defaults(), but can only be done when it's ok to draw + // (i.e. for OpenGL, no drawing can be done outside beginDraw/endDraw). + if (!settingsInited) { + defaultSettings(); + +// polygon = new PPolygon(this); + fpolygon = new PPolygon(this); + spolygon = new PPolygon(this); + spolygon.vertexCount = 4; + svertices = new float[2][]; + } + + resetMatrix(); // reset model matrix + + // reset vertices + vertexCount = 0; + } + + + public void endDraw() { + if (mis != null) { + mis.newPixels(pixels, cm, 0, width); + } + // mark pixels as having been updated, so that they'll work properly + // when this PGraphics is drawn using image(). + updatePixels(); + } + + + // public void flush() + + + + ////////////////////////////////////////////////////////////// + + + //protected void checkSettings() + + + //protected void defaultSettings() + + + //protected void reapplySettings() + + + + ////////////////////////////////////////////////////////////// + + + //public void hint(int which) + + + + ////////////////////////////////////////////////////////////// + + + //public void beginShape() + + + public void beginShape(int kind) { + shape = kind; + vertexCount = 0; + curveVertexCount = 0; + +// polygon.reset(0); + fpolygon.reset(4); + spolygon.reset(4); + + textureImage = null; +// polygon.interpUV = false; + } + + + //public void edge(boolean e) + + + //public void normal(float nx, float ny, float nz) + + + //public void textureMode(int mode) + + + //public void texture(PImage image) + + + /* + public void vertex(float x, float y) { + if (shape == POINTS) { + point(x, y); + } else { + super.vertex(x, y); + } + } + */ + + + public void vertex(float x, float y, float z) { + showDepthWarningXYZ("vertex"); + } + + + //public void vertex(float x, float y, float u, float v) + + + public void vertex(float x, float y, float z, float u, float v) { + showDepthWarningXYZ("vertex"); + } + + + //protected void vertexTexture(float u, float v); + + + public void breakShape() { + showWarning("This renderer cannot handle concave shapes " + + "or shapes with holes."); + } + + + //public void endShape() + + + public void endShape(int mode) { + if (ctm.isIdentity()) { + for (int i = 0; i < vertexCount; i++) { + vertices[i][TX] = vertices[i][X]; + vertices[i][TY] = vertices[i][Y]; + } + } else { + for (int i = 0; i < vertexCount; i++) { + vertices[i][TX] = ctm.multX(vertices[i][X], vertices[i][Y]); + vertices[i][TY] = ctm.multY(vertices[i][X], vertices[i][Y]); + } + } + + // ------------------------------------------------------------------ + // TEXTURES + + fpolygon.texture(textureImage); + + // ------------------------------------------------------------------ + // COLORS + // calculate RGB for each vertex + + spolygon.interpARGB = true; //strokeChanged; //false; + fpolygon.interpARGB = true; //fillChanged; //false; + + // all the values for r, g, b have been set with calls to vertex() + // (no need to re-calculate anything here) + + // ------------------------------------------------------------------ + // RENDER SHAPES + + int increment; + + switch (shape) { + case POINTS: + // stroke cannot change inside beginShape(POINTS); + if (stroke) { + if ((ctm.m00 == ctm.m11) && (strokeWeight == 1)) { + for (int i = 0; i < vertexCount; i++) { + thin_point(vertices[i][TX], vertices[i][TY], strokeColor); + } + } else { + for (int i = 0; i < vertexCount; i++) { + float[] v = vertices[i]; + thick_point(v[TX], v[TY], v[TZ], v[SR], v[SG], v[SB], v[SA]); + } + } + } + break; + + case LINES: + if (stroke) { + // increment by two for individual lines + increment = (shape == LINES) ? 2 : 1; + draw_lines(vertices, vertexCount-1, 1, increment, 0); + } + break; + + case TRIANGLE_FAN: + // do fill and stroke separately because otherwise + // the lines will be stroked more than necessary + if (fill || textureImage != null) { + fpolygon.vertexCount = 3; + + for (int i = 1; i < vertexCount-1; i++) { +// System.out.println(i + " of " + vertexCount); + + fpolygon.vertices[2][R] = vertices[0][R]; + fpolygon.vertices[2][G] = vertices[0][G]; + fpolygon.vertices[2][B] = vertices[0][B]; + fpolygon.vertices[2][A] = vertices[0][A]; + + fpolygon.vertices[2][TX] = vertices[0][TX]; + fpolygon.vertices[2][TY] = vertices[0][TY]; + + if (textureImage != null) { + fpolygon.vertices[2][U] = vertices[0][U]; + fpolygon.vertices[2][V] = vertices[0][V]; + } +// System.out.println(fpolygon.vertices[2][TX] + " " + fpolygon.vertices[2][TY]); + + for (int j = 0; j < 2; j++) { + fpolygon.vertices[j][R] = vertices[i+j][R]; + fpolygon.vertices[j][G] = vertices[i+j][G]; + fpolygon.vertices[j][B] = vertices[i+j][B]; + fpolygon.vertices[j][A] = vertices[i+j][A]; + + fpolygon.vertices[j][TX] = vertices[i+j][TX]; + fpolygon.vertices[j][TY] = vertices[i+j][TY]; + +// System.out.println(fpolygon.vertices[j][TX] + " " + fpolygon.vertices[j][TY]); + + if (textureImage != null) { + fpolygon.vertices[j][U] = vertices[i+j][U]; + fpolygon.vertices[j][V] = vertices[i+j][V]; + } + } +// System.out.println(); + fpolygon.render(); + } + } + if (stroke) { + // draw internal lines + for (int i = 1; i < vertexCount; i++) { + draw_line(vertices[0], vertices[i]); + } + // draw a ring around the outside + for (int i = 1; i < vertexCount-1; i++) { + draw_line(vertices[i], vertices[i+1]); + } + // close the shape + draw_line(vertices[vertexCount-1], vertices[1]); + } + break; + + case TRIANGLES: + case TRIANGLE_STRIP: + increment = (shape == TRIANGLES) ? 3 : 1; + // do fill and stroke separately because otherwise + // the lines will be stroked more than necessary + if (fill || textureImage != null) { + fpolygon.vertexCount = 3; + for (int i = 0; i < vertexCount-2; i += increment) { + for (int j = 0; j < 3; j++) { + fpolygon.vertices[j][R] = vertices[i+j][R]; + fpolygon.vertices[j][G] = vertices[i+j][G]; + fpolygon.vertices[j][B] = vertices[i+j][B]; + fpolygon.vertices[j][A] = vertices[i+j][A]; + + fpolygon.vertices[j][TX] = vertices[i+j][TX]; + fpolygon.vertices[j][TY] = vertices[i+j][TY]; + fpolygon.vertices[j][TZ] = vertices[i+j][TZ]; + + if (textureImage != null) { + fpolygon.vertices[j][U] = vertices[i+j][U]; + fpolygon.vertices[j][V] = vertices[i+j][V]; + } + } + fpolygon.render(); + } + } + if (stroke) { + // first draw all vertices as a line strip + if (shape == TRIANGLE_STRIP) { + draw_lines(vertices, vertexCount-1, 1, 1, 0); + } else { + draw_lines(vertices, vertexCount-1, 1, 1, 3); + } + // then draw from vertex (n) to (n+2) + // incrementing n using the same as above + draw_lines(vertices, vertexCount-2, 2, increment, 0); + // changed this to vertexCount-2, because it seemed + // to be adding an extra (nonexistant) line + } + break; + + case QUADS: + if (fill || textureImage != null) { + fpolygon.vertexCount = 4; + for (int i = 0; i < vertexCount-3; i += 4) { + for (int j = 0; j < 4; j++) { + int jj = i+j; + fpolygon.vertices[j][R] = vertices[jj][R]; + fpolygon.vertices[j][G] = vertices[jj][G]; + fpolygon.vertices[j][B] = vertices[jj][B]; + fpolygon.vertices[j][A] = vertices[jj][A]; + + fpolygon.vertices[j][TX] = vertices[jj][TX]; + fpolygon.vertices[j][TY] = vertices[jj][TY]; + fpolygon.vertices[j][TZ] = vertices[jj][TZ]; + + if (textureImage != null) { + fpolygon.vertices[j][U] = vertices[jj][U]; + fpolygon.vertices[j][V] = vertices[jj][V]; + } + } + fpolygon.render(); + } + } + if (stroke) { + for (int i = 0; i < vertexCount-3; i += 4) { + draw_line(vertices[i+0], vertices[i+1]); + draw_line(vertices[i+1], vertices[i+2]); + draw_line(vertices[i+2], vertices[i+3]); + draw_line(vertices[i+3], vertices[i+0]); + } + } + break; + + case QUAD_STRIP: + if (fill || textureImage != null) { + fpolygon.vertexCount = 4; + for (int i = 0; i < vertexCount-3; i += 2) { + for (int j = 0; j < 4; j++) { + int jj = i+j; + if (j == 2) jj = i+3; // swap 2nd and 3rd vertex + if (j == 3) jj = i+2; + + fpolygon.vertices[j][R] = vertices[jj][R]; + fpolygon.vertices[j][G] = vertices[jj][G]; + fpolygon.vertices[j][B] = vertices[jj][B]; + fpolygon.vertices[j][A] = vertices[jj][A]; + + fpolygon.vertices[j][TX] = vertices[jj][TX]; + fpolygon.vertices[j][TY] = vertices[jj][TY]; + fpolygon.vertices[j][TZ] = vertices[jj][TZ]; + + if (textureImage != null) { + fpolygon.vertices[j][U] = vertices[jj][U]; + fpolygon.vertices[j][V] = vertices[jj][V]; + } + } + fpolygon.render(); + } + } + if (stroke) { + draw_lines(vertices, vertexCount-1, 1, 2, 0); // inner lines + draw_lines(vertices, vertexCount-2, 2, 1, 0); // outer lines + } + break; + + case POLYGON: + if (isConvex()) { + if (fill || textureImage != null) { + //System.out.println("convex"); + fpolygon.renderPolygon(vertices, vertexCount); + //if (stroke) polygon.unexpand(); + } + + if (stroke) { + draw_lines(vertices, vertexCount-1, 1, 1, 0); + if (mode == CLOSE) { + // draw the last line connecting back to the first point in poly + //svertices[0] = vertices[vertexCount-1]; + //svertices[1] = vertices[0]; + //draw_lines(svertices, 1, 1, 1, 0); + draw_line(vertices[vertexCount-1], vertices[0]); + } + } + } else { // not convex + //System.out.println("concave"); + if (fill || textureImage != null) { + // the triangulator produces polygons that don't align + // when smoothing is enabled. but if there is a stroke around + // the polygon, then smoothing can be temporarily disabled. + boolean smoov = smooth; + //if (stroke && !hints[DISABLE_SMOOTH_HACK]) smooth = false; + if (stroke) smooth = false; + concaveRender(); + //if (stroke && !hints[DISABLE_SMOOTH_HACK]) smooth = smoov; + if (stroke) smooth = smoov; + } + + if (stroke) { + draw_lines(vertices, vertexCount-1, 1, 1, 0); + if (mode == CLOSE) { + // draw the last line connecting back + // to the first point in poly +// svertices[0] = vertices[vertexCount-1]; +// svertices[1] = vertices[0]; +// draw_lines(svertices, 1, 1, 1, 0); + draw_line(vertices[vertexCount-1], vertices[0]); + } + } + } + break; + } + + // to signify no shape being drawn + shape = 0; + } + + + + ////////////////////////////////////////////////////////////// + + // CONCAVE/CONVEX POLYGONS + + + private boolean isConvex() { + //float v[][] = polygon.vertices; + //int n = polygon.vertexCount; + //int j,k; + //float tol = 0.001f; + + if (vertexCount < 3) { + // ERROR: this is a line or a point, render as convex + return true; + } + + int flag = 0; + // iterate along border doing dot product. + // if the sign of the result changes, then is concave + for (int i = 0; i < vertexCount; i++) { + float[] vi = vertices[i]; + float[] vj = vertices[(i + 1) % vertexCount]; + float[] vk = vertices[(i + 2) % vertexCount]; + float calc = ((vj[TX] - vi[TX]) * (vk[TY] - vj[TY]) - + (vj[TY] - vi[TY]) * (vk[TX] - vj[TX])); + if (calc < 0) { + flag |= 1; + } else if (calc > 0) { + flag |= 2; + } + if (flag == 3) { + return false; // CONCAVE + } + } + if (flag != 0) { + return true; // CONVEX + } else { + // ERROR: colinear points, self intersection + // treat as CONVEX + return true; + } + } + + + /** + * Triangulate the current polygon. + *

+ * Simple ear clipping polygon triangulation adapted from code by + * John W. Ratcliff (jratcliff at verant.com). Presumably + * this + * bit of code from the web. + */ + protected void concaveRender() { + if (vertexOrder == null || vertexOrder.length != vertices.length) { + vertexOrder = new int[vertices.length]; +// int[] temp = new int[vertices.length]; +// // since vertex_start may not be zero, might need to keep old stuff around +// PApplet.arrayCopy(vertexOrder, temp, vertexCount); +// vertexOrder = temp; + } + + if (tpolygon == null) { + tpolygon = new PPolygon(this); + } + tpolygon.reset(3); + + // first we check if the polygon goes clockwise or counterclockwise + float area = 0; + for (int p = vertexCount - 1, q = 0; q < vertexCount; p = q++) { + area += (vertices[q][X] * vertices[p][Y] - + vertices[p][X] * vertices[q][Y]); + } + // ain't nuthin there + if (area == 0) return; + + // don't allow polygons to come back and meet themselves, + // otherwise it will anger the triangulator + // http://dev.processing.org/bugs/show_bug.cgi?id=97 + float vfirst[] = vertices[0]; + float vlast[] = vertices[vertexCount-1]; + if ((Math.abs(vfirst[X] - vlast[X]) < EPSILON) && + (Math.abs(vfirst[Y] - vlast[Y]) < EPSILON) && + (Math.abs(vfirst[Z] - vlast[Z]) < EPSILON)) { + vertexCount--; + } + + // then sort the vertices so they are always in a counterclockwise order + for (int i = 0; i < vertexCount; i++) { + vertexOrder[i] = (area > 0) ? i : (vertexCount-1 - i); + } + + // remove vc-2 Vertices, creating 1 triangle every time + int vc = vertexCount; // vc will be decremented while working + int count = 2*vc; // complex polygon detection + + for (int m = 0, v = vc - 1; vc > 2; ) { + boolean snip = true; + + // if we start over again, is a complex polygon + if (0 >= (count--)) { + break; // triangulation failed + } + + // get 3 consecutive vertices + int u = v ; if (vc <= u) u = 0; // previous + v = u + 1; if (vc <= v) v = 0; // current + int w = v + 1; if (vc <= w) w = 0; // next + + // Upgrade values to doubles, and multiply by 10 so that we can have + // some better accuracy as we tessellate. This seems to have negligible + // speed differences on Windows and Intel Macs, but causes a 50% speed + // drop for PPC Macs with the bug's example code that draws ~200 points + // in a concave polygon. Apple has abandoned PPC so we may as well too. + // http://dev.processing.org/bugs/show_bug.cgi?id=774 + + // triangle A B C + double Ax = -10 * vertices[vertexOrder[u]][X]; + double Ay = 10 * vertices[vertexOrder[u]][Y]; + double Bx = -10 * vertices[vertexOrder[v]][X]; + double By = 10 * vertices[vertexOrder[v]][Y]; + double Cx = -10 * vertices[vertexOrder[w]][X]; + double Cy = 10 * vertices[vertexOrder[w]][Y]; + + // first we check if continues going ccw + if (EPSILON > (((Bx-Ax) * (Cy-Ay)) - ((By-Ay) * (Cx-Ax)))) { + continue; + } + + for (int p = 0; p < vc; p++) { + if ((p == u) || (p == v) || (p == w)) { + continue; + } + + double Px = -10 * vertices[vertexOrder[p]][X]; + double Py = 10 * vertices[vertexOrder[p]][Y]; + + double ax = Cx - Bx; double ay = Cy - By; + double bx = Ax - Cx; double by = Ay - Cy; + double cx = Bx - Ax; double cy = By - Ay; + double apx = Px - Ax; double apy = Py - Ay; + double bpx = Px - Bx; double bpy = Py - By; + double cpx = Px - Cx; double cpy = Py - Cy; + + double aCROSSbp = ax * bpy - ay * bpx; + double cCROSSap = cx * apy - cy * apx; + double bCROSScp = bx * cpy - by * cpx; + + if ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0)) { + snip = false; + } + } + + if (snip) { + tpolygon.renderTriangle(vertices[vertexOrder[u]], + vertices[vertexOrder[v]], + vertices[vertexOrder[w]]); + m++; + + // remove v from remaining polygon + for (int s = v, t = v + 1; t < vc; s++, t++) { + vertexOrder[s] = vertexOrder[t]; + } + vc--; + + // reset error detection counter + count = 2 * vc; + } + } + } + + + /* + // triangulate the current polygon + private void concaveRender() { + float polyVertices[][] = polygon.vertices; + + if (tpolygon == null) { + // allocate on first use, rather than slowing + // the startup of the class. + tpolygon = new PPolygon(this); + tpolygon_vertex_order = new int[TPOLYGON_MAX_VERTICES]; + } + tpolygon.reset(3); + + // copy render parameters + + if (textureImage != null) { + tpolygon.texture(textureImage); //polygon.timage); + } + + tpolygon.interpX = polygon.interpX; + tpolygon.interpUV = polygon.interpUV; + tpolygon.interpARGB = polygon.interpARGB; + + // simple ear clipping polygon triangulation + // addapted from code by john w. ratcliff (jratcliff@verant.com) + + // 1 - first we check if the polygon goes CW or CCW + // CW-CCW ordering adapted from code by + // Joseph O'Rourke orourke@cs.smith.edu + // 1A - we start by finding the lowest-right most vertex + + boolean ccw = false; // clockwise + + int n = polygon.vertexCount; + int mm; // postion for LR vertex + //float min[] = new float[2]; + float minX = polyVertices[0][TX]; + float minY = polyVertices[0][TY]; + mm = 0; + + for(int i = 0; i < n; i++ ) { + if ((polyVertices[i][TY] < minY) || + ((polyVertices[i][TY] == minY) && (polyVertices[i][TX] > minX) ) + ) { + mm = i; + minX = polyVertices[mm][TX]; + minY = polyVertices[mm][TY]; + } + } + + // 1B - now we compute the cross product of the edges of this vertex + float cp; + int mm1; + + // just for renaming + float a[] = new float[2]; + float b[] = new float[2]; + float c[] = new float[2]; + + mm1 = (mm + (n-1)) % n; + + // assign a[0] to point to poly[m1][0] etc. + for(int i = 0; i < 2; i++ ) { + a[i] = polyVertices[mm1][i]; + b[i] = polyVertices[mm][i]; + c[i] = polyVertices[(mm+1)%n][i]; + } + + cp = a[0] * b[1] - a[1] * b[0] + + a[1] * c[0] - a[0] * c[1] + + b[0] * c[1] - c[0] * b[1]; + + if ( cp > 0 ) + ccw = true; // CCW + else + ccw = false; // CW + + // 1C - then we sort the vertices so they + // are always in a counterclockwise order + //int j = 0; + if (!ccw) { + // keep the same order + for (int i = 0; i < n; i++) { + tpolygon_vertex_order[i] = i; + } + + } else { + // invert the order + for (int i = 0; i < n; i++) { + tpolygon_vertex_order[i] = (n - 1) - i; + } + } + + // 2 - begin triangulation + // resulting triangles are stored in the triangle array + // remove vc-2 Vertices, creating 1 triangle every time + int vc = n; + int count = 2*vc; // complex polygon detection + + for (int m = 0, v = vc - 1; vc > 2; ) { + boolean snip = true; + + // if we start over again, is a complex polygon + if (0 >= (count--)) { + break; // triangulation failed + } + + // get 3 consecutive vertices + int u = v ; if (vc <= u) u = 0; // previous + v = u+1; if (vc <= v) v = 0; // current + int w = v+1; if (vc <= w) w = 0; // next + + // triangle A B C + float Ax, Ay, Bx, By, Cx, Cy, Px, Py; + + Ax = -polyVertices[tpolygon_vertex_order[u]][TX]; + Ay = polyVertices[tpolygon_vertex_order[u]][TY]; + Bx = -polyVertices[tpolygon_vertex_order[v]][TX]; + By = polyVertices[tpolygon_vertex_order[v]][TY]; + Cx = -polyVertices[tpolygon_vertex_order[w]][TX]; + Cy = polyVertices[tpolygon_vertex_order[w]][TY]; + + if ( EPSILON > (((Bx-Ax) * (Cy-Ay)) - ((By-Ay) * (Cx-Ax)))) { + continue; + } + + for (int p = 0; p < vc; p++) { + + // this part is a bit osbscure, basically what it does + // is test if this tree vertices are and ear or not, looking for + // intersections with the remaining vertices using a cross product + float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; + float cCROSSap, bCROSScp, aCROSSbp; + + if( (p == u) || (p == v) || (p == w) ) { + continue; + } + + Px = -polyVertices[tpolygon_vertex_order[p]][TX]; + Py = polyVertices[tpolygon_vertex_order[p]][TY]; + + ax = Cx - Bx; ay = Cy - By; + bx = Ax - Cx; by = Ay - Cy; + cx = Bx - Ax; cy = By - Ay; + apx= Px - Ax; apy= Py - Ay; + bpx= Px - Bx; bpy= Py - By; + cpx= Px - Cx; cpy= Py - Cy; + + aCROSSbp = ax * bpy - ay * bpx; + cCROSSap = cx * apy - cy * apx; + bCROSScp = bx * cpy - by * cpx; + + if ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)) { + snip = false; + } + } + + if (snip) { + // yes, the trio is an ear, render it and cut it + + int triangle_vertices[] = new int[3]; + int s,t; + + // true names of the vertices + triangle_vertices[0] = tpolygon_vertex_order[u]; + triangle_vertices[1] = tpolygon_vertex_order[v]; + triangle_vertices[2] = tpolygon_vertex_order[w]; + + // create triangle + //render_triangle(triangle_vertices); + //private final void render_triangle(int[] triangle_vertices) { + // copy all fields of the triangle vertices + for (int i = 0; i < 3; i++) { + float[] src = polygon.vertices[triangle_vertices[i]]; + float[] dest = tpolygon.vertices[i]; + for (int k = 0; k < VERTEX_FIELD_COUNT; k++) { + dest[k] = src[k]; + } + } + // render triangle + tpolygon.render(); + //} + + m++; + + // remove v from remaining polygon + for( s = v, t = v + 1; t < vc; s++, t++) { + tpolygon_vertex_order[s] = tpolygon_vertex_order[t]; + } + + vc--; + + // resest error detection counter + count = 2 * vc; + } + } + } + */ + + + + ////////////////////////////////////////////////////////////// + + // BEZIER VERTICES + + + //public void bezierVertex(float x2, float y2, + // float x3, float y3, + // float x4, float y4) + + + //public void bezierVertex(float x2, float y2, float z2, + // float x3, float y3, float z3, + // float x4, float y4, float z4) + + + + ////////////////////////////////////////////////////////////// + + // CURVE VERTICES + + + //public void curveVertex(float x, float y) + + + //public void curveVertex(float x, float y, float z) + + + + ////////////////////////////////////////////////////////////// + + // FLUSH + + + //public void flush() + + + + ////////////////////////////////////////////////////////////// + + // PRIMITIVES + + + //public void point(float x, float y) + + + public void point(float x, float y, float z) { + showDepthWarningXYZ("point"); + } + + + //public void line(float x1, float y1, float x2, float y2) + + + //public void line(float x1, float y1, float z1, + // float x2, float y2, float z2) + + + //public void triangle(float x1, float y1, + // float x2, float y2, + // float x3, float y3) + + + //public void quad(float x1, float y1, float x2, float y2, + // float x3, float y3, float x4, float y4) + + + + ////////////////////////////////////////////////////////////// + + // RECT + + + protected void rectImpl(float x1f, float y1f, float x2f, float y2f) { + if (smooth || strokeAlpha || ctm.isWarped()) { + // screw the efficiency, send this off to beginShape(). + super.rectImpl(x1f, y1f, x2f, y2f); + + } else { + int x1 = (int) (x1f + ctm.m02); + int y1 = (int) (y1f + ctm.m12); + int x2 = (int) (x2f + ctm.m02); + int y2 = (int) (y2f + ctm.m12); + + if (fill) { + simple_rect_fill(x1, y1, x2, y2); + } + + if (stroke) { + if (strokeWeight == 1) { + thin_flat_line(x1, y1, x2, y1); + thin_flat_line(x2, y1, x2, y2); + thin_flat_line(x2, y2, x1, y2); + thin_flat_line(x1, y2, x1, y1); + + } else { + thick_flat_line(x1, y1, strokeR, strokeG, strokeB, strokeA, + x2, y1, strokeR, strokeG, strokeB, strokeA); + thick_flat_line(x2, y1, strokeR, strokeG, strokeB, strokeA, + x2, y2, strokeR, strokeG, strokeB, strokeA); + thick_flat_line(x2, y2, strokeR, strokeG, strokeB, strokeA, + x1, y2, strokeR, strokeG, strokeB, strokeA); + thick_flat_line(x1, y2, strokeR, strokeG, strokeB, strokeA, + x1, y1, strokeR, strokeG, strokeB, strokeA); + } + } + } + } + + + /** + * Draw a rectangle that hasn't been warped by the CTM (though it may be + * translated). Just fill a bunch of pixels, or blend them if there's alpha. + */ + private void simple_rect_fill(int x1, int y1, int x2, int y2) { + if (y2 < y1) { + int temp = y1; y1 = y2; y2 = temp; + } + if (x2 < x1) { + int temp = x1; x1 = x2; x2 = temp; + } + // check to see if completely off-screen (e.g. if the left edge of the + // rectangle is bigger than the width, and so on.) + if ((x1 > width1) || (x2 < 0) || + (y1 > height1) || (y2 < 0)) return; + + // these only affect the fill, not the stroke + // (otherwise strange boogers at edges b/c frame changes shape) + if (x1 < 0) x1 = 0; + if (x2 > width) x2 = width; + if (y1 < 0) y1 = 0; + if (y2 > height) y2 = height; + + int ww = x2 - x1; + + if (fillAlpha) { + for (int y = y1; y < y2; y++) { + int index = y*width + x1; + for (int x = 0; x < ww; x++) { + pixels[index] = blend_fill(pixels[index]); + index++; + } + } + + } else { + // on avg. 20-25% faster fill routine using System.arraycopy() [toxi 031223] + // removed temporary row[] array for (hopefully) better performance [fry 081117] + int hh = y2 - y1; + // int[] row = new int[ww]; + // for (int i = 0; i < ww; i++) row[i] = fillColor; + int index = y1 * width + x1; + int rowIndex = index; + for (int i = 0; i < ww; i++) { + pixels[index + i] = fillColor; + } + for (int y = 0; y < hh; y++) { + // System.arraycopy(row, 0, pixels, idx, ww); + System.arraycopy(pixels, rowIndex, pixels, index, ww); + index += width; + } + // row = null; + } + } + + + + ////////////////////////////////////////////////////////////// + + // ELLIPSE AND ARC + + + protected void ellipseImpl(float x, float y, float w, float h) { + if (smooth || (strokeWeight != 1) || + fillAlpha || strokeAlpha || ctm.isWarped()) { + // identical to PGraphics version, but uses POLYGON + // for the fill instead of a TRIANGLE_FAN + float radiusH = w / 2; + float radiusV = h / 2; + + float centerX = x + radiusH; + float centerY = y + radiusV; + + float sx1 = screenX(x, y); + float sy1 = screenY(x, y); + float sx2 = screenX(x+w, y+h); + float sy2 = screenY(x+w, y+h); + int accuracy = (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / 8); + if (accuracy < 4) return; // don't bother? + //System.out.println("diameter " + w + " " + h + " -> " + accuracy); + + float inc = (float)SINCOS_LENGTH / accuracy; + + float val = 0; + + if (fill) { + boolean savedStroke = stroke; + stroke = false; + + beginShape(); + for (int i = 0; i < accuracy; i++) { + vertex(centerX + cosLUT[(int) val] * radiusH, + centerY + sinLUT[(int) val] * radiusV); + val += inc; + } + endShape(CLOSE); + + stroke = savedStroke; + } + + if (stroke) { + boolean savedFill = fill; + fill = false; + + val = 0; + beginShape(); + for (int i = 0; i < accuracy; i++) { + vertex(centerX + cosLUT[(int) val] * radiusH, + centerY + sinLUT[(int) val] * radiusV); + val += inc; + } + endShape(CLOSE); + + fill = savedFill; + } + } else { + float hradius = w / 2f; + float vradius = h / 2f; + + int centerX = (int) (x + hradius + ctm.m02); + int centerY = (int) (y + vradius + ctm.m12); + + int hradiusi = (int) hradius; + int vradiusi = (int) vradius; + + if (hradiusi == vradiusi) { + if (fill) flat_circle_fill(centerX, centerY, hradiusi); + if (stroke) flat_circle_stroke(centerX, centerY, hradiusi); + + } else { + if (fill) flat_ellipse_internal(centerX, centerY, hradiusi, vradiusi, true); + if (stroke) flat_ellipse_internal(centerX, centerY, hradiusi, vradiusi, false); + } + } + } + + + /** + * Draw the outline around a flat circle using a bresenham-style + * algorithm. Adapted from drawCircle function in "Computer Graphics + * for Java Programmers" by Leen Ammeraal, p. 110. + *

+ * This function is included because the quality is so much better, + * and the drawing significantly faster than with adaptive ellipses + * drawn using the sine/cosine tables. + *

+ * Circle quadrants break down like so: + *

+   *              |
+   *        \ NNW | NNE /
+   *          \   |   /
+   *       WNW  \ | /  ENE
+   *     -------------------
+   *       WSW  / | \  ESE
+   *          /   |   \
+   *        / SSW | SSE \
+   *              |
+   * 
+ * @param xc x center + * @param yc y center + * @param r radius + */ + private void flat_circle_stroke(int xC, int yC, int r) { + int x = 0, y = r, u = 1, v = 2 * r - 1, E = 0; + while (x < y) { + thin_point(xC + x, yC + y, strokeColor); // NNE + thin_point(xC + y, yC - x, strokeColor); // ESE + thin_point(xC - x, yC - y, strokeColor); // SSW + thin_point(xC - y, yC + x, strokeColor); // WNW + + x++; E += u; u += 2; + if (v < 2 * E) { + y--; E -= v; v -= 2; + } + if (x > y) break; + + thin_point(xC + y, yC + x, strokeColor); // ENE + thin_point(xC + x, yC - y, strokeColor); // SSE + thin_point(xC - y, yC - x, strokeColor); // WSW + thin_point(xC - x, yC + y, strokeColor); // NNW + } + } + + + /** + * Heavily adapted version of the above algorithm that handles + * filling the ellipse. Works by drawing from the center and + * outwards to the points themselves. Has to be done this way + * because the values for the points are changed halfway through + * the function, making it impossible to just store a series of + * left and right edges to be drawn more quickly. + * + * @param xc x center + * @param yc y center + * @param r radius + */ + private void flat_circle_fill(int xc, int yc, int r) { + int x = 0, y = r, u = 1, v = 2 * r - 1, E = 0; + while (x < y) { + for (int xx = xc; xx < xc + x; xx++) { // NNE + thin_point(xx, yc + y, fillColor); + } + for (int xx = xc; xx < xc + y; xx++) { // ESE + thin_point(xx, yc - x, fillColor); + } + for (int xx = xc - x; xx < xc; xx++) { // SSW + thin_point(xx, yc - y, fillColor); + } + for (int xx = xc - y; xx < xc; xx++) { // WNW + thin_point(xx, yc + x, fillColor); + } + + x++; E += u; u += 2; + if (v < 2 * E) { + y--; E -= v; v -= 2; + } + if (x > y) break; + + for (int xx = xc; xx < xc + y; xx++) { // ENE + thin_point(xx, yc + x, fillColor); + } + for (int xx = xc; xx < xc + x; xx++) { // SSE + thin_point(xx, yc - y, fillColor); + } + for (int xx = xc - y; xx < xc; xx++) { // WSW + thin_point(xx, yc - x, fillColor); + } + for (int xx = xc - x; xx < xc; xx++) { // NNW + thin_point(xx, yc + y, fillColor); + } + } + } + + + // unfortunately this can't handle fill and stroke simultaneously, + // because the fill will later replace some of the stroke points + + private final void flat_ellipse_symmetry(int centerX, int centerY, + int ellipseX, int ellipseY, + boolean filling) { + if (filling) { + for (int i = centerX - ellipseX + 1; i < centerX + ellipseX; i++) { + thin_point(i, centerY - ellipseY, fillColor); + thin_point(i, centerY + ellipseY, fillColor); + } + } else { + thin_point(centerX - ellipseX, centerY + ellipseY, strokeColor); + thin_point(centerX + ellipseX, centerY + ellipseY, strokeColor); + thin_point(centerX - ellipseX, centerY - ellipseY, strokeColor); + thin_point(centerX + ellipseX, centerY - ellipseY, strokeColor); + } + } + + + /** + * Bresenham-style ellipse drawing function, adapted from a posting to + * comp.graphics.algortihms. + * + * This function is included because the quality is so much better, + * and the drawing significantly faster than with adaptive ellipses + * drawn using the sine/cosine tables. + * + * @param centerX x coordinate of the center + * @param centerY y coordinate of the center + * @param a horizontal radius + * @param b vertical radius + */ + private void flat_ellipse_internal(int centerX, int centerY, + int a, int b, boolean filling) { + int x, y, a2, b2, s, t; + + a2 = a*a; + b2 = b*b; + x = 0; + y = b; + s = a2*(1-2*b) + 2*b2; + t = b2 - 2*a2*(2*b-1); + flat_ellipse_symmetry(centerX, centerY, x, y, filling); + + do { + if (s < 0) { + s += 2*b2*(2*x+3); + t += 4*b2*(x+1); + x++; + } else if (t < 0) { + s += 2*b2*(2*x+3) - 4*a2*(y-1); + t += 4*b2*(x+1) - 2*a2*(2*y-3); + x++; + y--; + } else { + s -= 4*a2*(y-1); + t -= 2*a2*(2*y-3); + y--; + } + flat_ellipse_symmetry(centerX, centerY, x, y, filling); + + } while (y > 0); + } + + + // TODO really need a decent arc function in here.. + + protected void arcImpl(float x, float y, float w, float h, + float start, float stop) { + float hr = w / 2f; + float vr = h / 2f; + + float centerX = x + hr; + float centerY = y + vr; + + if (fill) { + // shut off stroke for a minute + boolean savedStroke = stroke; + stroke = false; + + int startLUT = (int) (-0.5f + (start / TWO_PI) * SINCOS_LENGTH); + int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH); + + beginShape(); + vertex(centerX, centerY); + for (int i = startLUT; i < stopLUT; i++) { + int ii = i % SINCOS_LENGTH; + // modulo won't make the value positive + if (ii < 0) ii += SINCOS_LENGTH; + vertex(centerX + cosLUT[ii] * hr, + centerY + sinLUT[ii] * vr); + } + endShape(CLOSE); + + stroke = savedStroke; + } + + if (stroke) { + // Almost identical to above, but this uses a LINE_STRIP + // and doesn't include the first (center) vertex. + + boolean savedFill = fill; + fill = false; + + int startLUT = (int) (0.5f + (start / TWO_PI) * SINCOS_LENGTH); + int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH); + + beginShape(); //LINE_STRIP); + int increment = 1; // what's a good algorithm? stopLUT - startLUT; + for (int i = startLUT; i < stopLUT; i += increment) { + int ii = i % SINCOS_LENGTH; + if (ii < 0) ii += SINCOS_LENGTH; + vertex(centerX + cosLUT[ii] * hr, + centerY + sinLUT[ii] * vr); + } + // draw last point explicitly for accuracy + vertex(centerX + cosLUT[stopLUT % SINCOS_LENGTH] * hr, + centerY + sinLUT[stopLUT % SINCOS_LENGTH] * vr); + endShape(); + + fill = savedFill; + } + } + + + + ////////////////////////////////////////////////////////////// + + // BOX + + + public void box(float size) { + showDepthWarning("box"); + } + + public void box(float w, float h, float d) { + showDepthWarning("box"); + } + + + + ////////////////////////////////////////////////////////////// + + // SPHERE + + + public void sphereDetail(int res) { + showDepthWarning("sphereDetail"); + } + + public void sphereDetail(int ures, int vres) { + showDepthWarning("sphereDetail"); + } + + public void sphere(float r) { + showDepthWarning("sphere"); + } + + + + ////////////////////////////////////////////////////////////// + + // BEZIER & CURVE + + + public void bezier(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + showDepthWarningXYZ("bezier"); + } + + + public void curve(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + showDepthWarningXYZ("curve"); + } + + + + ////////////////////////////////////////////////////////////// + + // IMAGE + + + protected void imageImpl(PImage image, + float x1, float y1, float x2, float y2, + int u1, int v1, int u2, int v2) { + if ((x2 - x1 == image.width) && + (y2 - y1 == image.height) && + !tint && !ctm.isWarped()) { + simple_image(image, (int) (x1 + ctm.m02), (int) (y1 + ctm.m12), u1, v1, u2, v2); + + } else { + super.imageImpl(image, x1, y1, x2, y2, u1, v1, u2, v2); + } + } + + + /** + * Image drawn in flat "screen space", with no scaling or warping. + * this is so common that a special routine is included for it, + * because the alternative is much slower. + * + * @param image image to be drawn + * @param sx1 x coordinate of upper-lefthand corner in screen space + * @param sy1 y coordinate of upper-lefthand corner in screen space + */ + private void simple_image(PImage image, int sx1, int sy1, + int ix1, int iy1, int ix2, int iy2) { + int sx2 = sx1 + image.width; + int sy2 = sy1 + image.height; + + // don't draw if completely offscreen + // (without this check, ArrayIndexOutOfBoundsException) + if ((sx1 > width1) || (sx2 < 0) || + (sy1 > height1) || (sy2 < 0)) return; + + if (sx1 < 0) { // off left edge + ix1 -= sx1; + sx1 = 0; + } + if (sy1 < 0) { // off top edge + iy1 -= sy1; + sy1 = 0; + } + if (sx2 > width) { // off right edge + ix2 -= sx2 - width; + sx2 = width; + } + if (sy2 > height) { // off bottom edge + iy2 -= sy2 - height; + sy2 = height; + } + + int source = iy1 * image.width + ix1; + int target = sy1 * width; + + if (image.format == ARGB) { + for (int y = sy1; y < sy2; y++) { + int tx = 0; + + for (int x = sx1; x < sx2; x++) { + pixels[target + x] = +// _blend(pixels[target + x], +// image.pixels[source + tx], +// image.pixels[source + tx++] >>> 24); + blend_color(pixels[target + x], + image.pixels[source + tx++]); + } + source += image.width; + target += width; + } + } else if (image.format == ALPHA) { + for (int y = sy1; y < sy2; y++) { + int tx = 0; + + for (int x = sx1; x < sx2; x++) { + pixels[target + x] = + blend_color_alpha(pixels[target + x], + fillColor, + image.pixels[source + tx++]); + } + source += image.width; + target += width; + } + + } else if (image.format == RGB) { + target += sx1; + int tw = sx2 - sx1; + for (int y = sy1; y < sy2; y++) { + System.arraycopy(image.pixels, source, pixels, target, tw); + // should set z coordinate in here + // or maybe not, since dims=0, meaning no relevant z + source += image.width; + target += width; + } + } + } + + + ////////////////////////////////////////////////////////////// + + // TEXT/FONTS + + + // These will be handled entirely by PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // UGLY RENDERING SHITE + + + // expects properly clipped coords, hence does + // NOT check if x/y are in bounds [toxi] + private void thin_point_at(int x, int y, float z, int color) { + int index = y*width+x; // offset values are pre-calced in constructor + pixels[index] = color; + } + + // expects offset/index in pixelbuffer array instead of x/y coords + // used by optimized parts of thin_flat_line() [toxi] + private void thin_point_at_index(int offset, float z, int color) { + pixels[offset] = color; + } + + + private void thick_point(float x, float y, float z, // note floats + float r, float g, float b, float a) { + spolygon.reset(4); + spolygon.interpARGB = false; // no changes for vertices of a point + + float strokeWidth2 = strokeWeight/2.0f; + + float svertex[] = spolygon.vertices[0]; + svertex[TX] = x - strokeWidth2; + svertex[TY] = y - strokeWidth2; + svertex[TZ] = z; + + svertex[R] = r; + svertex[G] = g; + svertex[B] = b; + svertex[A] = a; + + svertex = spolygon.vertices[1]; + svertex[TX] = x + strokeWidth2; + svertex[TY] = y - strokeWidth2; + svertex[TZ] = z; + + svertex = spolygon.vertices[2]; + svertex[TX] = x + strokeWidth2; + svertex[TY] = y + strokeWidth2; + svertex[TZ] = z; + + svertex = spolygon.vertices[3]; + svertex[TX] = x - strokeWidth2; + svertex[TY] = y + strokeWidth2; + svertex[TZ] = z; + + spolygon.render(); + } + + + // new bresenham clipping code, as old one was buggy [toxi] + private void thin_flat_line(int x1, int y1, int x2, int y2) { + int nx1,ny1,nx2,ny2; + + // get the "dips" for the points to clip + int code1 = thin_flat_line_clip_code(x1, y1); + int code2 = thin_flat_line_clip_code(x2, y2); + + if ((code1 & code2)!=0) { + return; + } else { + int dip = code1 | code2; + if (dip != 0) { + // now calculate the clipped points + float a1 = 0, a2 = 1, a = 0; + for (int i=0;i<4;i++) { + if (((dip>>i)%2)==1) { + a = thin_flat_line_slope((float)x1, (float)y1, + (float)x2, (float)y2, i+1); + if (((code1>>i)%2)==1) { + a1 = (float)Math.max(a, a1); + } else { + a2 = (float)Math.min(a, a2); + } + } + } + if (a1>a2) return; + else { + nx1=(int) (x1+a1*(x2-x1)); + ny1=(int) (y1+a1*(y2-y1)); + nx2=(int) (x1+a2*(x2-x1)); + ny2=(int) (y1+a2*(y2-y1)); + } + // line is fully visible/unclipped + } else { + nx1=x1; nx2=x2; + ny1=y1; ny2=y2; + } + } + + // new "extremely fast" line code + // adapted from http://www.edepot.com/linee.html + + boolean yLonger=false; + int shortLen=ny2-ny1; + int longLen=nx2-nx1; + if (Math.abs(shortLen)>Math.abs(longLen)) { + int swap=shortLen; + shortLen=longLen; + longLen=swap; + yLonger=true; + } + int decInc; + if (longLen==0) decInc=0; + else decInc = (shortLen << 16) / longLen; + + if (nx1==nx2) { + // special case: vertical line + if (ny1>ny2) { int ty=ny1; ny1=ny2; ny2=ty; } + int offset=ny1*width+nx1; + for(int j=ny1; j<=ny2; j++) { + thin_point_at_index(offset,0,strokeColor); + offset+=width; + } + return; + } else if (ny1==ny2) { + // special case: horizontal line + if (nx1>nx2) { int tx=nx1; nx1=nx2; nx2=tx; } + int offset=ny1*width+nx1; + for(int j=nx1; j<=nx2; j++) thin_point_at_index(offset++,0,strokeColor); + return; + } else if (yLonger) { + if (longLen>0) { + longLen+=ny1; + for (int j=0x8000+(nx1<<16);ny1<=longLen;++ny1) { + thin_point_at(j>>16, ny1, 0, strokeColor); + j+=decInc; + } + return; + } + longLen+=ny1; + for (int j=0x8000+(nx1<<16);ny1>=longLen;--ny1) { + thin_point_at(j>>16, ny1, 0, strokeColor); + j-=decInc; + } + return; + } else if (longLen>0) { + longLen+=nx1; + for (int j=0x8000+(ny1<<16);nx1<=longLen;++nx1) { + thin_point_at(nx1, j>>16, 0, strokeColor); + j+=decInc; + } + return; + } + longLen+=nx1; + for (int j=0x8000+(ny1<<16);nx1>=longLen;--nx1) { + thin_point_at(nx1, j>>16, 0, strokeColor); + j-=decInc; + } + } + + + private int thin_flat_line_clip_code(float x, float y) { + return ((y < 0 ? 8 : 0) | (y > height1 ? 4 : 0) | + (x < 0 ? 2 : 0) | (x > width1 ? 1 : 0)); + } + + + private float thin_flat_line_slope(float x1, float y1, + float x2, float y2, int border) { + switch (border) { + case 4: { + return (-y1)/(y2-y1); + } + case 3: { + return (height1-y1)/(y2-y1); + } + case 2: { + return (-x1)/(x2-x1); + } + case 1: { + return (width1-x1)/(x2-x1); + } + } + return -1f; + } + + + private void thick_flat_line(float ox1, float oy1, + float r1, float g1, float b1, float a1, + float ox2, float oy2, + float r2, float g2, float b2, float a2) { + spolygon.interpARGB = (r1 != r2) || (g1 != g2) || (b1 != b2) || (a1 != a2); +// spolygon.interpZ = false; + + float dX = ox2-ox1 + EPSILON; + float dY = oy2-oy1 + EPSILON; + float len = (float) Math.sqrt(dX*dX + dY*dY); + + // TODO stroke width should be transformed! + float rh = (strokeWeight / len) / 2; + + float dx0 = rh * dY; + float dy0 = rh * dX; + float dx1 = rh * dY; + float dy1 = rh * dX; + + spolygon.reset(4); + + float svertex[] = spolygon.vertices[0]; + svertex[TX] = ox1+dx0; + svertex[TY] = oy1-dy0; + svertex[R] = r1; + svertex[G] = g1; + svertex[B] = b1; + svertex[A] = a1; + + svertex = spolygon.vertices[1]; + svertex[TX] = ox1-dx0; + svertex[TY] = oy1+dy0; + svertex[R] = r1; + svertex[G] = g1; + svertex[B] = b1; + svertex[A] = a1; + + svertex = spolygon.vertices[2]; + svertex[TX] = ox2-dx1; + svertex[TY] = oy2+dy1; + svertex[R] = r2; + svertex[G] = g2; + svertex[B] = b2; + svertex[A] = a2; + + svertex = spolygon.vertices[3]; + svertex[TX] = ox2+dx1; + svertex[TY] = oy2-dy1; + svertex[R] = r2; + svertex[G] = g2; + svertex[B] = b2; + svertex[A] = a2; + + spolygon.render(); + } + + + private void draw_line(float[] v1, float[] v2) { + if (strokeWeight == 1) { + if (line == null) line = new PLine(this); + + line.reset(); + line.setIntensities(v1[SR], v1[SG], v1[SB], v1[SA], + v2[SR], v2[SG], v2[SB], v2[SA]); + line.setVertices(v1[TX], v1[TY], v1[TZ], + v2[TX], v2[TY], v2[TZ]); + line.draw(); + + } else { // use old line code for thickness != 1 + thick_flat_line(v1[TX], v1[TY], v1[SR], v1[SG], v1[SB], v1[SA], + v2[TX], v2[TY], v2[SR], v2[SG], v2[SB], v2[SA]); + } + } + + + /** + * @param max is what to count to + * @param offset is offset to the 'next' vertex + * @param increment is how much to increment in the loop + */ + private void draw_lines(float vertices[][], int max, + int offset, int increment, int skip) { + + if (strokeWeight == 1) { + for (int i = 0; i < max; i += increment) { + if ((skip != 0) && (((i+offset) % skip) == 0)) continue; + + float a[] = vertices[i]; + float b[] = vertices[i+offset]; + + if (line == null) line = new PLine(this); + + line.reset(); + line.setIntensities(a[SR], a[SG], a[SB], a[SA], + b[SR], b[SG], b[SB], b[SA]); + line.setVertices(a[TX], a[TY], a[TZ], + b[TX], b[TY], b[TZ]); + line.draw(); + } + + } else { // use old line code for thickness != 1 + for (int i = 0; i < max; i += increment) { + if ((skip != 0) && (((i+offset) % skip) == 0)) continue; + + float v1[] = vertices[i]; + float v2[] = vertices[i+offset]; + thick_flat_line(v1[TX], v1[TY], v1[SR], v1[SG], v1[SB], v1[SA], + v2[TX], v2[TY], v2[SR], v2[SG], v2[SB], v2[SA]); + } + } + } + + + private void thin_point(float fx, float fy, int color) { + int x = (int) (fx + 0.4999f); + int y = (int) (fy + 0.4999f); + if (x < 0 || x > width1 || y < 0 || y > height1) return; + + int index = y*width + x; + if ((color & 0xff000000) == 0xff000000) { // opaque + pixels[index] = color; + + } else { // transparent + // a1 is how much of the orig pixel + int a2 = (color >> 24) & 0xff; + int a1 = a2 ^ 0xff; + + int p2 = strokeColor; + int p1 = pixels[index]; + + int r = (a1 * ((p1 >> 16) & 0xff) + a2 * ((p2 >> 16) & 0xff)) & 0xff00; + int g = (a1 * ((p1 >> 8) & 0xff) + a2 * ((p2 >> 8) & 0xff)) & 0xff00; + int b = (a1 * ( p1 & 0xff) + a2 * ( p2 & 0xff)) >> 8; + + pixels[index] = 0xff000000 | (r << 8) | g | b; + } + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX TRANSFORMATIONS + + + public void translate(float tx, float ty) { + ctm.translate(tx, ty); + } + + + public void translate(float tx, float ty, float tz) { + showDepthWarningXYZ("translate"); + } + + + public void rotate(float angle) { + ctm.rotate(angle); +// float c = (float) Math.cos(angle); +// float s = (float) Math.sin(angle); +// applyMatrix(c, -s, 0, s, c, 0); + } + + + public void rotateX(float angle) { + showDepthWarning("rotateX"); + } + + public void rotateY(float angle) { + showDepthWarning("rotateY"); + } + + + public void rotateZ(float angle) { + showDepthWarning("rotateZ"); + } + + + public void rotate(float angle, float vx, float vy, float vz) { + showVariationWarning("rotate(angle, x, y, z)"); + } + + + public void scale(float s) { + ctm.scale(s); +// applyMatrix(s, 0, 0, +// 0, s, 0); + } + + + public void scale(float sx, float sy) { + ctm.scale(sx, sy); +// applyMatrix(sx, 0, 0, +// 0, sy, 0); + } + + + public void scale(float x, float y, float z) { + showDepthWarningXYZ("scale"); + } + + + + ////////////////////////////////////////////////////////////// + + // TRANSFORMATION MATRIX + + + public void pushMatrix() { + if (matrixStackDepth == MATRIX_STACK_DEPTH) { + throw new RuntimeException(ERROR_PUSHMATRIX_OVERFLOW); + } + ctm.get(matrixStack[matrixStackDepth]); + matrixStackDepth++; + } + + + public void popMatrix() { + if (matrixStackDepth == 0) { + throw new RuntimeException(ERROR_PUSHMATRIX_UNDERFLOW); + } + matrixStackDepth--; + ctm.set(matrixStack[matrixStackDepth]); + } + + + /** + * Load identity as the transform/model matrix. + * Same as glLoadIdentity(). + */ + public void resetMatrix() { + ctm.reset(); +// m00 = 1; m01 = 0; m02 = 0; +// m10 = 0; m11 = 1; m12 = 0; + } + + + /** + * Apply a 3x2 affine transformation matrix. + */ + public void applyMatrix(float n00, float n01, float n02, + float n10, float n11, float n12) { + ctm.apply(n00, n01, n02, + n10, n11, n12); +// +// float r00 = m00*n00 + m01*n10; +// float r01 = m00*n01 + m01*n11; +// float r02 = m00*n02 + m01*n12 + m02; +// +// float r10 = m10*n00 + m11*n10; +// float r11 = m10*n01 + m11*n11; +// float r12 = m10*n02 + m11*n12 + m12; +// +// m00 = r00; m01 = r01; m02 = r02; +// m10 = r10; m11 = r11; m12 = r12; + } + + + public void applyMatrix(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + showDepthWarningXYZ("applyMatrix"); + } + + + /** + * Loads the current matrix into m00, m01 etc (or modelview and + * projection when using 3D) so that the values can be read. + *

+ * Note that there is no "updateMatrix" because that gets too + * complicated (unnecessary) when considering the 3D matrices. + */ +// public void loadMatrix() { + // no-op on base PGraphics because they're used directly +// } + + + /** + * Print the current model (or "transformation") matrix. + */ + public void printMatrix() { + ctm.print(); + +// loadMatrix(); // just to make sure +// +// float big = Math.abs(m00); +// if (Math.abs(m01) > big) big = Math.abs(m01); +// if (Math.abs(m02) > big) big = Math.abs(m02); +// if (Math.abs(m10) > big) big = Math.abs(m10); +// if (Math.abs(m11) > big) big = Math.abs(m11); +// if (Math.abs(m12) > big) big = Math.abs(m12); +// +// // avoid infinite loop +// if (Float.isNaN(big) || Float.isInfinite(big)) { +// big = 1000000; // set to something arbitrary +// } +// +// int d = 1; +// int bigi = (int) big; +// while ((bigi /= 10) != 0) d++; // cheap log() +// +// System.out.println(PApplet.nfs(m00, d, 4) + " " + +// PApplet.nfs(m01, d, 4) + " " + +// PApplet.nfs(m02, d, 4)); +// +// System.out.println(PApplet.nfs(m10, d, 4) + " " + +// PApplet.nfs(m11, d, 4) + " " + +// PApplet.nfs(m12, d, 4)); +// +// System.out.println(); + } + + + + ////////////////////////////////////////////////////////////// + + // SCREEN TRANSFORMS + + + public float screenX(float x, float y) { + return ctm.m00 * x + ctm.m01 * y + ctm.m02; + } + + + public float screenY(float x, float y) { + return ctm.m10 * x + ctm.m11 * y + ctm.m12; + } + + + + ////////////////////////////////////////////////////////////// + + // BACKGROUND AND FRIENDS + + + /** + * Clear the pixel buffer. + */ + protected void backgroundImpl() { + Arrays.fill(pixels, backgroundColor); + } + + + + /* + public void ambient(int rgb) { + showDepthError("ambient"); + } + + public void ambient(float gray) { + showDepthError("ambient"); + } + + public void ambient(float x, float y, float z) { + // This doesn't take + if ((x != PMaterial.DEFAULT_AMBIENT) || + (y != PMaterial.DEFAULT_AMBIENT) || + (z != PMaterial.DEFAULT_AMBIENT)) { + showDepthError("ambient"); + } + } + + public void specular(int rgb) { + showDepthError("specular"); + } + + public void specular(float gray) { + showDepthError("specular"); + } + + public void specular(float x, float y, float z) { + showDepthError("specular"); + } + + public void shininess(float shine) { + showDepthError("shininess"); + } + + + public void emissive(int rgb) { + showDepthError("emissive"); + } + + public void emissive(float gray) { + showDepthError("emissive"); + } + + public void emissive(float x, float y, float z ) { + showDepthError("emissive"); + } + */ + + + + ////////////////////////////////////////////////////////////// + + // INTERNAL SCHIZZLE + + + // TODO make this more efficient, or move into PMatrix2D +// private boolean untransformed() { +// return ((ctm.m00 == 1) && (ctm.m01 == 0) && (ctm.m02 == 0) && +// (ctm.m10 == 0) && (ctm.m11 == 1) && (ctm.m12 == 0)); +// } +// +// +// // TODO make this more efficient, or move into PMatrix2D +// private boolean unwarped() { +// return ((ctm.m00 == 1) && (ctm.m01 == 0) && +// (ctm.m10 == 0) && (ctm.m11 == 1)); +// } + + + // only call this if there's an alpha in the fill + private final int blend_fill(int p1) { + int a2 = fillAi; + int a1 = a2 ^ 0xff; + + int r = (a1 * ((p1 >> 16) & 0xff)) + (a2 * fillRi) & 0xff00; + int g = (a1 * ((p1 >> 8) & 0xff)) + (a2 * fillGi) & 0xff00; + int b = (a1 * ( p1 & 0xff)) + (a2 * fillBi) & 0xff00; + + return 0xff000000 | (r << 8) | g | (b >> 8); + } + + + private final int blend_color(int p1, int p2) { + int a2 = (p2 >>> 24); + + if (a2 == 0xff) { + // full replacement + return p2; + + } else { + int a1 = a2 ^ 0xff; + int r = (a1 * ((p1 >> 16) & 0xff) + a2 * ((p2 >> 16) & 0xff)) & 0xff00; + int g = (a1 * ((p1 >> 8) & 0xff) + a2 * ((p2 >> 8) & 0xff)) & 0xff00; + int b = (a1 * ( p1 & 0xff) + a2 * ( p2 & 0xff)) >> 8; + + return 0xff000000 | (r << 8) | g | b; + } + } + + + private final int blend_color_alpha(int p1, int p2, int a2) { + // scale alpha by alpha of incoming pixel + a2 = (a2 * (p2 >>> 24)) >> 8; + + int a1 = a2 ^ 0xff; + int r = (a1 * ((p1 >> 16) & 0xff) + a2 * ((p2 >> 16) & 0xff)) & 0xff00; + int g = (a1 * ((p1 >> 8) & 0xff) + a2 * ((p2 >> 8) & 0xff)) & 0xff00; + int b = (a1 * ( p1 & 0xff) + a2 * ( p2 & 0xff)) >> 8; + + return 0xff000000 | (r << 8) | g | b; + } +} diff --git a/support/Processing_core_src/processing/core/PGraphics3D.java b/support/Processing_core_src/processing/core/PGraphics3D.java new file mode 100644 index 0000000..d515e1e --- /dev/null +++ b/support/Processing_core_src/processing/core/PGraphics3D.java @@ -0,0 +1,4397 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-08 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.Toolkit; +import java.awt.image.*; +import java.util.*; + + +/** + * Subclass of PGraphics that handles 3D rendering. + * It can render 3D inside a browser window and requires no plug-ins. + *

+ * The renderer is mostly set up based on the structure of the OpenGL API, + * if you have questions about specifics that aren't covered here, + * look for reference on the OpenGL implementation of a similar feature. + *

+ * Lighting and camera implementation by Simon Greenwold. + */ +public class PGraphics3D extends PGraphics { + + /** The depth buffer. */ + public float[] zbuffer; + + // ........................................................ + + /** The modelview matrix. */ + public PMatrix3D modelview; + + /** Inverse modelview matrix, used for lighting. */ + public PMatrix3D modelviewInv; + + /** + * Marks when changes to the size have occurred, so that the camera + * will be reset in beginDraw(). + */ + protected boolean sizeChanged; + + /** The camera matrix, the modelview will be set to this on beginDraw. */ + public PMatrix3D camera; + + /** Inverse camera matrix */ + protected PMatrix3D cameraInv; + + /** Camera field of view. */ + public float cameraFOV; + + /** Position of the camera. */ + public float cameraX, cameraY, cameraZ; + public float cameraNear, cameraFar; + /** Aspect ratio of camera's view. */ + public float cameraAspect; + + /** Current projection matrix. */ + public PMatrix3D projection; + + + ////////////////////////////////////////////////////////////// + + + /** + * Maximum lights by default is 8, which is arbitrary for this renderer, + * but is the minimum defined by OpenGL + */ + public static final int MAX_LIGHTS = 8; + + public int lightCount = 0; + + /** Light types */ + public int[] lightType; + + /** Light positions */ + //public float[][] lightPosition; + public PVector[] lightPosition; + + /** Light direction (normalized vector) */ + //public float[][] lightNormal; + public PVector[] lightNormal; + + /** Light falloff */ + public float[] lightFalloffConstant; + public float[] lightFalloffLinear; + public float[] lightFalloffQuadratic; + + /** Light spot angle */ + public float[] lightSpotAngle; + + /** Cosine of light spot angle */ + public float[] lightSpotAngleCos; + + /** Light spot concentration */ + public float[] lightSpotConcentration; + + /** Diffuse colors for lights. + * For an ambient light, this will hold the ambient color. + * Internally these are stored as numbers between 0 and 1. */ + public float[][] lightDiffuse; + + /** Specular colors for lights. + Internally these are stored as numbers between 0 and 1. */ + public float[][] lightSpecular; + + /** Current specular color for lighting */ + public float[] currentLightSpecular; + + /** Current light falloff */ + public float currentLightFalloffConstant; + public float currentLightFalloffLinear; + public float currentLightFalloffQuadratic; + + + ////////////////////////////////////////////////////////////// + + + static public final int TRI_DIFFUSE_R = 0; + static public final int TRI_DIFFUSE_G = 1; + static public final int TRI_DIFFUSE_B = 2; + static public final int TRI_DIFFUSE_A = 3; + static public final int TRI_SPECULAR_R = 4; + static public final int TRI_SPECULAR_G = 5; + static public final int TRI_SPECULAR_B = 6; + static public final int TRI_COLOR_COUNT = 7; + + // ........................................................ + + // Whether or not we have to worry about vertex position for lighting calcs + private boolean lightingDependsOnVertexPosition; + + static final int LIGHT_AMBIENT_R = 0; + static final int LIGHT_AMBIENT_G = 1; + static final int LIGHT_AMBIENT_B = 2; + static final int LIGHT_DIFFUSE_R = 3; + static final int LIGHT_DIFFUSE_G = 4; + static final int LIGHT_DIFFUSE_B = 5; + static final int LIGHT_SPECULAR_R = 6; + static final int LIGHT_SPECULAR_G = 7; + static final int LIGHT_SPECULAR_B = 8; + static final int LIGHT_COLOR_COUNT = 9; + + // Used to shuttle lighting calcs around + // (no need to re-allocate all the time) + protected float[] tempLightingContribution = new float[LIGHT_COLOR_COUNT]; +// protected float[] worldNormal = new float[4]; + + /// Used in lightTriangle(). Allocated here once to avoid re-allocating + protected PVector lightTriangleNorm = new PVector(); + + // ........................................................ + + /** + * This is turned on at beginCamera, and off at endCamera + * Currently we don't support nested begin/end cameras. + * If we wanted to, this variable would have to become a stack. + */ + protected boolean manipulatingCamera; + + float[][] matrixStack = new float[MATRIX_STACK_DEPTH][16]; + float[][] matrixInvStack = new float[MATRIX_STACK_DEPTH][16]; + int matrixStackDepth; + + // These two matrices always point to either the modelview + // or the modelviewInv, but they are swapped during + // when in camera manipulation mode. That way camera transforms + // are automatically accumulated in inverse on the modelview matrix. + protected PMatrix3D forwardTransform; + protected PMatrix3D reverseTransform; + + // Added by ewjordan for accurate texturing purposes. Screen plane is + // not scaled to pixel-size, so these manually keep track of its size + // from frustum() calls. Sorry to add public vars, is there a way + // to compute these from something publicly available without matrix ops? + // (used once per triangle in PTriangle with ENABLE_ACCURATE_TEXTURES) + protected float leftScreen; + protected float rightScreen; + protected float topScreen; + protected float bottomScreen; + protected float nearPlane; //depth of near clipping plane + + /** true if frustum has been called to set perspective, false if ortho */ + private boolean frustumMode = false; + + /** + * Use PSmoothTriangle for rendering instead of PTriangle? + * Usually set by calling smooth() or noSmooth() + */ + static protected boolean s_enableAccurateTextures = false; //maybe just use smooth instead? + + /** Used for anti-aliased and perspective corrected rendering. */ + public PSmoothTriangle smoothTriangle; + + + // ........................................................ + + // pos of first vertex of current shape in vertices array + protected int shapeFirst; + + // i think vertex_end is actually the last vertex in the current shape + // and is separate from vertexCount for occasions where drawing happens + // on endDraw() with all the triangles being depth sorted + protected int shapeLast; + + // vertices may be added during clipping against the near plane. + protected int shapeLastPlusClipped; + + // used for sorting points when triangulating a polygon + // warning - maximum number of vertices for a polygon is DEFAULT_VERTICES + protected int vertexOrder[] = new int[DEFAULT_VERTICES]; + + // ........................................................ + + // This is done to keep track of start/stop information for lines in the + // line array, so that lines can be shown as a single path, rather than just + // individual segments. Currently only in use inside PGraphicsOpenGL. + protected int pathCount; + protected int[] pathOffset = new int[64]; + protected int[] pathLength = new int[64]; + + // ........................................................ + + // line & triangle fields (note that these overlap) +// static protected final int INDEX = 0; // shape index + static protected final int VERTEX1 = 0; + static protected final int VERTEX2 = 1; + static protected final int VERTEX3 = 2; // (triangles only) + /** used to store the strokeColor int for efficient drawing. */ + static protected final int STROKE_COLOR = 1; // (points only) + static protected final int TEXTURE_INDEX = 3; // (triangles only) + //static protected final int STROKE_MODE = 2; // (lines only) + //static protected final int STROKE_WEIGHT = 3; // (lines only) + + static protected final int POINT_FIELD_COUNT = 2; //4 + static protected final int LINE_FIELD_COUNT = 2; //4 + static protected final int TRIANGLE_FIELD_COUNT = 4; + + // points + static final int DEFAULT_POINTS = 512; + protected int[][] points = new int[DEFAULT_POINTS][POINT_FIELD_COUNT]; + protected int pointCount; + + // lines + static final int DEFAULT_LINES = 512; + public PLine line; // used for drawing + protected int[][] lines = new int[DEFAULT_LINES][LINE_FIELD_COUNT]; + protected int lineCount; + + // triangles + static final int DEFAULT_TRIANGLES = 256; + public PTriangle triangle; + protected int[][] triangles = + new int[DEFAULT_TRIANGLES][TRIANGLE_FIELD_COUNT]; + protected float triangleColors[][][] = + new float[DEFAULT_TRIANGLES][3][TRI_COLOR_COUNT]; + protected int triangleCount; // total number of triangles + + // cheap picking someday + //public int shape_index; + + // ........................................................ + + static final int DEFAULT_TEXTURES = 3; + protected PImage[] textures = new PImage[DEFAULT_TEXTURES]; + int textureIndex; + + // ........................................................ + + DirectColorModel cm; + MemoryImageSource mis; + + + ////////////////////////////////////////////////////////////// + + + public PGraphics3D() { } + + + //public void setParent(PApplet parent) + + + //public void setPrimary(boolean primary) + + + //public void setPath(String path) + + + /** + * Called in response to a resize event, handles setting the + * new width and height internally, as well as re-allocating + * the pixel buffer for the new size. + * + * Note that this will nuke any cameraMode() settings. + * + * No drawing can happen in this function, and no talking to the graphics + * context. That is, no glXxxx() calls, or other things that change state. + */ + public void setSize(int iwidth, int iheight) { // ignore + width = iwidth; + height = iheight; + width1 = width - 1; + height1 = height - 1; + + allocate(); + reapplySettings(); + + // init lights (in resize() instead of allocate() b/c needed by opengl) + lightType = new int[MAX_LIGHTS]; + lightPosition = new PVector[MAX_LIGHTS]; + lightNormal = new PVector[MAX_LIGHTS]; + for (int i = 0; i < MAX_LIGHTS; i++) { + lightPosition[i] = new PVector(); + lightNormal[i] = new PVector(); + } + lightDiffuse = new float[MAX_LIGHTS][3]; + lightSpecular = new float[MAX_LIGHTS][3]; + lightFalloffConstant = new float[MAX_LIGHTS]; + lightFalloffLinear = new float[MAX_LIGHTS]; + lightFalloffQuadratic = new float[MAX_LIGHTS]; + lightSpotAngle = new float[MAX_LIGHTS]; + lightSpotAngleCos = new float[MAX_LIGHTS]; + lightSpotConcentration = new float[MAX_LIGHTS]; + currentLightSpecular = new float[3]; + + projection = new PMatrix3D(); + modelview = new PMatrix3D(); + modelviewInv = new PMatrix3D(); + +// modelviewStack = new float[MATRIX_STACK_DEPTH][16]; +// modelviewInvStack = new float[MATRIX_STACK_DEPTH][16]; +// modelviewStackPointer = 0; + + forwardTransform = modelview; + reverseTransform = modelviewInv; + + // init perspective projection based on new dimensions + cameraFOV = 60 * DEG_TO_RAD; // at least for now + cameraX = width / 2.0f; + cameraY = height / 2.0f; + cameraZ = cameraY / ((float) Math.tan(cameraFOV / 2.0f)); + cameraNear = cameraZ / 10.0f; + cameraFar = cameraZ * 10.0f; + cameraAspect = (float)width / (float)height; + + camera = new PMatrix3D(); + cameraInv = new PMatrix3D(); + + // set this flag so that beginDraw() will do an update to the camera. + sizeChanged = true; + } + + + protected void allocate() { + //System.out.println(this + " allocating for " + width + " " + height); + //new Exception().printStackTrace(); + + pixelCount = width * height; + pixels = new int[pixelCount]; + zbuffer = new float[pixelCount]; + + if (primarySurface) { + cm = new DirectColorModel(32, 0x00ff0000, 0x0000ff00, 0x000000ff);; + mis = new MemoryImageSource(width, height, pixels, 0, width); + mis.setFullBufferUpdates(true); + mis.setAnimated(true); + image = Toolkit.getDefaultToolkit().createImage(mis); + + } else { + // when not the main drawing surface, need to set the zbuffer, + // because there's a possibility that background() will not be called + Arrays.fill(zbuffer, Float.MAX_VALUE); + } + + line = new PLine(this); + triangle = new PTriangle(this); + smoothTriangle = new PSmoothTriangle(this); + } + + + //public void dispose() + + + //////////////////////////////////////////////////////////// + + + //public boolean canDraw() + + + public void beginDraw() { + // need to call defaults(), but can only be done when it's ok + // to draw (i.e. for opengl, no drawing can be done outside + // beginDraw/endDraw). + if (!settingsInited) defaultSettings(); + + if (sizeChanged) { + // set up the default camera + camera(); + + // defaults to perspective, if the user has setup up their + // own projection, they'll need to fix it after resize anyway. + // this helps the people who haven't set up their own projection. + perspective(); + + // clear the flag + sizeChanged = false; + } + + resetMatrix(); // reset model matrix + + // reset vertices + vertexCount = 0; + + modelview.set(camera); + modelviewInv.set(cameraInv); + + // clear out the lights, they'll have to be turned on again + lightCount = 0; + lightingDependsOnVertexPosition = false; + lightFalloff(1, 0, 0); + lightSpecular(0, 0, 0); + + /* + // reset lines + lineCount = 0; + if (line != null) line.reset(); // is this necessary? + pathCount = 0; + + // reset triangles + triangleCount = 0; + if (triangle != null) triangle.reset(); // necessary? + */ + + shapeFirst = 0; + + // reset textures + Arrays.fill(textures, null); + textureIndex = 0; + + normal(0, 0, 1); + } + + + /** + * See notes in PGraphics. + * If z-sorting has been turned on, then the triangles will + * all be quicksorted here (to make alpha work more properly) + * and then blit to the screen. + */ + public void endDraw() { + // no need to z order and render + // shapes were already rendered in endShape(); + // (but can't return, since needs to update memimgsrc) + if (hints[ENABLE_DEPTH_SORT]) { + flush(); + } + if (mis != null) { + mis.newPixels(pixels, cm, 0, width); + } + // mark pixels as having been updated, so that they'll work properly + // when this PGraphics is drawn using image(). + updatePixels(); + } + + + //////////////////////////////////////////////////////////// + + + //protected void checkSettings() + + + protected void defaultSettings() { + super.defaultSettings(); + + manipulatingCamera = false; + forwardTransform = modelview; + reverseTransform = modelviewInv; + + // set up the default camera + camera(); + + // defaults to perspective, if the user has setup up their + // own projection, they'll need to fix it after resize anyway. + // this helps the people who haven't set up their own projection. + perspective(); + + // easiest for beginners + textureMode(IMAGE); + + emissive(0.0f); + specular(0.5f); + shininess(1.0f); + } + + + //protected void reapplySettings() + + + //////////////////////////////////////////////////////////// + + + public void hint(int which) { + if (which == DISABLE_DEPTH_SORT) { + flush(); + } else if (which == DISABLE_DEPTH_TEST) { + if (zbuffer != null) { // will be null in OpenGL and others + Arrays.fill(zbuffer, Float.MAX_VALUE); + } + } + super.hint(which); + } + + + ////////////////////////////////////////////////////////////// + + + //public void beginShape() + + + public void beginShape(int kind) { + shape = kind; + +// shape_index = shape_index + 1; +// if (shape_index == -1) { +// shape_index = 0; +// } + + if (hints[ENABLE_DEPTH_SORT]) { + // continue with previous vertex, line and triangle count + // all shapes are rendered at endDraw(); + shapeFirst = vertexCount; + shapeLast = 0; + + } else { + // reset vertex, line and triangle information + // every shape is rendered at endShape(); + vertexCount = 0; + if (line != null) line.reset(); // necessary? + lineCount = 0; +// pathCount = 0; + if (triangle != null) triangle.reset(); // necessary? + triangleCount = 0; + } + + textureImage = null; + curveVertexCount = 0; + normalMode = NORMAL_MODE_AUTO; +// normalCount = 0; + } + + + //public void normal(float nx, float ny, float nz) + + + //public void textureMode(int mode) + + + public void texture(PImage image) { + textureImage = image; + + if (textureIndex == textures.length - 1) { + textures = (PImage[]) PApplet.expand(textures); + } + if (textures[textureIndex] != null) { // ??? + textureIndex++; + } + textures[textureIndex] = image; + } + + + public void vertex(float x, float y) { + // override so that the default 3D implementation will be used, + // which will pick up all 3D settings (e.g. emissive, ambient) + vertex(x, y, 0); + } + + + //public void vertex(float x, float y, float z) + + + public void vertex(float x, float y, float u, float v) { + // see vertex(x, y) for note + vertex(x, y, 0, u, v); + } + + + //public void vertex(float x, float y, float z, float u, float v) + + + //public void breakShape() + + + //public void endShape() + + + public void endShape(int mode) { + shapeLast = vertexCount; + shapeLastPlusClipped = shapeLast; + + // don't try to draw if there are no vertices + // (fixes a bug in LINE_LOOP that re-adds a nonexistent vertex) + if (vertexCount == 0) { + shape = 0; + return; + } + + // convert points from model (X/Y/Z) to camera space (VX/VY/VZ). + // Do this now because we will be clipping them on add_triangle. + endShapeModelToCamera(shapeFirst, shapeLast); + + if (stroke) { + endShapeStroke(mode); + } + + if (fill || textureImage != null) { + endShapeFill(); + } + + // transform, light, and clip + endShapeLighting(lightCount > 0 && fill); + + // convert points from camera space (VX, VY, VZ) to screen space (X, Y, Z) + // (this appears to be wasted time with the OpenGL renderer) + endShapeCameraToScreen(shapeFirst, shapeLastPlusClipped); + + // render shape and fill here if not saving the shapes for later + // if true, the shapes will be rendered on endDraw + if (!hints[ENABLE_DEPTH_SORT]) { + if (fill || textureImage != null) { + if (triangleCount > 0) { + renderTriangles(0, triangleCount); + if (raw != null) { + rawTriangles(0, triangleCount); + } + triangleCount = 0; + } + } + if (stroke) { + if (pointCount > 0) { + renderPoints(0, pointCount); + if (raw != null) { + rawPoints(0, pointCount); + } + pointCount = 0; + } + + if (lineCount > 0) { + renderLines(0, lineCount); + if (raw != null) { + rawLines(0, lineCount); + } + lineCount = 0; + } + } + pathCount = 0; + } + + shape = 0; + } + + + protected void endShapeModelToCamera(int start, int stop) { + for (int i = start; i < stop; i++) { + float vertex[] = vertices[i]; + + vertex[VX] = + modelview.m00*vertex[X] + modelview.m01*vertex[Y] + + modelview.m02*vertex[Z] + modelview.m03; + vertex[VY] = + modelview.m10*vertex[X] + modelview.m11*vertex[Y] + + modelview.m12*vertex[Z] + modelview.m13; + vertex[VZ] = + modelview.m20*vertex[X] + modelview.m21*vertex[Y] + + modelview.m22*vertex[Z] + modelview.m23; + vertex[VW] = + modelview.m30*vertex[X] + modelview.m31*vertex[Y] + + modelview.m32*vertex[Z] + modelview.m33; + + // normalize + if (vertex[VW] != 0 && vertex[VW] != 1) { + vertex[VX] /= vertex[VW]; + vertex[VY] /= vertex[VW]; + vertex[VZ] /= vertex[VW]; + } + vertex[VW] = 1; + } + } + + + protected void endShapeStroke(int mode) { + switch (shape) { + case POINTS: + { + int stop = shapeLast; + for (int i = shapeFirst; i < stop; i++) { +// if (strokeWeight == 1) { + addPoint(i); +// } else { +// addLineBreak(); // total overkill for points +// addLine(i, i); +// } + } + } + break; + + case LINES: + { + // store index of first vertex + int first = lineCount; + int stop = shapeLast - 1; + //increment = (shape == LINES) ? 2 : 1; + + // for LINE_STRIP and LINE_LOOP, make this all one path + if (shape != LINES) addLineBreak(); + + for (int i = shapeFirst; i < stop; i += 2) { + // for LINES, make a new path for each segment + if (shape == LINES) addLineBreak(); + addLine(i, i+1); + } + + // for LINE_LOOP, close the loop with a final segment + //if (shape == LINE_LOOP) { + if (mode == CLOSE) { + addLine(stop, lines[first][VERTEX1]); + } + } + break; + + case TRIANGLES: + { + for (int i = shapeFirst; i < shapeLast-2; i += 3) { + addLineBreak(); + //counter = i - vertex_start; + addLine(i+0, i+1); + addLine(i+1, i+2); + addLine(i+2, i+0); + } + } + break; + + case TRIANGLE_STRIP: + { + // first draw all vertices as a line strip + int stop = shapeLast-1; + + addLineBreak(); + for (int i = shapeFirst; i < stop; i++) { + //counter = i - vertex_start; + addLine(i, i+1); + } + + // then draw from vertex (n) to (n+2) + stop = shapeLast-2; + for (int i = shapeFirst; i < stop; i++) { + addLineBreak(); + addLine(i, i+2); + } + } + break; + + case TRIANGLE_FAN: + { + // this just draws a series of line segments + // from the center to each exterior point + for (int i = shapeFirst + 1; i < shapeLast; i++) { + addLineBreak(); + addLine(shapeFirst, i); + } + + // then a single line loop around the outside. + addLineBreak(); + for (int i = shapeFirst + 1; i < shapeLast-1; i++) { + addLine(i, i+1); + } + // closing the loop + addLine(shapeLast-1, shapeFirst + 1); + } + break; + + case QUADS: + { + for (int i = shapeFirst; i < shapeLast; i += 4) { + addLineBreak(); + //counter = i - vertex_start; + addLine(i+0, i+1); + addLine(i+1, i+2); + addLine(i+2, i+3); + addLine(i+3, i+0); + } + } + break; + + case QUAD_STRIP: + { + for (int i = shapeFirst; i < shapeLast - 3; i += 2) { + addLineBreak(); + addLine(i+0, i+2); + addLine(i+2, i+3); + addLine(i+3, i+1); + addLine(i+1, i+0); + } + } + break; + + case POLYGON: + { + // store index of first vertex + int stop = shapeLast - 1; + + addLineBreak(); + for (int i = shapeFirst; i < stop; i++) { + addLine(i, i+1); + } + if (mode == CLOSE) { + // draw the last line connecting back to the first point in poly + addLine(stop, shapeFirst); //lines[first][VERTEX1]); + } + } + break; + } + } + + + protected void endShapeFill() { + switch (shape) { + case TRIANGLE_FAN: + { + int stop = shapeLast - 1; + for (int i = shapeFirst + 1; i < stop; i++) { + addTriangle(shapeFirst, i, i+1); + } + } + break; + + case TRIANGLES: + { + int stop = shapeLast - 2; + for (int i = shapeFirst; i < stop; i += 3) { + // have to switch between clockwise/counter-clockwise + // otherwise the feller is backwards and renderer won't draw + if ((i % 2) == 0) { + addTriangle(i, i+2, i+1); + } else { + addTriangle(i, i+1, i+2); + } + } + } + break; + + case TRIANGLE_STRIP: + { + int stop = shapeLast - 2; + for (int i = shapeFirst; i < stop; i++) { + // have to switch between clockwise/counter-clockwise + // otherwise the feller is backwards and renderer won't draw + if ((i % 2) == 0) { + addTriangle(i, i+2, i+1); + } else { + addTriangle(i, i+1, i+2); + } + } + } + break; + + case QUADS: + { + int stop = vertexCount-3; + for (int i = shapeFirst; i < stop; i += 4) { + // first triangle + addTriangle(i, i+1, i+2); + // second triangle + addTriangle(i, i+2, i+3); + } + } + break; + + case QUAD_STRIP: + { + int stop = vertexCount-3; + for (int i = shapeFirst; i < stop; i += 2) { + // first triangle + addTriangle(i+0, i+2, i+1); + // second triangle + addTriangle(i+2, i+3, i+1); + } + } + break; + + case POLYGON: + { + addPolygonTriangles(); + } + break; + } + } + + + protected void endShapeLighting(boolean lights) { + if (lights) { + // If the lighting does not depend on vertex position and there is a single + // normal specified for this shape, go ahead and apply the same lighting + // contribution to every vertex in this shape (one lighting calc!) + if (!lightingDependsOnVertexPosition && normalMode == NORMAL_MODE_SHAPE) { + calcLightingContribution(shapeFirst, tempLightingContribution); + for (int tri = 0; tri < triangleCount; tri++) { + lightTriangle(tri, tempLightingContribution); + } + } else { // Otherwise light each triangle individually... + for (int tri = 0; tri < triangleCount; tri++) { + lightTriangle(tri); + } + } + } else { + for (int tri = 0; tri < triangleCount; tri++) { + int index = triangles[tri][VERTEX1]; + copyPrelitVertexColor(tri, index, 0); + index = triangles[tri][VERTEX2]; + copyPrelitVertexColor(tri, index, 1); + index = triangles[tri][VERTEX3]; + copyPrelitVertexColor(tri, index, 2); + } + } + } + + + protected void endShapeCameraToScreen(int start, int stop) { + for (int i = start; i < stop; i++) { + float vx[] = vertices[i]; + + float ox = + projection.m00*vx[VX] + projection.m01*vx[VY] + + projection.m02*vx[VZ] + projection.m03*vx[VW]; + float oy = + projection.m10*vx[VX] + projection.m11*vx[VY] + + projection.m12*vx[VZ] + projection.m13*vx[VW]; + float oz = + projection.m20*vx[VX] + projection.m21*vx[VY] + + projection.m22*vx[VZ] + projection.m23*vx[VW]; + float ow = + projection.m30*vx[VX] + projection.m31*vx[VY] + + projection.m32*vx[VZ] + projection.m33*vx[VW]; + + if (ow != 0 && ow != 1) { + ox /= ow; oy /= ow; oz /= ow; + } + + vx[TX] = width * (1 + ox) / 2.0f; + vx[TY] = height * (1 + oy) / 2.0f; + vx[TZ] = (oz + 1) / 2.0f; + } + } + + + + ///////////////////////////////////////////////////////////////////////////// + + // POINTS + + + protected void addPoint(int a) { + if (pointCount == points.length) { + int[][] temp = new int[pointCount << 1][LINE_FIELD_COUNT]; + System.arraycopy(points, 0, temp, 0, pointCount); + points = temp; + } + points[pointCount][VERTEX1] = a; + //points[pointCount][STROKE_MODE] = strokeCap | strokeJoin; + points[pointCount][STROKE_COLOR] = strokeColor; + //points[pointCount][STROKE_WEIGHT] = (int) (strokeWeight + 0.5f); // hmm + pointCount++; + } + + + protected void renderPoints(int start, int stop) { + if (strokeWeight != 1) { + for (int i = start; i < stop; i++) { + float[] a = vertices[points[i][VERTEX1]]; + renderLineVertices(a, a); + } + } else { + for (int i = start; i < stop; i++) { + float[] a = vertices[points[i][VERTEX1]]; + int sx = (int) (a[TX] + 0.4999f); + int sy = (int) (a[TY] + 0.4999f); + if (sx >= 0 && sx < width && sy >= 0 && sy < height) { + int index = sy*width + sx; + pixels[index] = points[i][STROKE_COLOR]; + zbuffer[index] = a[TZ]; + } + } + } + } + + + // alternative implementations of point rendering code... + + /* + int sx = (int) (screenX(x, y, z) + 0.5f); + int sy = (int) (screenY(x, y, z) + 0.5f); + + int index = sy*width + sx; + pixels[index] = strokeColor; + zbuffer[index] = screenZ(x, y, z); + + */ + + /* + protected void renderPoints(int start, int stop) { + for (int i = start; i < stop; i++) { + float a[] = vertices[points[i][VERTEX1]]; + + line.reset(); + + line.setIntensities(a[SR], a[SG], a[SB], a[SA], + a[SR], a[SG], a[SB], a[SA]); + + line.setVertices(a[TX], a[TY], a[TZ], + a[TX] + 0.5f, a[TY] + 0.5f, a[TZ] + 0.5f); + + line.draw(); + } + } + */ + + /* + // handle points with an actual stroke weight (or scaled by renderer) + private void point3(float x, float y, float z, int color) { + // need to get scaled version of the stroke + float x1 = screenX(x - 0.5f, y - 0.5f, z); + float y1 = screenY(x - 0.5f, y - 0.5f, z); + float x2 = screenX(x + 0.5f, y + 0.5f, z); + float y2 = screenY(x + 0.5f, y + 0.5f, z); + + float weight = (abs(x2 - x1) + abs(y2 - y1)) / 2f; + if (weight < 1.5f) { + int xx = (int) ((x1 + x2) / 2f); + int yy = (int) ((y1 + y2) / 2f); + //point0(xx, yy, z, color); + zbuffer[yy*width + xx] = screenZ(x, y, z); + //stencil? + + } else { + // actually has some weight, need to draw shapes instead + // these will be + } + } + */ + + + protected void rawPoints(int start, int stop) { + raw.colorMode(RGB, 1); + raw.noFill(); + raw.strokeWeight(vertices[lines[start][VERTEX1]][SW]); + raw.beginShape(POINTS); + + for (int i = start; i < stop; i++) { + float a[] = vertices[lines[i][VERTEX1]]; + + if (raw.is3D()) { + if (a[VW] != 0) { + raw.stroke(a[SR], a[SG], a[SB], a[SA]); + raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW]); + } + } else { // if is2D() + raw.stroke(a[SR], a[SG], a[SB], a[SA]); + raw.vertex(a[TX], a[TY]); + } + } + raw.endShape(); + } + + + + ///////////////////////////////////////////////////////////////////////////// + + // LINES + + + /** + * Begin a new section of stroked geometry. + */ + protected final void addLineBreak() { + if (pathCount == pathOffset.length) { + pathOffset = PApplet.expand(pathOffset); + pathLength = PApplet.expand(pathLength); + } + pathOffset[pathCount] = lineCount; + pathLength[pathCount] = 0; + pathCount++; + } + + + protected void addLine(int a, int b) { + addLineWithClip(a, b); + } + + + protected final void addLineWithClip(int a, int b) { + float az = vertices[a][VZ]; + float bz = vertices[b][VZ]; + if (az > cameraNear) { + if (bz > cameraNear) { + return; + } + int cb = interpolateClipVertex(a, b); + addLineWithoutClip(cb, b); + return; + } + else { + if (bz <= cameraNear) { + addLineWithoutClip(a, b); + return; + } + int cb = interpolateClipVertex(a, b); + addLineWithoutClip(a, cb); + return; + } + } + + + protected final void addLineWithoutClip(int a, int b) { + if (lineCount == lines.length) { + int temp[][] = new int[lineCount<<1][LINE_FIELD_COUNT]; + System.arraycopy(lines, 0, temp, 0, lineCount); + lines = temp; + } + lines[lineCount][VERTEX1] = a; + lines[lineCount][VERTEX2] = b; + + //lines[lineCount][STROKE_MODE] = strokeCap | strokeJoin; + //lines[lineCount][STROKE_WEIGHT] = (int) (strokeWeight + 0.5f); // hmm + lineCount++; + + // mark this piece as being part of the current path + pathLength[pathCount-1]++; + } + + + protected void renderLines(int start, int stop) { + for (int i = start; i < stop; i++) { + renderLineVertices(vertices[lines[i][VERTEX1]], + vertices[lines[i][VERTEX2]]); + } + } + + + protected void renderLineVertices(float[] a, float[] b) { + // 2D hack added by ewjordan 6/13/07 + // Offset coordinates by a little bit if drawing 2D graphics. + // http://dev.processing.org/bugs/show_bug.cgi?id=95 + + // This hack fixes a bug caused by numerical precision issues when + // applying the 3D transformations to coordinates in the screen plane + // that should actually not be altered under said transformations. + // It will not be applied if any transformations other than translations + // are active, nor should it apply in OpenGL mode (PGraphicsOpenGL + // overrides render_lines(), so this should be fine). + // This fix exposes a last-pixel bug in the lineClipCode() function + // of PLine.java, so that fix must remain in place if this one is used. + + // Note: the "true" fix for this bug is to change the pixel coverage + // model so that the threshold for display does not lie on an integer + // boundary. Search "diamond exit rule" for info the OpenGL approach. + + /* + // removing for 0149 with the return of P2D + if (drawing2D() && a[Z] == 0) { + a[TX] += 0.01; + a[TY] += 0.01; + a[VX] += 0.01*a[VW]; + a[VY] += 0.01*a[VW]; + b[TX] += 0.01; + b[TY] += 0.01; + b[VX] += 0.01*b[VW]; + b[VY] += 0.01*b[VW]; + } + */ + // end 2d-hack + + if (a[SW] > 1.25f || a[SW] < 0.75f) { + float ox1 = a[TX]; + float oy1 = a[TY]; + float ox2 = b[TX]; + float oy2 = b[TY]; + + // TODO strokeWeight should be transformed! + float weight = a[SW] / 2; + + // when drawing points with stroke weight, need to extend a bit + if (ox1 == ox2 && oy1 == oy2) { + oy1 -= weight; + oy2 += weight; + } + + float dX = ox2 - ox1 + EPSILON; + float dY = oy2 - oy1 + EPSILON; + float len = (float) Math.sqrt(dX*dX + dY*dY); + + float rh = weight / len; + + float dx0 = rh * dY; + float dy0 = rh * dX; + float dx1 = rh * dY; + float dy1 = rh * dX; + + float ax1 = ox1+dx0; + float ay1 = oy1-dy0; + + float ax2 = ox1-dx0; + float ay2 = oy1+dy0; + + float bx1 = ox2+dx1; + float by1 = oy2-dy1; + + float bx2 = ox2-dx1; + float by2 = oy2+dy1; + + if (smooth) { + smoothTriangle.reset(3); + smoothTriangle.smooth = true; + smoothTriangle.interpARGB = true; // ? + + // render first triangle for thick line + smoothTriangle.setVertices(ax1, ay1, a[TZ], + bx2, by2, b[TZ], + ax2, ay2, a[TZ]); + smoothTriangle.setIntensities(a[SR], a[SG], a[SB], a[SA], + b[SR], b[SG], b[SB], b[SA], + a[SR], a[SG], a[SB], a[SA]); + smoothTriangle.render(); + + // render second triangle for thick line + smoothTriangle.setVertices(ax1, ay1, a[TZ], + bx2, by2, b[TZ], + bx1, by1, b[TZ]); + smoothTriangle.setIntensities(a[SR], a[SG], a[SB], a[SA], + b[SR], b[SG], b[SB], b[SA], + b[SR], b[SG], b[SB], b[SA]); + smoothTriangle.render(); + + } else { + triangle.reset(); + + // render first triangle for thick line + triangle.setVertices(ax1, ay1, a[TZ], + bx2, by2, b[TZ], + ax2, ay2, a[TZ]); + triangle.setIntensities(a[SR], a[SG], a[SB], a[SA], + b[SR], b[SG], b[SB], b[SA], + a[SR], a[SG], a[SB], a[SA]); + triangle.render(); + + // render second triangle for thick line + triangle.setVertices(ax1, ay1, a[TZ], + bx2, by2, b[TZ], + bx1, by1, b[TZ]); + triangle.setIntensities(a[SR], a[SG], a[SB], a[SA], + b[SR], b[SG], b[SB], b[SA], + b[SR], b[SG], b[SB], b[SA]); + triangle.render(); + } + + } else { + line.reset(); + + line.setIntensities(a[SR], a[SG], a[SB], a[SA], + b[SR], b[SG], b[SB], b[SA]); + + line.setVertices(a[TX], a[TY], a[TZ], + b[TX], b[TY], b[TZ]); + + /* + // Seems okay to remove this because these vertices are not used again, + // but if problems arise, this needs to be uncommented because the above + // change is destructive and may need to be undone before proceeding. + if (drawing2D() && a[MZ] == 0) { + a[X] -= 0.01; + a[Y] -= 0.01; + a[VX] -= 0.01*a[VW]; + a[VY] -= 0.01*a[VW]; + b[X] -= 0.01; + b[Y] -= 0.01; + b[VX] -= 0.01*b[VW]; + b[VY] -= 0.01*b[VW]; + } + */ + + line.draw(); + } + } + + + /** + * Handle echoing line data to a raw shape recording renderer. This has been + * broken out of the renderLines() procedure so that renderLines() can be + * optimized per-renderer without having to deal with this code. This code, + * for instance, will stay the same when OpenGL is in use, but renderLines() + * can be optimized significantly. + *

+ * Values for start and stop are specified, so that in the future, sorted + * rendering can be implemented, which will require sequences of lines, + * triangles, or points to be rendered in the neighborhood of one another. + * That is, if we're gonna depth sort, we can't just draw all the triangles + * and then draw all the lines, cuz that defeats the purpose. + */ + protected void rawLines(int start, int stop) { + raw.colorMode(RGB, 1); + raw.noFill(); + raw.beginShape(LINES); + + for (int i = start; i < stop; i++) { + float a[] = vertices[lines[i][VERTEX1]]; + float b[] = vertices[lines[i][VERTEX2]]; + raw.strokeWeight(vertices[lines[i][VERTEX2]][SW]); + + if (raw.is3D()) { + if ((a[VW] != 0) && (b[VW] != 0)) { + raw.stroke(a[SR], a[SG], a[SB], a[SA]); + raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW]); + raw.stroke(b[SR], b[SG], b[SB], b[SA]); + raw.vertex(b[VX] / b[VW], b[VY] / b[VW], b[VZ] / b[VW]); + } + } else if (raw.is2D()) { + raw.stroke(a[SR], a[SG], a[SB], a[SA]); + raw.vertex(a[TX], a[TY]); + raw.stroke(b[SR], b[SG], b[SB], b[SA]); + raw.vertex(b[TX], b[TY]); + } + } + raw.endShape(); + } + + + + ///////////////////////////////////////////////////////////////////////////// + + // TRIANGLES + + + protected void addTriangle(int a, int b, int c) { + addTriangleWithClip(a, b, c); + } + + + protected final void addTriangleWithClip(int a, int b, int c) { + boolean aClipped = false; + boolean bClipped = false; + int clippedCount = 0; + + // This is a hack for temporary clipping. Clipping still needs to + // be implemented properly, however. Please help! + // http://dev.processing.org/bugs/show_bug.cgi?id=1393 + cameraNear = -8; + if (vertices[a][VZ] > cameraNear) { + aClipped = true; + clippedCount++; + } + if (vertices[b][VZ] > cameraNear) { + bClipped = true; + clippedCount++; + } + if (vertices[c][VZ] > cameraNear) { + //cClipped = true; + clippedCount++; + } + if (clippedCount == 0) { +// if (vertices[a][VZ] < cameraFar && +// vertices[b][VZ] < cameraFar && +// vertices[c][VZ] < cameraFar) { + addTriangleWithoutClip(a, b, c); +// } + +// } else if (true) { +// return; + + } else if (clippedCount == 3) { + // In this case there is only one visible point. |/| + // So we'll have to make two new points on the clip line <| | + // and add that triangle instead. |\| + + } else if (clippedCount == 2) { + //System.out.println("Clipped two"); + + int ca, cb, cc, cd, ce; + if (!aClipped) { + ca = a; + cb = b; + cc = c; + } + else if (!bClipped) { + ca = b; + cb = a; + cc = c; + } + else { //if (!cClipped) { + ca = c; + cb = b; + cc = a; + } + + cd = interpolateClipVertex(ca, cb); + ce = interpolateClipVertex(ca, cc); + addTriangleWithoutClip(ca, cd, ce); + + } else { // (clippedCount == 1) { + // . | + // In this case there are two visible points. |\| + // So we'll have to make two new points on the clip line | |> + // and then add two new triangles. |/| + // . | + //System.out.println("Clipped one"); + int ca, cb, cc, cd, ce; + if (aClipped) { + //System.out.println("aClipped"); + ca = c; + cb = b; + cc = a; + } + else if (bClipped) { + //System.out.println("bClipped"); + ca = a; + cb = c; + cc = b; + } + else { //if (cClipped) { + //System.out.println("cClipped"); + ca = a; + cb = b; + cc = c; + } + + cd = interpolateClipVertex(ca, cc); + ce = interpolateClipVertex(cb, cc); + addTriangleWithoutClip(ca, cd, cb); + //System.out.println("ca: " + ca + ", " + vertices[ca][VX] + ", " + vertices[ca][VY] + ", " + vertices[ca][VZ]); + //System.out.println("cd: " + cd + ", " + vertices[cd][VX] + ", " + vertices[cd][VY] + ", " + vertices[cd][VZ]); + //System.out.println("cb: " + cb + ", " + vertices[cb][VX] + ", " + vertices[cb][VY] + ", " + vertices[cb][VZ]); + addTriangleWithoutClip(cb, cd, ce); + } + } + + + protected final int interpolateClipVertex(int a, int b) { + float[] va; + float[] vb; + // Set up va, vb such that va[VZ] >= vb[VZ] + if (vertices[a][VZ] < vertices[b][VZ]) { + va = vertices[b]; + vb = vertices[a]; + } + else { + va = vertices[a]; + vb = vertices[b]; + } + float az = va[VZ]; + float bz = vb[VZ]; + + float dz = az - bz; + // If they have the same z, just use pt. a. + if (dz == 0) { + return a; + } + //float pa = (az - cameraNear) / dz; + //float pb = (cameraNear - bz) / dz; + float pa = (cameraNear - bz) / dz; + float pb = 1 - pa; + + vertex(pa * va[X] + pb * vb[X], + pa * va[Y] + pb * vb[Y], + pa * va[Z] + pb * vb[Z]); + int irv = vertexCount - 1; + shapeLastPlusClipped++; + + float[] rv = vertices[irv]; + + rv[TX] = pa * va[TX] + pb * vb[TX]; + rv[TY] = pa * va[TY] + pb * vb[TY]; + rv[TZ] = pa * va[TZ] + pb * vb[TZ]; + + rv[VX] = pa * va[VX] + pb * vb[VX]; + rv[VY] = pa * va[VY] + pb * vb[VY]; + rv[VZ] = pa * va[VZ] + pb * vb[VZ]; + rv[VW] = pa * va[VW] + pb * vb[VW]; + + rv[R] = pa * va[R] + pb * vb[R]; + rv[G] = pa * va[G] + pb * vb[G]; + rv[B] = pa * va[B] + pb * vb[B]; + rv[A] = pa * va[A] + pb * vb[A]; + + rv[U] = pa * va[U] + pb * vb[U]; + rv[V] = pa * va[V] + pb * vb[V]; + + rv[SR] = pa * va[SR] + pb * vb[SR]; + rv[SG] = pa * va[SG] + pb * vb[SG]; + rv[SB] = pa * va[SB] + pb * vb[SB]; + rv[SA] = pa * va[SA] + pb * vb[SA]; + + rv[NX] = pa * va[NX] + pb * vb[NX]; + rv[NY] = pa * va[NY] + pb * vb[NY]; + rv[NZ] = pa * va[NZ] + pb * vb[NZ]; + +// rv[SW] = pa * va[SW] + pb * vb[SW]; + + rv[AR] = pa * va[AR] + pb * vb[AR]; + rv[AG] = pa * va[AG] + pb * vb[AG]; + rv[AB] = pa * va[AB] + pb * vb[AB]; + + rv[SPR] = pa * va[SPR] + pb * vb[SPR]; + rv[SPG] = pa * va[SPG] + pb * vb[SPG]; + rv[SPB] = pa * va[SPB] + pb * vb[SPB]; + //rv[SPA] = pa * va[SPA] + pb * vb[SPA]; + + rv[ER] = pa * va[ER] + pb * vb[ER]; + rv[EG] = pa * va[EG] + pb * vb[EG]; + rv[EB] = pa * va[EB] + pb * vb[EB]; + + rv[SHINE] = pa * va[SHINE] + pb * vb[SHINE]; + + rv[BEEN_LIT] = 0; + + return irv; + } + + + protected final void addTriangleWithoutClip(int a, int b, int c) { + if (triangleCount == triangles.length) { + int temp[][] = new int[triangleCount<<1][TRIANGLE_FIELD_COUNT]; + System.arraycopy(triangles, 0, temp, 0, triangleCount); + triangles = temp; + //message(CHATTER, "allocating more triangles " + triangles.length); + float ftemp[][][] = new float[triangleCount<<1][3][TRI_COLOR_COUNT]; + System.arraycopy(triangleColors, 0, ftemp, 0, triangleCount); + triangleColors = ftemp; + } + triangles[triangleCount][VERTEX1] = a; + triangles[triangleCount][VERTEX2] = b; + triangles[triangleCount][VERTEX3] = c; + + if (textureImage == null) { + triangles[triangleCount][TEXTURE_INDEX] = -1; + } else { + triangles[triangleCount][TEXTURE_INDEX] = textureIndex; + } + +// triangles[triangleCount][INDEX] = shape_index; + triangleCount++; + } + + + /** + * Triangulate the current polygon. + *

+ * Simple ear clipping polygon triangulation adapted from code by + * John W. Ratcliff (jratcliff at verant.com). Presumably + * this + * bit of code from the web. + */ + protected void addPolygonTriangles() { + if (vertexOrder.length != vertices.length) { + int[] temp = new int[vertices.length]; + // vertex_start may not be zero, might need to keep old stuff around + // also, copy vertexOrder.length, not vertexCount because vertexCount + // may be larger than vertexOrder.length (since this is a post-processing + // step that happens after the vertex arrays are built). + PApplet.arrayCopy(vertexOrder, temp, vertexOrder.length); + vertexOrder = temp; + } + + // this clipping algorithm only works in 2D, so in cases where a + // polygon is drawn perpendicular to the z-axis, the area will be zero, + // and triangulation will fail. as such, when the area calculates to + // zero, figure out whether x or y is empty, and calculate based on the + // two dimensions that actually contain information. + // http://dev.processing.org/bugs/show_bug.cgi?id=111 + int d1 = X; + int d2 = Y; + // this brings up the nastier point that there may be cases where + // a polygon is irregular in space and will throw off the + // clockwise/counterclockwise calculation. for instance, if clockwise + // relative to x and z, but counter relative to y and z or something + // like that.. will wait to see if this is in fact a problem before + // hurting my head on the math. + + /* + // trying to track down bug #774 + for (int i = vertex_start; i < vertex_end; i++) { + if (i > vertex_start) { + if (vertices[i-1][MX] == vertices[i][MX] && + vertices[i-1][MY] == vertices[i][MY]) { + System.out.print("**** " ); + } + } + System.out.println(i + " " + vertices[i][MX] + " " + vertices[i][MY]); + } + System.out.println(); + */ + + // first we check if the polygon goes clockwise or counterclockwise + float area = 0; + for (int p = shapeLast - 1, q = shapeFirst; q < shapeLast; p = q++) { + area += (vertices[q][d1] * vertices[p][d2] - + vertices[p][d1] * vertices[q][d2]); + } + // rather than checking for the perpendicular case first, only do it + // when the area calculates to zero. checking for perpendicular would be + // a needless waste of time for the 99% case. + if (area == 0) { + // figure out which dimension is the perpendicular axis + boolean foundValidX = false; + boolean foundValidY = false; + + for (int i = shapeFirst; i < shapeLast; i++) { + for (int j = i; j < shapeLast; j++){ + if ( vertices[i][X] != vertices[j][X] ) foundValidX = true; + if ( vertices[i][Y] != vertices[j][Y] ) foundValidY = true; + } + } + + if (foundValidX) { + //d1 = MX; // already the case + d2 = Z; + } else if (foundValidY) { + // ermm.. which is the proper order for cw/ccw here? + d1 = Y; + d2 = Z; + } else { + // screw it, this polygon is just f-ed up + return; + } + + // re-calculate the area, with what should be good values + for (int p = shapeLast - 1, q = shapeFirst; q < shapeLast; p = q++) { + area += (vertices[q][d1] * vertices[p][d2] - + vertices[p][d1] * vertices[q][d2]); + } + } + + // don't allow polygons to come back and meet themselves, + // otherwise it will anger the triangulator + // http://dev.processing.org/bugs/show_bug.cgi?id=97 + float vfirst[] = vertices[shapeFirst]; + float vlast[] = vertices[shapeLast-1]; + if ((abs(vfirst[X] - vlast[X]) < EPSILON) && + (abs(vfirst[Y] - vlast[Y]) < EPSILON) && + (abs(vfirst[Z] - vlast[Z]) < EPSILON)) { + shapeLast--; + } + + // then sort the vertices so they are always in a counterclockwise order + int j = 0; + if (area > 0) { + for (int i = shapeFirst; i < shapeLast; i++) { + j = i - shapeFirst; + vertexOrder[j] = i; + } + } else { + for (int i = shapeFirst; i < shapeLast; i++) { + j = i - shapeFirst; + vertexOrder[j] = (shapeLast - 1) - j; + } + } + + // remove vc-2 Vertices, creating 1 triangle every time + int vc = shapeLast - shapeFirst; + int count = 2*vc; // complex polygon detection + + for (int m = 0, v = vc - 1; vc > 2; ) { + boolean snip = true; + + // if we start over again, is a complex polygon + if (0 >= (count--)) { + break; // triangulation failed + } + + // get 3 consecutive vertices + int u = v ; if (vc <= u) u = 0; // previous + v = u + 1; if (vc <= v) v = 0; // current + int w = v + 1; if (vc <= w) w = 0; // next + + // Upgrade values to doubles, and multiply by 10 so that we can have + // some better accuracy as we tessellate. This seems to have negligible + // speed differences on Windows and Intel Macs, but causes a 50% speed + // drop for PPC Macs with the bug's example code that draws ~200 points + // in a concave polygon. Apple has abandoned PPC so we may as well too. + // http://dev.processing.org/bugs/show_bug.cgi?id=774 + + // triangle A B C + double Ax = -10 * vertices[vertexOrder[u]][d1]; + double Ay = 10 * vertices[vertexOrder[u]][d2]; + double Bx = -10 * vertices[vertexOrder[v]][d1]; + double By = 10 * vertices[vertexOrder[v]][d2]; + double Cx = -10 * vertices[vertexOrder[w]][d1]; + double Cy = 10 * vertices[vertexOrder[w]][d2]; + + // first we check if continues going ccw + if (EPSILON > (((Bx-Ax) * (Cy-Ay)) - ((By-Ay) * (Cx-Ax)))) { + continue; + } + + for (int p = 0; p < vc; p++) { + if ((p == u) || (p == v) || (p == w)) { + continue; + } + + double Px = -10 * vertices[vertexOrder[p]][d1]; + double Py = 10 * vertices[vertexOrder[p]][d2]; + + double ax = Cx - Bx; double ay = Cy - By; + double bx = Ax - Cx; double by = Ay - Cy; + double cx = Bx - Ax; double cy = By - Ay; + double apx = Px - Ax; double apy = Py - Ay; + double bpx = Px - Bx; double bpy = Py - By; + double cpx = Px - Cx; double cpy = Py - Cy; + + double aCROSSbp = ax * bpy - ay * bpx; + double cCROSSap = cx * apy - cy * apx; + double bCROSScp = bx * cpy - by * cpx; + + if ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0)) { + snip = false; + } + } + + if (snip) { + addTriangle(vertexOrder[u], vertexOrder[v], vertexOrder[w]); + + m++; + + // remove v from remaining polygon + for (int s = v, t = v + 1; t < vc; s++, t++) { + vertexOrder[s] = vertexOrder[t]; + } + vc--; + + // reset error detection counter + count = 2 * vc; + } + } + } + + + private void toWorldNormal(float nx, float ny, float nz, float[] out) { + out[0] = + modelviewInv.m00*nx + modelviewInv.m10*ny + + modelviewInv.m20*nz + modelviewInv.m30; + out[1] = + modelviewInv.m01*nx + modelviewInv.m11*ny + + modelviewInv.m21*nz + modelviewInv.m31; + out[2] = + modelviewInv.m02*nx + modelviewInv.m12*ny + + modelviewInv.m22*nz + modelviewInv.m32; + out[3] = + modelviewInv.m03*nx + modelviewInv.m13*ny + + modelviewInv.m23*nz + modelviewInv.m33; + + if (out[3] != 0 && out[3] != 1) { + // divide by perspective coordinate + out[0] /= out[3]; out[1] /= out[3]; out[2] /= out[3]; + } + out[3] = 1; + + float nlen = mag(out[0], out[1], out[2]); // normalize + if (nlen != 0 && nlen != 1) { + out[0] /= nlen; out[1] /= nlen; out[2] /= nlen; + } + } + + + //private PVector calcLightingNorm = new PVector(); + //private PVector calcLightingWorldNorm = new PVector(); + float[] worldNormal = new float[4]; + + + private void calcLightingContribution(int vIndex, + float[] contribution) { + calcLightingContribution(vIndex, contribution, false); + } + + + private void calcLightingContribution(int vIndex, + float[] contribution, + boolean normalIsWorld) { + float[] v = vertices[vIndex]; + + float sr = v[SPR]; + float sg = v[SPG]; + float sb = v[SPB]; + + float wx = v[VX]; + float wy = v[VY]; + float wz = v[VZ]; + float shine = v[SHINE]; + + float nx = v[NX]; + float ny = v[NY]; + float nz = v[NZ]; + + if (!normalIsWorld) { +// System.out.println("um, hello?"); +// calcLightingNorm.set(nx, ny, nz); +// //modelviewInv.mult(calcLightingNorm, calcLightingWorldNorm); +// +//// PMatrix3D mvi = modelViewInv; +//// float ox = mvi.m00*nx + mvi.m10*ny + mvi*m20+nz + +// modelviewInv.cmult(calcLightingNorm, calcLightingWorldNorm); +// +// calcLightingWorldNorm.normalize(); +// nx = calcLightingWorldNorm.x; +// ny = calcLightingWorldNorm.y; +// nz = calcLightingWorldNorm.z; + + toWorldNormal(v[NX], v[NY], v[NZ], worldNormal); + nx = worldNormal[X]; + ny = worldNormal[Y]; + nz = worldNormal[Z]; + +// float wnx = modelviewInv.multX(nx, ny, nz); +// float wny = modelviewInv.multY(nx, ny, nz); +// float wnz = modelviewInv.multZ(nx, ny, nz); +// float wnw = modelviewInv.multW(nx, ny, nz); + +// if (wnw != 0 && wnw != 1) { +// wnx /= wnw; +// wny /= wnw; +// wnz /= wnw; +// } +// float nlen = mag(wnx, wny, wnw); +// if (nlen != 0 && nlen != 1) { +// nx = wnx / nlen; +// ny = wny / nlen; +// nz = wnz / nlen; +// } else { +// nx = wnx; +// ny = wny; +// nz = wnz; +// } +// */ + } else { + nx = v[NX]; + ny = v[NY]; + nz = v[NZ]; + } + + // Since the camera space == world space, + // we can test for visibility by the dot product of + // the normal with the direction from pt. to eye. + float dir = dot(nx, ny, nz, -wx, -wy, -wz); + // If normal is away from camera, choose its opposite. + // If we add backface culling, this will be backfacing + // (but since this is per vertex, it's more complicated) + if (dir < 0) { + nx = -nx; + ny = -ny; + nz = -nz; + } + + // These two terms will sum the contributions from the various lights + contribution[LIGHT_AMBIENT_R] = 0; + contribution[LIGHT_AMBIENT_G] = 0; + contribution[LIGHT_AMBIENT_B] = 0; + + contribution[LIGHT_DIFFUSE_R] = 0; + contribution[LIGHT_DIFFUSE_G] = 0; + contribution[LIGHT_DIFFUSE_B] = 0; + + contribution[LIGHT_SPECULAR_R] = 0; + contribution[LIGHT_SPECULAR_G] = 0; + contribution[LIGHT_SPECULAR_B] = 0; + + // for (int i = 0; i < MAX_LIGHTS; i++) { + // if (!light[i]) continue; + for (int i = 0; i < lightCount; i++) { + + float denom = lightFalloffConstant[i]; + float spotTerm = 1; + + if (lightType[i] == AMBIENT) { + if (lightFalloffQuadratic[i] != 0 || lightFalloffLinear[i] != 0) { + // Falloff depends on distance + float distSq = mag(lightPosition[i].x - wx, + lightPosition[i].y - wy, + lightPosition[i].z - wz); + denom += + lightFalloffQuadratic[i] * distSq + + lightFalloffLinear[i] * sqrt(distSq); + } + if (denom == 0) denom = 1; + + contribution[LIGHT_AMBIENT_R] += lightDiffuse[i][0] / denom; + contribution[LIGHT_AMBIENT_G] += lightDiffuse[i][1] / denom; + contribution[LIGHT_AMBIENT_B] += lightDiffuse[i][2] / denom; + + } else { + // If not ambient, we must deal with direction + + // li is the vector from the vertex to the light + float lix, liy, liz; + float lightDir_dot_li = 0; + float n_dot_li = 0; + + if (lightType[i] == DIRECTIONAL) { + lix = -lightNormal[i].x; + liy = -lightNormal[i].y; + liz = -lightNormal[i].z; + denom = 1; + n_dot_li = (nx * lix + ny * liy + nz * liz); + // If light is lighting the face away from the camera, ditch + if (n_dot_li <= 0) { + continue; + } + } else { // Point or spot light (must deal also with light location) + lix = lightPosition[i].x - wx; + liy = lightPosition[i].y - wy; + liz = lightPosition[i].z - wz; + // normalize + float distSq = mag(lix, liy, liz); + if (distSq != 0) { + lix /= distSq; + liy /= distSq; + liz /= distSq; + } + n_dot_li = (nx * lix + ny * liy + nz * liz); + // If light is lighting the face away from the camera, ditch + if (n_dot_li <= 0) { + continue; + } + + if (lightType[i] == SPOT) { // Must deal with spot cone + lightDir_dot_li = + -(lightNormal[i].x * lix + + lightNormal[i].y * liy + + lightNormal[i].z * liz); + // Outside of spot cone + if (lightDir_dot_li <= lightSpotAngleCos[i]) { + continue; + } + spotTerm = (float) Math.pow(lightDir_dot_li, lightSpotConcentration[i]); + } + + if (lightFalloffQuadratic[i] != 0 || lightFalloffLinear[i] != 0) { + // Falloff depends on distance + denom += + lightFalloffQuadratic[i] * distSq + + lightFalloffLinear[i] * (float) sqrt(distSq); + } + } + // Directional, point, or spot light: + + // We know n_dot_li > 0 from above "continues" + + if (denom == 0) + denom = 1; + float mul = n_dot_li * spotTerm / denom; + contribution[LIGHT_DIFFUSE_R] += lightDiffuse[i][0] * mul; + contribution[LIGHT_DIFFUSE_G] += lightDiffuse[i][1] * mul; + contribution[LIGHT_DIFFUSE_B] += lightDiffuse[i][2] * mul; + + // SPECULAR + + // If the material and light have a specular component. + if ((sr > 0 || sg > 0 || sb > 0) && + (lightSpecular[i][0] > 0 || + lightSpecular[i][1] > 0 || + lightSpecular[i][2] > 0)) { + + float vmag = mag(wx, wy, wz); + if (vmag != 0) { + wx /= vmag; + wy /= vmag; + wz /= vmag; + } + float sx = lix - wx; + float sy = liy - wy; + float sz = liz - wz; + vmag = mag(sx, sy, sz); + if (vmag != 0) { + sx /= vmag; + sy /= vmag; + sz /= vmag; + } + float s_dot_n = (sx * nx + sy * ny + sz * nz); + + if (s_dot_n > 0) { + s_dot_n = (float) Math.pow(s_dot_n, shine); + mul = s_dot_n * spotTerm / denom; + contribution[LIGHT_SPECULAR_R] += lightSpecular[i][0] * mul; + contribution[LIGHT_SPECULAR_G] += lightSpecular[i][1] * mul; + contribution[LIGHT_SPECULAR_B] += lightSpecular[i][2] * mul; + } + + } + } + } + return; + } + + + // Multiply the lighting contribution into the vertex's colors. + // Only do this when there is ONE lighting per vertex + // (MANUAL_VERTEX_NORMAL or SHAPE_NORMAL mode). + private void applyLightingContribution(int vIndex, float[] contribution) { + float[] v = vertices[vIndex]; + + v[R] = clamp(v[ER] + v[AR] * contribution[LIGHT_AMBIENT_R] + v[DR] * contribution[LIGHT_DIFFUSE_R]); + v[G] = clamp(v[EG] + v[AG] * contribution[LIGHT_AMBIENT_G] + v[DG] * contribution[LIGHT_DIFFUSE_G]); + v[B] = clamp(v[EB] + v[AB] * contribution[LIGHT_AMBIENT_B] + v[DB] * contribution[LIGHT_DIFFUSE_B]); + v[A] = clamp(v[DA]); + + v[SPR] = clamp(v[SPR] * contribution[LIGHT_SPECULAR_R]); + v[SPG] = clamp(v[SPG] * contribution[LIGHT_SPECULAR_G]); + v[SPB] = clamp(v[SPB] * contribution[LIGHT_SPECULAR_B]); + //v[SPA] = min(1, v[SPA]); + + v[BEEN_LIT] = 1; + } + + + private void lightVertex(int vIndex, float[] contribution) { + calcLightingContribution(vIndex, contribution); + applyLightingContribution(vIndex, contribution); + } + + + private void lightUnlitVertex(int vIndex, float[] contribution) { + if (vertices[vIndex][BEEN_LIT] == 0) { + lightVertex(vIndex, contribution); + } + } + + + private void copyPrelitVertexColor(int triIndex, int index, int colorIndex) { + float[] triColor = triangleColors[triIndex][colorIndex]; + float[] v = vertices[index]; + + triColor[TRI_DIFFUSE_R] = v[R]; + triColor[TRI_DIFFUSE_G] = v[G]; + triColor[TRI_DIFFUSE_B] = v[B]; + triColor[TRI_DIFFUSE_A] = v[A]; + triColor[TRI_SPECULAR_R] = v[SPR]; + triColor[TRI_SPECULAR_G] = v[SPG]; + triColor[TRI_SPECULAR_B] = v[SPB]; + //triColor[TRI_SPECULAR_A] = v[SPA]; + } + + + private void copyVertexColor(int triIndex, int index, int colorIndex, + float[] contrib) { + float[] triColor = triangleColors[triIndex][colorIndex]; + float[] v = vertices[index]; + + triColor[TRI_DIFFUSE_R] = + clamp(v[ER] + v[AR] * contrib[LIGHT_AMBIENT_R] + v[DR] * contrib[LIGHT_DIFFUSE_R]); + triColor[TRI_DIFFUSE_G] = + clamp(v[EG] + v[AG] * contrib[LIGHT_AMBIENT_G] + v[DG] * contrib[LIGHT_DIFFUSE_G]); + triColor[TRI_DIFFUSE_B] = + clamp(v[EB] + v[AB] * contrib[LIGHT_AMBIENT_B] + v[DB] * contrib[LIGHT_DIFFUSE_B]); + triColor[TRI_DIFFUSE_A] = clamp(v[DA]); + + triColor[TRI_SPECULAR_R] = clamp(v[SPR] * contrib[LIGHT_SPECULAR_R]); + triColor[TRI_SPECULAR_G] = clamp(v[SPG] * contrib[LIGHT_SPECULAR_G]); + triColor[TRI_SPECULAR_B] = clamp(v[SPB] * contrib[LIGHT_SPECULAR_B]); + } + + + private void lightTriangle(int triIndex, float[] lightContribution) { + int vIndex = triangles[triIndex][VERTEX1]; + copyVertexColor(triIndex, vIndex, 0, lightContribution); + vIndex = triangles[triIndex][VERTEX2]; + copyVertexColor(triIndex, vIndex, 1, lightContribution); + vIndex = triangles[triIndex][VERTEX3]; + copyVertexColor(triIndex, vIndex, 2, lightContribution); + } + + + private void lightTriangle(int triIndex) { + int vIndex; + + // Handle lighting on, but no lights (in this case, just use emissive) + // This wont be used currently because lightCount == 0 is don't use + // lighting at all... So. OK. If that ever changes, use the below: + /* + if (lightCount == 0) { + vIndex = triangles[triIndex][VERTEX1]; + copy_emissive_vertex_color_to_triangle(triIndex, vIndex, 0); + vIndex = triangles[triIndex][VERTEX2]; + copy_emissive_vertex_color_to_triangle(triIndex, vIndex, 1); + vIndex = triangles[triIndex][VERTEX3]; + copy_emissive_vertex_color_to_triangle(triIndex, vIndex, 2); + return; + } + */ + + // In MANUAL_VERTEX_NORMAL mode, we have a specific normal + // for each vertex. In that case, we light any verts that + // haven't already been lit and copy their colors straight + // into the triangle. + if (normalMode == NORMAL_MODE_VERTEX) { + vIndex = triangles[triIndex][VERTEX1]; + lightUnlitVertex(vIndex, tempLightingContribution); + copyPrelitVertexColor(triIndex, vIndex, 0); + + vIndex = triangles[triIndex][VERTEX2]; + lightUnlitVertex(vIndex, tempLightingContribution); + copyPrelitVertexColor(triIndex, vIndex, 1); + + vIndex = triangles[triIndex][VERTEX3]; + lightUnlitVertex(vIndex, tempLightingContribution); + copyPrelitVertexColor(triIndex, vIndex, 2); + + } + + // If the lighting doesn't depend on the vertex position, do the + // following: We've already dealt with NORMAL_MODE_SHAPE mode before + // we got into this function, so here we only have to deal with + // NORMAL_MODE_AUTO. So we calculate the normal for this triangle, + // and use that for the lighting. + else if (!lightingDependsOnVertexPosition) { + vIndex = triangles[triIndex][VERTEX1]; + int vIndex2 = triangles[triIndex][VERTEX2]; + int vIndex3 = triangles[triIndex][VERTEX3]; + + /* + dv1[0] = vertices[vIndex2][VX] - vertices[vIndex][VX]; + dv1[1] = vertices[vIndex2][VY] - vertices[vIndex][VY]; + dv1[2] = vertices[vIndex2][VZ] - vertices[vIndex][VZ]; + + dv2[0] = vertices[vIndex3][VX] - vertices[vIndex][VX]; + dv2[1] = vertices[vIndex3][VY] - vertices[vIndex][VY]; + dv2[2] = vertices[vIndex3][VZ] - vertices[vIndex][VZ]; + + cross(dv1, dv2, norm); + */ + + cross(vertices[vIndex2][VX] - vertices[vIndex][VX], + vertices[vIndex2][VY] - vertices[vIndex][VY], + vertices[vIndex2][VZ] - vertices[vIndex][VZ], + vertices[vIndex3][VX] - vertices[vIndex][VX], + vertices[vIndex3][VY] - vertices[vIndex][VY], + vertices[vIndex3][VZ] - vertices[vIndex][VZ], lightTriangleNorm); + + lightTriangleNorm.normalize(); + vertices[vIndex][NX] = lightTriangleNorm.x; + vertices[vIndex][NY] = lightTriangleNorm.y; + vertices[vIndex][NZ] = lightTriangleNorm.z; + + // The true at the end says the normal is already in world coordinates + calcLightingContribution(vIndex, tempLightingContribution, true); + copyVertexColor(triIndex, vIndex, 0, tempLightingContribution); + copyVertexColor(triIndex, vIndex2, 1, tempLightingContribution); + copyVertexColor(triIndex, vIndex3, 2, tempLightingContribution); + } + + // If lighting is position-dependent + else { + if (normalMode == NORMAL_MODE_SHAPE) { + vIndex = triangles[triIndex][VERTEX1]; + vertices[vIndex][NX] = vertices[shapeFirst][NX]; + vertices[vIndex][NY] = vertices[shapeFirst][NY]; + vertices[vIndex][NZ] = vertices[shapeFirst][NZ]; + calcLightingContribution(vIndex, tempLightingContribution); + copyVertexColor(triIndex, vIndex, 0, tempLightingContribution); + + vIndex = triangles[triIndex][VERTEX2]; + vertices[vIndex][NX] = vertices[shapeFirst][NX]; + vertices[vIndex][NY] = vertices[shapeFirst][NY]; + vertices[vIndex][NZ] = vertices[shapeFirst][NZ]; + calcLightingContribution(vIndex, tempLightingContribution); + copyVertexColor(triIndex, vIndex, 1, tempLightingContribution); + + vIndex = triangles[triIndex][VERTEX3]; + vertices[vIndex][NX] = vertices[shapeFirst][NX]; + vertices[vIndex][NY] = vertices[shapeFirst][NY]; + vertices[vIndex][NZ] = vertices[shapeFirst][NZ]; + calcLightingContribution(vIndex, tempLightingContribution); + copyVertexColor(triIndex, vIndex, 2, tempLightingContribution); + } + + // lighting mode is AUTO_NORMAL + else { + vIndex = triangles[triIndex][VERTEX1]; + int vIndex2 = triangles[triIndex][VERTEX2]; + int vIndex3 = triangles[triIndex][VERTEX3]; + + /* + dv1[0] = vertices[vIndex2][VX] - vertices[vIndex][VX]; + dv1[1] = vertices[vIndex2][VY] - vertices[vIndex][VY]; + dv1[2] = vertices[vIndex2][VZ] - vertices[vIndex][VZ]; + + dv2[0] = vertices[vIndex3][VX] - vertices[vIndex][VX]; + dv2[1] = vertices[vIndex3][VY] - vertices[vIndex][VY]; + dv2[2] = vertices[vIndex3][VZ] - vertices[vIndex][VZ]; + + cross(dv1, dv2, norm); + */ + + cross(vertices[vIndex2][VX] - vertices[vIndex][VX], + vertices[vIndex2][VY] - vertices[vIndex][VY], + vertices[vIndex2][VZ] - vertices[vIndex][VZ], + vertices[vIndex3][VX] - vertices[vIndex][VX], + vertices[vIndex3][VY] - vertices[vIndex][VY], + vertices[vIndex3][VZ] - vertices[vIndex][VZ], lightTriangleNorm); +// float nmag = mag(norm[X], norm[Y], norm[Z]); +// if (nmag != 0 && nmag != 1) { +// norm[X] /= nmag; norm[Y] /= nmag; norm[Z] /= nmag; +// } + lightTriangleNorm.normalize(); + vertices[vIndex][NX] = lightTriangleNorm.x; + vertices[vIndex][NY] = lightTriangleNorm.y; + vertices[vIndex][NZ] = lightTriangleNorm.z; + // The true at the end says the normal is already in world coordinates + calcLightingContribution(vIndex, tempLightingContribution, true); + copyVertexColor(triIndex, vIndex, 0, tempLightingContribution); + + vertices[vIndex2][NX] = lightTriangleNorm.x; + vertices[vIndex2][NY] = lightTriangleNorm.y; + vertices[vIndex2][NZ] = lightTriangleNorm.z; + // The true at the end says the normal is already in world coordinates + calcLightingContribution(vIndex2, tempLightingContribution, true); + copyVertexColor(triIndex, vIndex2, 1, tempLightingContribution); + + vertices[vIndex3][NX] = lightTriangleNorm.x; + vertices[vIndex3][NY] = lightTriangleNorm.y; + vertices[vIndex3][NZ] = lightTriangleNorm.z; + // The true at the end says the normal is already in world coordinates + calcLightingContribution(vIndex3, tempLightingContribution, true); + copyVertexColor(triIndex, vIndex3, 2, tempLightingContribution); + } + } + } + + + protected void renderTriangles(int start, int stop) { + for (int i = start; i < stop; i++) { + float a[] = vertices[triangles[i][VERTEX1]]; + float b[] = vertices[triangles[i][VERTEX2]]; + float c[] = vertices[triangles[i][VERTEX3]]; + int tex = triangles[i][TEXTURE_INDEX]; + + /* + // removing for 0149 with the return of P2D + // ewjordan: hack to 'fix' accuracy issues when drawing in 2d + // see also render_lines() where similar hack is employed + float shift = 0.15f;//was 0.49f + boolean shifted = false; + if (drawing2D() && (a[Z] == 0)) { + shifted = true; + a[TX] += shift; + a[TY] += shift; + a[VX] += shift*a[VW]; + a[VY] += shift*a[VW]; + b[TX] += shift; + b[TY] += shift; + b[VX] += shift*b[VW]; + b[VY] += shift*b[VW]; + c[TX] += shift; + c[TY] += shift; + c[VX] += shift*c[VW]; + c[VY] += shift*c[VW]; + } + */ + + triangle.reset(); + + // This is only true when not textured. + // We really should pass specular straight through to triangle rendering. + float ar = clamp(triangleColors[i][0][TRI_DIFFUSE_R] + triangleColors[i][0][TRI_SPECULAR_R]); + float ag = clamp(triangleColors[i][0][TRI_DIFFUSE_G] + triangleColors[i][0][TRI_SPECULAR_G]); + float ab = clamp(triangleColors[i][0][TRI_DIFFUSE_B] + triangleColors[i][0][TRI_SPECULAR_B]); + float br = clamp(triangleColors[i][1][TRI_DIFFUSE_R] + triangleColors[i][1][TRI_SPECULAR_R]); + float bg = clamp(triangleColors[i][1][TRI_DIFFUSE_G] + triangleColors[i][1][TRI_SPECULAR_G]); + float bb = clamp(triangleColors[i][1][TRI_DIFFUSE_B] + triangleColors[i][1][TRI_SPECULAR_B]); + float cr = clamp(triangleColors[i][2][TRI_DIFFUSE_R] + triangleColors[i][2][TRI_SPECULAR_R]); + float cg = clamp(triangleColors[i][2][TRI_DIFFUSE_G] + triangleColors[i][2][TRI_SPECULAR_G]); + float cb = clamp(triangleColors[i][2][TRI_DIFFUSE_B] + triangleColors[i][2][TRI_SPECULAR_B]); + + // ACCURATE TEXTURE CODE + boolean failedToPrecalc = false; + if (s_enableAccurateTextures && frustumMode){ + boolean textured = true; + smoothTriangle.reset(3); + smoothTriangle.smooth = true; + smoothTriangle.interpARGB = true; + smoothTriangle.setIntensities(ar, ag, ab, a[A], + br, bg, bb, b[A], + cr, cg, cb, c[A]); + if (tex > -1 && textures[tex] != null) { + smoothTriangle.setCamVertices(a[VX], a[VY], a[VZ], + b[VX], b[VY], b[VZ], + c[VX], c[VY], c[VZ]); + smoothTriangle.interpUV = true; + smoothTriangle.texture(textures[tex]); + float umult = textures[tex].width; // apparently no check for textureMode is needed here + float vmult = textures[tex].height; + smoothTriangle.vertices[0][U] = a[U]*umult; + smoothTriangle.vertices[0][V] = a[V]*vmult; + smoothTriangle.vertices[1][U] = b[U]*umult; + smoothTriangle.vertices[1][V] = b[V]*vmult; + smoothTriangle.vertices[2][U] = c[U]*umult; + smoothTriangle.vertices[2][V] = c[V]*vmult; + } else { + smoothTriangle.interpUV = false; + textured = false; + } + + smoothTriangle.setVertices(a[TX], a[TY], a[TZ], + b[TX], b[TY], b[TZ], + c[TX], c[TY], c[TZ]); + + + if (!textured || smoothTriangle.precomputeAccurateTexturing()){ + smoothTriangle.render(); + } else { + // Something went wrong with the precomputation, + // so we need to fall back on normal PTriangle + // rendering. + failedToPrecalc = true; + } + } + + // Normal triangle rendering + // Note: this is not an end-if from the smoothed texturing mode + // because it's possible that the precalculation will fail and we + // need to fall back on normal rendering. + if (!s_enableAccurateTextures || failedToPrecalc || (frustumMode == false)){ + if (tex > -1 && textures[tex] != null) { + triangle.setTexture(textures[tex]); + triangle.setUV(a[U], a[V], b[U], b[V], c[U], c[V]); + } + + triangle.setIntensities(ar, ag, ab, a[A], + br, bg, bb, b[A], + cr, cg, cb, c[A]); + + triangle.setVertices(a[TX], a[TY], a[TZ], + b[TX], b[TY], b[TZ], + c[TX], c[TY], c[TZ]); + + triangle.render(); + } + + /* + // removing for 0149 with the return of P2D + if (drawing2D() && shifted){ + a[TX] -= shift; + a[TY] -= shift; + a[VX] -= shift*a[VW]; + a[VY] -= shift*a[VW]; + b[TX] -= shift; + b[TY] -= shift; + b[VX] -= shift*b[VW]; + b[VY] -= shift*b[VW]; + c[TX] -= shift; + c[TY] -= shift; + c[VX] -= shift*c[VW]; + c[VY] -= shift*c[VW]; + } + */ + } + } + + + protected void rawTriangles(int start, int stop) { + raw.colorMode(RGB, 1); + raw.noStroke(); + raw.beginShape(TRIANGLES); + + for (int i = start; i < stop; i++) { + float a[] = vertices[triangles[i][VERTEX1]]; + float b[] = vertices[triangles[i][VERTEX2]]; + float c[] = vertices[triangles[i][VERTEX3]]; + + float ar = clamp(triangleColors[i][0][TRI_DIFFUSE_R] + triangleColors[i][0][TRI_SPECULAR_R]); + float ag = clamp(triangleColors[i][0][TRI_DIFFUSE_G] + triangleColors[i][0][TRI_SPECULAR_G]); + float ab = clamp(triangleColors[i][0][TRI_DIFFUSE_B] + triangleColors[i][0][TRI_SPECULAR_B]); + float br = clamp(triangleColors[i][1][TRI_DIFFUSE_R] + triangleColors[i][1][TRI_SPECULAR_R]); + float bg = clamp(triangleColors[i][1][TRI_DIFFUSE_G] + triangleColors[i][1][TRI_SPECULAR_G]); + float bb = clamp(triangleColors[i][1][TRI_DIFFUSE_B] + triangleColors[i][1][TRI_SPECULAR_B]); + float cr = clamp(triangleColors[i][2][TRI_DIFFUSE_R] + triangleColors[i][2][TRI_SPECULAR_R]); + float cg = clamp(triangleColors[i][2][TRI_DIFFUSE_G] + triangleColors[i][2][TRI_SPECULAR_G]); + float cb = clamp(triangleColors[i][2][TRI_DIFFUSE_B] + triangleColors[i][2][TRI_SPECULAR_B]); + + int tex = triangles[i][TEXTURE_INDEX]; + PImage texImage = (tex > -1) ? textures[tex] : null; + if (texImage != null) { + if (raw.is3D()) { + if ((a[VW] != 0) && (b[VW] != 0) && (c[VW] != 0)) { + raw.fill(ar, ag, ab, a[A]); + raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW], a[U], a[V]); + raw.fill(br, bg, bb, b[A]); + raw.vertex(b[VX] / b[VW], b[VY] / b[VW], b[VZ] / b[VW], b[U], b[V]); + raw.fill(cr, cg, cb, c[A]); + raw.vertex(c[VX] / c[VW], c[VY] / c[VW], c[VZ] / c[VW], c[U], c[V]); + } + } else if (raw.is2D()) { + raw.fill(ar, ag, ab, a[A]); + raw.vertex(a[TX], a[TY], a[U], a[V]); + raw.fill(br, bg, bb, b[A]); + raw.vertex(b[TX], b[TY], b[U], b[V]); + raw.fill(cr, cg, cb, c[A]); + raw.vertex(c[TX], c[TY], c[U], c[V]); + } + } else { // no texture + if (raw.is3D()) { + if ((a[VW] != 0) && (b[VW] != 0) && (c[VW] != 0)) { + raw.fill(ar, ag, ab, a[A]); + raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW]); + raw.fill(br, bg, bb, b[A]); + raw.vertex(b[VX] / b[VW], b[VY] / b[VW], b[VZ] / b[VW]); + raw.fill(cr, cg, cb, c[A]); + raw.vertex(c[VX] / c[VW], c[VY] / c[VW], c[VZ] / c[VW]); + } + } else if (raw.is2D()) { + raw.fill(ar, ag, ab, a[A]); + raw.vertex(a[TX], a[TY]); + raw.fill(br, bg, bb, b[A]); + raw.vertex(b[TX], b[TY]); + raw.fill(cr, cg, cb, c[A]); + raw.vertex(c[TX], c[TY]); + } + } + } + + raw.endShape(); + } + + + ////////////////////////////////////////////////////////////// + + + //public void bezierVertex(float x2, float y2, + // float x3, float y3, + // float x4, float y4) + + + //public void bezierVertex(float x2, float y2, float z2, + // float x3, float y3, float z3, + // float x4, float y4, float z4) + + + + ////////////////////////////////////////////////////////////// + + + //public void curveVertex(float x, float y) + + + //public void curveVertex(float x, float y, float z) + + + + //////////////////////////////////////////////////////////// + + + /** + * Emit any sorted geometry that's been collected on this frame. + */ + public void flush() { + if (hints[ENABLE_DEPTH_SORT]) { + sort(); + } + render(); + + /* + if (triangleCount > 0) { + if (hints[ENABLE_DEPTH_SORT]) { + sortTriangles(); + } + renderTriangles(); + } + if (lineCount > 0) { + if (hints[ENABLE_DEPTH_SORT]) { + sortLines(); + } + renderLines(); + } + // Clear this out in case flush() is called again. + // For instance, with hint(ENABLE_DEPTH_SORT), it will be called + // once on endRaw(), and once again at endDraw(). + triangleCount = 0; + lineCount = 0; + */ + } + + + protected void render() { + if (pointCount > 0) { + renderPoints(0, pointCount); + if (raw != null) { + rawPoints(0, pointCount); + } + pointCount = 0; + } + if (lineCount > 0) { + renderLines(0, lineCount); + if (raw != null) { + rawLines(0, lineCount); + } + lineCount = 0; + pathCount = 0; + } + if (triangleCount > 0) { + renderTriangles(0, triangleCount); + if (raw != null) { + rawTriangles(0, triangleCount); + } + triangleCount = 0; + } + } + + + /** + * Handle depth sorting of geometry. Currently this only handles triangles, + * however in the future it will be expanded for points and lines, which + * will also need to be interspersed with one another while rendering. + */ + protected void sort() { + if (triangleCount > 0) { + sortTrianglesInternal(0, triangleCount-1); + } + } + + + private void sortTrianglesInternal(int i, int j) { + int pivotIndex = (i+j)/2; + sortTrianglesSwap(pivotIndex, j); + int k = sortTrianglesPartition(i-1, j); + sortTrianglesSwap(k, j); + if ((k-i) > 1) sortTrianglesInternal(i, k-1); + if ((j-k) > 1) sortTrianglesInternal(k+1, j); + } + + + private int sortTrianglesPartition(int left, int right) { + int pivot = right; + do { + while (sortTrianglesCompare(++left, pivot) < 0) { } + while ((right != 0) && + (sortTrianglesCompare(--right, pivot) > 0)) { } + sortTrianglesSwap(left, right); + } while (left < right); + sortTrianglesSwap(left, right); + return left; + } + + + private void sortTrianglesSwap(int a, int b) { + int tempi[] = triangles[a]; + triangles[a] = triangles[b]; + triangles[b] = tempi; + float tempf[][] = triangleColors[a]; + triangleColors[a] = triangleColors[b]; + triangleColors[b] = tempf; + } + + + private float sortTrianglesCompare(int a, int b) { + /* + if (Float.isNaN(vertices[triangles[a][VERTEX1]][TZ]) || + Float.isNaN(vertices[triangles[a][VERTEX2]][TZ]) || + Float.isNaN(vertices[triangles[a][VERTEX3]][TZ]) || + Float.isNaN(vertices[triangles[b][VERTEX1]][TZ]) || + Float.isNaN(vertices[triangles[b][VERTEX2]][TZ]) || + Float.isNaN(vertices[triangles[b][VERTEX3]][TZ])) { + System.err.println("NaN values in triangle"); + } + */ + return ((vertices[triangles[b][VERTEX1]][TZ] + + vertices[triangles[b][VERTEX2]][TZ] + + vertices[triangles[b][VERTEX3]][TZ]) - + (vertices[triangles[a][VERTEX1]][TZ] + + vertices[triangles[a][VERTEX2]][TZ] + + vertices[triangles[a][VERTEX3]][TZ])); + } + + + + ////////////////////////////////////////////////////////////// + + // POINT, LINE, TRIANGLE, QUAD + + // Because vertex(x, y) is mapped to vertex(x, y, 0), none of these commands + // need to be overridden from their default implementation in PGraphics. + + + //public void point(float x, float y) + + + //public void point(float x, float y, float z) + + + //public void line(float x1, float y1, float x2, float y2) + + + //public void line(float x1, float y1, float z1, + // float x2, float y2, float z2) + + + //public void triangle(float x1, float y1, float x2, float y2, + // float x3, float y3) + + + //public void quad(float x1, float y1, float x2, float y2, + // float x3, float y3, float x4, float y4) + + + + ////////////////////////////////////////////////////////////// + + // RECT + + + //public void rectMode(int mode) + + + //public void rect(float a, float b, float c, float d) + + + //protected void rectImpl(float x1, float y1, float x2, float y2) + + + + ////////////////////////////////////////////////////////////// + + // ELLIPSE + + + //public void ellipseMode(int mode) + + + //public void ellipse(float a, float b, float c, float d) + + + protected void ellipseImpl(float x, float y, float w, float h) { + float radiusH = w / 2; + float radiusV = h / 2; + + float centerX = x + radiusH; + float centerY = y + radiusV; + +// float sx1 = screenX(x, y); +// float sy1 = screenY(x, y); +// float sx2 = screenX(x+w, y+h); +// float sy2 = screenY(x+w, y+h); + + // returning to pre-1.0 version of algorithm because of problems + int rough = (int)(4+Math.sqrt(w+h)*3); + int accuracy = PApplet.constrain(rough, 6, 100); + + if (fill) { + // returning to pre-1.0 version of algorithm because of problems +// int rough = (int)(4+Math.sqrt(w+h)*3); +// int rough = (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / 20); +// int accuracy = PApplet.constrain(rough, 6, 100); + + float inc = (float)SINCOS_LENGTH / accuracy; + float val = 0; + + boolean strokeSaved = stroke; + stroke = false; + boolean smoothSaved = smooth; + if (smooth && stroke) { + smooth = false; + } + + beginShape(TRIANGLE_FAN); + normal(0, 0, 1); + vertex(centerX, centerY); + for (int i = 0; i < accuracy; i++) { + vertex(centerX + cosLUT[(int) val] * radiusH, + centerY + sinLUT[(int) val] * radiusV); + val = (val + inc) % SINCOS_LENGTH; + } + // back to the beginning + vertex(centerX + cosLUT[0] * radiusH, + centerY + sinLUT[0] * radiusV); + endShape(); + + stroke = strokeSaved; + smooth = smoothSaved; + } + + if (stroke) { +// int rough = (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / 8); +// int accuracy = PApplet.constrain(rough, 6, 100); + + float inc = (float)SINCOS_LENGTH / accuracy; + float val = 0; + + boolean savedFill = fill; + fill = false; + + val = 0; + beginShape(); + for (int i = 0; i < accuracy; i++) { + vertex(centerX + cosLUT[(int) val] * radiusH, + centerY + sinLUT[(int) val] * radiusV); + val = (val + inc) % SINCOS_LENGTH; + } + endShape(CLOSE); + + fill = savedFill; + } + } + + + //public void arc(float a, float b, float c, float d, + // float start, float stop) + + + protected void arcImpl(float x, float y, float w, float h, + float start, float stop) { + float hr = w / 2f; + float vr = h / 2f; + + float centerX = x + hr; + float centerY = y + vr; + + if (fill) { + // shut off stroke for a minute + boolean savedStroke = stroke; + stroke = false; + + int startLUT = (int) (0.5f + (start / TWO_PI) * SINCOS_LENGTH); + int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH); + + beginShape(TRIANGLE_FAN); + vertex(centerX, centerY); + int increment = 1; // what's a good algorithm? stopLUT - startLUT; + for (int i = startLUT; i < stopLUT; i += increment) { + int ii = i % SINCOS_LENGTH; + // modulo won't make the value positive + if (ii < 0) ii += SINCOS_LENGTH; + vertex(centerX + cosLUT[ii] * hr, + centerY + sinLUT[ii] * vr); + } + // draw last point explicitly for accuracy + vertex(centerX + cosLUT[stopLUT % SINCOS_LENGTH] * hr, + centerY + sinLUT[stopLUT % SINCOS_LENGTH] * vr); + endShape(); + + stroke = savedStroke; + } + + if (stroke) { + // Almost identical to above, but this uses a LINE_STRIP + // and doesn't include the first (center) vertex. + + boolean savedFill = fill; + fill = false; + + int startLUT = (int) (0.5f + (start / TWO_PI) * SINCOS_LENGTH); + int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH); + + beginShape(); //LINE_STRIP); + int increment = 1; // what's a good algorithm? stopLUT - startLUT; + for (int i = startLUT; i < stopLUT; i += increment) { + int ii = i % SINCOS_LENGTH; + if (ii < 0) ii += SINCOS_LENGTH; + vertex(centerX + cosLUT[ii] * hr, + centerY + sinLUT[ii] * vr); + } + // draw last point explicitly for accuracy + vertex(centerX + cosLUT[stopLUT % SINCOS_LENGTH] * hr, + centerY + sinLUT[stopLUT % SINCOS_LENGTH] * vr); + endShape(); + + fill = savedFill; + } + } + + + + ////////////////////////////////////////////////////////////// + + // BOX + + + //public void box(float size) + + + public void box(float w, float h, float d) { + if (triangle != null) { // triangle is null in gl + triangle.setCulling(true); + } + + super.box(w, h, d); + + if (triangle != null) { // triangle is null in gl + triangle.setCulling(false); + } + } + + + + ////////////////////////////////////////////////////////////// + + // SPHERE + + + //public void sphereDetail(int res) + + + //public void sphereDetail(int ures, int vres) + + + public void sphere(float r) { + if (triangle != null) { // triangle is null in gl + triangle.setCulling(true); + } + + super.sphere(r); + + if (triangle != null) { // triangle is null in gl + triangle.setCulling(false); + } + } + + + + ////////////////////////////////////////////////////////////// + + // BEZIER + + + //public float bezierPoint(float a, float b, float c, float d, float t) + + + //public float bezierTangent(float a, float b, float c, float d, float t) + + + //public void bezierDetail(int detail) + + + //public void bezier(float x1, float y1, + // float x2, float y2, + // float x3, float y3, + // float x4, float y4) + + + //public void bezier(float x1, float y1, float z1, + // float x2, float y2, float z2, + // float x3, float y3, float z3, + // float x4, float y4, float z4) + + + + ////////////////////////////////////////////////////////////// + + // CATMULL-ROM CURVES + + + //public float curvePoint(float a, float b, float c, float d, float t) + + + //public float curveTangent(float a, float b, float c, float d, float t) + + + //public void curveDetail(int detail) + + + //public void curveTightness(float tightness) + + + //public void curve(float x1, float y1, + // float x2, float y2, + // float x3, float y3, + // float x4, float y4) + + + //public void curve(float x1, float y1, float z1, + // float x2, float y2, float z2, + // float x3, float y3, float z3, + // float x4, float y4, float z4) + + + + ////////////////////////////////////////////////////////////// + + // SMOOTH + + + public void smooth() { + //showMethodWarning("smooth"); + s_enableAccurateTextures = true; + smooth = true; + } + + + public void noSmooth() { + s_enableAccurateTextures = false; + smooth = false; + } + + + + ////////////////////////////////////////////////////////////// + + // IMAGES + + + //public void imageMode(int mode) + + + //public void image(PImage image, float x, float y) + + + //public void image(PImage image, float x, float y, float c, float d) + + + //public void image(PImage image, + // float a, float b, float c, float d, + // int u1, int v1, int u2, int v2) + + + //protected void imageImpl(PImage image, + // float x1, float y1, float x2, float y2, + // int u1, int v1, int u2, int v2) + + + + ////////////////////////////////////////////////////////////// + + // SHAPE + + + //public void shapeMode(int mode) + + + //public void shape(PShape shape) + + + //public void shape(PShape shape, float x, float y) + + + //public void shape(PShape shape, float x, float y, float c, float d) + + + + ////////////////////////////////////////////////////////////// + + // TEXT SETTINGS + + // Only textModeCheck overridden from PGraphics, no textAlign, textAscent, + // textDescent, textFont, textLeading, textMode, textSize, textWidth + + + protected boolean textModeCheck(int mode) { + return (textMode == MODEL) || (textMode == SCREEN); + } + + + + ////////////////////////////////////////////////////////////// + + // TEXT + + // None of the variations of text() are overridden from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // TEXT IMPL + + // Not even the text drawing implementation stuff is overridden. + + + + ////////////////////////////////////////////////////////////// + + // MATRIX STACK + + + public void pushMatrix() { + if (matrixStackDepth == MATRIX_STACK_DEPTH) { + throw new RuntimeException(ERROR_PUSHMATRIX_OVERFLOW); + } + modelview.get(matrixStack[matrixStackDepth]); + modelviewInv.get(matrixInvStack[matrixStackDepth]); + matrixStackDepth++; + } + + + public void popMatrix() { + if (matrixStackDepth == 0) { + throw new RuntimeException(ERROR_PUSHMATRIX_UNDERFLOW); + } + matrixStackDepth--; + modelview.set(matrixStack[matrixStackDepth]); + modelviewInv.set(matrixInvStack[matrixStackDepth]); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX TRANSFORMATIONS + + + public void translate(float tx, float ty) { + translate(tx, ty, 0); + } + + + public void translate(float tx, float ty, float tz) { + forwardTransform.translate(tx, ty, tz); + reverseTransform.invTranslate(tx, ty, tz); + } + + + /** + * Two dimensional rotation. Same as rotateZ (this is identical + * to a 3D rotation along the z-axis) but included for clarity -- + * it'd be weird for people drawing 2D graphics to be using rotateZ. + * And they might kick our a-- for the confusion. + */ + public void rotate(float angle) { + rotateZ(angle); + } + + + public void rotateX(float angle) { + forwardTransform.rotateX(angle); + reverseTransform.invRotateX(angle); + } + + + public void rotateY(float angle) { + forwardTransform.rotateY(angle); + reverseTransform.invRotateY(angle); + } + + + public void rotateZ(float angle) { + forwardTransform.rotateZ(angle); + reverseTransform.invRotateZ(angle); + } + + + /** + * Rotate around an arbitrary vector, similar to glRotate(), + * except that it takes radians (instead of degrees). + */ + public void rotate(float angle, float v0, float v1, float v2) { + forwardTransform.rotate(angle, v0, v1, v2); + reverseTransform.invRotate(angle, v0, v1, v2); + } + + + /** + * Same as scale(s, s, s). + */ + public void scale(float s) { + scale(s, s, s); + } + + + /** + * Same as scale(sx, sy, 1). + */ + public void scale(float sx, float sy) { + scale(sx, sy, 1); + } + + + /** + * Scale in three dimensions. + */ + public void scale(float x, float y, float z) { + forwardTransform.scale(x, y, z); + reverseTransform.invScale(x, y, z); + } + + + public void shearX(float angle) { + float t = (float) Math.tan(angle); + applyMatrix(1, t, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void shearY(float angle) { + float t = (float) Math.tan(angle); + applyMatrix(1, 0, 0, 0, + t, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX MORE! + + + public void resetMatrix() { + forwardTransform.reset(); + reverseTransform.reset(); + } + + + public void applyMatrix(PMatrix2D source) { + applyMatrix(source.m00, source.m01, source.m02, + source.m10, source.m11, source.m12); + } + + + public void applyMatrix(float n00, float n01, float n02, + float n10, float n11, float n12) { + applyMatrix(n00, n01, n02, 0, + n10, n11, n12, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void applyMatrix(PMatrix3D source) { + applyMatrix(source.m00, source.m01, source.m02, source.m03, + source.m10, source.m11, source.m12, source.m13, + source.m20, source.m21, source.m22, source.m23, + source.m30, source.m31, source.m32, source.m33); + } + + + /** + * Apply a 4x4 transformation matrix. Same as glMultMatrix(). + * This call will be slow because it will try to calculate the + * inverse of the transform. So avoid it whenever possible. + */ + public void applyMatrix(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + + forwardTransform.apply(n00, n01, n02, n03, + n10, n11, n12, n13, + n20, n21, n22, n23, + n30, n31, n32, n33); + + reverseTransform.invApply(n00, n01, n02, n03, + n10, n11, n12, n13, + n20, n21, n22, n23, + n30, n31, n32, n33); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX GET/SET/PRINT + + + public PMatrix getMatrix() { + return modelview.get(); + } + + + //public PMatrix2D getMatrix(PMatrix2D target) + + + public PMatrix3D getMatrix(PMatrix3D target) { + if (target == null) { + target = new PMatrix3D(); + } + target.set(modelview); + return target; + } + + + //public void setMatrix(PMatrix source) + + + public void setMatrix(PMatrix2D source) { + // not efficient, but at least handles the inverse stuff. + resetMatrix(); + applyMatrix(source); + } + + + /** + * Set the current transformation to the contents of the specified source. + */ + public void setMatrix(PMatrix3D source) { + // not efficient, but at least handles the inverse stuff. + resetMatrix(); + applyMatrix(source); + } + + + /** + * Print the current model (or "transformation") matrix. + */ + public void printMatrix() { + modelview.print(); + } + + + /* + * This function checks if the modelview matrix is set up to likely be + * drawing in 2D. It merely checks if the non-translational piece of the + * matrix is unity. If this is to be used, it should be coupled with a + * check that the raw vertex coordinates lie in the z=0 plane. + * Mainly useful for applying sub-pixel shifts to avoid 2d artifacts + * in the screen plane. + * Added by ewjordan 6/13/07 + * + * TODO need to invert the logic here so that we can simply return + * the value, rather than calculating true/false and returning it. + */ + /* + private boolean drawing2D() { + if (modelview.m00 != 1.0f || + modelview.m11 != 1.0f || + modelview.m22 != 1.0f || // check scale + modelview.m01 != 0.0f || + modelview.m02 != 0.0f || // check rotational pieces + modelview.m10 != 0.0f || + modelview.m12 != 0.0f || + modelview.m20 != 0.0f || + modelview.m21 != 0.0f || + !((camera.m23-modelview.m23) <= EPSILON && + (camera.m23-modelview.m23) >= -EPSILON)) { // check for z-translation + // Something about the modelview matrix indicates 3d drawing + // (or rotated 2d, in which case 2d subpixel fixes probably aren't needed) + return false; + } else { + //The matrix is mapping z=0 vertices to the screen plane, + // which means it's likely that 2D drawing is happening. + return true; + } + } + */ + + + + ////////////////////////////////////////////////////////////// + + // CAMERA + + + /** + * Set matrix mode to the camera matrix (instead of the current + * transformation matrix). This means applyMatrix, resetMatrix, etc. + * will affect the camera. + *

+ * Note that the camera matrix is *not* the perspective matrix, + * it is in front of the modelview matrix (hence the name "model" + * and "view" for that matrix). + *

+ * beginCamera() specifies that all coordinate transforms until endCamera() + * should be pre-applied in inverse to the camera transform matrix. + * Note that this is only challenging when a user specifies an arbitrary + * matrix with applyMatrix(). Then that matrix will need to be inverted, + * which may not be possible. But take heart, if a user is applying a + * non-invertible matrix to the camera transform, then he is clearly + * up to no good, and we can wash our hands of those bad intentions. + *

+ * begin/endCamera clauses do not automatically reset the camera transform + * matrix. That's because we set up a nice default camera transform int + * setup(), and we expect it to hold through draw(). So we don't reset + * the camera transform matrix at the top of draw(). That means that an + * innocuous-looking clause like + *

+   * beginCamera();
+   * translate(0, 0, 10);
+   * endCamera();
+   * 
+ * at the top of draw(), will result in a runaway camera that shoots + * infinitely out of the screen over time. In order to prevent this, + * it is necessary to call some function that does a hard reset of the + * camera transform matrix inside of begin/endCamera. Two options are + *
+   * camera(); // sets up the nice default camera transform
+   * resetMatrix(); // sets up the identity camera transform
+   * 
+ * So to rotate a camera a constant amount, you might try + *
+   * beginCamera();
+   * camera();
+   * rotateY(PI/8);
+   * endCamera();
+   * 
+ */ + public void beginCamera() { + if (manipulatingCamera) { + throw new RuntimeException("beginCamera() cannot be called again " + + "before endCamera()"); + } else { + manipulatingCamera = true; + forwardTransform = cameraInv; + reverseTransform = camera; + } + } + + + /** + * Record the current settings into the camera matrix, and set + * the matrix mode back to the current transformation matrix. + *

+ * Note that this will destroy any settings to scale(), translate(), + * or whatever, because the final camera matrix will be copied + * (not multiplied) into the modelview. + */ + public void endCamera() { + if (!manipulatingCamera) { + throw new RuntimeException("Cannot call endCamera() " + + "without first calling beginCamera()"); + } + // reset the modelview to use this new camera matrix + modelview.set(camera); + modelviewInv.set(cameraInv); + + // set matrix mode back to modelview + forwardTransform = modelview; + reverseTransform = modelviewInv; + + // all done + manipulatingCamera = false; + } + + + /** + * Set camera to the default settings. + *

+ * Processing camera behavior: + *

+ * Camera behavior can be split into two separate components, camera + * transformation, and projection. The transformation corresponds to the + * physical location, orientation, and scale of the camera. In a physical + * camera metaphor, this is what can manipulated by handling the camera + * body (with the exception of scale, which doesn't really have a physcial + * analog). The projection corresponds to what can be changed by + * manipulating the lens. + *

+ * We maintain separate matrices to represent the camera transform and + * projection. An important distinction between the two is that the camera + * transform should be invertible, where the projection matrix should not, + * since it serves to map three dimensions to two. It is possible to bake + * the two matrices into a single one just by multiplying them together, + * but it isn't a good idea, since lighting, z-ordering, and z-buffering + * all demand a true camera z coordinate after modelview and camera + * transforms have been applied but before projection. If the camera + * transform and projection are combined there is no way to recover a + * good camera-space z-coordinate from a model coordinate. + *

+ * Fortunately, there are no functions that manipulate both camera + * transformation and projection. + *

+ * camera() sets the camera position, orientation, and center of the scene. + * It replaces the camera transform with a new one. This is different from + * gluLookAt(), but I think the only reason that GLU's lookat doesn't fully + * replace the camera matrix with the new one, but instead multiplies it, + * is that GL doesn't enforce the separation of camera transform and + * projection, so it wouldn't be safe (you'd probably stomp your projection). + *

+ * The transformation functions are the same ones used to manipulate the + * modelview matrix (scale, translate, rotate, etc.). But they are bracketed + * with beginCamera(), endCamera() to indicate that they should apply + * (in inverse), to the camera transformation matrix. + *

+ * This differs considerably from camera transformation in OpenGL. + * OpenGL only lets you say, apply everything from here out to the + * projection or modelview matrix. This makes it very hard to treat camera + * manipulation as if it were a physical camera. Imagine that you want to + * move your camera 100 units forward. In OpenGL, you need to apply the + * inverse of that transformation or else you'll move your scene 100 units + * forward--whether or not you've specified modelview or projection matrix. + * Remember they're just multiplied by model coods one after another. + * So in order to treat a camera like a physical camera, it is necessary + * to pre-apply inverse transforms to a matrix that will be applied to model + * coordinates. OpenGL provides nothing of this sort, but Processing does! + * This is the camera transform matrix. + */ + public void camera() { + camera(cameraX, cameraY, cameraZ, + cameraX, cameraY, 0, + 0, 1, 0); + } + + + /** + * More flexible method for dealing with camera(). + *

+ * The actual call is like gluLookat. Here's the real skinny on + * what does what: + *

+   * camera(); or
+   * camera(ex, ey, ez, cx, cy, cz, ux, uy, uz);
+   * 
+ * do not need to be called from with beginCamera();/endCamera(); + * That's because they always apply to the camera transformation, + * and they always totally replace it. That means that any coordinate + * transforms done before camera(); in draw() will be wiped out. + * It also means that camera() always operates in untransformed world + * coordinates. Therefore it is always redundant to call resetMatrix(); + * before camera(); This isn't technically true of gluLookat, but it's + * pretty much how it's used. + *

+ * Now, beginCamera(); and endCamera(); are useful if you want to move + * the camera around using transforms like translate(), etc. They will + * wipe out any coordinate system transforms that occur before them in + * draw(), but they will not automatically wipe out the camera transform. + * This means that they should be at the top of draw(). It also means + * that the following: + *

+   * beginCamera();
+   * rotateY(PI/8);
+   * endCamera();
+   * 
+ * will result in a camera that spins without stopping. If you want to + * just rotate a small constant amount, try this: + *
+   * beginCamera();
+   * camera(); // sets up the default view
+   * rotateY(PI/8);
+   * endCamera();
+   * 
+ * That will rotate a little off of the default view. Note that this + * is entirely equivalent to + *
+   * camera(); // sets up the default view
+   * beginCamera();
+   * rotateY(PI/8);
+   * endCamera();
+   * 
+ * because camera() doesn't care whether or not it's inside a + * begin/end clause. Basically it's safe to use camera() or + * camera(ex, ey, ez, cx, cy, cz, ux, uy, uz) as naked calls because + * they do all the matrix resetting automatically. + */ + public void camera(float eyeX, float eyeY, float eyeZ, + float centerX, float centerY, float centerZ, + float upX, float upY, float upZ) { + float z0 = eyeX - centerX; + float z1 = eyeY - centerY; + float z2 = eyeZ - centerZ; + float mag = sqrt(z0*z0 + z1*z1 + z2*z2); + + if (mag != 0) { + z0 /= mag; + z1 /= mag; + z2 /= mag; + } + + float y0 = upX; + float y1 = upY; + float y2 = upZ; + + float x0 = y1*z2 - y2*z1; + float x1 = -y0*z2 + y2*z0; + float x2 = y0*z1 - y1*z0; + + y0 = z1*x2 - z2*x1; + y1 = -z0*x2 + z2*x0; + y2 = z0*x1 - z1*x0; + + mag = sqrt(x0*x0 + x1*x1 + x2*x2); + if (mag != 0) { + x0 /= mag; + x1 /= mag; + x2 /= mag; + } + + mag = sqrt(y0*y0 + y1*y1 + y2*y2); + if (mag != 0) { + y0 /= mag; + y1 /= mag; + y2 /= mag; + } + + // just does an apply to the main matrix, + // since that'll be copied out on endCamera + camera.set(x0, x1, x2, 0, + y0, y1, y2, 0, + z0, z1, z2, 0, + 0, 0, 0, 1); + camera.translate(-eyeX, -eyeY, -eyeZ); + + cameraInv.reset(); + cameraInv.invApply(x0, x1, x2, 0, + y0, y1, y2, 0, + z0, z1, z2, 0, + 0, 0, 0, 1); + cameraInv.translate(eyeX, eyeY, eyeZ); + + modelview.set(camera); + modelviewInv.set(cameraInv); + } + + + /** + * Print the current camera matrix. + */ + public void printCamera() { + camera.print(); + } + + + ////////////////////////////////////////////////////////////// + + // PROJECTION + + + /** + * Calls ortho() with the proper parameters for Processing's + * standard orthographic projection. + */ + public void ortho() { + ortho(0, width, 0, height, -10, 10); + } + + + /** + * Similar to gluOrtho(), but wipes out the current projection matrix. + *

+ * Implementation partially based on Mesa's matrix.c. + */ + public void ortho(float left, float right, + float bottom, float top, + float near, float far) { + float x = 2.0f / (right - left); + float y = 2.0f / (top - bottom); + float z = -2.0f / (far - near); + + float tx = -(right + left) / (right - left); + float ty = -(top + bottom) / (top - bottom); + float tz = -(far + near) / (far - near); + + projection.set(x, 0, 0, tx, + 0, y, 0, ty, + 0, 0, z, tz, + 0, 0, 0, 1); + updateProjection(); + + frustumMode = false; + } + + + /** + * Calls perspective() with Processing's standard coordinate projection. + *

+ * Projection functions: + *

    + *
  • frustrum() + *
  • ortho() + *
  • perspective() + *
+ * Each of these three functions completely replaces the projection + * matrix with a new one. They can be called inside setup(), and their + * effects will be felt inside draw(). At the top of draw(), the projection + * matrix is not reset. Therefore the last projection function to be + * called always dominates. On resize, the default projection is always + * established, which has perspective. + *

+ * This behavior is pretty much familiar from OpenGL, except where + * functions replace matrices, rather than multiplying against the + * previous. + *

+ */ + public void perspective() { + perspective(cameraFOV, cameraAspect, cameraNear, cameraFar); + } + + + /** + * Similar to gluPerspective(). Implementation based on Mesa's glu.c + */ + public void perspective(float fov, float aspect, float zNear, float zFar) { + //float ymax = zNear * tan(fovy * PI / 360.0f); + float ymax = zNear * (float) Math.tan(fov / 2); + float ymin = -ymax; + + float xmin = ymin * aspect; + float xmax = ymax * aspect; + + frustum(xmin, xmax, ymin, ymax, zNear, zFar); + } + + + /** + * Same as glFrustum(), except that it wipes out (rather than + * multiplies against) the current perspective matrix. + *

+ * Implementation based on the explanation in the OpenGL blue book. + */ + public void frustum(float left, float right, float bottom, + float top, float znear, float zfar) { + + leftScreen = left; + rightScreen = right; + bottomScreen = bottom; + topScreen = top; + nearPlane = znear; + frustumMode = true; + + //System.out.println(projection); + projection.set((2*znear)/(right-left), 0, (right+left)/(right-left), 0, + 0, (2*znear)/(top-bottom), (top+bottom)/(top-bottom), 0, + 0, 0, -(zfar+znear)/(zfar-znear),-(2*zfar*znear)/(zfar-znear), + 0, 0, -1, 0); + updateProjection(); + } + + + /** Called after the 'projection' PMatrix3D has changed. */ + protected void updateProjection() { + } + + + /** + * Print the current projection matrix. + */ + public void printProjection() { + projection.print(); + } + + + + ////////////////////////////////////////////////////////////// + + // SCREEN AND MODEL COORDS + + + public float screenX(float x, float y) { + return screenX(x, y, 0); + } + + + public float screenY(float x, float y) { + return screenY(x, y, 0); + } + + + public float screenX(float x, float y, float z) { + float ax = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + float ay = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + float az = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + float aw = + modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33; + + float ox = + projection.m00*ax + projection.m01*ay + + projection.m02*az + projection.m03*aw; + float ow = + projection.m30*ax + projection.m31*ay + + projection.m32*az + projection.m33*aw; + + if (ow != 0) ox /= ow; + return width * (1 + ox) / 2.0f; + } + + + public float screenY(float x, float y, float z) { + float ax = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + float ay = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + float az = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + float aw = + modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33; + + float oy = + projection.m10*ax + projection.m11*ay + + projection.m12*az + projection.m13*aw; + float ow = + projection.m30*ax + projection.m31*ay + + projection.m32*az + projection.m33*aw; + + if (ow != 0) oy /= ow; + return height * (1 + oy) / 2.0f; + } + + + public float screenZ(float x, float y, float z) { + float ax = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + float ay = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + float az = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + float aw = + modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33; + + float oz = + projection.m20*ax + projection.m21*ay + + projection.m22*az + projection.m23*aw; + float ow = + projection.m30*ax + projection.m31*ay + + projection.m32*az + projection.m33*aw; + + if (ow != 0) oz /= ow; + return (oz + 1) / 2.0f; + } + + + public float modelX(float x, float y, float z) { + float ax = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + float ay = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + float az = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + float aw = + modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33; + + float ox = + cameraInv.m00*ax + cameraInv.m01*ay + + cameraInv.m02*az + cameraInv.m03*aw; + float ow = + cameraInv.m30*ax + cameraInv.m31*ay + + cameraInv.m32*az + cameraInv.m33*aw; + + return (ow != 0) ? ox / ow : ox; + } + + + public float modelY(float x, float y, float z) { + float ax = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + float ay = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + float az = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + float aw = + modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33; + + float oy = + cameraInv.m10*ax + cameraInv.m11*ay + + cameraInv.m12*az + cameraInv.m13*aw; + float ow = + cameraInv.m30*ax + cameraInv.m31*ay + + cameraInv.m32*az + cameraInv.m33*aw; + + return (ow != 0) ? oy / ow : oy; + } + + + public float modelZ(float x, float y, float z) { + float ax = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + float ay = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + float az = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + float aw = + modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33; + + float oz = + cameraInv.m20*ax + cameraInv.m21*ay + + cameraInv.m22*az + cameraInv.m23*aw; + float ow = + cameraInv.m30*ax + cameraInv.m31*ay + + cameraInv.m32*az + cameraInv.m33*aw; + + return (ow != 0) ? oz / ow : oz; + } + + + + ////////////////////////////////////////////////////////////// + + // STYLE + + // pushStyle(), popStyle(), style() and getStyle() inherited. + + + + ////////////////////////////////////////////////////////////// + + // STROKE CAP/JOIN/WEIGHT + + +// public void strokeWeight(float weight) { +// if (weight != DEFAULT_STROKE_WEIGHT) { +// showMethodWarning("strokeWeight"); +// } +// } + + + public void strokeJoin(int join) { + if (join != DEFAULT_STROKE_JOIN) { + showMethodWarning("strokeJoin"); + } + } + + + public void strokeCap(int cap) { + if (cap != DEFAULT_STROKE_CAP) { + showMethodWarning("strokeCap"); + } + } + + + + ////////////////////////////////////////////////////////////// + + // STROKE COLOR + + // All methods inherited from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // TINT COLOR + + // All methods inherited from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // FILL COLOR + + + protected void fillFromCalc() { + super.fillFromCalc(); + ambientFromCalc(); + } + + + + ////////////////////////////////////////////////////////////// + + // MATERIAL PROPERTIES + + // ambient, specular, shininess, and emissive all inherited. + + + + ////////////////////////////////////////////////////////////// + + // LIGHTS + + + PVector lightPositionVec = new PVector(); + PVector lightDirectionVec = new PVector(); + + /** + * Sets up an ambient and directional light. + *

+   * The Lighting Skinny:
+   *
+   * The way lighting works is complicated enough that it's worth
+   * producing a document to describe it. Lighting calculations proceed
+   * pretty much exactly as described in the OpenGL red book.
+   *
+   * Light-affecting material properties:
+   *
+   *   AMBIENT COLOR
+   *   - multiplies by light's ambient component
+   *   - for believability this should match diffuse color
+   *
+   *   DIFFUSE COLOR
+   *   - multiplies by light's diffuse component
+   *
+   *   SPECULAR COLOR
+   *   - multiplies by light's specular component
+   *   - usually less colored than diffuse/ambient
+   *
+   *   SHININESS
+   *   - the concentration of specular effect
+   *   - this should be set pretty high (20-50) to see really
+   *     noticeable specularity
+   *
+   *   EMISSIVE COLOR
+   *   - constant additive color effect
+   *
+   * Light types:
+   *
+   *   AMBIENT
+   *   - one color
+   *   - no specular color
+   *   - no direction
+   *   - may have falloff (constant, linear, and quadratic)
+   *   - may have position (which matters in non-constant falloff case)
+   *   - multiplies by a material's ambient reflection
+   *
+   *   DIRECTIONAL
+   *   - has diffuse color
+   *   - has specular color
+   *   - has direction
+   *   - no position
+   *   - no falloff
+   *   - multiplies by a material's diffuse and specular reflections
+   *
+   *   POINT
+   *   - has diffuse color
+   *   - has specular color
+   *   - has position
+   *   - no direction
+   *   - may have falloff (constant, linear, and quadratic)
+   *   - multiplies by a material's diffuse and specular reflections
+   *
+   *   SPOT
+   *   - has diffuse color
+   *   - has specular color
+   *   - has position
+   *   - has direction
+   *   - has cone angle (set to half the total cone angle)
+   *   - has concentration value
+   *   - may have falloff (constant, linear, and quadratic)
+   *   - multiplies by a material's diffuse and specular reflections
+   *
+   * Normal modes:
+   *
+   * All of the primitives (rect, box, sphere, etc.) have their normals
+   * set nicely. During beginShape/endShape normals can be set by the user.
+   *
+   *   AUTO-NORMAL
+   *   - if no normal is set during the shape, we are in auto-normal mode
+   *   - auto-normal calculates one normal per triangle (face-normal mode)
+   *
+   *   SHAPE-NORMAL
+   *   - if one normal is set during the shape, it will be used for
+   *     all vertices
+   *
+   *   VERTEX-NORMAL
+   *   - if multiple normals are set, each normal applies to
+   *     subsequent vertices
+   *   - (except for the first one, which applies to previous
+   *     and subsequent vertices)
+   *
+   * Efficiency consequences:
+   *
+   *   There is a major efficiency consequence of position-dependent
+   *   lighting calculations per vertex. (See below for determining
+   *   whether lighting is vertex position-dependent.) If there is no
+   *   position dependency then the only factors that affect the lighting
+   *   contribution per vertex are its colors and its normal.
+   *   There is a major efficiency win if
+   *
+   *   1) lighting is not position dependent
+   *   2) we are in AUTO-NORMAL or SHAPE-NORMAL mode
+   *
+   *   because then we can calculate one lighting contribution per shape
+   *   (SHAPE-NORMAL) or per triangle (AUTO-NORMAL) and simply multiply it
+   *   into the vertex colors. The converse is our worst-case performance when
+   *
+   *   1) lighting is position dependent
+   *   2) we are in AUTO-NORMAL mode
+   *
+   *   because then we must calculate lighting per-face * per-vertex.
+   *   Each vertex has a different lighting contribution per face in
+   *   which it appears. Yuck.
+   *
+   * Determining vertex position dependency:
+   *
+   *   If any of the following factors are TRUE then lighting is
+   *   vertex position dependent:
+   *
+   *   1) Any lights uses non-constant falloff
+   *   2) There are any point or spot lights
+   *   3) There is a light with specular color AND there is a
+   *      material with specular color
+   *
+   * So worth noting is that default lighting (a no-falloff ambient
+   * and a directional without specularity) is not position-dependent.
+   * We should capitalize.
+   *
+   * Simon Greenwold, April 2005
+   * 
+ */ + public void lights() { + // need to make sure colorMode is RGB 255 here + int colorModeSaved = colorMode; + colorMode = RGB; + + lightFalloff(1, 0, 0); + lightSpecular(0, 0, 0); + + ambientLight(colorModeX * 0.5f, + colorModeY * 0.5f, + colorModeZ * 0.5f); + directionalLight(colorModeX * 0.5f, + colorModeY * 0.5f, + colorModeZ * 0.5f, + 0, 0, -1); + + colorMode = colorModeSaved; + + lightingDependsOnVertexPosition = false; + } + + + /** + * Turn off all lights. + */ + public void noLights() { + // write any queued geometry, because lighting will be goofed after + flush(); + // set the light count back to zero + lightCount = 0; + } + + + /** + * Add an ambient light based on the current color mode. + */ + public void ambientLight(float r, float g, float b) { + ambientLight(r, g, b, 0, 0, 0); + } + + + /** + * Add an ambient light based on the current color mode. + * This version includes an (x, y, z) position for situations + * where the falloff distance is used. + */ + public void ambientLight(float r, float g, float b, + float x, float y, float z) { + if (lightCount == MAX_LIGHTS) { + throw new RuntimeException("can only create " + MAX_LIGHTS + " lights"); + } + colorCalc(r, g, b); + lightDiffuse[lightCount][0] = calcR; + lightDiffuse[lightCount][1] = calcG; + lightDiffuse[lightCount][2] = calcB; + + lightType[lightCount] = AMBIENT; + lightFalloffConstant[lightCount] = currentLightFalloffConstant; + lightFalloffLinear[lightCount] = currentLightFalloffLinear; + lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic; + lightPosition(lightCount, x, y, z); + lightCount++; + //return lightCount-1; + } + + + public void directionalLight(float r, float g, float b, + float nx, float ny, float nz) { + if (lightCount == MAX_LIGHTS) { + throw new RuntimeException("can only create " + MAX_LIGHTS + " lights"); + } + colorCalc(r, g, b); + lightDiffuse[lightCount][0] = calcR; + lightDiffuse[lightCount][1] = calcG; + lightDiffuse[lightCount][2] = calcB; + + lightType[lightCount] = DIRECTIONAL; + lightFalloffConstant[lightCount] = currentLightFalloffConstant; + lightFalloffLinear[lightCount] = currentLightFalloffLinear; + lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic; + lightSpecular[lightCount][0] = currentLightSpecular[0]; + lightSpecular[lightCount][1] = currentLightSpecular[1]; + lightSpecular[lightCount][2] = currentLightSpecular[2]; + lightDirection(lightCount, nx, ny, nz); + lightCount++; + } + + + public void pointLight(float r, float g, float b, + float x, float y, float z) { + if (lightCount == MAX_LIGHTS) { + throw new RuntimeException("can only create " + MAX_LIGHTS + " lights"); + } + colorCalc(r, g, b); + lightDiffuse[lightCount][0] = calcR; + lightDiffuse[lightCount][1] = calcG; + lightDiffuse[lightCount][2] = calcB; + + lightType[lightCount] = POINT; + lightFalloffConstant[lightCount] = currentLightFalloffConstant; + lightFalloffLinear[lightCount] = currentLightFalloffLinear; + lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic; + lightSpecular[lightCount][0] = currentLightSpecular[0]; + lightSpecular[lightCount][1] = currentLightSpecular[1]; + lightSpecular[lightCount][2] = currentLightSpecular[2]; + lightPosition(lightCount, x, y, z); + lightCount++; + + lightingDependsOnVertexPosition = true; + } + + + public void spotLight(float r, float g, float b, + float x, float y, float z, + float nx, float ny, float nz, + float angle, float concentration) { + if (lightCount == MAX_LIGHTS) { + throw new RuntimeException("can only create " + MAX_LIGHTS + " lights"); + } + colorCalc(r, g, b); + lightDiffuse[lightCount][0] = calcR; + lightDiffuse[lightCount][1] = calcG; + lightDiffuse[lightCount][2] = calcB; + + lightType[lightCount] = SPOT; + lightFalloffConstant[lightCount] = currentLightFalloffConstant; + lightFalloffLinear[lightCount] = currentLightFalloffLinear; + lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic; + lightSpecular[lightCount][0] = currentLightSpecular[0]; + lightSpecular[lightCount][1] = currentLightSpecular[1]; + lightSpecular[lightCount][2] = currentLightSpecular[2]; + lightPosition(lightCount, x, y, z); + lightDirection(lightCount, nx, ny, nz); + lightSpotAngle[lightCount] = angle; + lightSpotAngleCos[lightCount] = Math.max(0, (float) Math.cos(angle)); + lightSpotConcentration[lightCount] = concentration; + lightCount++; + + lightingDependsOnVertexPosition = true; + } + + + /** + * Set the light falloff rates for the last light that was created. + * Default is lightFalloff(1, 0, 0). + */ + public void lightFalloff(float constant, float linear, float quadratic) { + currentLightFalloffConstant = constant; + currentLightFalloffLinear = linear; + currentLightFalloffQuadratic = quadratic; + + lightingDependsOnVertexPosition = true; + } + + + /** + * Set the specular color of the last light created. + */ + public void lightSpecular(float x, float y, float z) { + colorCalc(x, y, z); + currentLightSpecular[0] = calcR; + currentLightSpecular[1] = calcG; + currentLightSpecular[2] = calcB; + + lightingDependsOnVertexPosition = true; + } + + + /** + * internal function to set the light position + * based on the current modelview matrix. + */ + protected void lightPosition(int num, float x, float y, float z) { + lightPositionVec.set(x, y, z); + modelview.mult(lightPositionVec, lightPosition[num]); + /* + lightPosition[num][0] = + modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03; + lightPosition[num][1] = + modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13; + lightPosition[num][2] = + modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23; + */ + } + + + /** + * internal function to set the light direction + * based on the current modelview matrix. + */ + protected void lightDirection(int num, float x, float y, float z) { + lightNormal[num].set(modelviewInv.m00*x + modelviewInv.m10*y + modelviewInv.m20*z + modelviewInv.m30, + modelviewInv.m01*x + modelviewInv.m11*y + modelviewInv.m21*z + modelviewInv.m31, + modelviewInv.m02*x + modelviewInv.m12*y + modelviewInv.m22*z + modelviewInv.m32); + lightNormal[num].normalize(); + + /* + lightDirectionVec.set(x, y, z); + System.out.println("dir vec " + lightDirectionVec); + //modelviewInv.mult(lightDirectionVec, lightNormal[num]); + modelviewInv.cmult(lightDirectionVec, lightNormal[num]); + System.out.println("cmult vec " + lightNormal[num]); + lightNormal[num].normalize(); + System.out.println("setting light direction " + lightNormal[num]); + */ + + /* + // Multiply by inverse transpose. + lightNormal[num][0] = + modelviewInv.m00*x + modelviewInv.m10*y + + modelviewInv.m20*z + modelviewInv.m30; + lightNormal[num][1] = + modelviewInv.m01*x + modelviewInv.m11*y + + modelviewInv.m21*z + modelviewInv.m31; + lightNormal[num][2] = + modelviewInv.m02*x + modelviewInv.m12*y + + modelviewInv.m22*z + modelviewInv.m32; + + float n = mag(lightNormal[num][0], lightNormal[num][1], lightNormal[num][2]); + if (n == 0 || n == 1) return; + + lightNormal[num][0] /= n; + lightNormal[num][1] /= n; + lightNormal[num][2] /= n; + */ + } + + + + ////////////////////////////////////////////////////////////// + + // BACKGROUND + + // Base background() variations inherited from PGraphics. + + + protected void backgroundImpl(PImage image) { + System.arraycopy(image.pixels, 0, pixels, 0, pixels.length); + Arrays.fill(zbuffer, Float.MAX_VALUE); + } + + + /** + * Clear pixel buffer. With P3D and OPENGL, this also clears the zbuffer. + */ + protected void backgroundImpl() { + Arrays.fill(pixels, backgroundColor); + Arrays.fill(zbuffer, Float.MAX_VALUE); + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR MODE + + // all colorMode() variations inherited from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // COLOR CALCULATIONS + + // protected colorCalc and colorCalcARGB inherited. + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE STUFFING + + // final color() variations inherited. + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE EXTRACTION + + // final methods alpha, red, green, blue, + // hue, saturation, and brightness all inherited. + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE INTERPOLATION + + // both lerpColor variants inherited. + + + + ////////////////////////////////////////////////////////////// + + // BEGIN/END RAW + + // beginRaw, endRaw() both inherited. + + + + ////////////////////////////////////////////////////////////// + + // WARNINGS and EXCEPTIONS + + // showWarning and showException inherited. + + + + ////////////////////////////////////////////////////////////// + + // RENDERER SUPPORT QUERIES + + + //public boolean displayable() + + + public boolean is2D() { + return false; + } + + + public boolean is3D() { + return true; + } + + + + ////////////////////////////////////////////////////////////// + + // PIMAGE METHODS + + // All these methods are inherited, because this render has a + // pixels[] array that can be accessed directly. + + // getImage + // setCache, getCache, removeCache + // isModified, setModified + // loadPixels, updatePixels + // resize + // get, getImpl, set, setImpl + // mask + // filter + // copy + // blendColor, blend + + + + ////////////////////////////////////////////////////////////// + + // MATH (internal use only) + + + private final float sqrt(float a) { + return (float) Math.sqrt(a); + } + + + private final float mag(float a, float b, float c) { + return (float) Math.sqrt(a*a + b*b + c*c); + } + + + private final float clamp(float a) { + return (a < 1) ? a : 1; + } + + + private final float abs(float a) { + return (a < 0) ? -a : a; + } + + + private float dot(float ax, float ay, float az, + float bx, float by, float bz) { + return ax*bx + ay*by + az*bz; + } + + + /* + private final void cross(float a0, float a1, float a2, + float b0, float b1, float b2, + float[] out) { + out[0] = a1*b2 - a2*b1; + out[1] = a2*b0 - a0*b2; + out[2] = a0*b1 - a1*b0; + } + */ + + + private final void cross(float a0, float a1, float a2, + float b0, float b1, float b2, + PVector out) { + out.x = a1*b2 - a2*b1; + out.y = a2*b0 - a0*b2; + out.z = a0*b1 - a1*b0; + } + + + /* + private final void cross(float[] a, float[] b, float[] out) { + out[0] = a[1]*b[2] - a[2]*b[1]; + out[1] = a[2]*b[0] - a[0]*b[2]; + out[2] = a[0]*b[1] - a[1]*b[0]; + } + */ +} + diff --git a/support/Processing_core_src/processing/core/PGraphicsJava2D.java b/support/Processing_core_src/processing/core/PGraphicsJava2D.java new file mode 100644 index 0000000..f72a566 --- /dev/null +++ b/support/Processing_core_src/processing/core/PGraphicsJava2D.java @@ -0,0 +1,1847 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2005-08 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.*; +import java.awt.geom.*; +import java.awt.image.*; + + +/** + * Subclass for PGraphics that implements the graphics API using Java2D. + * + *

Pixel operations too slow? As of release 0085 (the first beta), + * the default renderer uses Java2D. It's more accurate than the renderer + * used in alpha releases of Processing (it handles stroke caps and joins, + * and has better polygon tessellation), but it's super slow for handling + * pixels. At least until we get a chance to get the old 2D renderer + * (now called P2D) working in a similar fashion, you can use + * size(w, h, P3D) instead of size(w, h) which will + * be faster for general pixel flipping madness.

+ * + *

To get access to the Java 2D "Graphics2D" object for the default + * renderer, use: + *

Graphics2D g2 = ((PGraphicsJava2D)g).g2;
+ * This will let you do Java 2D stuff directly, but is not supported in + * any way shape or form. Which just means "have fun, but don't complain + * if it breaks."

+ */ +public class PGraphicsJava2D extends PGraphics /*PGraphics2D*/ { + + public Graphics2D g2; + GeneralPath gpath; + + /// break the shape at the next vertex (next vertex() call is a moveto()) + boolean breakShape; + + /// coordinates for internal curve calculation + float[] curveCoordX; + float[] curveCoordY; + float[] curveDrawX; + float[] curveDrawY; + + int transformCount; + AffineTransform transformStack[] = + new AffineTransform[MATRIX_STACK_DEPTH]; + double[] transform = new double[6]; + + Line2D.Float line = new Line2D.Float(); + Ellipse2D.Float ellipse = new Ellipse2D.Float(); + Rectangle2D.Float rect = new Rectangle2D.Float(); + Arc2D.Float arc = new Arc2D.Float(); + + protected Color tintColorObject; + + protected Color fillColorObject; + public boolean fillGradient; + public Paint fillGradientObject; + + protected Color strokeColorObject; + public boolean strokeGradient; + public Paint strokeGradientObject; + + + + ////////////////////////////////////////////////////////////// + + // INTERNAL + + + public PGraphicsJava2D() { } + + + //public void setParent(PApplet parent) + + + //public void setPrimary(boolean primary) + + + //public void setPath(String path) + + + /** + * Called in response to a resize event, handles setting the + * new width and height internally, as well as re-allocating + * the pixel buffer for the new size. + * + * Note that this will nuke any cameraMode() settings. + */ + public void setSize(int iwidth, int iheight) { // ignore + width = iwidth; + height = iheight; + width1 = width - 1; + height1 = height - 1; + + allocate(); + reapplySettings(); + } + + + // broken out because of subclassing for opengl + protected void allocate() { +// System.out.println("PGraphicsJava2D allocate() " + width + " " + height); +// System.out.println("allocate " + Thread.currentThread().getName()); + image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + g2 = (Graphics2D) image.getGraphics(); + // can't un-set this because this may be only a resize + // http://dev.processing.org/bugs/show_bug.cgi?id=463 + //defaultsInited = false; + //checkSettings(); + //reapplySettings = true; + } + + + //public void dispose() + + + + ////////////////////////////////////////////////////////////// + + // FRAME + + + public boolean canDraw() { + return true; + } + + + public void beginDraw() { + checkSettings(); + + resetMatrix(); // reset model matrix + + // reset vertices + vertexCount = 0; + } + + + public void endDraw() { + // hm, mark pixels as changed, because this will instantly do a full + // copy of all the pixels to the surface.. so that's kind of a mess. + //updatePixels(); + + // TODO this is probably overkill for most tasks... + if (!primarySurface) { + loadPixels(); + } + modified = true; + } + + + + ////////////////////////////////////////////////////////////// + + // SETTINGS + + + //protected void checkSettings() + + + //protected void defaultSettings() + + + //protected void reapplySettings() + + + + ////////////////////////////////////////////////////////////// + + // HINT + + + //public void hint(int which) + + + + ////////////////////////////////////////////////////////////// + + // SHAPES + + + //public void beginShape(int kind) + + + public void beginShape(int kind) { + //super.beginShape(kind); + shape = kind; + vertexCount = 0; + curveVertexCount = 0; + + // set gpath to null, because when mixing curves and straight + // lines, vertexCount will be set back to zero, so vertexCount == 1 + // is no longer a good indicator of whether the shape is new. + // this way, just check to see if gpath is null, and if it isn't + // then just use it to continue the shape. + gpath = null; + } + + + //public boolean edge(boolean e) + + + //public void normal(float nx, float ny, float nz) { + + + //public void textureMode(int mode) + + + public void texture(PImage image) { + showMethodWarning("texture"); + } + + + public void vertex(float x, float y) { + curveVertexCount = 0; + //float vertex[]; + + if (vertexCount == vertices.length) { + float temp[][] = new float[vertexCount<<1][VERTEX_FIELD_COUNT]; + System.arraycopy(vertices, 0, temp, 0, vertexCount); + vertices = temp; + //message(CHATTER, "allocating more vertices " + vertices.length); + } + // not everyone needs this, but just easier to store rather + // than adding another moving part to the code... + vertices[vertexCount][X] = x; + vertices[vertexCount][Y] = y; + vertexCount++; + + switch (shape) { + + case POINTS: + point(x, y); + break; + + case LINES: + if ((vertexCount % 2) == 0) { + line(vertices[vertexCount-2][X], + vertices[vertexCount-2][Y], x, y); + } + break; + + case TRIANGLES: + if ((vertexCount % 3) == 0) { + triangle(vertices[vertexCount - 3][X], + vertices[vertexCount - 3][Y], + vertices[vertexCount - 2][X], + vertices[vertexCount - 2][Y], + x, y); + } + break; + + case TRIANGLE_STRIP: + if (vertexCount >= 3) { + triangle(vertices[vertexCount - 2][X], + vertices[vertexCount - 2][Y], + vertices[vertexCount - 1][X], + vertices[vertexCount - 1][Y], + vertices[vertexCount - 3][X], + vertices[vertexCount - 3][Y]); + } + break; + + case TRIANGLE_FAN: + if (vertexCount == 3) { + triangle(vertices[0][X], vertices[0][Y], + vertices[1][X], vertices[1][Y], + x, y); + } else if (vertexCount > 3) { + gpath = new GeneralPath(); + // when vertexCount > 3, draw an un-closed triangle + // for indices 0 (center), previous, current + gpath.moveTo(vertices[0][X], + vertices[0][Y]); + gpath.lineTo(vertices[vertexCount - 2][X], + vertices[vertexCount - 2][Y]); + gpath.lineTo(x, y); + drawShape(gpath); + } + break; + + case QUADS: + if ((vertexCount % 4) == 0) { + quad(vertices[vertexCount - 4][X], + vertices[vertexCount - 4][Y], + vertices[vertexCount - 3][X], + vertices[vertexCount - 3][Y], + vertices[vertexCount - 2][X], + vertices[vertexCount - 2][Y], + x, y); + } + break; + + case QUAD_STRIP: + // 0---2---4 + // | | | + // 1---3---5 + if ((vertexCount >= 4) && ((vertexCount % 2) == 0)) { + quad(vertices[vertexCount - 4][X], + vertices[vertexCount - 4][Y], + vertices[vertexCount - 2][X], + vertices[vertexCount - 2][Y], + x, y, + vertices[vertexCount - 3][X], + vertices[vertexCount - 3][Y]); + } + break; + + case POLYGON: + if (gpath == null) { + gpath = new GeneralPath(); + gpath.moveTo(x, y); + } else if (breakShape) { + gpath.moveTo(x, y); + breakShape = false; + } else { + gpath.lineTo(x, y); + } + break; + } + } + + + public void vertex(float x, float y, float z) { + showDepthWarningXYZ("vertex"); + } + + + public void vertex(float x, float y, float u, float v) { + showVariationWarning("vertex(x, y, u, v)"); + } + + + public void vertex(float x, float y, float z, float u, float v) { + showDepthWarningXYZ("vertex"); + } + + + public void breakShape() { + breakShape = true; + } + + + public void endShape(int mode) { + if (gpath != null) { // make sure something has been drawn + if (shape == POLYGON) { + if (mode == CLOSE) { + gpath.closePath(); + } + drawShape(gpath); + } + } + shape = 0; + } + + + + ////////////////////////////////////////////////////////////// + + // BEZIER VERTICES + + + public void bezierVertex(float x1, float y1, + float x2, float y2, + float x3, float y3) { + bezierVertexCheck(); + gpath.curveTo(x1, y1, x2, y2, x3, y3); + } + + + public void bezierVertex(float x2, float y2, float z2, + float x3, float y3, float z3, + float x4, float y4, float z4) { + showDepthWarningXYZ("bezierVertex"); + } + + + + ////////////////////////////////////////////////////////////// + + // CURVE VERTICES + + + protected void curveVertexCheck() { + super.curveVertexCheck(); + + if (curveCoordX == null) { + curveCoordX = new float[4]; + curveCoordY = new float[4]; + curveDrawX = new float[4]; + curveDrawY = new float[4]; + } + } + + + protected void curveVertexSegment(float x1, float y1, + float x2, float y2, + float x3, float y3, + float x4, float y4) { + curveCoordX[0] = x1; + curveCoordY[0] = y1; + + curveCoordX[1] = x2; + curveCoordY[1] = y2; + + curveCoordX[2] = x3; + curveCoordY[2] = y3; + + curveCoordX[3] = x4; + curveCoordY[3] = y4; + + curveToBezierMatrix.mult(curveCoordX, curveDrawX); + curveToBezierMatrix.mult(curveCoordY, curveDrawY); + + // since the paths are continuous, + // only the first point needs the actual moveto + if (gpath == null) { + gpath = new GeneralPath(); + gpath.moveTo(curveDrawX[0], curveDrawY[0]); + } + + gpath.curveTo(curveDrawX[1], curveDrawY[1], + curveDrawX[2], curveDrawY[2], + curveDrawX[3], curveDrawY[3]); + } + + + public void curveVertex(float x, float y, float z) { + showDepthWarningXYZ("curveVertex"); + } + + + + ////////////////////////////////////////////////////////////// + + // RENDERER + + + //public void flush() + + + + ////////////////////////////////////////////////////////////// + + // POINT, LINE, TRIANGLE, QUAD + + + public void point(float x, float y) { + if (stroke) { +// if (strokeWeight > 1) { + line(x, y, x + EPSILON, y + EPSILON); +// } else { +// set((int) screenX(x, y), (int) screenY(x, y), strokeColor); +// } + } + } + + + public void line(float x1, float y1, float x2, float y2) { + line.setLine(x1, y1, x2, y2); + strokeShape(line); + } + + + public void triangle(float x1, float y1, float x2, float y2, + float x3, float y3) { + gpath = new GeneralPath(); + gpath.moveTo(x1, y1); + gpath.lineTo(x2, y2); + gpath.lineTo(x3, y3); + gpath.closePath(); + drawShape(gpath); + } + + + public void quad(float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4) { + GeneralPath gp = new GeneralPath(); + gp.moveTo(x1, y1); + gp.lineTo(x2, y2); + gp.lineTo(x3, y3); + gp.lineTo(x4, y4); + gp.closePath(); + drawShape(gp); + } + + + + ////////////////////////////////////////////////////////////// + + // RECT + + + //public void rectMode(int mode) + + + //public void rect(float a, float b, float c, float d) + + + protected void rectImpl(float x1, float y1, float x2, float y2) { + rect.setFrame(x1, y1, x2-x1, y2-y1); + drawShape(rect); + } + + + + ////////////////////////////////////////////////////////////// + + // ELLIPSE + + + //public void ellipseMode(int mode) + + + //public void ellipse(float a, float b, float c, float d) + + + protected void ellipseImpl(float x, float y, float w, float h) { + ellipse.setFrame(x, y, w, h); + drawShape(ellipse); + } + + + + ////////////////////////////////////////////////////////////// + + // ARC + + + //public void arc(float a, float b, float c, float d, + // float start, float stop) + + + protected void arcImpl(float x, float y, float w, float h, + float start, float stop) { + // 0 to 90 in java would be 0 to -90 for p5 renderer + // but that won't work, so -90 to 0? + + start = -start * RAD_TO_DEG; + stop = -stop * RAD_TO_DEG; + + // ok to do this because already checked for NaN +// while (start < 0) { +// start += 360; +// stop += 360; +// } +// if (start > stop) { +// float temp = start; +// start = stop; +// stop = temp; +// } + float sweep = stop - start; + + // stroke as Arc2D.OPEN, fill as Arc2D.PIE + if (fill) { + //System.out.println("filla"); + arc.setArc(x, y, w, h, start, sweep, Arc2D.PIE); + fillShape(arc); + } + if (stroke) { + //System.out.println("strokey"); + arc.setArc(x, y, w, h, start, sweep, Arc2D.OPEN); + strokeShape(arc); + } + } + + + + ////////////////////////////////////////////////////////////// + + // JAVA2D SHAPE/PATH HANDLING + + + protected void fillShape(Shape s) { + if (fillGradient) { + g2.setPaint(fillGradientObject); + g2.fill(s); + } else if (fill) { + g2.setColor(fillColorObject); + g2.fill(s); + } + } + + + protected void strokeShape(Shape s) { + if (strokeGradient) { + g2.setPaint(strokeGradientObject); + g2.draw(s); + } else if (stroke) { + g2.setColor(strokeColorObject); + g2.draw(s); + } + } + + + protected void drawShape(Shape s) { + if (fillGradient) { + g2.setPaint(fillGradientObject); + g2.fill(s); + } else if (fill) { + g2.setColor(fillColorObject); + g2.fill(s); + } + if (strokeGradient) { + g2.setPaint(strokeGradientObject); + g2.draw(s); + } else if (stroke) { + g2.setColor(strokeColorObject); + g2.draw(s); + } + } + + + + ////////////////////////////////////////////////////////////// + + // BOX + + + //public void box(float size) + + + public void box(float w, float h, float d) { + showMethodWarning("box"); + } + + + + ////////////////////////////////////////////////////////////// + + // SPHERE + + + //public void sphereDetail(int res) + + + //public void sphereDetail(int ures, int vres) + + + public void sphere(float r) { + showMethodWarning("sphere"); + } + + + + ////////////////////////////////////////////////////////////// + + // BEZIER + + + //public float bezierPoint(float a, float b, float c, float d, float t) + + + //public float bezierTangent(float a, float b, float c, float d, float t) + + + //protected void bezierInitCheck() + + + //protected void bezierInit() + + + /** Ignored (not needed) in Java 2D. */ + public void bezierDetail(int detail) { + } + + + //public void bezier(float x1, float y1, + // float x2, float y2, + // float x3, float y3, + // float x4, float y4) + + + //public void bezier(float x1, float y1, float z1, + // float x2, float y2, float z2, + // float x3, float y3, float z3, + // float x4, float y4, float z4) + + + + ////////////////////////////////////////////////////////////// + + // CURVE + + + //public float curvePoint(float a, float b, float c, float d, float t) + + + //public float curveTangent(float a, float b, float c, float d, float t) + + + /** Ignored (not needed) in Java 2D. */ + public void curveDetail(int detail) { + } + + //public void curveTightness(float tightness) + + + //protected void curveInitCheck() + + + //protected void curveInit() + + + //public void curve(float x1, float y1, + // float x2, float y2, + // float x3, float y3, + // float x4, float y4) + + + //public void curve(float x1, float y1, float z1, + // float x2, float y2, float z2, + // float x3, float y3, float z3, + // float x4, float y4, float z4) + + + + ////////////////////////////////////////////////////////////// + + // SMOOTH + + + public void smooth() { + smooth = true; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, +// RenderingHints.VALUE_INTERPOLATION_BILINEAR); + RenderingHints.VALUE_INTERPOLATION_BICUBIC); + } + + + public void noSmooth() { + smooth = false; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_OFF); + g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); + } + + + + ////////////////////////////////////////////////////////////// + + // IMAGE + + + //public void imageMode(int mode) + + + //public void image(PImage image, float x, float y) + + + //public void image(PImage image, float x, float y, float c, float d) + + + //public void image(PImage image, + // float a, float b, float c, float d, + // int u1, int v1, int u2, int v2) + + + /** + * Handle renderer-specific image drawing. + */ + protected void imageImpl(PImage who, + float x1, float y1, float x2, float y2, + int u1, int v1, int u2, int v2) { + // Image not ready yet, or an error + if (who.width <= 0 || who.height <= 0) return; + + if (who.getCache(this) == null) { + //System.out.println("making new image cache"); + who.setCache(this, new ImageCache(who)); + who.updatePixels(); // mark the whole thing for update + who.modified = true; + } + + ImageCache cash = (ImageCache) who.getCache(this); + // if image previously was tinted, or the color changed + // or the image was tinted, and tint is now disabled + if ((tint && !cash.tinted) || + (tint && (cash.tintedColor != tintColor)) || + (!tint && cash.tinted)) { + // for tint change, mark all pixels as needing update + who.updatePixels(); + } + + if (who.modified) { + cash.update(tint, tintColor); + who.modified = false; + } + + g2.drawImage(((ImageCache) who.getCache(this)).image, + (int) x1, (int) y1, (int) x2, (int) y2, + u1, v1, u2, v2, null); + } + + + class ImageCache { + PImage source; + boolean tinted; + int tintedColor; + int tintedPixels[]; // one row of tinted pixels + BufferedImage image; + + public ImageCache(PImage source) { + this.source = source; + // even if RGB, set the image type to ARGB, because the + // image may have an alpha value for its tint(). +// int type = BufferedImage.TYPE_INT_ARGB; + //System.out.println("making new buffered image"); +// image = new BufferedImage(source.width, source.height, type); + } + + /** + * Update the pixels of the cache image. Already determined that the tint + * has changed, or the pixels have changed, so should just go through + * with the update without further checks. + */ + public void update(boolean tint, int tintColor) { + int bufferType = BufferedImage.TYPE_INT_ARGB; + boolean opaque = (tintColor & 0xFF000000) == 0xFF000000; + if (source.format == RGB) { + if (!tint || (tint && opaque)) { + bufferType = BufferedImage.TYPE_INT_RGB; + } + } + boolean wrongType = (image != null) && (image.getType() != bufferType); + if ((image == null) || wrongType) { + image = new BufferedImage(source.width, source.height, bufferType); + } + + WritableRaster wr = image.getRaster(); + if (tint) { + if (tintedPixels == null || tintedPixels.length != source.width) { + tintedPixels = new int[source.width]; + } + int a2 = (tintColor >> 24) & 0xff; + int r2 = (tintColor >> 16) & 0xff; + int g2 = (tintColor >> 8) & 0xff; + int b2 = (tintColor) & 0xff; + + if (bufferType == BufferedImage.TYPE_INT_RGB) { + //int alpha = tintColor & 0xFF000000; + int index = 0; + for (int y = 0; y < source.height; y++) { + for (int x = 0; x < source.width; x++) { + int argb1 = source.pixels[index++]; + int r1 = (argb1 >> 16) & 0xff; + int g1 = (argb1 >> 8) & 0xff; + int b1 = (argb1) & 0xff; + + tintedPixels[x] = //0xFF000000 | + (((r2 * r1) & 0xff00) << 8) | + ((g2 * g1) & 0xff00) | + (((b2 * b1) & 0xff00) >> 8); + } + wr.setDataElements(0, y, source.width, 1, tintedPixels); + } + // could this be any slower? +// float[] scales = { tintR, tintG, tintB }; +// float[] offsets = new float[3]; +// RescaleOp op = new RescaleOp(scales, offsets, null); +// op.filter(image, image); + + } else if (bufferType == BufferedImage.TYPE_INT_ARGB) { + int index = 0; + for (int y = 0; y < source.height; y++) { + if (source.format == RGB) { + int alpha = tintColor & 0xFF000000; + for (int x = 0; x < source.width; x++) { + int argb1 = source.pixels[index++]; + int r1 = (argb1 >> 16) & 0xff; + int g1 = (argb1 >> 8) & 0xff; + int b1 = (argb1) & 0xff; + tintedPixels[x] = alpha | + (((r2 * r1) & 0xff00) << 8) | + ((g2 * g1) & 0xff00) | + (((b2 * b1) & 0xff00) >> 8); + } + } else if (source.format == ARGB) { + for (int x = 0; x < source.width; x++) { + int argb1 = source.pixels[index++]; + int a1 = (argb1 >> 24) & 0xff; + int r1 = (argb1 >> 16) & 0xff; + int g1 = (argb1 >> 8) & 0xff; + int b1 = (argb1) & 0xff; + tintedPixels[x] = + (((a2 * a1) & 0xff00) << 16) | + (((r2 * r1) & 0xff00) << 8) | + ((g2 * g1) & 0xff00) | + (((b2 * b1) & 0xff00) >> 8); + } + } else if (source.format == ALPHA) { + int lower = tintColor & 0xFFFFFF; + for (int x = 0; x < source.width; x++) { + int a1 = source.pixels[index++]; + tintedPixels[x] = + (((a2 * a1) & 0xff00) << 16) | lower; + } + } + wr.setDataElements(0, y, source.width, 1, tintedPixels); + } + // Not sure why ARGB images take the scales in this order... +// float[] scales = { tintR, tintG, tintB, tintA }; +// float[] offsets = new float[4]; +// RescaleOp op = new RescaleOp(scales, offsets, null); +// op.filter(image, image); + } + } else { + wr.setDataElements(0, 0, source.width, source.height, source.pixels); + } + this.tinted = tint; + this.tintedColor = tintColor; + } + } + + + + ////////////////////////////////////////////////////////////// + + // SHAPE + + + //public void shapeMode(int mode) + + + //public void shape(PShape shape) + + + //public void shape(PShape shape, float x, float y) + + + //public void shape(PShape shape, float x, float y, float c, float d) + + + + ////////////////////////////////////////////////////////////// + + // TEXT ATTRIBTUES + + + //public void textAlign(int align) + + + //public void textAlign(int alignX, int alignY) + + + public float textAscent() { + if (textFont == null) { + defaultFontOrDeath("textAscent"); + } + Font font = textFont.getFont(); + if (font == null) { + return super.textAscent(); + } + FontMetrics metrics = parent.getFontMetrics(font); + return metrics.getAscent(); + } + + + public float textDescent() { + if (textFont == null) { + defaultFontOrDeath("textAscent"); + } + Font font = textFont.getFont(); + if (font == null) { + return super.textDescent(); + } + FontMetrics metrics = parent.getFontMetrics(font); + return metrics.getDescent(); + } + + + //public void textFont(PFont which) + + + //public void textFont(PFont which, float size) + + + //public void textLeading(float leading) + + + //public void textMode(int mode) + + + protected boolean textModeCheck(int mode) { + return (mode == MODEL) || (mode == SCREEN); + } + + + /** + * Same as parent, but override for native version of the font. + *

+ * Also gets called by textFont, so the metrics + * will get recorded properly. + */ + public void textSize(float size) { + if (textFont == null) { + defaultFontOrDeath("textAscent", size); + } + + // if a native version available, derive this font +// if (textFontNative != null) { +// textFontNative = textFontNative.deriveFont(size); +// g2.setFont(textFontNative); +// textFontNativeMetrics = g2.getFontMetrics(textFontNative); +// } + Font font = textFont.getFont(); + if (font != null) { + Font dfont = font.deriveFont(size); + g2.setFont(dfont); + textFont.setFont(dfont); + } + + // take care of setting the textSize and textLeading vars + // this has to happen second, because it calls textAscent() + // (which requires the native font metrics to be set) + super.textSize(size); + } + + + //public float textWidth(char c) + + + //public float textWidth(String str) + + + protected float textWidthImpl(char buffer[], int start, int stop) { + Font font = textFont.getFont(); + if (font == null) { + return super.textWidthImpl(buffer, start, stop); + } + // maybe should use one of the newer/fancier functions for this? + int length = stop - start; + FontMetrics metrics = g2.getFontMetrics(font); + return metrics.charsWidth(buffer, start, length); + } + + + + ////////////////////////////////////////////////////////////// + + // TEXT + + // None of the variations of text() are overridden from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // TEXT IMPL + + + //protected void textLineAlignImpl(char buffer[], int start, int stop, + // float x, float y) + + + protected void textLineImpl(char buffer[], int start, int stop, + float x, float y) { + Font font = textFont.getFont(); + if (font == null) { + super.textLineImpl(buffer, start, stop, x, y); + return; + } + + /* + // save the current setting for text smoothing. note that this is + // different from the smooth() function, because the font smoothing + // is controlled when the font is created, not now as it's drawn. + // fixed a bug in 0116 that handled this incorrectly. + Object textAntialias = + g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); + + // override the current text smoothing setting based on the font + // (don't change the global smoothing settings) + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + textFont.smooth ? + RenderingHints.VALUE_ANTIALIAS_ON : + RenderingHints.VALUE_ANTIALIAS_OFF); + */ + + Object antialias = + g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); + if (antialias == null) { + // if smooth() and noSmooth() not called, this will be null (0120) + antialias = RenderingHints.VALUE_ANTIALIAS_DEFAULT; + } + + // override the current smoothing setting based on the font + // also changes global setting for antialiasing, but this is because it's + // not possible to enable/disable them independently in some situations. + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + textFont.smooth ? + RenderingHints.VALUE_ANTIALIAS_ON : + RenderingHints.VALUE_ANTIALIAS_OFF); + + //System.out.println("setting frac metrics"); + //g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + // RenderingHints.VALUE_FRACTIONALMETRICS_ON); + + g2.setColor(fillColorObject); + int length = stop - start; + g2.drawChars(buffer, start, length, (int) (x + 0.5f), (int) (y + 0.5f)); + // better to use drawString() with floats? (nope, draws the same) + //g2.drawString(new String(buffer, start, length), x, y); + + // this didn't seem to help the scaling issue + // and creates garbage because of the new temporary object + //java.awt.font.GlyphVector gv = textFontNative.createGlyphVector(g2.getFontRenderContext(), new String(buffer, start, stop)); + //g2.drawGlyphVector(gv, x, y); + +// System.out.println("text() " + new String(buffer, start, stop)); + + // return to previous smoothing state if it was changed + //g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialias); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias); + + textX = x + textWidthImpl(buffer, start, stop); + textY = y; + textZ = 0; // this will get set by the caller if non-zero + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX STACK + + + public void pushMatrix() { + if (transformCount == transformStack.length) { + throw new RuntimeException("pushMatrix() cannot use push more than " + + transformStack.length + " times"); + } + transformStack[transformCount] = g2.getTransform(); + transformCount++; + } + + + public void popMatrix() { + if (transformCount == 0) { + throw new RuntimeException("missing a popMatrix() " + + "to go with that pushMatrix()"); + } + transformCount--; + g2.setTransform(transformStack[transformCount]); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX TRANSFORMS + + + public void translate(float tx, float ty) { + g2.translate(tx, ty); + } + + + //public void translate(float tx, float ty, float tz) + + + public void rotate(float angle) { + g2.rotate(angle); + } + + + public void rotateX(float angle) { + showDepthWarning("rotateX"); + } + + + public void rotateY(float angle) { + showDepthWarning("rotateY"); + } + + + public void rotateZ(float angle) { + showDepthWarning("rotateZ"); + } + + + public void rotate(float angle, float vx, float vy, float vz) { + showVariationWarning("rotate"); + } + + + public void scale(float s) { + g2.scale(s, s); + } + + + public void scale(float sx, float sy) { + g2.scale(sx, sy); + } + + + public void scale(float sx, float sy, float sz) { + showDepthWarningXYZ("scale"); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX MORE + + + public void resetMatrix() { + g2.setTransform(new AffineTransform()); + } + + + //public void applyMatrix(PMatrix2D source) + + + public void applyMatrix(float n00, float n01, float n02, + float n10, float n11, float n12) { + //System.out.println("PGraphicsJava2D.applyMatrix()"); + //System.out.println(new AffineTransform(n00, n10, n01, n11, n02, n12)); + g2.transform(new AffineTransform(n00, n10, n01, n11, n02, n12)); + //g2.transform(new AffineTransform(n00, n01, n02, n10, n11, n12)); + } + + + //public void applyMatrix(PMatrix3D source) + + + public void applyMatrix(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + showVariationWarning("applyMatrix"); + } + + + + ////////////////////////////////////////////////////////////// + + // MATRIX GET/SET + + + public PMatrix getMatrix() { + return getMatrix((PMatrix2D) null); + } + + + public PMatrix2D getMatrix(PMatrix2D target) { + if (target == null) { + target = new PMatrix2D(); + } + g2.getTransform().getMatrix(transform); + target.set((float) transform[0], (float) transform[2], (float) transform[4], + (float) transform[1], (float) transform[3], (float) transform[5]); + return target; + } + + + public PMatrix3D getMatrix(PMatrix3D target) { + showVariationWarning("getMatrix"); + return target; + } + + + //public void setMatrix(PMatrix source) + + + public void setMatrix(PMatrix2D source) { + g2.setTransform(new AffineTransform(source.m00, source.m10, + source.m01, source.m11, + source.m02, source.m12)); + } + + + public void setMatrix(PMatrix3D source) { + showVariationWarning("setMatrix"); + } + + + public void printMatrix() { + getMatrix((PMatrix2D) null).print(); + } + + + + ////////////////////////////////////////////////////////////// + + // CAMERA and PROJECTION + + // Inherit the plaintive warnings from PGraphics + + + //public void beginCamera() + //public void endCamera() + //public void camera() + //public void camera(float eyeX, float eyeY, float eyeZ, + // float centerX, float centerY, float centerZ, + // float upX, float upY, float upZ) + //public void printCamera() + + //public void ortho() + //public void ortho(float left, float right, + // float bottom, float top, + // float near, float far) + //public void perspective() + //public void perspective(float fov, float aspect, float near, float far) + //public void frustum(float left, float right, + // float bottom, float top, + // float near, float far) + //public void printProjection() + + + + ////////////////////////////////////////////////////////////// + + // SCREEN and MODEL transforms + + + public float screenX(float x, float y) { + g2.getTransform().getMatrix(transform); + return (float)transform[0]*x + (float)transform[2]*y + (float)transform[4]; + } + + + public float screenY(float x, float y) { + g2.getTransform().getMatrix(transform); + return (float)transform[1]*x + (float)transform[3]*y + (float)transform[5]; + } + + + public float screenX(float x, float y, float z) { + showDepthWarningXYZ("screenX"); + return 0; + } + + + public float screenY(float x, float y, float z) { + showDepthWarningXYZ("screenY"); + return 0; + } + + + public float screenZ(float x, float y, float z) { + showDepthWarningXYZ("screenZ"); + return 0; + } + + + //public float modelX(float x, float y, float z) + + + //public float modelY(float x, float y, float z) + + + //public float modelZ(float x, float y, float z) + + + + ////////////////////////////////////////////////////////////// + + // STYLE + + // pushStyle(), popStyle(), style() and getStyle() inherited. + + + + ////////////////////////////////////////////////////////////// + + // STROKE CAP/JOIN/WEIGHT + + + public void strokeCap(int cap) { + super.strokeCap(cap); + strokeImpl(); + } + + + public void strokeJoin(int join) { + super.strokeJoin(join); + strokeImpl(); + } + + + public void strokeWeight(float weight) { + super.strokeWeight(weight); + strokeImpl(); + } + + + protected void strokeImpl() { + int cap = BasicStroke.CAP_BUTT; + if (strokeCap == ROUND) { + cap = BasicStroke.CAP_ROUND; + } else if (strokeCap == PROJECT) { + cap = BasicStroke.CAP_SQUARE; + } + + int join = BasicStroke.JOIN_BEVEL; + if (strokeJoin == MITER) { + join = BasicStroke.JOIN_MITER; + } else if (strokeJoin == ROUND) { + join = BasicStroke.JOIN_ROUND; + } + + g2.setStroke(new BasicStroke(strokeWeight, cap, join)); + } + + + + ////////////////////////////////////////////////////////////// + + // STROKE + + // noStroke() and stroke() inherited from PGraphics. + + + protected void strokeFromCalc() { + super.strokeFromCalc(); + strokeColorObject = new Color(strokeColor, true); + strokeGradient = false; + } + + + + ////////////////////////////////////////////////////////////// + + // TINT + + // noTint() and tint() inherited from PGraphics. + + + protected void tintFromCalc() { + super.tintFromCalc(); + // TODO actually implement tinted images + tintColorObject = new Color(tintColor, true); + } + + + + ////////////////////////////////////////////////////////////// + + // FILL + + // noFill() and fill() inherited from PGraphics. + + + protected void fillFromCalc() { + super.fillFromCalc(); + fillColorObject = new Color(fillColor, true); + fillGradient = false; + } + + + + ////////////////////////////////////////////////////////////// + + // MATERIAL PROPERTIES + + + //public void ambient(int rgb) + //public void ambient(float gray) + //public void ambient(float x, float y, float z) + //protected void ambientFromCalc() + //public void specular(int rgb) + //public void specular(float gray) + //public void specular(float x, float y, float z) + //protected void specularFromCalc() + //public void shininess(float shine) + //public void emissive(int rgb) + //public void emissive(float gray) + //public void emissive(float x, float y, float z ) + //protected void emissiveFromCalc() + + + + ////////////////////////////////////////////////////////////// + + // LIGHTS + + + //public void lights() + //public void noLights() + //public void ambientLight(float red, float green, float blue) + //public void ambientLight(float red, float green, float blue, + // float x, float y, float z) + //public void directionalLight(float red, float green, float blue, + // float nx, float ny, float nz) + //public void pointLight(float red, float green, float blue, + // float x, float y, float z) + //public void spotLight(float red, float green, float blue, + // float x, float y, float z, + // float nx, float ny, float nz, + // float angle, float concentration) + //public void lightFalloff(float constant, float linear, float quadratic) + //public void lightSpecular(float x, float y, float z) + //protected void lightPosition(int num, float x, float y, float z) + //protected void lightDirection(int num, float x, float y, float z) + + + + ////////////////////////////////////////////////////////////// + + // BACKGROUND + + // background() methods inherited from PGraphics, along with the + // PImage version of backgroundImpl(), since it just calls set(). + + + //public void backgroundImpl(PImage image) + + + int[] clearPixels; + + public void backgroundImpl() { + if (backgroundAlpha) { + // Create a small array that can be used to set the pixels several times. + // Using a single-pixel line of length 'width' is a tradeoff between + // speed (setting each pixel individually is too slow) and memory + // (an array for width*height would waste lots of memory if it stayed + // resident, and would terrify the gc if it were re-created on each trip + // to background(). + WritableRaster raster = ((BufferedImage) image).getRaster(); + if ((clearPixels == null) || (clearPixels.length < width)) { + clearPixels = new int[width]; + } + java.util.Arrays.fill(clearPixels, backgroundColor); + for (int i = 0; i < height; i++) { + raster.setDataElements(0, i, width, 1, clearPixels); + } + } else { + //new Exception().printStackTrace(System.out); + // in case people do transformations before background(), + // need to handle this with a push/reset/pop + pushMatrix(); + resetMatrix(); + g2.setColor(new Color(backgroundColor)); //, backgroundAlpha)); + g2.fillRect(0, 0, width, height); + popMatrix(); + } + } + + + + ////////////////////////////////////////////////////////////// + + // COLOR MODE + + // All colorMode() variations are inherited from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // COLOR CALC + + // colorCalc() and colorCalcARGB() inherited from PGraphics. + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE STUFFING + + // final color() variations inherited. + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE EXTRACTION + + // final methods alpha, red, green, blue, + // hue, saturation, and brightness all inherited. + + + + ////////////////////////////////////////////////////////////// + + // COLOR DATATYPE INTERPOLATION + + // both lerpColor variants inherited. + + + + ////////////////////////////////////////////////////////////// + + // BEGIN/END RAW + + + public void beginRaw(PGraphics recorderRaw) { + showMethodWarning("beginRaw"); + } + + + public void endRaw() { + showMethodWarning("endRaw"); + } + + + + ////////////////////////////////////////////////////////////// + + // WARNINGS and EXCEPTIONS + + // showWarning and showException inherited. + + + + ////////////////////////////////////////////////////////////// + + // RENDERER SUPPORT QUERIES + + + //public boolean displayable() // true + + + //public boolean is2D() // true + + + //public boolean is3D() // false + + + + ////////////////////////////////////////////////////////////// + + // PIMAGE METHODS + + + // getImage, setCache, getCache, removeCache, isModified, setModified + + + public void loadPixels() { + if ((pixels == null) || (pixels.length != width * height)) { + pixels = new int[width * height]; + } + //((BufferedImage) image).getRGB(0, 0, width, height, pixels, 0, width); + WritableRaster raster = ((BufferedImage) image).getRaster(); + raster.getDataElements(0, 0, width, height, pixels); + } + + + /** + * Update the pixels[] buffer to the PGraphics image. + *

+ * Unlike in PImage, where updatePixels() only requests that the + * update happens, in PGraphicsJava2D, this will happen immediately. + */ + public void updatePixels() { + //updatePixels(0, 0, width, height); + WritableRaster raster = ((BufferedImage) image).getRaster(); + raster.setDataElements(0, 0, width, height, pixels); + } + + + /** + * Update the pixels[] buffer to the PGraphics image. + *

+ * Unlike in PImage, where updatePixels() only requests that the + * update happens, in PGraphicsJava2D, this will happen immediately. + */ + public void updatePixels(int x, int y, int c, int d) { + //if ((x == 0) && (y == 0) && (c == width) && (d == height)) { + if ((x != 0) || (y != 0) || (c != width) || (d != height)) { + // Show a warning message, but continue anyway. + showVariationWarning("updatePixels(x, y, w, h)"); + } + updatePixels(); + } + + + public void resize(int wide, int high) { + showMethodWarning("resize"); + } + + + + ////////////////////////////////////////////////////////////// + + // GET/SET + + + static int getset[] = new int[1]; + + + public int get(int x, int y) { + if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0; + //return ((BufferedImage) image).getRGB(x, y); + WritableRaster raster = ((BufferedImage) image).getRaster(); + raster.getDataElements(x, y, getset); + return getset[0]; + } + + + //public PImage get(int x, int y, int w, int h) + + + public PImage getImpl(int x, int y, int w, int h) { + PImage output = new PImage(w, h); + output.parent = parent; + + // oops, the last parameter is the scan size of the *target* buffer + //((BufferedImage) image).getRGB(x, y, w, h, output.pixels, 0, w); + WritableRaster raster = ((BufferedImage) image).getRaster(); + raster.getDataElements(x, y, w, h, output.pixels); + + return output; + } + + + public PImage get() { + return get(0, 0, width, height); + } + + + public void set(int x, int y, int argb) { + if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return; +// ((BufferedImage) image).setRGB(x, y, argb); + getset[0] = argb; + WritableRaster raster = ((BufferedImage) image).getRaster(); + raster.setDataElements(x, y, getset); + } + + + protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh, + PImage src) { + WritableRaster raster = ((BufferedImage) image).getRaster(); + if ((sx == 0) && (sy == 0) && (sw == src.width) && (sh == src.height)) { + raster.setDataElements(dx, dy, src.width, src.height, src.pixels); + } else { + // TODO Optimize, incredibly inefficient to reallocate this much memory + PImage temp = src.get(sx, sy, sw, sh); + raster.setDataElements(dx, dy, temp.width, temp.height, temp.pixels); + } + } + + + + ////////////////////////////////////////////////////////////// + + // MASK + + + public void mask(int alpha[]) { + showMethodWarning("mask"); + } + + + public void mask(PImage alpha) { + showMethodWarning("mask"); + } + + + + ////////////////////////////////////////////////////////////// + + // FILTER + + // Because the PImage versions call loadPixels() and + // updatePixels(), no need to override anything here. + + + //public void filter(int kind) + + + //public void filter(int kind, float param) + + + + ////////////////////////////////////////////////////////////// + + // COPY + + + public void copy(int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh) { + if ((sw != dw) || (sh != dh)) { + // use slow version if changing size + copy(this, sx, sy, sw, sh, dx, dy, dw, dh); + + } else { + dx = dx - sx; // java2d's "dx" is the delta, not dest + dy = dy - sy; + g2.copyArea(sx, sy, sw, sh, dx, dy); + } + } + + +// public void copy(PImage src, +// int sx1, int sy1, int sx2, int sy2, +// int dx1, int dy1, int dx2, int dy2) { +// loadPixels(); +// super.copy(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); +// updatePixels(); +// } + + + + ////////////////////////////////////////////////////////////// + + // BLEND + + +// static public int blendColor(int c1, int c2, int mode) + + +// public void blend(int sx, int sy, int sw, int sh, +// int dx, int dy, int dw, int dh, int mode) + + +// public void blend(PImage src, +// int sx, int sy, int sw, int sh, +// int dx, int dy, int dw, int dh, int mode) + + + + ////////////////////////////////////////////////////////////// + + // SAVE + + +// public void save(String filename) { +// loadPixels(); +// super.save(filename); +// } +} \ No newline at end of file diff --git a/support/Processing_core_src/processing/core/PImage.java b/support/Processing_core_src/processing/core/PImage.java new file mode 100644 index 0000000..c38c52b --- /dev/null +++ b/support/Processing_core_src/processing/core/PImage.java @@ -0,0 +1,2863 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-08 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.image.*; +import java.io.*; +import java.util.HashMap; + +import javax.imageio.ImageIO; + + + + +/** + * Datatype for storing images. Processing can display .gif, .jpg, .tga, and .png images. Images may be displayed in 2D and 3D space. + * Before an image is used, it must be loaded with the loadImage() function. + * The PImage object contains fields for the width and height of the image, + * as well as an array called pixels[] which contains the values for every pixel in the image. + * A group of methods, described below, allow easy access to the image's pixels and alpha channel and simplify the process of compositing. + *

Before using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the pixel data is properly loaded. + *

To create a new image, use the createImage() function (do not use new PImage()). + * =advanced + * + * Storage class for pixel data. This is the base class for most image and + * pixel information, such as PGraphics and the video library classes. + *

+ * Code for copying, resizing, scaling, and blending contributed + * by toxi. + *

+ * + * @webref image + * @usage Web & Application + * @instanceName img any variable of type PImage + * @see processing.core.PApplet#loadImage(String) + * @see processing.core.PGraphics#imageMode(int) + * @see processing.core.PApplet#createImage(int, int) + */ +public class PImage implements PConstants, Cloneable { + + /** + * Format for this image, one of RGB, ARGB or ALPHA. + * note that RGB images still require 0xff in the high byte + * because of how they'll be manipulated by other functions + */ + public int format; + + /** + * Array containing the values for all the pixels in the image. These values are of the color datatype. + * This array is the size of the image, meaning if the image is 100x100 pixels, there will be 10000 values + * and if the window is 200x300 pixels, there will be 60000 values. + * The index value defines the position of a value within the array. + * For example, the statement color b = img.pixels[230] will set the variable b equal to the value at that location in the array. + * Before accessing this array, the data must loaded with the loadPixels() method. + * After the array data has been modified, the updatePixels() method must be run to update the changes. + * Without loadPixels(), running the code may (or will in future releases) result in a NullPointerException. + * @webref + * @brief Array containing the color of every pixel in the image + */ + public int[] pixels; + + /** + * The width of the image in units of pixels. + * @webref + * @brief Image width + */ + public int width; + /** + * The height of the image in units of pixels. + * @webref + * @brief Image height + */ + public int height; + + /** + * Path to parent object that will be used with save(). + * This prevents users from needing savePath() to use PImage.save(). + */ + public PApplet parent; + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + /** for subclasses that need to store info about the image */ + protected HashMap cacheMap; + + + /** modified portion of the image */ + protected boolean modified; + protected int mx1, my1, mx2, my2; + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + // private fields + private int fracU, ifU, fracV, ifV, u1, u2, v1, v2, sX, sY, iw, iw1, ih1; + private int ul, ll, ur, lr, cUL, cLL, cUR, cLR; + private int srcXOffset, srcYOffset; + private int r, g, b, a; + private int[] srcBuffer; + + // fixed point precision is limited to 15 bits!! + static final int PRECISIONB = 15; + static final int PRECISIONF = 1 << PRECISIONB; + static final int PREC_MAXVAL = PRECISIONF-1; + static final int PREC_ALPHA_SHIFT = 24-PRECISIONB; + static final int PREC_RED_SHIFT = 16-PRECISIONB; + + // internal kernel stuff for the gaussian blur filter + private int blurRadius; + private int blurKernelSize; + private int[] blurKernel; + private int[][] blurMult; + + + ////////////////////////////////////////////////////////////// + + + /** + * Create an empty image object, set its format to RGB. + * The pixel array is not allocated. + */ + public PImage() { + format = ARGB; // default to ARGB images for release 0116 +// cache = null; + } + + + /** + * Create a new RGB (alpha ignored) image of a specific size. + * All pixels are set to zero, meaning black, but since the + * alpha is zero, it will be transparent. + */ + public PImage(int width, int height) { + init(width, height, RGB); + + // toxi: is it maybe better to init the image with max alpha enabled? + //for(int i=0; i(); + cacheMap.put(parent, storage); + } + + + /** + * Get cache storage data for the specified renderer. Because each renderer + * will cache data in different formats, it's necessary to store cache data + * keyed by the renderer object. Otherwise, attempting to draw the same + * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. + * @param parent The PGraphics object (or any object, really) associated + * @return data stored for the specified parent + */ + public Object getCache(Object parent) { + if (cacheMap == null) return null; + return cacheMap.get(parent); + } + + + /** + * Remove information associated with this renderer from the cache, if any. + * @param parent The PGraphics object whose cache data should be removed + */ + public void removeCache(Object parent) { + if (cacheMap != null) { + cacheMap.remove(parent); + } + } + + + + ////////////////////////////////////////////////////////////// + + // MARKING IMAGE AS MODIFIED / FOR USE w/ GET/SET + + + public boolean isModified() { // ignore + return modified; + } + + + public void setModified() { // ignore + modified = true; + } + + + public void setModified(boolean m) { // ignore + modified = m; + } + + + /** + * Loads the pixel data for the image into its pixels[] array. This function must always be called before reading from or writing to pixels[]. + *

Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change. + * =advanced + * Call this when you want to mess with the pixels[] array. + *

+ * For subclasses where the pixels[] buffer isn't set by default, + * this should copy all data into the pixels[] array + * + * @webref + * @brief Loads the pixel data for the image into its pixels[] array + */ + public void loadPixels() { // ignore + } + + public void updatePixels() { // ignore + updatePixelsImpl(0, 0, width, height); + } + + /** + * Updates the image with the data in its pixels[] array. Use in conjunction with loadPixels(). If you're only reading pixels from the array, there's no need to call updatePixels(). + *

Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change. + *

Currently, none of the renderers use the additional parameters to updatePixels(), however this may be implemented in the future. + * =advanced + * Mark the pixels in this region as needing an update. + * This is not currently used by any of the renderers, however the api + * is structured this way in the hope of being able to use this to + * speed things up in the future. + * @webref + * @brief Updates the image with the data in its pixels[] array + * @param x + * @param y + * @param w + * @param h + */ + public void updatePixels(int x, int y, int w, int h) { // ignore +// if (imageMode == CORNER) { // x2, y2 are w/h +// x2 += x1; +// y2 += y1; +// +// } else if (imageMode == CENTER) { +// x1 -= x2 / 2; +// y1 -= y2 / 2; +// x2 += x1; +// y2 += y1; +// } + updatePixelsImpl(x, y, w, h); + } + + + protected void updatePixelsImpl(int x, int y, int w, int h) { + int x2 = x + w; + int y2 = y + h; + + if (!modified) { + mx1 = x; + mx2 = x2; + my1 = y; + my2 = y2; + modified = true; + + } else { + if (x < mx1) mx1 = x; + if (x > mx2) mx2 = x; + if (y < my1) my1 = y; + if (y > my2) my2 = y; + + if (x2 < mx1) mx1 = x2; + if (x2 > mx2) mx2 = x2; + if (y2 < my1) my1 = y2; + if (y2 > my2) my2 = y2; + } + } + + + + ////////////////////////////////////////////////////////////// + + // COPYING IMAGE DATA + + + /** + * Duplicate an image, returns new PImage object. + * The pixels[] array for the new object will be unique + * and recopied from the source image. This is implemented as an + * override of Object.clone(). We recommend using get() instead, + * because it prevents you from needing to catch the + * CloneNotSupportedException, and from doing a cast from the result. + */ + public Object clone() throws CloneNotSupportedException { // ignore + PImage c = (PImage) super.clone(); + + // super.clone() will only copy the reference to the pixels + // array, so this will do a proper duplication of it instead. + c.pixels = new int[width * height]; + System.arraycopy(pixels, 0, c.pixels, 0, pixels.length); + + // return the goods + return c; + } + + + /** + * Resize the image to a new width and height. To make the image scale proportionally, use 0 as the value for the wide or high parameter. + * + * @webref + * @brief Changes the size of an image to a new width and height + * @param wide the resized image width + * @param high the resized image height + * + * @see processing.core.PImage#get(int, int, int, int) + */ + public void resize(int wide, int high) { // ignore + // Make sure that the pixels[] array is valid + loadPixels(); + + if (wide <= 0 && high <= 0) { + width = 0; // Gimme a break, don't waste my time + height = 0; + pixels = new int[0]; + + } else { + if (wide == 0) { // Use height to determine relative size + float diff = (float) high / (float) height; + wide = (int) (width * diff); + } else if (high == 0) { // Use the width to determine relative size + float diff = (float) wide / (float) width; + high = (int) (height * diff); + } + PImage temp = new PImage(wide, high, this.format); + temp.copy(this, 0, 0, width, height, 0, 0, wide, high); + this.width = wide; + this.height = high; + this.pixels = temp.pixels; + } + // Mark the pixels array as altered + updatePixels(); + } + + + + ////////////////////////////////////////////////////////////// + + // GET/SET PIXELS + + + /** + * Returns an ARGB "color" type (a packed 32 bit int with the color. + * If the coordinate is outside the image, zero is returned + * (black, but completely transparent). + *

+ * If the image is in RGB format (i.e. on a PVideo object), + * the value will get its high bits set, just to avoid cases where + * they haven't been set already. + *

+ * If the image is in ALPHA format, this returns a white with its + * alpha value set. + *

+ * This function is included primarily for beginners. It is quite + * slow because it has to check to see if the x, y that was provided + * is inside the bounds, and then has to check to see what image + * type it is. If you want things to be more efficient, access the + * pixels[] array directly. + */ + public int get(int x, int y) { + if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0; + + switch (format) { + case RGB: + return pixels[y*width + x] | 0xff000000; + + case ARGB: + return pixels[y*width + x]; + + case ALPHA: + return (pixels[y*width + x] << 24) | 0xffffff; + } + return 0; + } + + + /** + * Reads the color of any pixel or grabs a group of pixels. If no parameters are specified, the entire image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display window by specifing an additional width and height parameter. If the pixel requested is outside of the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. Even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB. + *

Getting the color of a single pixel with get(x, y) is easy, but not as fast as grabbing the data directly from pixels[]. The equivalent statement to "get(x, y)" using pixels[] is "pixels[y*width+x]". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values. + *

As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Reads the color of any pixel or grabs a rectangle of pixels + * @param x x-coordinate of the pixel + * @param y y-coordinate of the pixel + * @param w width of pixel rectangle to get + * @param h height of pixel rectangle to get + * + * @see processing.core.PImage#set(int, int, int) + * @see processing.core.PImage#pixels + * @see processing.core.PImage#copy(PImage, int, int, int, int, int, int, int, int) + */ + public PImage get(int x, int y, int w, int h) { + /* + if (imageMode == CORNERS) { // if CORNER, do nothing + //x2 += x1; y2 += y1; + // w/h are x2/y2 in this case, bring em down to size + w = (w - x); + h = (h - y); + } else if (imageMode == CENTER) { + x -= w/2; + y -= h/2; + } + */ + + if (x < 0) { + w += x; // clip off the left edge + x = 0; + } + if (y < 0) { + h += y; // clip off some of the height + y = 0; + } + + if (x + w > width) w = width - x; + if (y + h > height) h = height - y; + + return getImpl(x, y, w, h); + } + + + /** + * Internal function to actually handle getting a block of pixels that + * has already been properly cropped to a valid region. That is, x/y/w/h + * are guaranteed to be inside the image space, so the implementation can + * use the fastest possible pixel copying method. + */ + protected PImage getImpl(int x, int y, int w, int h) { + PImage newbie = new PImage(w, h, format); + newbie.parent = parent; + + int index = y*width + x; + int index2 = 0; + for (int row = y; row < y+h; row++) { + System.arraycopy(pixels, index, newbie.pixels, index2, w); + index += width; + index2 += w; + } + return newbie; + } + + + /** + * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). + */ + public PImage get() { + try { + PImage clone = (PImage) clone(); + // don't want to pass this down to the others + // http://dev.processing.org/bugs/show_bug.cgi?id=1245 + clone.cacheMap = null; + return clone; + } catch (CloneNotSupportedException e) { + return null; + } + } + + + /** + * Changes the color of any pixel or writes an image directly into the display window. The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). When setting an image, the x and y parameters define the coordinates for the upper-left corner of the image. + *

Setting the color of a single pixel with set(x, y) is easy, but not as fast as putting the data directly into pixels[]. The equivalent statement to "set(x, y, #000000)" using pixels[] is "pixels[y*width+x] = #000000". You must call loadPixels() to load the display window data into the pixels[] array before setting the values and calling updatePixels() to update the window with any changes. + *

As of release 1.0, this function ignores imageMode(). + *

Due to what appears to be a bug in Apple's Java implementation, the point() and set() methods are extremely slow in some circumstances when used with the default renderer. Using P2D or P3D will fix the problem. Grouping many calls to point() or set() together can also help. (Bug 1094) + * =advanced + *

As of release 0149, this function ignores imageMode(). + * + * @webref image:pixels + * @param x x-coordinate of the pixel + * @param y y-coordinate of the pixel + * @param c any value of the color datatype + */ + public void set(int x, int y, int c) { + if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return; + pixels[y*width + x] = c; + updatePixelsImpl(x, y, x+1, y+1); // slow? + } + + + /** + * Efficient method of drawing an image's pixels directly to this surface. + * No variations are employed, meaning that any scale, tint, or imageMode + * settings will be ignored. + */ + public void set(int x, int y, PImage src) { + int sx = 0; + int sy = 0; + int sw = src.width; + int sh = src.height; + +// if (imageMode == CENTER) { +// x -= src.width/2; +// y -= src.height/2; +// } + if (x < 0) { // off left edge + sx -= x; + sw += x; + x = 0; + } + if (y < 0) { // off top edge + sy -= y; + sh += y; + y = 0; + } + if (x + sw > width) { // off right edge + sw = width - x; + } + if (y + sh > height) { // off bottom edge + sh = height - y; + } + + // this could be nonexistant + if ((sw <= 0) || (sh <= 0)) return; + + setImpl(x, y, sx, sy, sw, sh, src); + } + + + /** + * Internal function to actually handle setting a block of pixels that + * has already been properly cropped from the image to a valid region. + */ + protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh, + PImage src) { + int srcOffset = sy * src.width + sx; + int dstOffset = dy * width + dx; + + for (int y = sy; y < sy + sh; y++) { + System.arraycopy(src.pixels, srcOffset, pixels, dstOffset, sw); + srcOffset += src.width; + dstOffset += width; + } + updatePixelsImpl(sx, sy, sx+sw, sy+sh); + } + + + + ////////////////////////////////////////////////////////////// + + // ALPHA CHANNEL + + + /** + * Set alpha channel for an image. Black colors in the source + * image will make the destination image completely transparent, + * and white will make things fully opaque. Gray values will + * be in-between steps. + *

+ * Strictly speaking the "blue" value from the source image is + * used as the alpha color. For a fully grayscale image, this + * is correct, but for a color image it's not 100% accurate. + * For a more accurate conversion, first use filter(GRAY) + * which will make the image into a "correct" grayscale by + * performing a proper luminance-based conversion. + * + * @param maskArray any array of Integer numbers used as the alpha channel, needs to be same length as the image's pixel array + */ + public void mask(int maskArray[]) { + loadPixels(); + // don't execute if mask image is different size + if (maskArray.length != pixels.length) { + throw new RuntimeException("The PImage used with mask() must be " + + "the same size as the applet."); + } + for (int i = 0; i < pixels.length; i++) { + pixels[i] = ((maskArray[i] & 0xff) << 24) | (pixels[i] & 0xffffff); + } + format = ARGB; + updatePixels(); + } + + + /** + * Masks part of an image from displaying by loading another image and using it as an alpha channel. + * This mask image should only contain grayscale data, but only the blue color channel is used. + * The mask image needs to be the same size as the image to which it is applied. + * In addition to using a mask image, an integer array containing the alpha channel data can be specified directly. + * This method is useful for creating dynamically generated alpha masks. + * This array must be of the same length as the target image's pixels array and should contain only grayscale data of values between 0-255. + * @webref + * @brief Masks part of the image from displaying + * @param maskImg any PImage object used as the alpha channel for "img", needs to be same size as "img" + */ + public void mask(PImage maskImg) { + maskImg.loadPixels(); + mask(maskImg.pixels); + } + + + + ////////////////////////////////////////////////////////////// + + // IMAGE FILTERS + public void filter(int kind) { + loadPixels(); + + switch (kind) { + case BLUR: + // TODO write basic low-pass filter blur here + // what does photoshop do on the edges with this guy? + // better yet.. why bother? just use gaussian with radius 1 + filter(BLUR, 1); + break; + + case GRAY: + if (format == ALPHA) { + // for an alpha image, convert it to an opaque grayscale + for (int i = 0; i < pixels.length; i++) { + int col = 255 - pixels[i]; + pixels[i] = 0xff000000 | (col << 16) | (col << 8) | col; + } + format = RGB; + + } else { + // Converts RGB image data into grayscale using + // weighted RGB components, and keeps alpha channel intact. + // [toxi 040115] + for (int i = 0; i < pixels.length; i++) { + int col = pixels[i]; + // luminance = 0.3*red + 0.59*green + 0.11*blue + // 0.30 * 256 = 77 + // 0.59 * 256 = 151 + // 0.11 * 256 = 28 + int lum = (77*(col>>16&0xff) + 151*(col>>8&0xff) + 28*(col&0xff))>>8; + pixels[i] = (col & ALPHA_MASK) | lum<<16 | lum<<8 | lum; + } + } + break; + + case INVERT: + for (int i = 0; i < pixels.length; i++) { + //pixels[i] = 0xff000000 | + pixels[i] ^= 0xffffff; + } + break; + + case POSTERIZE: + throw new RuntimeException("Use filter(POSTERIZE, int levels) " + + "instead of filter(POSTERIZE)"); + + case OPAQUE: + for (int i = 0; i < pixels.length; i++) { + pixels[i] |= 0xff000000; + } + format = RGB; + break; + + case THRESHOLD: + filter(THRESHOLD, 0.5f); + break; + + // [toxi20050728] added new filters + case ERODE: + dilate(true); + break; + + case DILATE: + dilate(false); + break; + } + updatePixels(); // mark as modified + } + + + /** + * Filters an image as defined by one of the following modes:

THRESHOLD - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0(white). If no level is specified, 0.5 is used.

GRAY - converts any colors in the image to grayscale equivalents

INVERT - sets each pixel to its inverse value

POSTERIZE - limits each channel of the image to the number of colors specified as the level parameter

BLUR - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1.

OPAQUE - sets the alpha channel to entirely opaque.

ERODE - reduces the light areas with the amount defined by the level parameter.

DILATE - increases the light areas with the amount defined by the level parameter + * =advanced + * Method to apply a variety of basic filters to this image. + *

+ *

    + *
  • filter(BLUR) provides a basic blur. + *
  • filter(GRAY) converts the image to grayscale based on luminance. + *
  • filter(INVERT) will invert the color components in the image. + *
  • filter(OPAQUE) set all the high bits in the image to opaque + *
  • filter(THRESHOLD) converts the image to black and white. + *
  • filter(DILATE) grow white/light areas + *
  • filter(ERODE) shrink white/light areas + *
+ * Luminance conversion code contributed by + * toxi + *

+ * Gaussian blur code contributed by + * Mario Klingemann + * + * @webref + * @brief Converts the image to grayscale or black and white + * @param kind Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE + * @param param in the range from 0 to 1 + */ + public void filter(int kind, float param) { + loadPixels(); + + switch (kind) { + case BLUR: + if (format == ALPHA) + blurAlpha(param); + else if (format == ARGB) + blurARGB(param); + else + blurRGB(param); + break; + + case GRAY: + throw new RuntimeException("Use filter(GRAY) instead of " + + "filter(GRAY, param)"); + + case INVERT: + throw new RuntimeException("Use filter(INVERT) instead of " + + "filter(INVERT, param)"); + + case OPAQUE: + throw new RuntimeException("Use filter(OPAQUE) instead of " + + "filter(OPAQUE, param)"); + + case POSTERIZE: + int levels = (int)param; + if ((levels < 2) || (levels > 255)) { + throw new RuntimeException("Levels must be between 2 and 255 for " + + "filter(POSTERIZE, levels)"); + } + int levels1 = levels - 1; + for (int i = 0; i < pixels.length; i++) { + int rlevel = (pixels[i] >> 16) & 0xff; + int glevel = (pixels[i] >> 8) & 0xff; + int blevel = pixels[i] & 0xff; + rlevel = (((rlevel * levels) >> 8) * 255) / levels1; + glevel = (((glevel * levels) >> 8) * 255) / levels1; + blevel = (((blevel * levels) >> 8) * 255) / levels1; + pixels[i] = ((0xff000000 & pixels[i]) | + (rlevel << 16) | + (glevel << 8) | + blevel); + } + break; + + case THRESHOLD: // greater than or equal to the threshold + int thresh = (int) (param * 255); + for (int i = 0; i < pixels.length; i++) { + int max = Math.max((pixels[i] & RED_MASK) >> 16, + Math.max((pixels[i] & GREEN_MASK) >> 8, + (pixels[i] & BLUE_MASK))); + pixels[i] = (pixels[i] & ALPHA_MASK) | + ((max < thresh) ? 0x000000 : 0xffffff); + } + break; + + // [toxi20050728] added new filters + case ERODE: + throw new RuntimeException("Use filter(ERODE) instead of " + + "filter(ERODE, param)"); + case DILATE: + throw new RuntimeException("Use filter(DILATE) instead of " + + "filter(DILATE, param)"); + } + updatePixels(); // mark as modified + } + + + /** + * Optimized code for building the blur kernel. + * further optimized blur code (approx. 15% for radius=20) + * bigger speed gains for larger radii (~30%) + * added support for various image types (ALPHA, RGB, ARGB) + * [toxi 050728] + */ + protected void buildBlurKernel(float r) { + int radius = (int) (r * 3.5f); + radius = (radius < 1) ? 1 : ((radius < 248) ? radius : 248); + if (blurRadius != radius) { + blurRadius = radius; + blurKernelSize = 1 + blurRadius<<1; + blurKernel = new int[blurKernelSize]; + blurMult = new int[blurKernelSize][256]; + + int bk,bki; + int[] bm,bmi; + + for (int i = 1, radiusi = radius - 1; i < radius; i++) { + blurKernel[radius+i] = blurKernel[radiusi] = bki = radiusi * radiusi; + bm=blurMult[radius+i]; + bmi=blurMult[radiusi--]; + for (int j = 0; j < 256; j++) + bm[j] = bmi[j] = bki*j; + } + bk = blurKernel[radius] = radius * radius; + bm = blurMult[radius]; + for (int j = 0; j < 256; j++) + bm[j] = bk*j; + } + } + + + protected void blurAlpha(float r) { + int sum, cb; + int read, ri, ym, ymi, bk0; + int b2[] = new int[pixels.length]; + int yi = 0; + + buildBlurKernel(r); + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + //cb = cg = cr = sum = 0; + cb = sum = 0; + read = x - blurRadius; + if (read<0) { + bk0=-read; + read=0; + } else { + if (read >= width) + break; + bk0=0; + } + for (int i = bk0; i < blurKernelSize; i++) { + if (read >= width) + break; + int c = pixels[read + yi]; + int[] bm=blurMult[i]; + cb += bm[c & BLUE_MASK]; + sum += blurKernel[i]; + read++; + } + ri = yi + x; + b2[ri] = cb / sum; + } + yi += width; + } + + yi = 0; + ym=-blurRadius; + ymi=ym*width; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + //cb = cg = cr = sum = 0; + cb = sum = 0; + if (ym<0) { + bk0 = ri = -ym; + read = x; + } else { + if (ym >= height) + break; + bk0 = 0; + ri = ym; + read = x + ymi; + } + for (int i = bk0; i < blurKernelSize; i++) { + if (ri >= height) + break; + int[] bm=blurMult[i]; + cb += bm[b2[read]]; + sum += blurKernel[i]; + ri++; + read += width; + } + pixels[x+yi] = (cb/sum); + } + yi += width; + ymi += width; + ym++; + } + } + + + protected void blurRGB(float r) { + int sum, cr, cg, cb; //, k; + int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; + int r2[] = new int[pixels.length]; + int g2[] = new int[pixels.length]; + int b2[] = new int[pixels.length]; + int yi = 0; + + buildBlurKernel(r); + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + cb = cg = cr = sum = 0; + read = x - blurRadius; + if (read<0) { + bk0=-read; + read=0; + } else { + if (read >= width) + break; + bk0=0; + } + for (int i = bk0; i < blurKernelSize; i++) { + if (read >= width) + break; + int c = pixels[read + yi]; + int[] bm=blurMult[i]; + cr += bm[(c & RED_MASK) >> 16]; + cg += bm[(c & GREEN_MASK) >> 8]; + cb += bm[c & BLUE_MASK]; + sum += blurKernel[i]; + read++; + } + ri = yi + x; + r2[ri] = cr / sum; + g2[ri] = cg / sum; + b2[ri] = cb / sum; + } + yi += width; + } + + yi = 0; + ym=-blurRadius; + ymi=ym*width; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + cb = cg = cr = sum = 0; + if (ym<0) { + bk0 = ri = -ym; + read = x; + } else { + if (ym >= height) + break; + bk0 = 0; + ri = ym; + read = x + ymi; + } + for (int i = bk0; i < blurKernelSize; i++) { + if (ri >= height) + break; + int[] bm=blurMult[i]; + cr += bm[r2[read]]; + cg += bm[g2[read]]; + cb += bm[b2[read]]; + sum += blurKernel[i]; + ri++; + read += width; + } + pixels[x+yi] = 0xff000000 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); + } + yi += width; + ymi += width; + ym++; + } + } + + + protected void blurARGB(float r) { + int sum, cr, cg, cb, ca; + int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; + int wh = pixels.length; + int r2[] = new int[wh]; + int g2[] = new int[wh]; + int b2[] = new int[wh]; + int a2[] = new int[wh]; + int yi = 0; + + buildBlurKernel(r); + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + cb = cg = cr = ca = sum = 0; + read = x - blurRadius; + if (read<0) { + bk0=-read; + read=0; + } else { + if (read >= width) + break; + bk0=0; + } + for (int i = bk0; i < blurKernelSize; i++) { + if (read >= width) + break; + int c = pixels[read + yi]; + int[] bm=blurMult[i]; + ca += bm[(c & ALPHA_MASK) >>> 24]; + cr += bm[(c & RED_MASK) >> 16]; + cg += bm[(c & GREEN_MASK) >> 8]; + cb += bm[c & BLUE_MASK]; + sum += blurKernel[i]; + read++; + } + ri = yi + x; + a2[ri] = ca / sum; + r2[ri] = cr / sum; + g2[ri] = cg / sum; + b2[ri] = cb / sum; + } + yi += width; + } + + yi = 0; + ym=-blurRadius; + ymi=ym*width; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + cb = cg = cr = ca = sum = 0; + if (ym<0) { + bk0 = ri = -ym; + read = x; + } else { + if (ym >= height) + break; + bk0 = 0; + ri = ym; + read = x + ymi; + } + for (int i = bk0; i < blurKernelSize; i++) { + if (ri >= height) + break; + int[] bm=blurMult[i]; + ca += bm[a2[read]]; + cr += bm[r2[read]]; + cg += bm[g2[read]]; + cb += bm[b2[read]]; + sum += blurKernel[i]; + ri++; + read += width; + } + pixels[x+yi] = (ca/sum)<<24 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); + } + yi += width; + ymi += width; + ym++; + } + } + + + /** + * Generic dilate/erode filter using luminance values + * as decision factor. [toxi 050728] + */ + protected void dilate(boolean isInverted) { + int currIdx=0; + int maxIdx=pixels.length; + int[] out=new int[maxIdx]; + + if (!isInverted) { + // erosion (grow light areas) + while (currIdx=maxRowIdx) + idxRight=currIdx; + if (idxUp<0) + idxUp=currIdx; + if (idxDown>=maxIdx) + idxDown=currIdx; + + int colUp=pixels[idxUp]; + int colLeft=pixels[idxLeft]; + int colDown=pixels[idxDown]; + int colRight=pixels[idxRight]; + + // compute luminance + int currLum = + 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); + int lumLeft = + 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); + int lumRight = + 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); + int lumUp = + 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); + int lumDown = + 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); + + if (lumLeft>currLum) { + colOut=colLeft; + currLum=lumLeft; + } + if (lumRight>currLum) { + colOut=colRight; + currLum=lumRight; + } + if (lumUp>currLum) { + colOut=colUp; + currLum=lumUp; + } + if (lumDown>currLum) { + colOut=colDown; + currLum=lumDown; + } + out[currIdx++]=colOut; + } + } + } else { + // dilate (grow dark areas) + while (currIdx=maxRowIdx) + idxRight=currIdx; + if (idxUp<0) + idxUp=currIdx; + if (idxDown>=maxIdx) + idxDown=currIdx; + + int colUp=pixels[idxUp]; + int colLeft=pixels[idxLeft]; + int colDown=pixels[idxDown]; + int colRight=pixels[idxRight]; + + // compute luminance + int currLum = + 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); + int lumLeft = + 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); + int lumRight = + 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); + int lumUp = + 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); + int lumDown = + 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); + + if (lumLeft
As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Copies the entire image + * @param sx X coordinate of the source's upper left corner + * @param sy Y coordinate of the source's upper left corner + * @param sw source image width + * @param sh source image height + * @param dx X coordinate of the destination's upper left corner + * @param dy Y coordinate of the destination's upper left corner + * @param dw destination image width + * @param dh destination image height + * @param src an image variable referring to the source image. + * + * @see processing.core.PGraphics#alpha(int) + * @see processing.core.PImage#blend(PImage, int, int, int, int, int, int, int, int, int) + */ + public void copy(PImage src, + int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh) { + blend(src, sx, sy, sw, sh, dx, dy, dw, dh, REPLACE); + } + + + + ////////////////////////////////////////////////////////////// + + // BLEND + + + /** + * Blend two colors based on a particular mode. + *

    + *
  • REPLACE - destination colour equals colour of source pixel: C = A. + * Sometimes called "Normal" or "Copy" in other software. + * + *
  • BLEND - linear interpolation of colours: + * C = A*factor + B + * + *
  • ADD - additive blending with white clip: + * C = min(A*factor + B, 255). + * Clipped to 0..255, Photoshop calls this "Linear Burn", + * and Director calls it "Add Pin". + * + *
  • SUBTRACT - substractive blend with black clip: + * C = max(B - A*factor, 0). + * Clipped to 0..255, Photoshop calls this "Linear Dodge", + * and Director calls it "Subtract Pin". + * + *
  • DARKEST - only the darkest colour succeeds: + * C = min(A*factor, B). + * Illustrator calls this "Darken". + * + *
  • LIGHTEST - only the lightest colour succeeds: + * C = max(A*factor, B). + * Illustrator calls this "Lighten". + * + *
  • DIFFERENCE - subtract colors from underlying image. + * + *
  • EXCLUSION - similar to DIFFERENCE, but less extreme. + * + *
  • MULTIPLY - Multiply the colors, result will always be darker. + * + *
  • SCREEN - Opposite multiply, uses inverse values of the colors. + * + *
  • OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, + * and screens light values. + * + *
  • HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. + * + *
  • SOFT_LIGHT - Mix of DARKEST and LIGHTEST. + * Works like OVERLAY, but not as harsh. + * + *
  • DODGE - Lightens light tones and increases contrast, ignores darks. + * Called "Color Dodge" in Illustrator and Photoshop. + * + *
  • BURN - Darker areas are applied, increasing contrast, ignores lights. + * Called "Color Burn" in Illustrator and Photoshop. + *
+ *

A useful reference for blending modes and their algorithms can be + * found in the SVG + * specification.

+ *

It is important to note that Processing uses "fast" code, not + * necessarily "correct" code. No biggie, most software does. A nitpicker + * can find numerous "off by 1 division" problems in the blend code where + * >>8 or >>7 is used when strictly speaking + * /255.0 or /127.0 should have been used.

+ *

For instance, exclusion (not intended for real-time use) reads + * r1 + r2 - ((2 * r1 * r2) / 255) because 255 == 1.0 + * not 256 == 1.0. In other words, (255*255)>>8 is not + * the same as (255*255)/255. But for real-time use the shifts + * are preferrable, and the difference is insignificant for applications + * built with Processing.

+ */ + static public int blendColor(int c1, int c2, int mode) { + switch (mode) { + case REPLACE: return c2; + case BLEND: return blend_blend(c1, c2); + + case ADD: return blend_add_pin(c1, c2); + case SUBTRACT: return blend_sub_pin(c1, c2); + + case LIGHTEST: return blend_lightest(c1, c2); + case DARKEST: return blend_darkest(c1, c2); + + case DIFFERENCE: return blend_difference(c1, c2); + case EXCLUSION: return blend_exclusion(c1, c2); + + case MULTIPLY: return blend_multiply(c1, c2); + case SCREEN: return blend_screen(c1, c2); + + case HARD_LIGHT: return blend_hard_light(c1, c2); + case SOFT_LIGHT: return blend_soft_light(c1, c2); + case OVERLAY: return blend_overlay(c1, c2); + + case DODGE: return blend_dodge(c1, c2); + case BURN: return blend_burn(c1, c2); + } + return 0; + } + + + /** + * Blends one area of this image to another area. + * + * @see processing.core.PImage#blendColor(int,int,int) + */ + public void blend(int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh, int mode) { + blend(this, sx, sy, sw, sh, dx, dy, dw, dh, mode); + } + + + /** + * Blends a region of pixels into the image specified by the img parameter. These copies utilize full alpha channel support and a choice of the following modes to blend the colors of source pixels (A) with the ones of pixels in the destination image (B):

+ * BLEND - linear interpolation of colours: C = A*factor + B

+ * ADD - additive blending with white clip: C = min(A*factor + B, 255)

+ * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0)

+ * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)

+ * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)

+ * DIFFERENCE - subtract colors from underlying image.

+ * EXCLUSION - similar to DIFFERENCE, but less extreme.

+ * MULTIPLY - Multiply the colors, result will always be darker.

+ * SCREEN - Opposite multiply, uses inverse values of the colors.

+ * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values.

+ * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.

+ * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh.

+ * DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop.

+ * BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop.

+ * All modes use the alpha information (highest byte) of source image pixels as the blending factor. If the source and destination regions are different sizes, the image will be automatically resized to match the destination size. If the srcImg parameter is not used, the display window is used as the source image.

+ * As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Copies a pixel or rectangle of pixels using different blending modes + * @param src an image variable referring to the source image + * @param sx X coordinate of the source's upper left corner + * @param sy Y coordinate of the source's upper left corner + * @param sw source image width + * @param sh source image height + * @param dx X coordinate of the destinations's upper left corner + * @param dy Y coordinate of the destinations's upper left corner + * @param dw destination image width + * @param dh destination image height + * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN + * + * @see processing.core.PGraphics#alpha(int) + * @see processing.core.PGraphics#copy(PImage, int, int, int, int, int, int, int, int) + * @see processing.core.PImage#blendColor(int,int,int) + */ + public void blend(PImage src, + int sx, int sy, int sw, int sh, + int dx, int dy, int dw, int dh, int mode) { + /* + if (imageMode == CORNER) { // if CORNERS, do nothing + sx2 += sx1; + sy2 += sy1; + dx2 += dx1; + dy2 += dy1; + + } else if (imageMode == CENTER) { + sx1 -= sx2 / 2f; + sy1 -= sy2 / 2f; + sx2 += sx1; + sy2 += sy1; + dx1 -= dx2 / 2f; + dy1 -= dy2 / 2f; + dx2 += dx1; + dy2 += dy1; + } + */ + int sx2 = sx + sw; + int sy2 = sy + sh; + int dx2 = dx + dw; + int dy2 = dy + dh; + + loadPixels(); + if (src == this) { + if (intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) { + blit_resize(get(sx, sy, sx2 - sx, sy2 - sy), + 0, 0, sx2 - sx - 1, sy2 - sy - 1, + pixels, width, height, dx, dy, dx2, dy2, mode); + } else { + // same as below, except skip the loadPixels() because it'd be redundant + blit_resize(src, sx, sy, sx2, sy2, + pixels, width, height, dx, dy, dx2, dy2, mode); + } + } else { + src.loadPixels(); + blit_resize(src, sx, sy, sx2, sy2, + pixels, width, height, dx, dy, dx2, dy2, mode); + //src.updatePixels(); + } + updatePixels(); + } + + + /** + * Check to see if two rectangles intersect one another + */ + private boolean intersect(int sx1, int sy1, int sx2, int sy2, + int dx1, int dy1, int dx2, int dy2) { + int sw = sx2 - sx1 + 1; + int sh = sy2 - sy1 + 1; + int dw = dx2 - dx1 + 1; + int dh = dy2 - dy1 + 1; + + if (dx1 < sx1) { + dw += dx1 - sx1; + if (dw > sw) { + dw = sw; + } + } else { + int w = sw + sx1 - dx1; + if (dw > w) { + dw = w; + } + } + if (dy1 < sy1) { + dh += dy1 - sy1; + if (dh > sh) { + dh = sh; + } + } else { + int h = sh + sy1 - dy1; + if (dh > h) { + dh = h; + } + } + return !(dw <= 0 || dh <= 0); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Internal blitter/resizer/copier from toxi. + * Uses bilinear filtering if smooth() has been enabled + * 'mode' determines the blending mode used in the process. + */ + private void blit_resize(PImage img, + int srcX1, int srcY1, int srcX2, int srcY2, + int[] destPixels, int screenW, int screenH, + int destX1, int destY1, int destX2, int destY2, + int mode) { + if (srcX1 < 0) srcX1 = 0; + if (srcY1 < 0) srcY1 = 0; + if (srcX2 > img.width) srcX2 = img.width; + if (srcY2 > img.height) srcY2 = img.height; + + int srcW = srcX2 - srcX1; + int srcH = srcY2 - srcY1; + int destW = destX2 - destX1; + int destH = destY2 - destY1; + + boolean smooth = true; // may as well go with the smoothing these days + + if (!smooth) { + srcW++; srcH++; + } + + if (destW <= 0 || destH <= 0 || + srcW <= 0 || srcH <= 0 || + destX1 >= screenW || destY1 >= screenH || + srcX1 >= img.width || srcY1 >= img.height) { + return; + } + + int dx = (int) (srcW / (float) destW * PRECISIONF); + int dy = (int) (srcH / (float) destH * PRECISIONF); + + srcXOffset = (int) (destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF); + srcYOffset = (int) (destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF); + + if (destX1 < 0) { + destW += destX1; + destX1 = 0; + } + if (destY1 < 0) { + destH += destY1; + destY1 = 0; + } + + destW = low(destW, screenW - destX1); + destH = low(destH, screenH - destY1); + + int destOffset = destY1 * screenW + destX1; + srcBuffer = img.pixels; + + if (smooth) { + // use bilinear filtering + iw = img.width; + iw1 = img.width - 1; + ih1 = img.height - 1; + + switch (mode) { + + case BLEND: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + // davbol - renamed old blend_multiply to blend_blend + destPixels[destOffset + x] = + blend_blend(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case ADD: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_add_pin(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case SUBTRACT: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_sub_pin(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case LIGHTEST: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_lightest(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case DARKEST: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_darkest(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case REPLACE: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = filter_bilinear(); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case DIFFERENCE: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_difference(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case EXCLUSION: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_exclusion(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case MULTIPLY: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_multiply(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case SCREEN: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_screen(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case OVERLAY: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_overlay(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case HARD_LIGHT: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_hard_light(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case SOFT_LIGHT: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_soft_light(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + // davbol - proposed 2007-01-09 + case DODGE: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_dodge(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case BURN: + for (int y = 0; y < destH; y++) { + filter_new_scanline(); + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_burn(destPixels[destOffset + x], filter_bilinear()); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + } + + } else { + // nearest neighbour scaling (++fast!) + switch (mode) { + + case BLEND: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + // davbol - renamed old blend_multiply to blend_blend + destPixels[destOffset + x] = + blend_blend(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case ADD: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_add_pin(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case SUBTRACT: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_sub_pin(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case LIGHTEST: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_lightest(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case DARKEST: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_darkest(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case REPLACE: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = srcBuffer[sY + (sX >> PRECISIONB)]; + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case DIFFERENCE: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_difference(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case EXCLUSION: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_exclusion(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case MULTIPLY: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_multiply(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case SCREEN: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_screen(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case OVERLAY: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_overlay(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case HARD_LIGHT: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_hard_light(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case SOFT_LIGHT: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_soft_light(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + // davbol - proposed 2007-01-09 + case DODGE: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_dodge(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + case BURN: + for (int y = 0; y < destH; y++) { + sX = srcXOffset; + sY = (srcYOffset >> PRECISIONB) * img.width; + for (int x = 0; x < destW; x++) { + destPixels[destOffset + x] = + blend_burn(destPixels[destOffset + x], + srcBuffer[sY + (sX >> PRECISIONB)]); + sX += dx; + } + destOffset += screenW; + srcYOffset += dy; + } + break; + + } + } + } + + + private void filter_new_scanline() { + sX = srcXOffset; + fracV = srcYOffset & PREC_MAXVAL; + ifV = PREC_MAXVAL - fracV; + v1 = (srcYOffset >> PRECISIONB) * iw; + v2 = low((srcYOffset >> PRECISIONB) + 1, ih1) * iw; + } + + + private int filter_bilinear() { + fracU = sX & PREC_MAXVAL; + ifU = PREC_MAXVAL - fracU; + ul = (ifU * ifV) >> PRECISIONB; + ll = (ifU * fracV) >> PRECISIONB; + ur = (fracU * ifV) >> PRECISIONB; + lr = (fracU * fracV) >> PRECISIONB; + u1 = (sX >> PRECISIONB); + u2 = low(u1 + 1, iw1); + + // get color values of the 4 neighbouring texels + cUL = srcBuffer[v1 + u1]; + cUR = srcBuffer[v1 + u2]; + cLL = srcBuffer[v2 + u1]; + cLR = srcBuffer[v2 + u2]; + + r = ((ul*((cUL&RED_MASK)>>16) + ll*((cLL&RED_MASK)>>16) + + ur*((cUR&RED_MASK)>>16) + lr*((cLR&RED_MASK)>>16)) + << PREC_RED_SHIFT) & RED_MASK; + + g = ((ul*(cUL&GREEN_MASK) + ll*(cLL&GREEN_MASK) + + ur*(cUR&GREEN_MASK) + lr*(cLR&GREEN_MASK)) + >>> PRECISIONB) & GREEN_MASK; + + b = (ul*(cUL&BLUE_MASK) + ll*(cLL&BLUE_MASK) + + ur*(cUR&BLUE_MASK) + lr*(cLR&BLUE_MASK)) + >>> PRECISIONB; + + a = ((ul*((cUL&ALPHA_MASK)>>>24) + ll*((cLL&ALPHA_MASK)>>>24) + + ur*((cUR&ALPHA_MASK)>>>24) + lr*((cLR&ALPHA_MASK)>>>24)) + << PREC_ALPHA_SHIFT) & ALPHA_MASK; + + return a | r | g | b; + } + + + + ////////////////////////////////////////////////////////////// + + // internal blending methods + + + private static int low(int a, int b) { + return (a < b) ? a : b; + } + + + private static int high(int a, int b) { + return (a > b) ? a : b; + } + + // davbol - added peg helper, equiv to constrain(n,0,255) + private static int peg(int n) { + return (n < 0) ? 0 : ((n > 255) ? 255 : n); + } + + private static int mix(int a, int b, int f) { + return a + (((b - a) * f) >> 8); + } + + + + ///////////////////////////////////////////////////////////// + + // BLEND MODE IMPLEMENTIONS + + + private static int blend_blend(int a, int b) { + int f = (b & ALPHA_MASK) >>> 24; + + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + mix(a & RED_MASK, b & RED_MASK, f) & RED_MASK | + mix(a & GREEN_MASK, b & GREEN_MASK, f) & GREEN_MASK | + mix(a & BLUE_MASK, b & BLUE_MASK, f)); + } + + + /** + * additive blend with clipping + */ + private static int blend_add_pin(int a, int b) { + int f = (b & ALPHA_MASK) >>> 24; + + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + low(((a & RED_MASK) + + ((b & RED_MASK) >> 8) * f), RED_MASK) & RED_MASK | + low(((a & GREEN_MASK) + + ((b & GREEN_MASK) >> 8) * f), GREEN_MASK) & GREEN_MASK | + low((a & BLUE_MASK) + + (((b & BLUE_MASK) * f) >> 8), BLUE_MASK)); + } + + + /** + * subtractive blend with clipping + */ + private static int blend_sub_pin(int a, int b) { + int f = (b & ALPHA_MASK) >>> 24; + + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + high(((a & RED_MASK) - ((b & RED_MASK) >> 8) * f), + GREEN_MASK) & RED_MASK | + high(((a & GREEN_MASK) - ((b & GREEN_MASK) >> 8) * f), + BLUE_MASK) & GREEN_MASK | + high((a & BLUE_MASK) - (((b & BLUE_MASK) * f) >> 8), 0)); + } + + + /** + * only returns the blended lightest colour + */ + private static int blend_lightest(int a, int b) { + int f = (b & ALPHA_MASK) >>> 24; + + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + high(a & RED_MASK, ((b & RED_MASK) >> 8) * f) & RED_MASK | + high(a & GREEN_MASK, ((b & GREEN_MASK) >> 8) * f) & GREEN_MASK | + high(a & BLUE_MASK, ((b & BLUE_MASK) * f) >> 8)); + } + + + /** + * only returns the blended darkest colour + */ + private static int blend_darkest(int a, int b) { + int f = (b & ALPHA_MASK) >>> 24; + + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + mix(a & RED_MASK, + low(a & RED_MASK, + ((b & RED_MASK) >> 8) * f), f) & RED_MASK | + mix(a & GREEN_MASK, + low(a & GREEN_MASK, + ((b & GREEN_MASK) >> 8) * f), f) & GREEN_MASK | + mix(a & BLUE_MASK, + low(a & BLUE_MASK, + ((b & BLUE_MASK) * f) >> 8), f)); + } + + + /** + * returns the absolute value of the difference of the input colors + * C = |A - B| + */ + private static int blend_difference(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = (ar > br) ? (ar-br) : (br-ar); + int cg = (ag > bg) ? (ag-bg) : (bg-ag); + int cb = (ab > bb) ? (ab-bb) : (bb-ab); + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * Cousin of difference, algorithm used here is based on a Lingo version + * found here: http://www.mediamacros.com/item/item-1006687616/ + * (Not yet verified to be correct). + */ + private static int blend_exclusion(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = ar + br - ((ar * br) >> 7); + int cg = ag + bg - ((ag * bg) >> 7); + int cb = ab + bb - ((ab * bb) >> 7); + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * returns the product of the input colors + * C = A * B + */ + private static int blend_multiply(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = (ar * br) >> 8; + int cg = (ag * bg) >> 8; + int cb = (ab * bb) >> 8; + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * returns the inverse of the product of the inverses of the input colors + * (the inverse of multiply). C = 1 - (1-A) * (1-B) + */ + private static int blend_screen(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = 255 - (((255 - ar) * (255 - br)) >> 8); + int cg = 255 - (((255 - ag) * (255 - bg)) >> 8); + int cb = 255 - (((255 - ab) * (255 - bb)) >> 8); + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * returns either multiply or screen for darker or lighter values of A + * (the inverse of hard light) + * C = + * A < 0.5 : 2 * A * B + * A >=0.5 : 1 - (2 * (255-A) * (255-B)) + */ + private static int blend_overlay(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = (ar < 128) ? ((ar*br)>>7) : (255-(((255-ar)*(255-br))>>7)); + int cg = (ag < 128) ? ((ag*bg)>>7) : (255-(((255-ag)*(255-bg))>>7)); + int cb = (ab < 128) ? ((ab*bb)>>7) : (255-(((255-ab)*(255-bb))>>7)); + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * returns either multiply or screen for darker or lighter values of B + * (the inverse of overlay) + * C = + * B < 0.5 : 2 * A * B + * B >=0.5 : 1 - (2 * (255-A) * (255-B)) + */ + private static int blend_hard_light(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = (br < 128) ? ((ar*br)>>7) : (255-(((255-ar)*(255-br))>>7)); + int cg = (bg < 128) ? ((ag*bg)>>7) : (255-(((255-ag)*(255-bg))>>7)); + int cb = (bb < 128) ? ((ab*bb)>>7) : (255-(((255-ab)*(255-bb))>>7)); + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * returns the inverse multiply plus screen, which simplifies to + * C = 2AB + A^2 - 2A^2B + */ + private static int blend_soft_light(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = ((ar*br)>>7) + ((ar*ar)>>8) - ((ar*ar*br)>>15); + int cg = ((ag*bg)>>7) + ((ag*ag)>>8) - ((ag*ag*bg)>>15); + int cb = ((ab*bb)>>7) + ((ab*ab)>>8) - ((ab*ab*bb)>>15); + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * Returns the first (underlay) color divided by the inverse of + * the second (overlay) color. C = A / (255-B) + */ + private static int blend_dodge(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = (br==255) ? 255 : peg((ar << 8) / (255 - br)); // division requires pre-peg()-ing + int cg = (bg==255) ? 255 : peg((ag << 8) / (255 - bg)); // " + int cb = (bb==255) ? 255 : peg((ab << 8) / (255 - bb)); // " + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + /** + * returns the inverse of the inverse of the first (underlay) color + * divided by the second (overlay) color. C = 255 - (255-A) / B + */ + private static int blend_burn(int a, int b) { + // setup (this portion will always be the same) + int f = (b & ALPHA_MASK) >>> 24; + int ar = (a & RED_MASK) >> 16; + int ag = (a & GREEN_MASK) >> 8; + int ab = (a & BLUE_MASK); + int br = (b & RED_MASK) >> 16; + int bg = (b & GREEN_MASK) >> 8; + int bb = (b & BLUE_MASK); + // formula: + int cr = (br==0) ? 0 : 255 - peg(((255 - ar) << 8) / br); // division requires pre-peg()-ing + int cg = (bg==0) ? 0 : 255 - peg(((255 - ag) << 8) / bg); // " + int cb = (bb==0) ? 0 : 255 - peg(((255 - ab) << 8) / bb); // " + // alpha blend (this portion will always be the same) + return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | + (peg(ar + (((cr - ar) * f) >> 8)) << 16) | + (peg(ag + (((cg - ag) * f) >> 8)) << 8) | + (peg(ab + (((cb - ab) * f) >> 8)) ) ); + } + + + ////////////////////////////////////////////////////////////// + + // FILE I/O + + + static byte TIFF_HEADER[] = { + 77, 77, 0, 42, 0, 0, 0, 8, 0, 9, 0, -2, 0, 4, 0, 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 0, 1, + 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0, 122, 1, 6, 0, 3, 0, + 0, 0, 1, 0, 2, 0, 0, 1, 17, 0, 4, 0, 0, 0, 1, 0, 0, 3, 0, 1, 21, + 0, 3, 0, 0, 0, 1, 0, 3, 0, 0, 1, 22, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, + 1, 23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 8 + }; + + + static final String TIFF_ERROR = + "Error: Processing can only read its own TIFF files."; + + static protected PImage loadTIFF(byte tiff[]) { + if ((tiff[42] != tiff[102]) || // width/height in both places + (tiff[43] != tiff[103])) { + System.err.println(TIFF_ERROR); + return null; + } + + int width = + ((tiff[30] & 0xff) << 8) | (tiff[31] & 0xff); + int height = + ((tiff[42] & 0xff) << 8) | (tiff[43] & 0xff); + + int count = + ((tiff[114] & 0xff) << 24) | + ((tiff[115] & 0xff) << 16) | + ((tiff[116] & 0xff) << 8) | + (tiff[117] & 0xff); + if (count != width * height * 3) { + System.err.println(TIFF_ERROR + " (" + width + ", " + height +")"); + return null; + } + + // check the rest of the header + for (int i = 0; i < TIFF_HEADER.length; i++) { + if ((i == 30) || (i == 31) || (i == 42) || (i == 43) || + (i == 102) || (i == 103) || + (i == 114) || (i == 115) || (i == 116) || (i == 117)) continue; + + if (tiff[i] != TIFF_HEADER[i]) { + System.err.println(TIFF_ERROR + " (" + i + ")"); + return null; + } + } + + PImage outgoing = new PImage(width, height, RGB); + int index = 768; + count /= 3; + for (int i = 0; i < count; i++) { + outgoing.pixels[i] = + 0xFF000000 | + (tiff[index++] & 0xff) << 16 | + (tiff[index++] & 0xff) << 8 | + (tiff[index++] & 0xff); + } + return outgoing; + } + + + protected boolean saveTIFF(OutputStream output) { + // shutting off the warning, people can figure this out themselves + /* + if (format != RGB) { + System.err.println("Warning: only RGB information is saved with " + + ".tif files. Use .tga or .png for ARGB images and others."); + } + */ + try { + byte tiff[] = new byte[768]; + System.arraycopy(TIFF_HEADER, 0, tiff, 0, TIFF_HEADER.length); + + tiff[30] = (byte) ((width >> 8) & 0xff); + tiff[31] = (byte) ((width) & 0xff); + tiff[42] = tiff[102] = (byte) ((height >> 8) & 0xff); + tiff[43] = tiff[103] = (byte) ((height) & 0xff); + + int count = width*height*3; + tiff[114] = (byte) ((count >> 24) & 0xff); + tiff[115] = (byte) ((count >> 16) & 0xff); + tiff[116] = (byte) ((count >> 8) & 0xff); + tiff[117] = (byte) ((count) & 0xff); + + // spew the header to the disk + output.write(tiff); + + for (int i = 0; i < pixels.length; i++) { + output.write((pixels[i] >> 16) & 0xff); + output.write((pixels[i] >> 8) & 0xff); + output.write(pixels[i] & 0xff); + } + output.flush(); + return true; + + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + + /** + * Creates a Targa32 formatted byte sequence of specified + * pixel buffer using RLE compression. + *

+ * Also figured out how to avoid parsing the image upside-down + * (there's a header flag to set the image origin to top-left) + *

+ * Starting with revision 0092, the format setting is taken into account: + *
    + *
  • ALPHA images written as 8bit grayscale (uses lowest byte) + *
  • RGB → 24 bits + *
  • ARGB → 32 bits + *
+ * All versions are RLE compressed. + *

+ * Contributed by toxi 8-10 May 2005, based on this RLE + * specification + */ + protected boolean saveTGA(OutputStream output) { + byte header[] = new byte[18]; + + if (format == ALPHA) { // save ALPHA images as 8bit grayscale + header[2] = 0x0B; + header[16] = 0x08; + header[17] = 0x28; + + } else if (format == RGB) { + header[2] = 0x0A; + header[16] = 24; + header[17] = 0x20; + + } else if (format == ARGB) { + header[2] = 0x0A; + header[16] = 32; + header[17] = 0x28; + + } else { + throw new RuntimeException("Image format not recognized inside save()"); + } + // set image dimensions lo-hi byte order + header[12] = (byte) (width & 0xff); + header[13] = (byte) (width >> 8); + header[14] = (byte) (height & 0xff); + header[15] = (byte) (height >> 8); + + try { + output.write(header); + + int maxLen = height * width; + int index = 0; + int col; //, prevCol; + int[] currChunk = new int[128]; + + // 8bit image exporter is in separate loop + // to avoid excessive conditionals... + if (format == ALPHA) { + while (index < maxLen) { + boolean isRLE = false; + int rle = 1; + currChunk[0] = col = pixels[index] & 0xff; + while (index + rle < maxLen) { + if (col != (pixels[index + rle]&0xff) || rle == 128) { + isRLE = (rle > 1); + break; + } + rle++; + } + if (isRLE) { + output.write(0x80 | (rle - 1)); + output.write(col); + + } else { + rle = 1; + while (index + rle < maxLen) { + int cscan = pixels[index + rle] & 0xff; + if ((col != cscan && rle < 128) || rle < 3) { + currChunk[rle] = col = cscan; + } else { + if (col == cscan) rle -= 2; + break; + } + rle++; + } + output.write(rle - 1); + for (int i = 0; i < rle; i++) output.write(currChunk[i]); + } + index += rle; + } + } else { // export 24/32 bit TARGA + while (index < maxLen) { + boolean isRLE = false; + currChunk[0] = col = pixels[index]; + int rle = 1; + // try to find repeating bytes (min. len = 2 pixels) + // maximum chunk size is 128 pixels + while (index + rle < maxLen) { + if (col != pixels[index + rle] || rle == 128) { + isRLE = (rle > 1); // set flag for RLE chunk + break; + } + rle++; + } + if (isRLE) { + output.write(128 | (rle - 1)); + output.write(col & 0xff); + output.write(col >> 8 & 0xff); + output.write(col >> 16 & 0xff); + if (format == ARGB) output.write(col >>> 24 & 0xff); + + } else { // not RLE + rle = 1; + while (index + rle < maxLen) { + if ((col != pixels[index + rle] && rle < 128) || rle < 3) { + currChunk[rle] = col = pixels[index + rle]; + } else { + // check if the exit condition was the start of + // a repeating colour + if (col == pixels[index + rle]) rle -= 2; + break; + } + rle++; + } + // write uncompressed chunk + output.write(rle - 1); + if (format == ARGB) { + for (int i = 0; i < rle; i++) { + col = currChunk[i]; + output.write(col & 0xff); + output.write(col >> 8 & 0xff); + output.write(col >> 16 & 0xff); + output.write(col >>> 24 & 0xff); + } + } else { + for (int i = 0; i < rle; i++) { + col = currChunk[i]; + output.write(col & 0xff); + output.write(col >> 8 & 0xff); + output.write(col >> 16 & 0xff); + } + } + } + index += rle; + } + } + output.flush(); + return true; + + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + + /** + * Use ImageIO functions from Java 1.4 and later to handle image save. + * Various formats are supported, typically jpeg, png, bmp, and wbmp. + * To get a list of the supported formats for writing, use:
+ * println(javax.imageio.ImageIO.getReaderFormatNames()) + */ + protected void saveImageIO(String path) throws IOException { + try { + BufferedImage bimage = + new BufferedImage(width, height, (format == ARGB) ? + BufferedImage.TYPE_INT_ARGB : + BufferedImage.TYPE_INT_RGB); + /* + Class bufferedImageClass = + Class.forName("java.awt.image.BufferedImage"); + Constructor bufferedImageConstructor = + bufferedImageClass.getConstructor(new Class[] { + Integer.TYPE, + Integer.TYPE, + Integer.TYPE }); + Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB"); + int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField); + Field typeIntArgbField = bufferedImageClass.getField("TYPE_INT_ARGB"); + int typeIntArgb = typeIntArgbField.getInt(typeIntArgbField); + Object bimage = + bufferedImageConstructor.newInstance(new Object[] { + new Integer(width), + new Integer(height), + new Integer((format == ARGB) ? typeIntArgb : typeIntRgb) + }); + */ + + bimage.setRGB(0, 0, width, height, pixels, 0, width); + /* + Method setRgbMethod = + bufferedImageClass.getMethod("setRGB", new Class[] { + Integer.TYPE, Integer.TYPE, + Integer.TYPE, Integer.TYPE, + pixels.getClass(), + Integer.TYPE, Integer.TYPE + }); + setRgbMethod.invoke(bimage, new Object[] { + new Integer(0), new Integer(0), + new Integer(width), new Integer(height), + pixels, new Integer(0), new Integer(width) + }); + */ + + File file = new File(path); + String extension = path.substring(path.lastIndexOf('.') + 1); + + ImageIO.write(bimage, extension, file); + /* + Class renderedImageClass = + Class.forName("java.awt.image.RenderedImage"); + Class ioClass = Class.forName("javax.imageio.ImageIO"); + Method writeMethod = + ioClass.getMethod("write", new Class[] { + renderedImageClass, String.class, File.class + }); + writeMethod.invoke(null, new Object[] { bimage, extension, file }); + */ + + } catch (Exception e) { + e.printStackTrace(); + throw new IOException("image save failed."); + } + } + + + protected String[] saveImageFormats; + + /** + * Saves the image into a file. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on the extension within the filename parameter. + * For example, "image.tif" will have a TIFF image and "image.png" will save a PNG image. + * If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name. + * These files are saved to the sketch's folder, which may be opened by selecting "Show sketch folder" from the "Sketch" menu. + * It is not possible to use save() while running the program in a web browser.

+ * To save an image created within the code, rather than through loading, it's necessary to make the image with the createImage() + * function so it is aware of the location of the program and can therefore save the file to the right place. + * See the createImage() reference for more information. + * + * =advanced + * Save this image to disk. + *

+ * As of revision 0100, this function requires an absolute path, + * in order to avoid confusion. To save inside the sketch folder, + * use the function savePath() from PApplet, or use saveFrame() instead. + * As of revision 0116, savePath() is not needed if this object has been + * created (as recommended) via createImage() or createGraphics() or + * one of its neighbors. + *

+ * As of revision 0115, when using Java 1.4 and later, you can write + * to several formats besides tga and tiff. If Java 1.4 is installed + * and the extension used is supported (usually png, jpg, jpeg, bmp, + * and tiff), then those methods will be used to write the image. + * To get a list of the supported formats for writing, use:
+ * println(javax.imageio.ImageIO.getReaderFormatNames()) + *

+ * To use the original built-in image writers, use .tga or .tif as the + * extension, or don't include an extension. When no extension is used, + * the extension .tif will be added to the file name. + *

+ * The ImageIO API claims to support wbmp files, however they probably + * require a black and white image. Basic testing produced a zero-length + * file with no error. + * + * @webref + * @brief Saves the image to a TIFF, TARGA, PNG, or JPEG file + * @param filename a sequence of letters and numbers + */ + public void save(String filename) { // ignore + boolean success = false; + + File file = new File(filename); + if (!file.isAbsolute()) { + if (parent != null) { + //file = new File(parent.savePath(filename)); + filename = parent.savePath(filename); + } else { + String msg = "PImage.save() requires an absolute path. " + + "Use createImage(), or pass savePath() to save()."; + PGraphics.showException(msg); + } + } + + // Make sure the pixel data is ready to go + loadPixels(); + + try { + OutputStream os = null; + + if (saveImageFormats == null) { + saveImageFormats = javax.imageio.ImageIO.getWriterFormatNames(); + } + if (saveImageFormats != null) { + for (int i = 0; i < saveImageFormats.length; i++) { + if (filename.endsWith("." + saveImageFormats[i])) { + saveImageIO(filename); + return; + } + } + } + + if (filename.toLowerCase().endsWith(".tga")) { + os = new BufferedOutputStream(new FileOutputStream(filename), 32768); + success = saveTGA(os); //, pixels, width, height, format); + + } else { + if (!filename.toLowerCase().endsWith(".tif") && + !filename.toLowerCase().endsWith(".tiff")) { + // if no .tif extension, add it.. + filename += ".tif"; + } + os = new BufferedOutputStream(new FileOutputStream(filename), 32768); + success = saveTIFF(os); //, pixels, width, height); + } + os.flush(); + os.close(); + + } catch (IOException e) { + //System.err.println("Error while saving image."); + e.printStackTrace(); + success = false; + } + if (!success) { + throw new RuntimeException("Error while saving image."); + } + } +} + diff --git a/support/Processing_core_src/processing/core/PLine.java b/support/Processing_core_src/processing/core/PLine.java new file mode 100644 index 0000000..a18afda --- /dev/null +++ b/support/Processing_core_src/processing/core/PLine.java @@ -0,0 +1,1278 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-07 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + */ + +package processing.core; + + +/** + * Code for rendering lines with P2D and P3D. + * @author rocha + * @author fry + */ +public class PLine implements PConstants +{ + private int[] m_pixels; + private float[] m_zbuffer; + //private int[] m_stencil; + + private int m_index; + + static final int R_COLOR = 0x1; + static final int R_ALPHA = 0x2; + static final int R_SPATIAL = 0x8; + static final int R_THICK = 0x4; + static final int R_SMOOTH = 0x10; + + private int SCREEN_WIDTH; + private int SCREEN_HEIGHT; + private int SCREEN_WIDTH1; + private int SCREEN_HEIGHT1; + + public boolean INTERPOLATE_RGB; + public boolean INTERPOLATE_ALPHA; + public boolean INTERPOLATE_Z; + public boolean INTERPOLATE_THICK; + + // antialias + private boolean SMOOTH; + + // blender + //private boolean BLENDER; + + // stroke color + private int m_stroke; + + // draw flags + public int m_drawFlags; + + // vertex coordinates + private float[] x_array; + private float[] y_array; + private float[] z_array; + + // vertex intensity + private float[] r_array; + private float[] g_array; + private float[] b_array; + private float[] a_array; + + // vertex offsets + private int o0; + private int o1; + + // start values + private float m_r0; + private float m_g0; + private float m_b0; + private float m_a0; + private float m_z0; + + // deltas + private float dz; + + // rgba deltas + private float dr; + private float dg; + private float db; + private float da; + + private PGraphics parent; + + + public PLine(PGraphics g) { + INTERPOLATE_Z = false; + + x_array = new float[2]; + y_array = new float[2]; + z_array = new float[2]; + r_array = new float[2]; + g_array = new float[2]; + b_array = new float[2]; + a_array = new float[2]; + + this.parent = g; + } + + + public void reset() { + // reset these in case PGraphics was resized + SCREEN_WIDTH = parent.width; + SCREEN_HEIGHT = parent.height; + SCREEN_WIDTH1 = SCREEN_WIDTH-1; + SCREEN_HEIGHT1 = SCREEN_HEIGHT-1; + + m_pixels = parent.pixels; + //m_stencil = parent.stencil; + if (parent instanceof PGraphics3D) { + m_zbuffer = ((PGraphics3D) parent).zbuffer; + } + + // other things to reset + + INTERPOLATE_RGB = false; + INTERPOLATE_ALPHA = false; + //INTERPOLATE_Z = false; + m_drawFlags = 0; + m_index = 0; + //BLENDER = false; + } + + + public void setVertices(float x0, float y0, float z0, + float x1, float y1, float z1) { + // [rocha] fixed z drawing, so whenever a line turns on + // z interpolation, all the lines are z interpolated + if (z0 != z1 || z0 != 0.0f || z1 != 0.0f || INTERPOLATE_Z) { + INTERPOLATE_Z = true; + m_drawFlags |= R_SPATIAL; + } else { + INTERPOLATE_Z = false; + m_drawFlags &= ~R_SPATIAL; + } + + z_array[0] = z0; + z_array[1] = z1; + + x_array[0] = x0; + x_array[1] = x1; + + y_array[0] = y0; + y_array[1] = y1; + } + + + public void setIntensities(float r0, float g0, float b0, float a0, + float r1, float g1, float b1, float a1) { + a_array[0] = (a0 * 253f + 1.0f) * 65536f; + a_array[1] = (a1 * 253f + 1.0f) * 65536f; + + // check if we need alpha or not? + if ((a0 != 1.0f) || (a1 != 1.0f)) { + INTERPOLATE_ALPHA = true; + m_drawFlags |= R_ALPHA; + } else { + INTERPOLATE_ALPHA = false; + m_drawFlags &= ~R_ALPHA; + } + + // extra scaling added to prevent color "overflood" due to rounding errors + r_array[0] = (r0 * 253f + 1.0f) * 65536f; + r_array[1] = (r1 * 253f + 1.0f) * 65536f; + + g_array[0] = (g0 * 253f + 1.0f) * 65536f; + g_array[1] = (g1 * 253f + 1.0f) * 65536f; + + b_array[0] = (b0 * 253f + 1.0f) * 65536f; + b_array[1] = (b1 * 253f + 1.0f) * 65536f; + + // check if we need to interpolate the intensity values + if (r0 != r1) { + INTERPOLATE_RGB = true; + m_drawFlags |= R_COLOR; + + } else if (g0 != g1) { + INTERPOLATE_RGB = true; + m_drawFlags |= R_COLOR; + + } else if (b0 != b1) { + INTERPOLATE_RGB = true; + m_drawFlags |= R_COLOR; + + } else { + // when plain we use the stroke color of the first vertex + m_stroke = 0xFF000000 | + ((int)(255*r0) << 16) | ((int)(255*g0) << 8) | (int)(255*b0); + INTERPOLATE_RGB = false; + m_drawFlags &= ~R_COLOR; + } + } + + + public void setIndex(int index) { + m_index = index; + //BLENDER = false; + if (m_index != -1) { + //BLENDER = true; + } else { + m_index = 0; + } + } + + + public void draw() { + int xi; + int yi; + int length; + boolean visible = true; + + if (parent.smooth) { + SMOOTH = true; + m_drawFlags |= R_SMOOTH; + + } else { + SMOOTH = false; + m_drawFlags &= ~R_SMOOTH; + } + + /* + // line hack + if (parent.hints[DISABLE_FLYING_POO]) { + float nwidth2 = -SCREEN_WIDTH; + float nheight2 = -SCREEN_HEIGHT; + float width2 = SCREEN_WIDTH * 2; + float height2 = SCREEN_HEIGHT * 2; + if ((x_array[1] < nwidth2) || + (x_array[1] > width2) || + (x_array[0] < nwidth2) || + (x_array[0] > width2) || + (y_array[1] < nheight2) || + (y_array[1] > height2) || + (y_array[0] < nheight2) || + (y_array[0] > height2)) { + return; // this is a bad line + } + } + */ + + /////////////////////////////////////// + // line clipping + visible = lineClipping(); + if (!visible) { + return; + } + + /////////////////////////////////////// + // calculate line values + int shortLen; + int longLen; + boolean yLonger; + int dt; + + yLonger = false; + + // HACK for drawing lines left-to-right for rev 0069 + // some kind of bug exists with the line-stepping algorithm + // that causes strange patterns in the anti-aliasing. + // [040228 fry] + // + // swap rgba as well as the coords.. oops + // [040712 fry] + // + if (x_array[1] < x_array[0]) { + float t; + + t = x_array[1]; x_array[1] = x_array[0]; x_array[0] = t; + t = y_array[1]; y_array[1] = y_array[0]; y_array[0] = t; + t = z_array[1]; z_array[1] = z_array[0]; z_array[0] = t; + + t = r_array[1]; r_array[1] = r_array[0]; r_array[0] = t; + t = g_array[1]; g_array[1] = g_array[0]; g_array[0] = t; + t = b_array[1]; b_array[1] = b_array[0]; b_array[0] = t; + t = a_array[1]; a_array[1] = a_array[0]; a_array[0] = t; + } + + // important - don't change the casts + // is needed this way for line drawing algorithm + longLen = (int)x_array[1] - (int)x_array[0]; + shortLen = (int)y_array[1] - (int)y_array[0]; + + if (Math.abs(shortLen) > Math.abs(longLen)) { + int swap = shortLen; + shortLen = longLen; + longLen = swap; + yLonger = true; + } + + // now we sort points so longLen is always positive + // and we always start drawing from x[0], y[0] + if (longLen < 0) { + // swap order + o0 = 1; + o1 = 0; + + xi = (int) x_array[1]; + yi = (int) y_array[1]; + + length = -longLen; + + } else { + o0 = 0; + o1 = 1; + + xi = (int) x_array[0]; + yi = (int) y_array[0]; + + length = longLen; + } + + // calculate dt + if (length == 0) { + dt = 0; + } else { + dt = (shortLen << 16) / longLen; + } + + m_r0 = r_array[o0]; + m_g0 = g_array[o0]; + m_b0 = b_array[o0]; + + if (INTERPOLATE_RGB) { + dr = (r_array[o1] - r_array[o0]) / length; + dg = (g_array[o1] - g_array[o0]) / length; + db = (b_array[o1] - b_array[o0]) / length; + } else { + dr = 0; + dg = 0; + db = 0; + } + + m_a0 = a_array[o0]; + + if (INTERPOLATE_ALPHA) { + da = (a_array[o1] - a_array[o0]) / length; + } else { + da = 0; + } + + m_z0 = z_array[o0]; + //z0 += -0.001f; // [rocha] ugly fix for z buffer precision + + if (INTERPOLATE_Z) { + dz = (z_array[o1] - z_array[o0]) / length; + } else { + dz = 0; + } + + // draw thin points + if (length == 0) { + if (INTERPOLATE_ALPHA) { + drawPoint_alpha(xi, yi); + } else { + drawPoint(xi, yi); + } + return; + } + + /* + // draw antialias polygon lines for non stroked polygons + if (BLENDER && SMOOTH) { + // fix for endpoints not being drawn + // [rocha] + drawPoint_alpha((int)x_array[0], (int)x_array[0]); + drawPoint_alpha((int)x_array[1], (int)x_array[1]); + + drawline_blender(x_array[0], y_array[0], x_array[1], y_array[1]); + return; + } + */ + + // draw normal strokes + if (SMOOTH) { +// if ((m_drawFlags & R_SPATIAL) != 0) { +// drawLine_smooth_spatial(xi, yi, dt, length, yLonger); +// } else { + drawLine_smooth(xi, yi, dt, length, yLonger); +// } + + } else { + if (m_drawFlags == 0) { + drawLine_plain(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == R_ALPHA) { + drawLine_plain_alpha(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == R_COLOR) { + drawLine_color(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == (R_COLOR + R_ALPHA)) { + drawLine_color_alpha(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == R_SPATIAL) { + drawLine_plain_spatial(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == (R_SPATIAL + R_ALPHA)) { + drawLine_plain_alpha_spatial(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == (R_SPATIAL + R_COLOR)) { + drawLine_color_spatial(xi, yi, dt, length, yLonger); + + } else if (m_drawFlags == (R_SPATIAL + R_COLOR + R_ALPHA)) { + drawLine_color_alpha_spatial(xi, yi, dt, length, yLonger); + } + } + } + + + public boolean lineClipping() { + // new cohen-sutherland clipping code, as old one was buggy [toxi] + // get the "dips" for the points to clip + int code1 = lineClipCode(x_array[0], y_array[0]); + int code2 = lineClipCode(x_array[1], y_array[1]); + int dip = code1 | code2; + + if ((code1 & code2)!=0) { + + return false; + + } else if (dip != 0) { + + // now calculate the clipped points + float a0 = 0, a1 = 1, a = 0; + + for (int i = 0; i < 4; i++) { + if (((dip>>i)%2)==1){ + a = lineSlope(x_array[0], y_array[0], x_array[1], y_array[1], i+1); + if (((code1 >> i) % 2) == 1) { + a0 = (a>a0)?a:a0; // max(a,a0) + } else { + a1 = (a a1) { + return false; + } else { + float xt = x_array[0]; + float yt = y_array[0]; + + x_array[0] = xt + a0 * (x_array[1] - xt); + y_array[0] = yt + a0 * (y_array[1] - yt); + x_array[1] = xt + a1 * (x_array[1] - xt); + y_array[1] = yt + a1 * (y_array[1] - yt); + + // interpolate remaining parameters + if (INTERPOLATE_RGB) { + float t = r_array[0]; + r_array[0] = t + a0 * (r_array[1] - t); + r_array[1] = t + a1 * (r_array[1] - t); + t = g_array[0]; + g_array[0] = t + a0 * (g_array[1] - t); + g_array[1] = t + a1 * (g_array[1] - t); + t = b_array[0]; + b_array[0] = t + a0 * (b_array[1] - t); + b_array[1] = t + a1 * (b_array[1] - t); + } + + if (INTERPOLATE_ALPHA) { + float t = a_array[0]; + a_array[0] = t + a0 * (a_array[1] - t); + a_array[1] = t + a1 * (a_array[1] - t); + } + } + } + return true; + } + + + private int lineClipCode(float xi, float yi) { + int xmin = 0; + int ymin = 0; + int xmax = SCREEN_WIDTH1; + int ymax = SCREEN_HEIGHT1; + + //return ((yi < ymin ? 8 : 0) | (yi > ymax ? 4 : 0) | + // (xi < xmin ? 2 : 0) | (xi > xmax ? 1 : 0)); + //(int) added by ewjordan 6/13/07 because otherwise we sometimes clip last pixel when it should actually be displayed. + //Currently the min values are okay because values less than 0 should not be rendered; however, bear in mind that + //(int) casts towards zero, so without this clipping, values between -1+eps and +1-eps would all be rendered as 0. + return ((yi < ymin ? 8 : 0) | ((int)yi > ymax ? 4 : 0) | + (xi < xmin ? 2 : 0) | ((int)xi > xmax ? 1 : 0)); + } + + + private float lineSlope(float x1, float y1, float x2, float y2, int border) { + int xmin = 0; + int ymin = 0; + int xmax = SCREEN_WIDTH1; + int ymax = SCREEN_HEIGHT1; + + switch (border) { + case 4: return (ymin-y1)/(y2-y1); + case 3: return (ymax-y1)/(y2-y1); + case 2: return (xmin-x1)/(x2-x1); + case 1: return (xmax-x1)/(x2-x1); + } + return -1f; + } + + + private void drawPoint(int x0, int y0) { + float iz = m_z0; + int offset = y0 * SCREEN_WIDTH + x0; + + if (m_zbuffer == null) { + m_pixels[offset] = m_stroke; + + } else { + if (iz <= m_zbuffer[offset]) { + m_pixels[offset] = m_stroke; + m_zbuffer[offset] = iz; + } + } + } + + + private void drawPoint_alpha(int x0, int y0) { + int ia = (int) a_array[0]; + int pr = m_stroke & 0xFF0000; + int pg = m_stroke & 0xFF00; + int pb = m_stroke & 0xFF; + float iz = m_z0; + int offset = y0 * SCREEN_WIDTH + x0; + + if ((m_zbuffer == null) || iz <= m_zbuffer[offset]) { + int alpha = ia >> 16; + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = iz; + } + } + + + private void drawLine_plain(int x0, int y0, int dt, + int length, boolean vertical) { + // new "extremely fast" line code + // adapted from http://www.edepot.com/linee.html + // first version modified by [toxi] + // simplified by [rocha] + // length must be >= 0 + + //assert length>=0:length; + + int offset = 0; + + if (vertical) { + // vertical + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + m_pixels[offset] = m_stroke; + if (m_zbuffer != null) m_zbuffer[offset] = m_z0; + j+=dt; + } + + } else { + // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + m_pixels[offset] = m_stroke; + if (m_zbuffer != null) m_zbuffer[offset] = m_z0; + j+=dt; + } + } + } + + + private void drawLine_plain_alpha(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + + int pr = m_stroke & 0xFF0000; + int pg = m_stroke & 0xFF00; + int pb = m_stroke & 0xFF; + + int ia = (int) (m_a0); + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + + int alpha = ia >> 16; + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + //m_zbuffer[offset] = m_z0; // don't set zbuffer w/ alpha lines + + ia += da; + j += dt; + } + + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + + int alpha = ia >> 16; + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + //m_zbuffer[offset] = m_z0; // no zbuffer w/ alpha lines + + ia += da; + j += dt; + } + } + } + + + private void drawLine_color(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + + int ir = (int) m_r0; + int ig = (int) m_g0; + int ib = (int) m_b0; + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + m_pixels[offset] = 0xFF000000 | + ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16)); + if (m_zbuffer != null) m_zbuffer[offset] = m_z0; + ir += dr; + ig += dg; + ib += db; + j +=dt; + } + + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + m_pixels[offset] = 0xFF000000 | + ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16)); + if (m_zbuffer != null) m_zbuffer[offset] = m_z0; + ir += dr; + ig += dg; + ib += db; + j += dt; + } + } + } + + + private void drawLine_color_alpha(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + + int ir = (int) m_r0; + int ig = (int) m_g0; + int ib = (int) m_b0; + int ia = (int) m_a0; + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + + int alpha = ia >> 16; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = m_z0; + + ir+= dr; + ig+= dg; + ib+= db; + ia+= da; + j+=dt; + } + + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + + int alpha = ia >> 16; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = m_z0; + + ir+= dr; + ig+= dg; + ib+= db; + ia+= da; + j+=dt; + } + } + } + + + private void drawLine_plain_spatial(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + float iz = m_z0; + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + if (offset < m_pixels.length) { + if (iz <= m_zbuffer[offset]) { + m_pixels[offset] = m_stroke; + m_zbuffer[offset] = iz; + } + } + iz+=dz; + j+=dt; + } + + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + if (offset < m_pixels.length) { + if (iz <= m_zbuffer[offset]) { + m_pixels[offset] = m_stroke; + m_zbuffer[offset] = iz; + } + } + iz+=dz; + j+=dt; + } + } + } + + + private void drawLine_plain_alpha_spatial(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + float iz = m_z0; + + int pr = m_stroke & 0xFF0000; + int pg = m_stroke & 0xFF00; + int pb = m_stroke & 0xFF; + + int ia = (int) m_a0; + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + if (offset < m_pixels.length) { + if (iz <= m_zbuffer[offset]) { + int alpha = ia >> 16; + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + m_zbuffer[offset] = iz; + } + } + iz +=dz; + ia += da; + j += dt; + } + + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + + if (offset < m_pixels.length) { + if (iz <= m_zbuffer[offset]) { + int alpha = ia >> 16; + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + m_zbuffer[offset] = iz; + } + } + iz += dz; + ia += da; + j += dt; + } + } + } + + + private void drawLine_color_spatial(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + float iz = m_z0; + + int ir = (int) m_r0; + int ig = (int) m_g0; + int ib = (int) m_b0; + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + + if (iz <= m_zbuffer[offset]) { + m_pixels[offset] = 0xFF000000 | + ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16)); + m_zbuffer[offset] = iz; + } + iz +=dz; + ir += dr; + ig += dg; + ib += db; + j += dt; + } + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + if (iz <= m_zbuffer[offset]) { + m_pixels[offset] = 0xFF000000 | + ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16)); + m_zbuffer[offset] = iz; + } + iz += dz; + ir += dr; + ig += dg; + ib += db; + j += dt; + } + return; + } + } + + + private void drawLine_color_alpha_spatial(int x0, int y0, int dt, + int length, boolean vertical) { + int offset = 0; + float iz = m_z0; + + int ir = (int) m_r0; + int ig = (int) m_g0; + int ib = (int) m_b0; + int ia = (int) m_a0; + + if (vertical) { + length += y0; + for (int j = 0x8000 + (x0<<16); y0 <= length; ++y0) { + offset = y0 * SCREEN_WIDTH + (j>>16); + + if (iz <= m_zbuffer[offset]) { + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + + int alpha = ia >> 16; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + m_zbuffer[offset] = iz; + } + iz+=dz; + ir+= dr; + ig+= dg; + ib+= db; + ia+= da; + j+=dt; + } + + } else { // horizontal + length += x0; + for (int j = 0x8000 + (y0<<16); x0 <= length; ++x0) { + offset = (j>>16) * SCREEN_WIDTH + x0; + + if (iz <= m_zbuffer[offset]) { + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + int alpha = ia >> 16; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + m_zbuffer[offset] = iz; + } + iz += dz; + ir += dr; + ig += dg; + ib += db; + ia += da; + j += dt; + } + } + } + + + private void drawLine_smooth(int x0, int y0, int dt, + int length, boolean vertical) { + int xi, yi; // these must be >=32 bits + int offset = 0; + int temp; + int end; + + float iz = m_z0; + + int ir = (int) m_r0; + int ig = (int) m_g0; + int ib = (int) m_b0; + int ia = (int) m_a0; + + if (vertical) { + xi = x0 << 16; + yi = y0 << 16; + + end = length + y0; + + while ((yi >> 16) < end) { + + offset = (yi>>16) * SCREEN_WIDTH + (xi>>16); + + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) { + int alpha = (((~xi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = iz; + } + + // this if() makes things slow. there should be a better way to check + // if the second pixel is within the image array [rocha] + temp = ((xi>>16)+1); + if (temp >= SCREEN_WIDTH) { + xi += dt; + yi += (1 << 16); + continue; + } + + offset = (yi>>16) * SCREEN_WIDTH + temp; + + if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) { + int alpha = (((xi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = iz; + } + + xi += dt; + yi += (1 << 16); + + iz+=dz; + ir+= dr; + ig+= dg; + ib+= db; + ia+= da; + } + + } else { // horizontal + xi = x0 << 16; + yi = y0 << 16; + end = length + x0; + + while ((xi >> 16) < end) { + offset = (yi>>16) * SCREEN_WIDTH + (xi>>16); + + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) { + int alpha = (((~yi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = iz; + } + + // see above [rocha] + temp = ((yi>>16)+1); + if (temp >= SCREEN_HEIGHT) { + xi += (1 << 16); + yi += dt; + continue; + } + + offset = temp * SCREEN_WIDTH + (xi>>16); + + if ((m_zbuffer == null) || (iz <= m_zbuffer[offset])) { + int alpha = (((yi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0&=0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + if (m_zbuffer != null) m_zbuffer[offset] = iz; + } + + xi += (1 << 16); + yi += dt; + + iz += dz; + ir += dr; + ig += dg; + ib += db; + ia += da; + } + } + } + + + /* + void drawLine_smooth(int x0, int y0, int dt, + int length, boolean vertical) { + int xi, yi; // these must be >=32 bits + int offset = 0; + int temp; + int end; + + int ir = (int) m_r0; + int ig = (int) m_g0; + int ib = (int) m_b0; + int ia = (int) m_a0; + + if (vertical) { + xi = x0 << 16; + yi = y0 << 16; + + end = length + y0; + + while ((yi >> 16) < end) { + offset = (yi>>16) * SCREEN_WIDTH + (xi>>16); + + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + int alpha = (((~xi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + + // this if() makes things slow. there should be a better way to check + // if the second pixel is within the image array [rocha] + temp = ((xi>>16)+1); + if (temp >= SCREEN_WIDTH) { + xi += dt; + yi += (1 << 16); + continue; + } + + offset = (yi>>16) * SCREEN_WIDTH + temp; + + alpha = (((xi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + r0 = m_pixels[offset]; + g0 = r0 & 0xFF00; + b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + + xi += dt; + yi += (1 << 16); + + ir += dr; + ig += dg; + ib += db; + ia += da; + } + + } else { // horizontal + xi = x0 << 16; + yi = y0 << 16; + end = length + x0; + + while ((xi >> 16) < end) { + offset = (yi>>16) * SCREEN_WIDTH + (xi>>16); + + int pr = ir & 0xFF0000; + int pg = (ig >> 8) & 0xFF00; + int pb = (ib >> 16); + + int alpha = (((~yi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + int r0 = m_pixels[offset]; + int g0 = r0 & 0xFF00; + int b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + + // see above [rocha] + temp = ((yi>>16)+1); + if (temp >= SCREEN_HEIGHT) { + xi += (1 << 16); + yi += dt; + continue; + } + + offset = temp * SCREEN_WIDTH + (xi>>16); + + alpha = (((yi >> 8) & 0xFF) * (ia >> 16)) >> 8; + + r0 = m_pixels[offset]; + g0 = r0 & 0xFF00; + b0 = r0 & 0xFF; + r0 &= 0xFF0000; + + r0 = r0 + (((pr - r0) * alpha) >> 8); + g0 = g0 + (((pg - g0) * alpha) >> 8); + b0 = b0 + (((pb - b0) * alpha) >> 8); + + m_pixels[offset] = 0xFF000000 | + (r0 & 0xFF0000) | (g0 & 0xFF00) | (b0 & 0xFF); + + xi += (1 << 16); + yi += dt; + + ir+= dr; + ig+= dg; + ib+= db; + ia+= da; + } + } + } + */ +} diff --git a/support/Processing_core_src/processing/core/PMatrix.java b/support/Processing_core_src/processing/core/PMatrix.java new file mode 100644 index 0000000..53f7fa5 --- /dev/null +++ b/support/Processing_core_src/processing/core/PMatrix.java @@ -0,0 +1,150 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2005-08 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + + +public interface PMatrix { + + public void reset(); + + /** + * Returns a copy of this PMatrix. + */ + public PMatrix get(); + + /** + * Copies the matrix contents into a float array. + * If target is null (or not the correct size), a new array will be created. + */ + public float[] get(float[] target); + + + public void set(PMatrix src); + + public void set(float[] source); + + public void set(float m00, float m01, float m02, + float m10, float m11, float m12); + + public void set(float m00, float m01, float m02, float m03, + float m10, float m11, float m12, float m13, + float m20, float m21, float m22, float m23, + float m30, float m31, float m32, float m33); + + + public void translate(float tx, float ty); + + public void translate(float tx, float ty, float tz); + + public void rotate(float angle); + + public void rotateX(float angle); + + public void rotateY(float angle); + + public void rotateZ(float angle); + + public void rotate(float angle, float v0, float v1, float v2); + + public void scale(float s); + + public void scale(float sx, float sy); + + public void scale(float x, float y, float z); + + public void shearX(float angle); + + public void shearY(float angle); + + /** + * Multiply this matrix by another. + */ + public void apply(PMatrix source); + + public void apply(PMatrix2D source); + + public void apply(PMatrix3D source); + + public void apply(float n00, float n01, float n02, + float n10, float n11, float n12); + + public void apply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33); + + /** + * Apply another matrix to the left of this one. + */ + public void preApply(PMatrix2D left); + + public void preApply(PMatrix3D left); + + public void preApply(float n00, float n01, float n02, + float n10, float n11, float n12); + + public void preApply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33); + + + /** + * Multiply a PVector by this matrix. + */ + public PVector mult(PVector source, PVector target); + + + /** + * Multiply a multi-element vector against this matrix. + */ + public float[] mult(float[] source, float[] target); + + +// public float multX(float x, float y); +// public float multY(float x, float y); + +// public float multX(float x, float y, float z); +// public float multY(float x, float y, float z); +// public float multZ(float x, float y, float z); + + + /** + * Transpose this matrix. + */ + public void transpose(); + + + /** + * Invert this matrix. + * @return true if successful + */ + public boolean invert(); + + + /** + * @return the determinant of the matrix + */ + public float determinant(); +} \ No newline at end of file diff --git a/support/Processing_core_src/processing/core/PMatrix2D.java b/support/Processing_core_src/processing/core/PMatrix2D.java new file mode 100644 index 0000000..fb18dd7 --- /dev/null +++ b/support/Processing_core_src/processing/core/PMatrix2D.java @@ -0,0 +1,454 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2005-08 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + + +/** + * 3x2 affine matrix implementation. + */ +public class PMatrix2D implements PMatrix { + + public float m00, m01, m02; + public float m10, m11, m12; + + + public PMatrix2D() { + reset(); + } + + + public PMatrix2D(float m00, float m01, float m02, + float m10, float m11, float m12) { + set(m00, m01, m02, + m10, m11, m12); + } + + + public PMatrix2D(PMatrix matrix) { + set(matrix); + } + + + public void reset() { + set(1, 0, 0, + 0, 1, 0); + } + + + /** + * Returns a copy of this PMatrix. + */ + public PMatrix2D get() { + PMatrix2D outgoing = new PMatrix2D(); + outgoing.set(this); + return outgoing; + } + + + /** + * Copies the matrix contents into a 6 entry float array. + * If target is null (or not the correct size), a new array will be created. + */ + public float[] get(float[] target) { + if ((target == null) || (target.length != 6)) { + target = new float[6]; + } + target[0] = m00; + target[1] = m01; + target[2] = m02; + + target[3] = m10; + target[4] = m11; + target[5] = m12; + + return target; + } + + + public void set(PMatrix matrix) { + if (matrix instanceof PMatrix2D) { + PMatrix2D src = (PMatrix2D) matrix; + set(src.m00, src.m01, src.m02, + src.m10, src.m11, src.m12); + } else { + throw new IllegalArgumentException("PMatrix2D.set() only accepts PMatrix2D objects."); + } + } + + + public void set(PMatrix3D src) { + } + + + public void set(float[] source) { + m00 = source[0]; + m01 = source[1]; + m02 = source[2]; + + m10 = source[3]; + m11 = source[4]; + m12 = source[5]; + } + + + public void set(float m00, float m01, float m02, + float m10, float m11, float m12) { + this.m00 = m00; this.m01 = m01; this.m02 = m02; + this.m10 = m10; this.m11 = m11; this.m12 = m12; + } + + + public void set(float m00, float m01, float m02, float m03, + float m10, float m11, float m12, float m13, + float m20, float m21, float m22, float m23, + float m30, float m31, float m32, float m33) { + + } + + + public void translate(float tx, float ty) { + m02 = tx*m00 + ty*m01 + m02; + m12 = tx*m10 + ty*m11 + m12; + } + + + public void translate(float x, float y, float z) { + throw new IllegalArgumentException("Cannot use translate(x, y, z) on a PMatrix2D."); + } + + + // Implementation roughly based on AffineTransform. + public void rotate(float angle) { + float s = sin(angle); + float c = cos(angle); + + float temp1 = m00; + float temp2 = m01; + m00 = c * temp1 + s * temp2; + m01 = -s * temp1 + c * temp2; + temp1 = m10; + temp2 = m11; + m10 = c * temp1 + s * temp2; + m11 = -s * temp1 + c * temp2; + } + + + public void rotateX(float angle) { + throw new IllegalArgumentException("Cannot use rotateX() on a PMatrix2D."); + } + + + public void rotateY(float angle) { + throw new IllegalArgumentException("Cannot use rotateY() on a PMatrix2D."); + } + + + public void rotateZ(float angle) { + rotate(angle); + } + + + public void rotate(float angle, float v0, float v1, float v2) { + throw new IllegalArgumentException("Cannot use this version of rotate() on a PMatrix2D."); + } + + + public void scale(float s) { + scale(s, s); + } + + + public void scale(float sx, float sy) { + m00 *= sx; m01 *= sy; + m10 *= sx; m11 *= sy; + } + + + public void scale(float x, float y, float z) { + throw new IllegalArgumentException("Cannot use this version of scale() on a PMatrix2D."); + } + + + public void shearX(float angle) { + apply(1, 0, 1, tan(angle), 0, 0); + } + + + public void shearY(float angle) { + apply(1, 0, 1, 0, tan(angle), 0); + } + + + public void apply(PMatrix source) { + if (source instanceof PMatrix2D) { + apply((PMatrix2D) source); + } else if (source instanceof PMatrix3D) { + apply((PMatrix3D) source); + } + } + + + public void apply(PMatrix2D source) { + apply(source.m00, source.m01, source.m02, + source.m10, source.m11, source.m12); + } + + + public void apply(PMatrix3D source) { + throw new IllegalArgumentException("Cannot use apply(PMatrix3D) on a PMatrix2D."); + } + + + public void apply(float n00, float n01, float n02, + float n10, float n11, float n12) { + float t0 = m00; + float t1 = m01; + m00 = n00 * t0 + n10 * t1; + m01 = n01 * t0 + n11 * t1; + m02 += n02 * t0 + n12 * t1; + + t0 = m10; + t1 = m11; + m10 = n00 * t0 + n10 * t1; + m11 = n01 * t0 + n11 * t1; + m12 += n02 * t0 + n12 * t1; + } + + + public void apply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + throw new IllegalArgumentException("Cannot use this version of apply() on a PMatrix2D."); + } + + + /** + * Apply another matrix to the left of this one. + */ + public void preApply(PMatrix2D left) { + preApply(left.m00, left.m01, left.m02, + left.m10, left.m11, left.m12); + } + + + public void preApply(PMatrix3D left) { + throw new IllegalArgumentException("Cannot use preApply(PMatrix3D) on a PMatrix2D."); + } + + + public void preApply(float n00, float n01, float n02, + float n10, float n11, float n12) { + float t0 = m02; + float t1 = m12; + n02 += t0 * n00 + t1 * n01; + n12 += t0 * n10 + t1 * n11; + + m02 = n02; + m12 = n12; + + t0 = m00; + t1 = m10; + m00 = t0 * n00 + t1 * n01; + m10 = t0 * n10 + t1 * n11; + + t0 = m01; + t1 = m11; + m01 = t0 * n00 + t1 * n01; + m11 = t0 * n10 + t1 * n11; + } + + + public void preApply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + throw new IllegalArgumentException("Cannot use this version of preApply() on a PMatrix2D."); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * Multiply the x and y coordinates of a PVector against this matrix. + */ + public PVector mult(PVector source, PVector target) { + if (target == null) { + target = new PVector(); + } + target.x = m00*source.x + m01*source.y + m02; + target.y = m10*source.x + m11*source.y + m12; + return target; + } + + + /** + * Multiply a two element vector against this matrix. + * If out is null or not length four, a new float array will be returned. + * The values for vec and out can be the same (though that's less efficient). + */ + public float[] mult(float vec[], float out[]) { + if (out == null || out.length != 2) { + out = new float[2]; + } + + if (vec == out) { + float tx = m00*vec[0] + m01*vec[1] + m02; + float ty = m10*vec[0] + m11*vec[1] + m12; + + out[0] = tx; + out[1] = ty; + + } else { + out[0] = m00*vec[0] + m01*vec[1] + m02; + out[1] = m10*vec[0] + m11*vec[1] + m12; + } + + return out; + } + + + public float multX(float x, float y) { + return m00*x + m01*y + m02; + } + + + public float multY(float x, float y) { + return m10*x + m11*y + m12; + } + + + /** + * Transpose this matrix. + */ + public void transpose() { + } + + + /** + * Invert this matrix. Implementation stolen from OpenJDK. + * @return true if successful + */ + public boolean invert() { + float determinant = determinant(); + if (Math.abs(determinant) <= Float.MIN_VALUE) { + return false; + } + + float t00 = m00; + float t01 = m01; + float t02 = m02; + float t10 = m10; + float t11 = m11; + float t12 = m12; + + m00 = t11 / determinant; + m10 = -t10 / determinant; + m01 = -t01 / determinant; + m11 = t00 / determinant; + m02 = (t01 * t12 - t11 * t02) / determinant; + m12 = (t10 * t02 - t00 * t12) / determinant; + + return true; + } + + + /** + * @return the determinant of the matrix + */ + public float determinant() { + return m00 * m11 - m01 * m10; + } + + + ////////////////////////////////////////////////////////////// + + + public void print() { + int big = (int) abs(max(PApplet.max(abs(m00), abs(m01), abs(m02)), + PApplet.max(abs(m10), abs(m11), abs(m12)))); + + int digits = 1; + if (Float.isNaN(big) || Float.isInfinite(big)) { // avoid infinite loop + digits = 5; + } else { + while ((big /= 10) != 0) digits++; // cheap log() + } + + System.out.println(PApplet.nfs(m00, digits, 4) + " " + + PApplet.nfs(m01, digits, 4) + " " + + PApplet.nfs(m02, digits, 4)); + + System.out.println(PApplet.nfs(m10, digits, 4) + " " + + PApplet.nfs(m11, digits, 4) + " " + + PApplet.nfs(m12, digits, 4)); + + System.out.println(); + } + + + ////////////////////////////////////////////////////////////// + + // TODO these need to be added as regular API, but the naming and + // implementation needs to be improved first. (e.g. actually keeping track + // of whether the matrix is in fact identity internally.) + + + protected boolean isIdentity() { + return ((m00 == 1) && (m01 == 0) && (m02 == 0) && + (m10 == 0) && (m11 == 1) && (m12 == 0)); + } + + + // TODO make this more efficient, or move into PMatrix2D + protected boolean isWarped() { + return ((m00 != 1) || (m01 != 0) && + (m10 != 0) || (m11 != 1)); + } + + + ////////////////////////////////////////////////////////////// + + + private final float max(float a, float b) { + return (a > b) ? a : b; + } + + private final float abs(float a) { + return (a < 0) ? -a : a; + } + + private final float sin(float angle) { + return (float)Math.sin(angle); + } + + private final float cos(float angle) { + return (float)Math.cos(angle); + } + + private final float tan(float angle) { + return (float)Math.tan(angle); + } +} diff --git a/support/Processing_core_src/processing/core/PMatrix3D.java b/support/Processing_core_src/processing/core/PMatrix3D.java new file mode 100644 index 0000000..f4ac562 --- /dev/null +++ b/support/Processing_core_src/processing/core/PMatrix3D.java @@ -0,0 +1,782 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2005-08 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + + +/** + * 4x4 matrix implementation. + */ +public final class PMatrix3D implements PMatrix /*, PConstants*/ { + + public float m00, m01, m02, m03; + public float m10, m11, m12, m13; + public float m20, m21, m22, m23; + public float m30, m31, m32, m33; + + + // locally allocated version to avoid creating new memory + protected PMatrix3D inverseCopy; + + + public PMatrix3D() { + reset(); + } + + + public PMatrix3D(float m00, float m01, float m02, + float m10, float m11, float m12) { + set(m00, m01, m02, 0, + m10, m11, m12, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public PMatrix3D(float m00, float m01, float m02, float m03, + float m10, float m11, float m12, float m13, + float m20, float m21, float m22, float m23, + float m30, float m31, float m32, float m33) { + set(m00, m01, m02, m03, + m10, m11, m12, m13, + m20, m21, m22, m23, + m30, m31, m32, m33); + } + + + public PMatrix3D(PMatrix matrix) { + set(matrix); + } + + + public void reset() { + set(1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + /** + * Returns a copy of this PMatrix. + */ + public PMatrix3D get() { + PMatrix3D outgoing = new PMatrix3D(); + outgoing.set(this); + return outgoing; + } + + + /** + * Copies the matrix contents into a 16 entry float array. + * If target is null (or not the correct size), a new array will be created. + */ + public float[] get(float[] target) { + if ((target == null) || (target.length != 16)) { + target = new float[16]; + } + target[0] = m00; + target[1] = m01; + target[2] = m02; + target[3] = m03; + + target[4] = m10; + target[5] = m11; + target[6] = m12; + target[7] = m13; + + target[8] = m20; + target[9] = m21; + target[10] = m22; + target[11] = m23; + + target[12] = m30; + target[13] = m31; + target[14] = m32; + target[15] = m33; + + return target; + } + + + public void set(PMatrix matrix) { + if (matrix instanceof PMatrix3D) { + PMatrix3D src = (PMatrix3D) matrix; + set(src.m00, src.m01, src.m02, src.m03, + src.m10, src.m11, src.m12, src.m13, + src.m20, src.m21, src.m22, src.m23, + src.m30, src.m31, src.m32, src.m33); + } else { + PMatrix2D src = (PMatrix2D) matrix; + set(src.m00, src.m01, 0, src.m02, + src.m10, src.m11, 0, src.m12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + } + + + public void set(float[] source) { + if (source.length == 6) { + set(source[0], source[1], source[2], + source[3], source[4], source[5]); + + } else if (source.length == 16) { + m00 = source[0]; + m01 = source[1]; + m02 = source[2]; + m03 = source[3]; + + m10 = source[4]; + m11 = source[5]; + m12 = source[6]; + m13 = source[7]; + + m20 = source[8]; + m21 = source[9]; + m22 = source[10]; + m23 = source[11]; + + m30 = source[12]; + m31 = source[13]; + m32 = source[14]; + m33 = source[15]; + } + } + + + public void set(float m00, float m01, float m02, + float m10, float m11, float m12) { + set(m00, m01, 0, m02, + m10, m11, 0, m12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void set(float m00, float m01, float m02, float m03, + float m10, float m11, float m12, float m13, + float m20, float m21, float m22, float m23, + float m30, float m31, float m32, float m33) { + this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; + this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; + this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; + this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; + } + + + public void translate(float tx, float ty) { + translate(tx, ty, 0); + } + +// public void invTranslate(float tx, float ty) { +// invTranslate(tx, ty, 0); +// } + + + public void translate(float tx, float ty, float tz) { + m03 += tx*m00 + ty*m01 + tz*m02; + m13 += tx*m10 + ty*m11 + tz*m12; + m23 += tx*m20 + ty*m21 + tz*m22; + m33 += tx*m30 + ty*m31 + tz*m32; + } + + + public void rotate(float angle) { + rotateZ(angle); + } + + + public void rotateX(float angle) { + float c = cos(angle); + float s = sin(angle); + apply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); + } + + + public void rotateY(float angle) { + float c = cos(angle); + float s = sin(angle); + apply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + } + + + public void rotateZ(float angle) { + float c = cos(angle); + float s = sin(angle); + apply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + + + public void rotate(float angle, float v0, float v1, float v2) { + // TODO should make sure this vector is normalized + + float c = cos(angle); + float s = sin(angle); + float t = 1.0f - c; + + apply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0, + (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0, + (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0, + 0, 0, 0, 1); + } + + + public void scale(float s) { + //apply(s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1); + scale(s, s, s); + } + + + public void scale(float sx, float sy) { + //apply(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + scale(sx, sy, 1); + } + + + public void scale(float x, float y, float z) { + //apply(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + m00 *= x; m01 *= y; m02 *= z; + m10 *= x; m11 *= y; m12 *= z; + m20 *= x; m21 *= y; m22 *= z; + m30 *= x; m31 *= y; m32 *= z; + } + + + public void shearX(float angle) { + float t = (float) Math.tan(angle); + apply(1, t, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void shearY(float angle) { + float t = (float) Math.tan(angle); + apply(1, 0, 0, 0, + t, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void apply(PMatrix source) { + if (source instanceof PMatrix2D) { + apply((PMatrix2D) source); + } else if (source instanceof PMatrix3D) { + apply((PMatrix3D) source); + } + } + + + public void apply(PMatrix2D source) { + apply(source.m00, source.m01, 0, source.m02, + source.m10, source.m11, 0, source.m12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void apply(PMatrix3D source) { + apply(source.m00, source.m01, source.m02, source.m03, + source.m10, source.m11, source.m12, source.m13, + source.m20, source.m21, source.m22, source.m23, + source.m30, source.m31, source.m32, source.m33); + } + + + public void apply(float n00, float n01, float n02, + float n10, float n11, float n12) { + apply(n00, n01, 0, n02, + n10, n11, 0, n12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void apply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + + float r00 = m00*n00 + m01*n10 + m02*n20 + m03*n30; + float r01 = m00*n01 + m01*n11 + m02*n21 + m03*n31; + float r02 = m00*n02 + m01*n12 + m02*n22 + m03*n32; + float r03 = m00*n03 + m01*n13 + m02*n23 + m03*n33; + + float r10 = m10*n00 + m11*n10 + m12*n20 + m13*n30; + float r11 = m10*n01 + m11*n11 + m12*n21 + m13*n31; + float r12 = m10*n02 + m11*n12 + m12*n22 + m13*n32; + float r13 = m10*n03 + m11*n13 + m12*n23 + m13*n33; + + float r20 = m20*n00 + m21*n10 + m22*n20 + m23*n30; + float r21 = m20*n01 + m21*n11 + m22*n21 + m23*n31; + float r22 = m20*n02 + m21*n12 + m22*n22 + m23*n32; + float r23 = m20*n03 + m21*n13 + m22*n23 + m23*n33; + + float r30 = m30*n00 + m31*n10 + m32*n20 + m33*n30; + float r31 = m30*n01 + m31*n11 + m32*n21 + m33*n31; + float r32 = m30*n02 + m31*n12 + m32*n22 + m33*n32; + float r33 = m30*n03 + m31*n13 + m32*n23 + m33*n33; + + m00 = r00; m01 = r01; m02 = r02; m03 = r03; + m10 = r10; m11 = r11; m12 = r12; m13 = r13; + m20 = r20; m21 = r21; m22 = r22; m23 = r23; + m30 = r30; m31 = r31; m32 = r32; m33 = r33; + } + + + public void preApply(PMatrix2D left) { + preApply(left.m00, left.m01, 0, left.m02, + left.m10, left.m11, 0, left.m12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + /** + * Apply another matrix to the left of this one. + */ + public void preApply(PMatrix3D left) { + preApply(left.m00, left.m01, left.m02, left.m03, + left.m10, left.m11, left.m12, left.m13, + left.m20, left.m21, left.m22, left.m23, + left.m30, left.m31, left.m32, left.m33); + } + + + public void preApply(float n00, float n01, float n02, + float n10, float n11, float n12) { + preApply(n00, n01, 0, n02, + n10, n11, 0, n12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void preApply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + + float r00 = n00*m00 + n01*m10 + n02*m20 + n03*m30; + float r01 = n00*m01 + n01*m11 + n02*m21 + n03*m31; + float r02 = n00*m02 + n01*m12 + n02*m22 + n03*m32; + float r03 = n00*m03 + n01*m13 + n02*m23 + n03*m33; + + float r10 = n10*m00 + n11*m10 + n12*m20 + n13*m30; + float r11 = n10*m01 + n11*m11 + n12*m21 + n13*m31; + float r12 = n10*m02 + n11*m12 + n12*m22 + n13*m32; + float r13 = n10*m03 + n11*m13 + n12*m23 + n13*m33; + + float r20 = n20*m00 + n21*m10 + n22*m20 + n23*m30; + float r21 = n20*m01 + n21*m11 + n22*m21 + n23*m31; + float r22 = n20*m02 + n21*m12 + n22*m22 + n23*m32; + float r23 = n20*m03 + n21*m13 + n22*m23 + n23*m33; + + float r30 = n30*m00 + n31*m10 + n32*m20 + n33*m30; + float r31 = n30*m01 + n31*m11 + n32*m21 + n33*m31; + float r32 = n30*m02 + n31*m12 + n32*m22 + n33*m32; + float r33 = n30*m03 + n31*m13 + n32*m23 + n33*m33; + + m00 = r00; m01 = r01; m02 = r02; m03 = r03; + m10 = r10; m11 = r11; m12 = r12; m13 = r13; + m20 = r20; m21 = r21; m22 = r22; m23 = r23; + m30 = r30; m31 = r31; m32 = r32; m33 = r33; + } + + + ////////////////////////////////////////////////////////////// + + + public PVector mult(PVector source, PVector target) { + if (target == null) { + target = new PVector(); + } + target.x = m00*source.x + m01*source.y + m02*source.z + m03; + target.y = m10*source.x + m11*source.y + m12*source.z + m13; + target.z = m20*source.x + m21*source.y + m22*source.z + m23; +// float tw = m30*source.x + m31*source.y + m32*source.z + m33; +// if (tw != 0 && tw != 1) { +// target.div(tw); +// } + return target; + } + + + /* + public PVector cmult(PVector source, PVector target) { + if (target == null) { + target = new PVector(); + } + target.x = m00*source.x + m10*source.y + m20*source.z + m30; + target.y = m01*source.x + m11*source.y + m21*source.z + m31; + target.z = m02*source.x + m12*source.y + m22*source.z + m32; + float tw = m03*source.x + m13*source.y + m23*source.z + m33; + if (tw != 0 && tw != 1) { + target.div(tw); + } + return target; + } + */ + + + /** + * Multiply a three or four element vector against this matrix. If out is + * null or not length 3 or 4, a new float array (length 3) will be returned. + */ + public float[] mult(float[] source, float[] target) { + if (target == null || target.length < 3) { + target = new float[3]; + } + if (source == target) { + throw new RuntimeException("The source and target vectors used in " + + "PMatrix3D.mult() cannot be identical."); + } + if (target.length == 3) { + target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03; + target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13; + target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23; + //float w = m30*source[0] + m31*source[1] + m32*source[2] + m33; + //if (w != 0 && w != 1) { + // target[0] /= w; target[1] /= w; target[2] /= w; + //} + } else if (target.length > 3) { + target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03*source[3]; + target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13*source[3]; + target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23*source[3]; + target[3] = m30*source[0] + m31*source[1] + m32*source[2] + m33*source[3]; + } + return target; + } + + + public float multX(float x, float y) { + return m00*x + m01*y + m03; + } + + + public float multY(float x, float y) { + return m10*x + m11*y + m13; + } + + + public float multX(float x, float y, float z) { + return m00*x + m01*y + m02*z + m03; + } + + + public float multY(float x, float y, float z) { + return m10*x + m11*y + m12*z + m13; + } + + + public float multZ(float x, float y, float z) { + return m20*x + m21*y + m22*z + m23; + } + + + public float multW(float x, float y, float z) { + return m30*x + m31*y + m32*z + m33; + } + + + public float multX(float x, float y, float z, float w) { + return m00*x + m01*y + m02*z + m03*w; + } + + + public float multY(float x, float y, float z, float w) { + return m10*x + m11*y + m12*z + m13*w; + } + + + public float multZ(float x, float y, float z, float w) { + return m20*x + m21*y + m22*z + m23*w; + } + + + public float multW(float x, float y, float z, float w) { + return m30*x + m31*y + m32*z + m33*w; + } + + + /** + * Transpose this matrix. + */ + public void transpose() { + float temp; + temp = m01; m01 = m10; m10 = temp; + temp = m02; m02 = m20; m20 = temp; + temp = m03; m03 = m30; m30 = temp; + temp = m12; m12 = m21; m21 = temp; + temp = m13; m13 = m31; m31 = temp; + temp = m23; m23 = m32; m32 = temp; + } + + + /** + * Invert this matrix. + * @return true if successful + */ + public boolean invert() { + float determinant = determinant(); + if (determinant == 0) { + return false; + } + + // first row + float t00 = determinant3x3(m11, m12, m13, m21, m22, m23, m31, m32, m33); + float t01 = -determinant3x3(m10, m12, m13, m20, m22, m23, m30, m32, m33); + float t02 = determinant3x3(m10, m11, m13, m20, m21, m23, m30, m31, m33); + float t03 = -determinant3x3(m10, m11, m12, m20, m21, m22, m30, m31, m32); + + // second row + float t10 = -determinant3x3(m01, m02, m03, m21, m22, m23, m31, m32, m33); + float t11 = determinant3x3(m00, m02, m03, m20, m22, m23, m30, m32, m33); + float t12 = -determinant3x3(m00, m01, m03, m20, m21, m23, m30, m31, m33); + float t13 = determinant3x3(m00, m01, m02, m20, m21, m22, m30, m31, m32); + + // third row + float t20 = determinant3x3(m01, m02, m03, m11, m12, m13, m31, m32, m33); + float t21 = -determinant3x3(m00, m02, m03, m10, m12, m13, m30, m32, m33); + float t22 = determinant3x3(m00, m01, m03, m10, m11, m13, m30, m31, m33); + float t23 = -determinant3x3(m00, m01, m02, m10, m11, m12, m30, m31, m32); + + // fourth row + float t30 = -determinant3x3(m01, m02, m03, m11, m12, m13, m21, m22, m23); + float t31 = determinant3x3(m00, m02, m03, m10, m12, m13, m20, m22, m23); + float t32 = -determinant3x3(m00, m01, m03, m10, m11, m13, m20, m21, m23); + float t33 = determinant3x3(m00, m01, m02, m10, m11, m12, m20, m21, m22); + + // transpose and divide by the determinant + m00 = t00 / determinant; + m01 = t10 / determinant; + m02 = t20 / determinant; + m03 = t30 / determinant; + + m10 = t01 / determinant; + m11 = t11 / determinant; + m12 = t21 / determinant; + m13 = t31 / determinant; + + m20 = t02 / determinant; + m21 = t12 / determinant; + m22 = t22 / determinant; + m23 = t32 / determinant; + + m30 = t03 / determinant; + m31 = t13 / determinant; + m32 = t23 / determinant; + m33 = t33 / determinant; + + return true; + } + + + /** + * Calculate the determinant of a 3x3 matrix. + * @return result + */ + private float determinant3x3(float t00, float t01, float t02, + float t10, float t11, float t12, + float t20, float t21, float t22) { + return (t00 * (t11 * t22 - t12 * t21) + + t01 * (t12 * t20 - t10 * t22) + + t02 * (t10 * t21 - t11 * t20)); + } + + + /** + * @return the determinant of the matrix + */ + public float determinant() { + float f = + m00 + * ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32) + - m13 * m22 * m31 + - m11 * m23 * m32 + - m12 * m21 * m33); + f -= m01 + * ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32) + - m13 * m22 * m30 + - m10 * m23 * m32 + - m12 * m20 * m33); + f += m02 + * ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31) + - m13 * m21 * m30 + - m10 * m23 * m31 + - m11 * m20 * m33); + f -= m03 + * ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31) + - m12 * m21 * m30 + - m10 * m22 * m31 + - m11 * m20 * m32); + return f; + } + + + ////////////////////////////////////////////////////////////// + + // REVERSE VERSIONS OF MATRIX OPERATIONS + + // These functions should not be used, as they will be removed in the future. + + + protected void invTranslate(float tx, float ty, float tz) { + preApply(1, 0, 0, -tx, + 0, 1, 0, -ty, + 0, 0, 1, -tz, + 0, 0, 0, 1); + } + + + protected void invRotateX(float angle) { + float c = cos(-angle); + float s = sin(-angle); + preApply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); + } + + + protected void invRotateY(float angle) { + float c = cos(-angle); + float s = sin(-angle); + preApply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + } + + + protected void invRotateZ(float angle) { + float c = cos(-angle); + float s = sin(-angle); + preApply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + + + protected void invRotate(float angle, float v0, float v1, float v2) { + //TODO should make sure this vector is normalized + + float c = cos(-angle); + float s = sin(-angle); + float t = 1.0f - c; + + preApply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0, + (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0, + (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0, + 0, 0, 0, 1); + } + + + protected void invScale(float x, float y, float z) { + preApply(1/x, 0, 0, 0, 0, 1/y, 0, 0, 0, 0, 1/z, 0, 0, 0, 0, 1); + } + + + protected boolean invApply(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + if (inverseCopy == null) { + inverseCopy = new PMatrix3D(); + } + inverseCopy.set(n00, n01, n02, n03, + n10, n11, n12, n13, + n20, n21, n22, n23, + n30, n31, n32, n33); + if (!inverseCopy.invert()) { + return false; + } + preApply(inverseCopy); + return true; + } + + + ////////////////////////////////////////////////////////////// + + + public void print() { + /* + System.out.println(m00 + " " + m01 + " " + m02 + " " + m03 + "\n" + + m10 + " " + m11 + " " + m12 + " " + m13 + "\n" + + m20 + " " + m21 + " " + m22 + " " + m23 + "\n" + + m30 + " " + m31 + " " + m32 + " " + m33 + "\n"); + */ + int big = (int) Math.abs(max(max(max(max(abs(m00), abs(m01)), + max(abs(m02), abs(m03))), + max(max(abs(m10), abs(m11)), + max(abs(m12), abs(m13)))), + max(max(max(abs(m20), abs(m21)), + max(abs(m22), abs(m23))), + max(max(abs(m30), abs(m31)), + max(abs(m32), abs(m33)))))); + + int digits = 1; + if (Float.isNaN(big) || Float.isInfinite(big)) { // avoid infinite loop + digits = 5; + } else { + while ((big /= 10) != 0) digits++; // cheap log() + } + + System.out.println(PApplet.nfs(m00, digits, 4) + " " + + PApplet.nfs(m01, digits, 4) + " " + + PApplet.nfs(m02, digits, 4) + " " + + PApplet.nfs(m03, digits, 4)); + + System.out.println(PApplet.nfs(m10, digits, 4) + " " + + PApplet.nfs(m11, digits, 4) + " " + + PApplet.nfs(m12, digits, 4) + " " + + PApplet.nfs(m13, digits, 4)); + + System.out.println(PApplet.nfs(m20, digits, 4) + " " + + PApplet.nfs(m21, digits, 4) + " " + + PApplet.nfs(m22, digits, 4) + " " + + PApplet.nfs(m23, digits, 4)); + + System.out.println(PApplet.nfs(m30, digits, 4) + " " + + PApplet.nfs(m31, digits, 4) + " " + + PApplet.nfs(m32, digits, 4) + " " + + PApplet.nfs(m33, digits, 4)); + + System.out.println(); + } + + + ////////////////////////////////////////////////////////////// + + + private final float max(float a, float b) { + return (a > b) ? a : b; + } + + private final float abs(float a) { + return (a < 0) ? -a : a; + } + + private final float sin(float angle) { + return (float) Math.sin(angle); + } + + private final float cos(float angle) { + return (float) Math.cos(angle); + } +} diff --git a/support/Processing_core_src/processing/core/PPolygon.java b/support/Processing_core_src/processing/core/PPolygon.java new file mode 100644 index 0000000..0651fbe --- /dev/null +++ b/support/Processing_core_src/processing/core/PPolygon.java @@ -0,0 +1,701 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-08 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + + +/** + * Z-buffer polygon rendering object used by PGraphics2D. + */ +public class PPolygon implements PConstants { + + static final int DEFAULT_SIZE = 64; // this is needed for spheres + float vertices[][] = new float[DEFAULT_SIZE][VERTEX_FIELD_COUNT]; + int vertexCount; + + float r[] = new float[DEFAULT_SIZE]; // storage used by incrementalize + float dr[] = new float[DEFAULT_SIZE]; + float l[] = new float[DEFAULT_SIZE]; // more storage for incrementalize + float dl[] = new float[DEFAULT_SIZE]; + float sp[] = new float[DEFAULT_SIZE]; // temporary storage for scanline + float sdp[] = new float[DEFAULT_SIZE]; + + protected boolean interpX; + protected boolean interpUV; // is this necessary? could just check timage != null + protected boolean interpARGB; + + private int rgba; + private int r2, g2, b2, a2, a2orig; + + PGraphics parent; + int[] pixels; + // the parent's width/height, + // or if smooth is enabled, parent's w/h scaled + // up by the smooth dimension + int width, height; + int width1, height1; + + PImage timage; + int[] tpixels; + int theight, twidth; + int theight1, twidth1; + int tformat; + + // for anti-aliasing + static final int SUBXRES = 8; + static final int SUBXRES1 = 7; + static final int SUBYRES = 8; + static final int SUBYRES1 = 7; + static final int MAX_COVERAGE = SUBXRES * SUBYRES; + + boolean smooth; + int firstModY; + int lastModY; + int lastY; + int aaleft[] = new int[SUBYRES]; + int aaright[] = new int[SUBYRES]; + int aaleftmin, aarightmin; + int aaleftmax, aarightmax; + int aaleftfull, aarightfull; + + final private int MODYRES(int y) { + return (y & SUBYRES1); + } + + + public PPolygon(PGraphics iparent) { + parent = iparent; + reset(0); + } + + + protected void reset(int count) { + vertexCount = count; + interpX = true; +// interpZ = true; + interpUV = false; + interpARGB = true; + timage = null; + } + + + protected float[] nextVertex() { + if (vertexCount == vertices.length) { + float temp[][] = new float[vertexCount<<1][VERTEX_FIELD_COUNT]; + System.arraycopy(vertices, 0, temp, 0, vertexCount); + vertices = temp; + + r = new float[vertices.length]; + dr = new float[vertices.length]; + l = new float[vertices.length]; + dl = new float[vertices.length]; + sp = new float[vertices.length]; + sdp = new float[vertices.length]; + } + return vertices[vertexCount++]; // returns v[0], sets vc to 1 + } + + + /** + * Return true if this vertex is redundant. If so, will also + * decrement the vertex count. + */ + /* + public boolean redundantVertex(float x, float y, float z) { + // because vertexCount will be 2 when setting vertex[1] + if (vertexCount < 2) return false; + + // vertexCount-1 is the current vertex that would be used + // vertexCount-2 would be the previous feller + if ((Math.abs(vertices[vertexCount-2][MX] - x) < EPSILON) && + (Math.abs(vertices[vertexCount-2][MY] - y) < EPSILON) && + (Math.abs(vertices[vertexCount-2][MZ] - z) < EPSILON)) { + vertexCount--; + return true; + } + return false; + } + */ + + + protected void texture(PImage image) { + this.timage = image; + + if (image != null) { + this.tpixels = image.pixels; + this.twidth = image.width; + this.theight = image.height; + this.tformat = image.format; + + twidth1 = twidth - 1; + theight1 = theight - 1; + interpUV = true; + + } else { + interpUV = false; + } + } + + + protected void renderPolygon(float[][] v, int count) { + vertices = v; + vertexCount = count; + + if (r.length < vertexCount) { + r = new float[vertexCount]; // storage used by incrementalize + dr = new float[vertexCount]; + l = new float[vertexCount]; // more storage for incrementalize + dl = new float[vertexCount]; + sp = new float[vertexCount]; // temporary storage for scanline + sdp = new float[vertexCount]; + } + + render(); + checkExpand(); + } + + + protected void renderTriangle(float[] v1, float[] v2, float[] v3) { + // Calling code will have already done reset(3). + // Can't do it here otherwise would nuke any texture settings. + + vertices[0] = v1; + vertices[1] = v2; + vertices[2] = v3; + + render(); + checkExpand(); + } + + + protected void checkExpand() { + if (smooth) { + for (int i = 0; i < vertexCount; i++) { + vertices[i][TX] /= SUBXRES; + vertices[i][TY] /= SUBYRES; + } + } + } + + + protected void render() { + if (vertexCount < 3) return; + + // these may have changed due to a resize() + // so they should be refreshed here + pixels = parent.pixels; + //zbuffer = parent.zbuffer; + +// noDepthTest = parent.hints[DISABLE_DEPTH_TEST]; + smooth = parent.smooth; + + // by default, text turns on smooth for the textures + // themselves. but this should be shut off if the hint + // for DISABLE_TEXT_SMOOTH is set. +// texture_smooth = true; + + width = smooth ? parent.width*SUBXRES : parent.width; + height = smooth ? parent.height*SUBYRES : parent.height; + + width1 = width - 1; + height1 = height - 1; + + if (!interpARGB) { + r2 = (int) (vertices[0][R] * 255); + g2 = (int) (vertices[0][G] * 255); + b2 = (int) (vertices[0][B] * 255); + a2 = (int) (vertices[0][A] * 255); + a2orig = a2; // save an extra copy + rgba = 0xff000000 | (r2 << 16) | (g2 << 8) | b2; + } + + for (int i = 0; i < vertexCount; i++) { + r[i] = 0; dr[i] = 0; l[i] = 0; dl[i] = 0; + } + + /* + // hack to not make polygons fly into the screen + if (parent.hints[DISABLE_FLYING_POO]) { + float nwidth2 = -width * 2; + float nheight2 = -height * 2; + float width2 = width * 2; + float height2 = height * 2; + for (int i = 0; i < vertexCount; i++) { + if ((vertices[i][TX] < nwidth2) || + (vertices[i][TX] > width2) || + (vertices[i][TY] < nheight2) || + (vertices[i][TY] > height2)) { + return; // this is a bad poly + } + } + } + */ + +// for (int i = 0; i < 4; i++) { +// System.out.println(vertices[i][R] + " " + vertices[i][G] + " " + vertices[i][B]); +// } +// System.out.println(); + + if (smooth) { + for (int i = 0; i < vertexCount; i++) { + vertices[i][TX] *= SUBXRES; + vertices[i][TY] *= SUBYRES; + } + firstModY = -1; + } + + // find top vertex (y is zero at top, higher downwards) + int topi = 0; + float ymin = vertices[0][TY]; + float ymax = vertices[0][TY]; // fry 031001 + for (int i = 1; i < vertexCount; i++) { + if (vertices[i][TY] < ymin) { + ymin = vertices[i][TY]; + topi = i; + } + if (vertices[i][TY] > ymax) { + ymax = vertices[i][TY]; + } + } + + // the last row is an exceptional case, because there won't + // necessarily be 8 rows of subpixel lines that will force + // the final line to render. so instead, the algo keeps track + // of the lastY (in subpixel resolution) that will be rendered + // and that will force a scanline to happen the same as + // every eighth in the other situations + //lastY = -1; // fry 031001 + lastY = (int) (ymax - 0.5f); // global to class bc used by other fxns + + int lefti = topi; // li, index of left vertex + int righti = topi; // ri, index of right vertex + int y = (int) (ymin + 0.5f); // current scan line + int lefty = y - 1; // lower end of left edge + int righty = y - 1; // lower end of right edge + + interpX = true; + + int remaining = vertexCount; + + // scan in y, activating new edges on left & right + // as scan line passes over new vertices + while (remaining > 0) { + // advance left edge? + while ((lefty <= y) && (remaining > 0)) { + remaining--; + // step ccw down left side + int i = (lefti != 0) ? (lefti-1) : (vertexCount-1); + incrementalizeY(vertices[lefti], vertices[i], l, dl, y); + lefty = (int) (vertices[i][TY] + 0.5f); + lefti = i; + } + + // advance right edge? + while ((righty <= y) && (remaining > 0)) { + remaining--; + // step cw down right edge + int i = (righti != vertexCount-1) ? (righti + 1) : 0; + incrementalizeY(vertices[righti], vertices[i], r, dr, y); + righty = (int) (vertices[i][TY] + 0.5f); + righti = i; + } + + // do scanlines till end of l or r edge + while (y < lefty && y < righty) { + // this doesn't work because it's not always set here + //if (remaining == 0) { + //lastY = (lefty < righty) ? lefty-1 : righty-1; + //System.out.println("lastY is " + lastY); + //} + + if ((y >= 0) && (y < height)) { + //try { // hopefully this bug is fixed + if (l[TX] <= r[TX]) scanline(y, l, r); + else scanline(y, r, l); + //} catch (ArrayIndexOutOfBoundsException e) { + //e.printStackTrace(); + //} + } + y++; + // this increment probably needs to be different + // UV and RGB shouldn't be incremented until line is emitted + increment(l, dl); + increment(r, dr); + } + } + //if (smooth) { + //System.out.println("y/lasty/lastmody = " + y + " " + lastY + " " + lastModY); + //} + } + + + private void scanline(int y, float l[], float r[]) { + //System.out.println("scanline " + y); + for (int i = 0; i < vertexCount; i++) { // should be moved later + sp[i] = 0; sdp[i] = 0; + } + + // this rounding doesn't seem to be relevant with smooth + int lx = (int) (l[TX] + 0.49999f); // ceil(l[TX]-.5); + if (lx < 0) lx = 0; + int rx = (int) (r[TX] - 0.5f); + if (rx > width1) rx = width1; + + if (lx > rx) return; + + if (smooth) { + int mody = MODYRES(y); + + aaleft[mody] = lx; + aaright[mody] = rx; + + if (firstModY == -1) { + firstModY = mody; + aaleftmin = lx; aaleftmax = lx; + aarightmin = rx; aarightmax = rx; + + } else { + if (aaleftmin > aaleft[mody]) aaleftmin = aaleft[mody]; + if (aaleftmax < aaleft[mody]) aaleftmax = aaleft[mody]; + if (aarightmin > aaright[mody]) aarightmin = aaright[mody]; + if (aarightmax < aaright[mody]) aarightmax = aaright[mody]; + } + + lastModY = mody; // moved up here (before the return) 031001 + // not the eighth (or lastY) line, so not scanning this time + if ((mody != SUBYRES1) && (y != lastY)) return; + //lastModY = mody; // eeK! this was missing + //return; + + //if (y == lastY) { + //System.out.println("y is lasty"); + //} + //lastModY = mody; + aaleftfull = aaleftmax/SUBXRES + 1; + aarightfull = aarightmin/SUBXRES - 1; + } + + // this is the setup, based on lx + incrementalizeX(l, r, sp, sdp, lx); + + // scan in x, generating pixels + // using parent.width to get actual pixel index + // rather than scaled by smooth factor + int offset = smooth ? parent.width * (y / SUBYRES) : parent.width*y; + + int truelx = 0, truerx = 0; + if (smooth) { + truelx = lx / SUBXRES; + truerx = (rx + SUBXRES1) / SUBXRES; + + lx = aaleftmin / SUBXRES; + rx = (aarightmax + SUBXRES1) / SUBXRES; + if (lx < 0) lx = 0; + if (rx > parent.width1) rx = parent.width1; + } + + interpX = false; + int tr, tg, tb, ta; + +// System.out.println("P2D interp uv " + interpUV + " " + +// vertices[2][U] + " " + vertices[2][V]); + for (int x = lx; x <= rx; x++) { + // map texture based on U, V coords in sp[U] and sp[V] + if (interpUV) { + int tu = (int) (sp[U] * twidth); + int tv = (int) (sp[V] * theight); + + if (tu > twidth1) tu = twidth1; + if (tv > theight1) tv = theight1; + if (tu < 0) tu = 0; + if (tv < 0) tv = 0; + + int txy = tv*twidth + tu; + + int tuf1 = (int) (255f * (sp[U]*twidth - (float)tu)); + int tvf1 = (int) (255f * (sp[V]*theight - (float)tv)); + + // the closer sp[U or V] is to the decimal being zero + // the more coverage it should get of the original pixel + int tuf = 255 - tuf1; + int tvf = 255 - tvf1; + + // this code sucks! filled with bugs and slow as hell! + int pixel00 = tpixels[txy]; + int pixel01 = (tv < theight1) ? + tpixels[txy + twidth] : tpixels[txy]; + int pixel10 = (tu < twidth1) ? + tpixels[txy + 1] : tpixels[txy]; + int pixel11 = ((tv < theight1) && (tu < twidth1)) ? + tpixels[txy + twidth + 1] : tpixels[txy]; + + int p00, p01, p10, p11; + int px0, px1; //, pxy; + + + // calculate alpha component (ta) + + if (tformat == ALPHA) { + px0 = (pixel00*tuf + pixel10*tuf1) >> 8; + px1 = (pixel01*tuf + pixel11*tuf1) >> 8; + ta = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[A]*255)) : a2orig)) >> 8; + + } else if (tformat == ARGB) { + p00 = (pixel00 >> 24) & 0xff; + p01 = (pixel01 >> 24) & 0xff; + p10 = (pixel10 >> 24) & 0xff; + p11 = (pixel11 >> 24) & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + ta = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[A]*255)) : a2orig)) >> 8; + + } else { // RGB image, no alpha + ta = interpARGB ? ((int) (sp[A]*255)) : a2orig; + } + + // calculate r,g,b components (tr, tg, tb) + + if ((tformat == RGB) || (tformat == ARGB)) { + p00 = (pixel00 >> 16) & 0xff; // red + p01 = (pixel01 >> 16) & 0xff; + p10 = (pixel10 >> 16) & 0xff; + p11 = (pixel11 >> 16) & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + tr = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[R]*255)) : r2)) >> 8; + + p00 = (pixel00 >> 8) & 0xff; // green + p01 = (pixel01 >> 8) & 0xff; + p10 = (pixel10 >> 8) & 0xff; + p11 = (pixel11 >> 8) & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + tg = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[G]*255)) : g2)) >> 8; + + p00 = pixel00 & 0xff; // blue + p01 = pixel01 & 0xff; + p10 = pixel10 & 0xff; + p11 = pixel11 & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + tb = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[B]*255)) : b2)) >> 8; + + } else { // alpha image, only use current fill color + if (interpARGB) { + tr = (int) (sp[R] * 255); + tg = (int) (sp[G] * 255); + tb = (int) (sp[B] * 255); + + } else { + tr = r2; + tg = g2; + tb = b2; + } + } + + int weight = smooth ? coverage(x) : 255; + if (weight != 255) ta = ta*weight >> 8; + + if ((ta == 254) || (ta == 255)) { // if (ta & 0xf8) would be good + // no need to blend + pixels[offset+x] = 0xff000000 | (tr << 16) | (tg << 8) | tb; + + } else { + // blend with pixel on screen + int a1 = 255-ta; + int r1 = (pixels[offset+x] >> 16) & 0xff; + int g1 = (pixels[offset+x] >> 8) & 0xff; + int b1 = (pixels[offset+x]) & 0xff; + + pixels[offset+x] = 0xff000000 | + (((tr*ta + r1*a1) >> 8) << 16) | + ((tg*ta + g1*a1) & 0xff00) | + ((tb*ta + b1*a1) >> 8); + } + + } else { // no image applied + int weight = smooth ? coverage(x) : 255; + + if (interpARGB) { + r2 = (int) (sp[R] * 255); + g2 = (int) (sp[G] * 255); + b2 = (int) (sp[B] * 255); + if (sp[A] != 1) weight = (weight * ((int) (sp[A] * 255))) >> 8; + if (weight == 255) { + rgba = 0xff000000 | (r2 << 16) | (g2 << 8) | b2; + } + } else { + if (a2orig != 255) weight = (weight * a2orig) >> 8; + } + + if (weight == 255) { + // no blend, no aa, just the rgba + pixels[offset+x] = rgba; + //zbuffer[offset+x] = sp[Z]; + + } else { + int r1 = (pixels[offset+x] >> 16) & 0xff; + int g1 = (pixels[offset+x] >> 8) & 0xff; + int b1 = (pixels[offset+x]) & 0xff; + a2 = weight; + + int a1 = 255 - a2; + pixels[offset+x] = (0xff000000 | + ((r1*a1 + r2*a2) >> 8) << 16 | + // use & instead of >> and << below + ((g1*a1 + g2*a2) >> 8) << 8 | + ((b1*a1 + b2*a2) >> 8)); + } + } + + // if smooth enabled, don't increment values + // for the pixel in the stretch out version + // of the scanline used to get smooth edges. + if (!smooth || ((x >= truelx) && (x <= truerx))) { + increment(sp, sdp); + } + } + firstModY = -1; + interpX = true; + } + + + // x is in screen, not huge 8x coordinates + private int coverage(int x) { + if ((x >= aaleftfull) && (x <= aarightfull) && + // important since not all SUBYRES lines may have been covered + (firstModY == 0) && (lastModY == SUBYRES1)) { + return 255; + } + + int pixelLeft = x*SUBXRES; // huh? + int pixelRight = pixelLeft + 8; + + int amt = 0; + for (int i = firstModY; i <= lastModY; i++) { + if ((aaleft[i] > pixelRight) || (aaright[i] < pixelLeft)) { + continue; + } + // does this need a +1 ? + amt += ((aaright[i] < pixelRight ? aaright[i] : pixelRight) - + (aaleft[i] > pixelLeft ? aaleft[i] : pixelLeft)); + } + amt <<= 2; + return (amt == 256) ? 255 : amt; + } + + + private void incrementalizeY(float p1[], float p2[], + float p[], float dp[], int y) { + float delta = p2[TY] - p1[TY]; + if (delta == 0) delta = 1; + float fraction = y + 0.5f - p1[TY]; + + if (interpX) { + dp[TX] = (p2[TX] - p1[TX]) / delta; + p[TX] = p1[TX] + dp[TX] * fraction; + } + + if (interpARGB) { + dp[R] = (p2[R] - p1[R]) / delta; + dp[G] = (p2[G] - p1[G]) / delta; + dp[B] = (p2[B] - p1[B]) / delta; + dp[A] = (p2[A] - p1[A]) / delta; + p[R] = p1[R] + dp[R] * fraction; + p[G] = p1[G] + dp[G] * fraction; + p[B] = p1[B] + dp[B] * fraction; + p[A] = p1[A] + dp[A] * fraction; + } + + if (interpUV) { + dp[U] = (p2[U] - p1[U]) / delta; + dp[V] = (p2[V] - p1[V]) / delta; + + p[U] = p1[U] + dp[U] * fraction; + p[V] = p1[V] + dp[V] * fraction; + } + } + + + private void incrementalizeX(float p1[], float p2[], + float p[], float dp[], int x) { + float delta = p2[TX] - p1[TX]; + if (delta == 0) delta = 1; + float fraction = x + 0.5f - p1[TX]; + if (smooth) { + delta /= SUBXRES; + fraction /= SUBXRES; + } + + if (interpX) { + dp[TX] = (p2[TX] - p1[TX]) / delta; + p[TX] = p1[TX] + dp[TX] * fraction; + } + + if (interpARGB) { + dp[R] = (p2[R] - p1[R]) / delta; + dp[G] = (p2[G] - p1[G]) / delta; + dp[B] = (p2[B] - p1[B]) / delta; + dp[A] = (p2[A] - p1[A]) / delta; + p[R] = p1[R] + dp[R] * fraction; + p[G] = p1[G] + dp[G] * fraction; + p[B] = p1[B] + dp[B] * fraction; + p[A] = p1[A] + dp[A] * fraction; + } + + if (interpUV) { + dp[U] = (p2[U] - p1[U]) / delta; + dp[V] = (p2[V] - p1[V]) / delta; + + p[U] = p1[U] + dp[U] * fraction; + p[V] = p1[V] + dp[V] * fraction; + } + } + + + private void increment(float p[], float dp[]) { + if (interpX) p[TX] += dp[TX]; + + if (interpARGB) { + p[R] += dp[R]; + p[G] += dp[G]; + p[B] += dp[B]; + p[A] += dp[A]; + } + + if (interpUV) { + p[U] += dp[U]; + p[V] += dp[V]; + } + } +} diff --git a/support/Processing_core_src/processing/core/PShape.java b/support/Processing_core_src/processing/core/PShape.java new file mode 100644 index 0000000..3d9de31 --- /dev/null +++ b/support/Processing_core_src/processing/core/PShape.java @@ -0,0 +1,1062 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2006-10 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License version 2.1 as published by the Free Software Foundation. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.util.HashMap; + +import processing.core.PApplet; + + +/** + * Datatype for storing shapes. Processing can currently load and display SVG (Scalable Vector Graphics) shapes. + * Before a shape is used, it must be loaded with the loadShape() function. The shape() function is used to draw the shape to the display window. + * The PShape object contain a group of methods, linked below, that can operate on the shape data. + *

The loadShape() method supports SVG files created with Inkscape and Adobe Illustrator. + * It is not a full SVG implementation, but offers some straightforward support for handling vector data. + * =advanced + * + * In-progress class to handle shape data, currently to be considered of + * alpha or beta quality. Major structural work may be performed on this class + * after the release of Processing 1.0. Such changes may include: + * + *

    + *
  • addition of proper accessors to read shape vertex and coloring data + * (this is the second most important part of having a PShape class after all). + *
  • a means of creating PShape objects ala beginShape() and endShape(). + *
  • load(), update(), and cache methods ala PImage, so that shapes can + * have renderer-specific optimizations, such as vertex arrays in OpenGL. + *
  • splitting this class into multiple classes to handle different + * varieties of shape data (primitives vs collections of vertices vs paths) + *
  • change of package declaration, for instance moving the code into + * package processing.shape (if the code grows too much). + *
+ * + *

For the time being, this class and its shape() and loadShape() friends in + * PApplet exist as placeholders for more exciting things to come. If you'd + * like to work with this class, make a subclass (see how PShapeSVG works) + * and you can play with its internal methods all you like.

+ * + *

Library developers are encouraged to create PShape objects when loading + * shape data, so that they can eventually hook into the bounty that will be + * the PShape interface, and the ease of loadShape() and shape().

+ * + * @webref Shape + * @usage Web & Application + * @see PApplet#shape(PShape) + * @see PApplet#loadShape(String) + * @see PApplet#shapeMode(int) + * @instanceName sh any variable of type PShape + */ +public class PShape implements PConstants { + + protected String name; + protected HashMap nameTable; + + /** Generic, only draws its child objects. */ + static public final int GROUP = 0; + /** A line, ellipse, arc, image, etc. */ + static public final int PRIMITIVE = 1; + /** A series of vertex, curveVertex, and bezierVertex calls. */ + static public final int PATH = 2; + /** Collections of vertices created with beginShape(). */ + static public final int GEOMETRY = 3; + /** The shape type, one of GROUP, PRIMITIVE, PATH, or GEOMETRY. */ + protected int family; + + /** ELLIPSE, LINE, QUAD; TRIANGLE_FAN, QUAD_STRIP; etc. */ + protected int primitive; + + protected PMatrix matrix; + + /** Texture or image data associated with this shape. */ + protected PImage image; + + // boundary box of this shape + //protected float x; + //protected float y; + //protected float width; + //protected float height; + /** + * The width of the PShape document. + * @webref + * @brief Shape document width + */ + public float width; + /** + * The width of the PShape document. + * @webref + * @brief Shape document height + */ + public float height; + + // set to false if the object is hidden in the layers palette + protected boolean visible = true; + + protected boolean stroke; + protected int strokeColor; + protected float strokeWeight; // default is 1 + protected int strokeCap; + protected int strokeJoin; + + protected boolean fill; + protected int fillColor; + + /** Temporary toggle for whether styles should be honored. */ + protected boolean style = true; + + /** For primitive shapes in particular, parms like x/y/w/h or x1/y1/x2/y2. */ + protected float[] params; + + protected int vertexCount; + /** + * When drawing POLYGON shapes, the second param is an array of length + * VERTEX_FIELD_COUNT. When drawing PATH shapes, the second param has only + * two variables. + */ + protected float[][] vertices; + + static public final int VERTEX = 0; + static public final int BEZIER_VERTEX = 1; + static public final int CURVE_VERTEX = 2; + static public final int BREAK = 3; + /** Array of VERTEX, BEZIER_VERTEX, and CURVE_VERTEX calls. */ + protected int vertexCodeCount; + protected int[] vertexCodes; + /** True if this is a closed path. */ + protected boolean close; + + // should this be called vertices (consistent with PGraphics internals) + // or does that hurt flexibility? + + protected PShape parent; + protected int childCount; + protected PShape[] children; + + // POINTS, LINES, xLINE_STRIP, xLINE_LOOP + // TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN + // QUADS, QUAD_STRIP + // xPOLYGON +// static final int PATH = 1; // POLYGON, LINE_LOOP, LINE_STRIP +// static final int GROUP = 2; + + // how to handle rectmode/ellipsemode? + // are they bitshifted into the constant? + // CORNER, CORNERS, CENTER, (CENTER_RADIUS?) +// static final int RECT = 3; // could just be QUAD, but would be x1/y1/x2/y2 +// static final int ELLIPSE = 4; +// +// static final int VERTEX = 7; +// static final int CURVE = 5; +// static final int BEZIER = 6; + + + // fill and stroke functions will need a pointer to the parent + // PGraphics object.. may need some kind of createShape() fxn + // or maybe the values are stored until draw() is called? + + // attaching images is very tricky.. it's a different type of data + + // material parameters will be thrown out, + // except those currently supported (kinds of lights) + + // pivot point for transformations +// public float px; +// public float py; + + + public PShape() { + this.family = GROUP; + } + + + public PShape(int family) { + this.family = family; + } + + + public void setName(String name) { + this.name = name; + } + + + public String getName() { + return name; + } + + /** + * Returns a boolean value "true" if the image is set to be visible, "false" if not. This is modified with the setVisible() parameter. + *

The visibility of a shape is usually controlled by whatever program created the SVG file. + * For instance, this parameter is controlled by showing or hiding the shape in the layers palette in Adobe Illustrator. + * + * @webref + * @brief Returns a boolean value "true" if the image is set to be visible, "false" if not + */ + public boolean isVisible() { + return visible; + } + + /** + * Sets the shape to be visible or invisible. This is determined by the value of the visible parameter. + *

The visibility of a shape is usually controlled by whatever program created the SVG file. + * For instance, this parameter is controlled by showing or hiding the shape in the layers palette in Adobe Illustrator. + * @param visible "false" makes the shape invisible and "true" makes it visible + * @webref + * @brief Sets the shape to be visible or invisible + */ + public void setVisible(boolean visible) { + this.visible = visible; + } + + + /** + * Disables the shape's style data and uses Processing's current styles. Styles include attributes such as colors, stroke weight, and stroke joints. + * =advanced + * Overrides this shape's style information and uses PGraphics styles and + * colors. Identical to ignoreStyles(true). Also disables styles for all + * child shapes. + * @webref + * @brief Disables the shape's style data and uses Processing styles + */ + public void disableStyle() { + style = false; + + for (int i = 0; i < childCount; i++) { + children[i].disableStyle(); + } + } + + + /** + * Enables the shape's style data and ignores Processing's current styles. Styles include attributes such as colors, stroke weight, and stroke joints. + * @webref + * @brief Enables the shape's style data and ignores the Processing styles + */ + public void enableStyle() { + style = true; + + for (int i = 0; i < childCount; i++) { + children[i].enableStyle(); + } + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + +// protected void checkBounds() { +// if (width == 0 || height == 0) { +// // calculate bounds here (also take kids into account) +// width = 1; +// height = 1; +// } +// } + + + /** + * Get the width of the drawing area (not necessarily the shape boundary). + */ + public float getWidth() { + //checkBounds(); + return width; + } + + + /** + * Get the height of the drawing area (not necessarily the shape boundary). + */ + public float getHeight() { + //checkBounds(); + return height; + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + /* + boolean strokeSaved; + int strokeColorSaved; + float strokeWeightSaved; + int strokeCapSaved; + int strokeJoinSaved; + + boolean fillSaved; + int fillColorSaved; + + int rectModeSaved; + int ellipseModeSaved; + int shapeModeSaved; + */ + + + protected void pre(PGraphics g) { + if (matrix != null) { + g.pushMatrix(); + g.applyMatrix(matrix); + } + + /* + strokeSaved = g.stroke; + strokeColorSaved = g.strokeColor; + strokeWeightSaved = g.strokeWeight; + strokeCapSaved = g.strokeCap; + strokeJoinSaved = g.strokeJoin; + + fillSaved = g.fill; + fillColorSaved = g.fillColor; + + rectModeSaved = g.rectMode; + ellipseModeSaved = g.ellipseMode; + shapeModeSaved = g.shapeMode; + */ + if (style) { + g.pushStyle(); + styles(g); + } + } + + + protected void styles(PGraphics g) { + // should not be necessary because using only the int version of color + //parent.colorMode(PConstants.RGB, 255); + + if (stroke) { + g.stroke(strokeColor); + g.strokeWeight(strokeWeight); + g.strokeCap(strokeCap); + g.strokeJoin(strokeJoin); + } else { + g.noStroke(); + } + + if (fill) { + //System.out.println("filling " + PApplet.hex(fillColor)); + g.fill(fillColor); + } else { + g.noFill(); + } + } + + + public void post(PGraphics g) { +// for (int i = 0; i < childCount; i++) { +// children[i].draw(g); +// } + + /* + // TODO this is not sufficient, since not saving fillR et al. + g.stroke = strokeSaved; + g.strokeColor = strokeColorSaved; + g.strokeWeight = strokeWeightSaved; + g.strokeCap = strokeCapSaved; + g.strokeJoin = strokeJoinSaved; + + g.fill = fillSaved; + g.fillColor = fillColorSaved; + + g.ellipseMode = ellipseModeSaved; + */ + + if (matrix != null) { + g.popMatrix(); + } + + if (style) { + g.popStyle(); + } + } + + + /** + * Called by the following (the shape() command adds the g) + * PShape s = loadShapes("blah.svg"); + * shape(s); + */ + public void draw(PGraphics g) { + if (visible) { + pre(g); + drawImpl(g); + post(g); + } + } + + + /** + * Draws the SVG document. + */ + public void drawImpl(PGraphics g) { + //System.out.println("drawing " + family); + if (family == GROUP) { + drawGroup(g); + } else if (family == PRIMITIVE) { + drawPrimitive(g); + } else if (family == GEOMETRY) { + drawGeometry(g); + } else if (family == PATH) { + drawPath(g); + } + } + + + protected void drawGroup(PGraphics g) { + for (int i = 0; i < childCount; i++) { + children[i].draw(g); + } + } + + + protected void drawPrimitive(PGraphics g) { + if (primitive == POINT) { + g.point(params[0], params[1]); + + } else if (primitive == LINE) { + if (params.length == 4) { // 2D + g.line(params[0], params[1], + params[2], params[3]); + } else { // 3D + g.line(params[0], params[1], params[2], + params[3], params[4], params[5]); + } + + } else if (primitive == TRIANGLE) { + g.triangle(params[0], params[1], + params[2], params[3], + params[4], params[5]); + + } else if (primitive == QUAD) { + g.quad(params[0], params[1], + params[2], params[3], + params[4], params[5], + params[6], params[7]); + + } else if (primitive == RECT) { + if (image != null) { + g.imageMode(CORNER); + g.image(image, params[0], params[1], params[2], params[3]); + } else { + g.rectMode(CORNER); + g.rect(params[0], params[1], params[2], params[3]); + } + + } else if (primitive == ELLIPSE) { + g.ellipseMode(CORNER); + g.ellipse(params[0], params[1], params[2], params[3]); + + } else if (primitive == ARC) { + g.ellipseMode(CORNER); + g.arc(params[0], params[1], params[2], params[3], params[4], params[5]); + + } else if (primitive == BOX) { + if (params.length == 1) { + g.box(params[0]); + } else { + g.box(params[0], params[1], params[2]); + } + + } else if (primitive == SPHERE) { + g.sphere(params[0]); + } + } + + + protected void drawGeometry(PGraphics g) { + g.beginShape(primitive); + if (style) { + for (int i = 0; i < vertexCount; i++) { + g.vertex(vertices[i]); + } + } else { + for (int i = 0; i < vertexCount; i++) { + float[] vert = vertices[i]; + if (vert[PGraphics.Z] == 0) { + g.vertex(vert[X], vert[Y]); + } else { + g.vertex(vert[X], vert[Y], vert[Z]); + } + } + } + g.endShape(); + } + + + /* + protected void drawPath(PGraphics g) { + g.beginShape(); + for (int j = 0; j < childCount; j++) { + if (j > 0) g.breakShape(); + int count = children[j].vertexCount; + float[][] vert = children[j].vertices; + int[] code = children[j].vertexCodes; + + for (int i = 0; i < count; i++) { + if (style) { + if (children[j].fill) { + g.fill(vert[i][R], vert[i][G], vert[i][B]); + } else { + g.noFill(); + } + if (children[j].stroke) { + g.stroke(vert[i][R], vert[i][G], vert[i][B]); + } else { + g.noStroke(); + } + } + g.edge(vert[i][EDGE] == 1); + + if (code[i] == VERTEX) { + g.vertex(vert[i]); + + } else if (code[i] == BEZIER_VERTEX) { + float z0 = vert[i+0][Z]; + float z1 = vert[i+1][Z]; + float z2 = vert[i+2][Z]; + if (z0 == 0 && z1 == 0 && z2 == 0) { + g.bezierVertex(vert[i+0][X], vert[i+0][Y], z0, + vert[i+1][X], vert[i+1][Y], z1, + vert[i+2][X], vert[i+2][Y], z2); + } else { + g.bezierVertex(vert[i+0][X], vert[i+0][Y], + vert[i+1][X], vert[i+1][Y], + vert[i+2][X], vert[i+2][Y]); + } + } else if (code[i] == CURVE_VERTEX) { + float z = vert[i][Z]; + if (z == 0) { + g.curveVertex(vert[i][X], vert[i][Y]); + } else { + g.curveVertex(vert[i][X], vert[i][Y], z); + } + } + } + } + g.endShape(); + } + */ + + + protected void drawPath(PGraphics g) { + // Paths might be empty (go figure) + // http://dev.processing.org/bugs/show_bug.cgi?id=982 + if (vertices == null) return; + + g.beginShape(); + + if (vertexCodeCount == 0) { // each point is a simple vertex + if (vertices[0].length == 2) { // drawing 2D vertices + for (int i = 0; i < vertexCount; i++) { + g.vertex(vertices[i][X], vertices[i][Y]); + } + } else { // drawing 3D vertices + for (int i = 0; i < vertexCount; i++) { + g.vertex(vertices[i][X], vertices[i][Y], vertices[i][Z]); + } + } + + } else { // coded set of vertices + int index = 0; + + if (vertices[0].length == 2) { // drawing a 2D path + for (int j = 0; j < vertexCodeCount; j++) { + switch (vertexCodes[j]) { + + case VERTEX: + g.vertex(vertices[index][X], vertices[index][Y]); + index++; + break; + + case BEZIER_VERTEX: + g.bezierVertex(vertices[index+0][X], vertices[index+0][Y], + vertices[index+1][X], vertices[index+1][Y], + vertices[index+2][X], vertices[index+2][Y]); + index += 3; + break; + + case CURVE_VERTEX: + g.curveVertex(vertices[index][X], vertices[index][Y]); + index++; + + case BREAK: + g.breakShape(); + } + } + } else { // drawing a 3D path + for (int j = 0; j < vertexCodeCount; j++) { + switch (vertexCodes[j]) { + + case VERTEX: + g.vertex(vertices[index][X], vertices[index][Y], vertices[index][Z]); + index++; + break; + + case BEZIER_VERTEX: + g.bezierVertex(vertices[index+0][X], vertices[index+0][Y], vertices[index+0][Z], + vertices[index+1][X], vertices[index+1][Y], vertices[index+1][Z], + vertices[index+2][X], vertices[index+2][Y], vertices[index+2][Z]); + index += 3; + break; + + case CURVE_VERTEX: + g.curveVertex(vertices[index][X], vertices[index][Y], vertices[index][Z]); + index++; + + case BREAK: + g.breakShape(); + } + } + } + } + g.endShape(close ? CLOSE : OPEN); + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + public int getChildCount() { + return childCount; + } + + /** + * + * @param index the layer position of the shape to get + */ + public PShape getChild(int index) { + return children[index]; + } + + /** + * Extracts a child shape from a parent shape. Specify the name of the shape with the target parameter. + * The shape is returned as a PShape object, or null is returned if there is an error. + * @param target the name of the shape to get + * @webref + * @brief Returns a child element of a shape as a PShape object + */ + public PShape getChild(String target) { + if (name != null && name.equals(target)) { + return this; + } + if (nameTable != null) { + PShape found = nameTable.get(target); + if (found != null) return found; + } + for (int i = 0; i < childCount; i++) { + PShape found = children[i].getChild(target); + if (found != null) return found; + } + return null; + } + + + /** + * Same as getChild(name), except that it first walks all the way up the + * hierarchy to the eldest grandparent, so that children can be found anywhere. + */ + public PShape findChild(String target) { + if (parent == null) { + return getChild(target); + + } else { + return parent.findChild(target); + } + } + + + // can't be just 'add' because that suggests additive geometry + public void addChild(PShape who) { + if (children == null) { + children = new PShape[1]; + } + if (childCount == children.length) { + children = (PShape[]) PApplet.expand(children); + } + children[childCount++] = who; + who.parent = this; + + if (who.getName() != null) { + addName(who.getName(), who); + } + } + + + /** + * Add a shape to the name lookup table. + */ + protected void addName(String nom, PShape shape) { + if (parent != null) { + parent.addName(nom, shape); + } else { + if (nameTable == null) { + nameTable = new HashMap(); + } + nameTable.put(nom, shape); + } + } + + +// public PShape createGroup() { +// PShape group = new PShape(); +// group.kind = GROUP; +// addChild(group); +// return group; +// } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + /** The shape type, one of GROUP, PRIMITIVE, PATH, or GEOMETRY. */ + public int getFamily() { + return family; + } + + + public int getPrimitive() { + return primitive; + } + + + public float[] getParams() { + return getParams(null); + } + + + public float[] getParams(float[] target) { + if (target == null || target.length != params.length) { + target = new float[params.length]; + } + PApplet.arrayCopy(params, target); + return target; + } + + + public float getParam(int index) { + return params[index]; + } + + + public int getVertexCount() { + return vertexCount; + } + + + public float[] getVertex(int index) { + if (index < 0 || index >= vertexCount) { + String msg = "No vertex " + index + " for this shape, " + + "only vertices 0 through " + (vertexCount-1) + "."; + throw new IllegalArgumentException(msg); + } + return vertices[index]; + } + + + public float getVertexX(int index) { + return vertices[index][X]; + } + + + public float getVertexY(int index) { + return vertices[index][Y]; + } + + + public float getVertexZ(int index) { + return vertices[index][Z]; + } + + + public int[] getVertexCodes() { + if (vertexCodes.length != vertexCodeCount) { + vertexCodes = PApplet.subset(vertexCodes, 0, vertexCodeCount); + } + return vertexCodes; + } + + + public int getVertexCodeCount() { + return vertexCodeCount; + } + + + /** + * One of VERTEX, BEZIER_VERTEX, CURVE_VERTEX, or BREAK. + */ + public int getVertexCode(int index) { + return vertexCodes[index]; + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html + public boolean contains(float x, float y) { + if (family == PATH) { + boolean c = false; + for (int i = 0, j = vertexCount-1; i < vertexCount; j = i++) { + if (((vertices[i][Y] > y) != (vertices[j][Y] > y)) && + (x < + (vertices[j][X]-vertices[i][X]) * + (y-vertices[i][Y]) / + (vertices[j][1]-vertices[i][Y]) + + vertices[i][X])) { + c = !c; + } + } + return c; + } else { + throw new IllegalArgumentException("The contains() method is only implemented for paths."); + } + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + // translate, rotate, scale, apply (no push/pop) + // these each call matrix.translate, etc + // if matrix is null when one is called, + // it is created and set to identity + + public void translate(float tx, float ty) { + checkMatrix(2); + matrix.translate(tx, ty); + } + + /** + * Specifies an amount to displace the shape. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. Subsequent calls to the method accumulates the effect. For example, calling translate(50, 0) and then translate(20, 0) is the same as translate(70, 0). This transformation is applied directly to the shape, it's not refreshed each time draw() is run. + *

Using this method with the z parameter requires using the P3D or OPENGL parameter in combination with size. + * @webref + * @param tx left/right translation + * @param ty up/down translation + * @param tz forward/back translation + * @brief Displaces the shape + */ + public void translate(float tx, float ty, float tz) { + checkMatrix(3); + matrix.translate(tx, ty, 0); + } + + /** + * Rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. + *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. + * Subsequent calls to the method accumulates the effect. For example, calling rotateX(HALF_PI) and then rotateX(HALF_PI) is the same as rotateX(PI). + * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. + *

This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above. + * @param angle angle of rotation specified in radians + * @webref + * @brief Rotates the shape around the x-axis + */ + public void rotateX(float angle) { + rotate(angle, 1, 0, 0); + } + + /** + * Rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. + *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. + * Subsequent calls to the method accumulates the effect. For example, calling rotateY(HALF_PI) and then rotateY(HALF_PI) is the same as rotateY(PI). + * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. + *

This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above. + * @param angle angle of rotation specified in radians + * @webref + * @brief Rotates the shape around the y-axis + */ + public void rotateY(float angle) { + rotate(angle, 0, 1, 0); + } + + + /** + * Rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. + *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. + * Subsequent calls to the method accumulates the effect. For example, calling rotateZ(HALF_PI) and then rotateZ(HALF_PI) is the same as rotateZ(PI). + * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. + *

This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above. + * @param angle angle of rotation specified in radians + * @webref + * @brief Rotates the shape around the z-axis + */ + public void rotateZ(float angle) { + rotate(angle, 0, 0, 1); + } + + /** + * Rotates a shape the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. + *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. + * Transformations apply to everything that happens after and subsequent calls to the method accumulates the effect. + * For example, calling rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI). + * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. + * @param angle angle of rotation specified in radians + * @webref + * @brief Rotates the shape + */ + public void rotate(float angle) { + checkMatrix(2); // at least 2... + matrix.rotate(angle); + } + + + public void rotate(float angle, float v0, float v1, float v2) { + checkMatrix(3); + matrix.rotate(angle, v0, v1, v2); + } + + + // + + /** + * @param s percentage to scale the object + */ + public void scale(float s) { + checkMatrix(2); // at least 2... + matrix.scale(s); + } + + + public void scale(float x, float y) { + checkMatrix(2); + matrix.scale(x, y); + } + + + /** + * Increases or decreases the size of a shape by expanding and contracting vertices. Shapes always scale from the relative origin of their bounding box. + * Scale values are specified as decimal percentages. For example, the method call scale(2.0) increases the dimension of a shape by 200%. + * Subsequent calls to the method multiply the effect. For example, calling scale(2.0) and then scale(1.5) is the same as scale(3.0). + * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. + *

Using this fuction with the z parameter requires passing P3D or OPENGL into the size() parameter. + * @param x percentage to scale the object in the x-axis + * @param y percentage to scale the object in the y-axis + * @param z percentage to scale the object in the z-axis + * @webref + * @brief Increases and decreases the size of a shape + */ + public void scale(float x, float y, float z) { + checkMatrix(3); + matrix.scale(x, y, z); + } + + + // + + + public void resetMatrix() { + checkMatrix(2); + matrix.reset(); + } + + + public void applyMatrix(PMatrix source) { + if (source instanceof PMatrix2D) { + applyMatrix((PMatrix2D) source); + } else if (source instanceof PMatrix3D) { + applyMatrix((PMatrix3D) source); + } + } + + + public void applyMatrix(PMatrix2D source) { + applyMatrix(source.m00, source.m01, 0, source.m02, + source.m10, source.m11, 0, source.m12, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void applyMatrix(float n00, float n01, float n02, + float n10, float n11, float n12) { + checkMatrix(2); + matrix.apply(n00, n01, n02, 0, + n10, n11, n12, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } + + + public void apply(PMatrix3D source) { + applyMatrix(source.m00, source.m01, source.m02, source.m03, + source.m10, source.m11, source.m12, source.m13, + source.m20, source.m21, source.m22, source.m23, + source.m30, source.m31, source.m32, source.m33); + } + + + public void applyMatrix(float n00, float n01, float n02, float n03, + float n10, float n11, float n12, float n13, + float n20, float n21, float n22, float n23, + float n30, float n31, float n32, float n33) { + checkMatrix(3); + matrix.apply(n00, n01, n02, n03, + n10, n11, n12, n13, + n20, n21, n22, n23, + n30, n31, n32, n33); + } + + + // + + + /** + * Make sure that the shape's matrix is 1) not null, and 2) has a matrix + * that can handle at least the specified number of dimensions. + */ + protected void checkMatrix(int dimensions) { + if (matrix == null) { + if (dimensions == 2) { + matrix = new PMatrix2D(); + } else { + matrix = new PMatrix3D(); + } + } else if (dimensions == 3 && (matrix instanceof PMatrix2D)) { + // time for an upgrayedd for a double dose of my pimpin' + matrix = new PMatrix3D(matrix); + } + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + /** + * Center the shape based on its bounding box. Can't assume + * that the bounding box is 0, 0, width, height. Common case will be + * opening a letter size document in Illustrator, and drawing something + * in the middle, then reading it in as an svg file. + * This will also need to flip the y axis (scale(1, -1)) in cases + * like Adobe Illustrator where the coordinates start at the bottom. + */ +// public void center() { +// } + + + /** + * Set the pivot point for all transformations. + */ +// public void pivot(float x, float y) { +// px = x; +// py = y; +// } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + +} \ No newline at end of file diff --git a/support/Processing_core_src/processing/core/PShapeSVG.java b/support/Processing_core_src/processing/core/PShapeSVG.java new file mode 100644 index 0000000..3221d4b --- /dev/null +++ b/support/Processing_core_src/processing/core/PShapeSVG.java @@ -0,0 +1,1562 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2006-10 Ben Fry and Casey Reas + Copyright (c) 2004-06 Michael Chang + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License version 2.1 as published by the Free Software Foundation. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + +import java.awt.Paint; +import java.awt.PaintContext; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.geom.AffineTransform; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.ColorModel; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; +import java.util.HashMap; + +import processing.xml.XMLElement; + + +/** + * SVG stands for Scalable Vector Graphics, a portable graphics format. It is + * a vector format so it allows for infinite resolution and relatively small + * file sizes. Most modern media software can view SVG files, including Adobe + * products, Firefox, etc. Illustrator and Inkscape can edit SVG files. + *

+ * We have no intention of turning this into a full-featured SVG library. + * The goal of this project is a basic shape importer that is small enough + * to be included with applets, meaning that its download size should be + * in the neighborhood of 25-30k. Starting with release 0149, this library + * has been incorporated into the core via the loadShape() command, because + * vector shape data is just as important as the image data from loadImage(). + *

+ * For more sophisticated import/export, consider the + * Batik + * library from the Apache Software Foundation. Future improvements to this + * library may focus on this properly supporting a specific subset of SVG, + * for instance the simpler SVG profiles known as + * SVG Tiny or Basic, + * although we still would not support the interactivity options. + * + *


+ * + * A minimal example program using SVG: + * (assuming a working moo.svg is in your data folder) + * + *

+ * PShape moo;
+ *
+ * void setup() {
+ *   size(400, 400);
+ *   moo = loadShape("moo.svg");
+ * }
+ * void draw() {
+ *   background(255);
+ *   shape(moo, mouseX, mouseY);
+ * }
+ * 
+ * + * This code is based on the Candy library written by Michael Chang, which was + * later revised and expanded for use as a Processing core library by Ben Fry. + * Thanks to Ricard Marxer Pinon for help with better Inkscape support in 0154. + * + *


+ * + * Late October 2008 revisions from ricardmp, incorporated by fry (0154) + *

    + *
  • Better style attribute handling, enabling better Inkscape support. + *
+ * + * October 2008 revisions by fry (Processing 0149, pre-1.0) + *
    + *
  • Candy is no longer a separate library, and is instead part of core. + *
  • Loading now works through loadShape() + *
  • Shapes are now drawn using the new PGraphics shape() method. + *
+ * + * August 2008 revisions by fry (Processing 0149) + *
    + *
  • Major changes to rework around PShape. + *
  • Now implementing more of the "transform" attribute. + *
+ * + * February 2008 revisions by fry (Processing 0136) + *
    + *
  • Added support for quadratic curves in paths (Q, q, T, and t operators) + *
  • Support for reading SVG font data (though not rendering it yet) + *
+ * + * Revisions for "Candy 2" November 2006 by fry + *
    + *
  • Switch to the new processing.xml library + *
  • Several bug fixes for parsing of shape data + *
  • Support for linear and radial gradients + *
  • Support for additional types of shapes + *
  • Added compound shapes (shapes with interior points) + *
  • Added methods to get shapes from an internal table + *
+ * + * Revision 10/31/06 by flux + *
    + *
  • Now properly supports Processing 0118 + *
  • Fixed a bunch of things for Casey's students and general buggity. + *
  • Will now properly draw #FFFFFFFF colors (were being represented as -1) + *
  • SVGs without tags are now properly caught and loaded + *
  • Added a method customStyle() for overriding SVG colors/styles + *
  • Added a method SVGStyle() to go back to using SVG colors/styles + *
+ * + * Some SVG objects and features may not yet be supported. + * Here is a partial list of non-included features + *
    + *
  • Rounded rectangles + *
  • Drop shadow objects + *
  • Typography + *
  • Layers added for Candy 2 + *
  • Patterns + *
  • Embedded images + *
+ * + * For those interested, the SVG specification can be found + * here. + */ +public class PShapeSVG extends PShape { + XMLElement element; + + /// Values between 0 and 1. + float opacity; + float strokeOpacity; + float fillOpacity; + + + Gradient strokeGradient; + Paint strokeGradientPaint; + String strokeName; // id of another object, gradients only? + + Gradient fillGradient; + Paint fillGradientPaint; + String fillName; // id of another object + + + /** + * Initializes a new SVG Object with the given filename. + */ + public PShapeSVG(PApplet parent, String filename) { + // this will grab the root document, starting + // the xml version and initial comments are ignored + this(new XMLElement(parent, filename)); + } + + + /** + * Initializes a new SVG Object from the given XMLElement. + */ + public PShapeSVG(XMLElement svg) { + this(null, svg); + + if (!svg.getName().equals("svg")) { + throw new RuntimeException("root is not , it's <" + svg.getName() + ">"); + } + + // not proper parsing of the viewBox, but will cover us for cases where + // the width and height of the object is not specified + String viewBoxStr = svg.getString("viewBox"); + if (viewBoxStr != null) { + int[] viewBox = PApplet.parseInt(PApplet.splitTokens(viewBoxStr)); + width = viewBox[2]; + height = viewBox[3]; + } + + // TODO if viewbox is not same as width/height, then use it to scale + // the original objects. for now, viewbox only used when width/height + // are empty values (which by the spec means w/h of "100%" + String unitWidth = svg.getString("width"); + String unitHeight = svg.getString("height"); + if (unitWidth != null) { + width = parseUnitSize(unitWidth); + height = parseUnitSize(unitHeight); + } else { + if ((width == 0) || (height == 0)) { + //throw new RuntimeException("width/height not specified"); + PGraphics.showWarning("The width and/or height is not " + + "readable in the tag of this file."); + // For the spec, the default is 100% and 100%. For purposes + // here, insert a dummy value because this is prolly just a + // font or something for which the w/h doesn't matter. + width = 1; + height = 1; + } + } + + //root = new Group(null, svg); + parseChildren(svg); // ? + } + + + public PShapeSVG(PShapeSVG parent, XMLElement properties) { + // Need to set this so that findChild() works. + // Otherwise 'parent' is null until addChild() is called later. + this.parent = parent; + + if (parent == null) { + // set values to their defaults according to the SVG spec + stroke = false; + strokeColor = 0xff000000; + strokeWeight = 1; + strokeCap = PConstants.SQUARE; // equivalent to BUTT in svg spec + strokeJoin = PConstants.MITER; + strokeGradient = null; + strokeGradientPaint = null; + strokeName = null; + + fill = true; + fillColor = 0xff000000; + fillGradient = null; + fillGradientPaint = null; + fillName = null; + + //hasTransform = false; + //transformation = null; //new float[] { 1, 0, 0, 1, 0, 0 }; + + strokeOpacity = 1; + fillOpacity = 1; + opacity = 1; + + } else { + stroke = parent.stroke; + strokeColor = parent.strokeColor; + strokeWeight = parent.strokeWeight; + strokeCap = parent.strokeCap; + strokeJoin = parent.strokeJoin; + strokeGradient = parent.strokeGradient; + strokeGradientPaint = parent.strokeGradientPaint; + strokeName = parent.strokeName; + + fill = parent.fill; + fillColor = parent.fillColor; + fillGradient = parent.fillGradient; + fillGradientPaint = parent.fillGradientPaint; + fillName = parent.fillName; + + //hasTransform = parent.hasTransform; + //transformation = parent.transformation; + + opacity = parent.opacity; + } + + element = properties; + name = properties.getString("id"); + // @#$(* adobe illustrator mangles names of objects when re-saving + if (name != null) { + while (true) { + String[] m = PApplet.match(name, "_x([A-Za-z0-9]{2})_"); + if (m == null) break; + char repair = (char) PApplet.unhex(m[1]); + name = name.replace(m[0], "" + repair); + } + } + + String displayStr = properties.getString("display", "inline"); + visible = !displayStr.equals("none"); + + String transformStr = properties.getString("transform"); + if (transformStr != null) { + matrix = parseMatrix(transformStr); + } + + parseColors(properties); + parseChildren(properties); + } + + + protected void parseChildren(XMLElement graphics) { + XMLElement[] elements = graphics.getChildren(); + children = new PShape[elements.length]; + childCount = 0; + + for (XMLElement elem : elements) { + PShape kid = parseChild(elem); + if (kid != null) { +// if (kid.name != null) { +// System.out.println("adding child " + kid.name); +// } + addChild(kid); + } + } + } + + + /** + * Parse a child XML element. + * Override this method to add parsing for more SVG elements. + */ + protected PShape parseChild(XMLElement elem) { + String name = elem.getName(); + PShapeSVG shape = null; + + if (name.equals("g")) { + //return new BaseObject(this, elem); + shape = new PShapeSVG(this, elem); + + } else if (name.equals("defs")) { + // generally this will contain gradient info, so may + // as well just throw it into a group element for parsing + //return new BaseObject(this, elem); + shape = new PShapeSVG(this, elem); + + } else if (name.equals("line")) { + //return new Line(this, elem); + //return new BaseObject(this, elem, LINE); + shape = new PShapeSVG(this, elem); + shape.parseLine(); + + } else if (name.equals("circle")) { + //return new BaseObject(this, elem, ELLIPSE); + shape = new PShapeSVG(this, elem); + shape.parseEllipse(true); + + } else if (name.equals("ellipse")) { + //return new BaseObject(this, elem, ELLIPSE); + shape = new PShapeSVG(this, elem); + shape.parseEllipse(false); + + } else if (name.equals("rect")) { + //return new BaseObject(this, elem, RECT); + shape = new PShapeSVG(this, elem); + shape.parseRect(); + + } else if (name.equals("polygon")) { + //return new BaseObject(this, elem, POLYGON); + shape = new PShapeSVG(this, elem); + shape.parsePoly(true); + + } else if (name.equals("polyline")) { + //return new BaseObject(this, elem, POLYGON); + shape = new PShapeSVG(this, elem); + shape.parsePoly(false); + + } else if (name.equals("path")) { + //return new BaseObject(this, elem, PATH); + shape = new PShapeSVG(this, elem); + shape.parsePath(); + + } else if (name.equals("radialGradient")) { + return new RadialGradient(this, elem); + + } else if (name.equals("linearGradient")) { + return new LinearGradient(this, elem); + + } else if (name.equals("text") || name.equals("font")) { + PGraphics.showWarning("Text and fonts in SVG files " + + "are not currently supported, " + + "convert text to outlines instead."); + + } else if (name.equals("filter")) { + PGraphics.showWarning("Filters are not supported."); + + } else if (name.equals("mask")) { + PGraphics.showWarning("Masks are not supported."); + + } else if (name.equals("pattern")) { + PGraphics.showWarning("Patterns are not supported."); + + } else if (name.equals("stop")) { + // stop tag is handled by gradient parser, so don't warn about it + + } else if (name.equals("sodipodi:namedview")) { + // these are always in Inkscape files, the warnings get tedious + + } else { + PGraphics.showWarning("Ignoring <" + name + "> tag."); + } + return shape; + } + + + protected void parseLine() { + primitive = LINE; + family = PRIMITIVE; + params = new float[] { + getFloatWithUnit(element, "x1"), + getFloatWithUnit(element, "y1"), + getFloatWithUnit(element, "x2"), + getFloatWithUnit(element, "y2") + }; + } + + + /** + * Handles parsing ellipse and circle tags. + * @param circle true if this is a circle and not an ellipse + */ + protected void parseEllipse(boolean circle) { + primitive = ELLIPSE; + family = PRIMITIVE; + params = new float[4]; + + params[0] = getFloatWithUnit(element, "cx"); + params[1] = getFloatWithUnit(element, "cy"); + + float rx, ry; + if (circle) { + rx = ry = getFloatWithUnit(element, "r"); + } else { + rx = getFloatWithUnit(element, "rx"); + ry = getFloatWithUnit(element, "ry"); + } + params[0] -= rx; + params[1] -= ry; + + params[2] = rx*2; + params[3] = ry*2; + } + + + protected void parseRect() { + primitive = RECT; + family = PRIMITIVE; + params = new float[] { + getFloatWithUnit(element, "x"), + getFloatWithUnit(element, "y"), + getFloatWithUnit(element, "width"), + getFloatWithUnit(element, "height") + }; + } + + + /** + * Parse a polyline or polygon from an SVG file. + * @param close true if shape is closed (polygon), false if not (polyline) + */ + protected void parsePoly(boolean close) { + family = PATH; + this.close = close; + + String pointsAttr = element.getString("points"); + if (pointsAttr != null) { + String[] pointsBuffer = PApplet.splitTokens(pointsAttr); + vertexCount = pointsBuffer.length; + vertices = new float[vertexCount][2]; + for (int i = 0; i < vertexCount; i++) { + String pb[] = PApplet.split(pointsBuffer[i], ','); + vertices[i][X] = Float.valueOf(pb[0]).floatValue(); + vertices[i][Y] = Float.valueOf(pb[1]).floatValue(); + } + } + } + + + protected void parsePath() { + family = PATH; + primitive = 0; + + String pathData = element.getString("d"); + if (pathData == null) return; + char[] pathDataChars = pathData.toCharArray(); + + StringBuffer pathBuffer = new StringBuffer(); + boolean lastSeparate = false; + + for (int i = 0; i < pathDataChars.length; i++) { + char c = pathDataChars[i]; + boolean separate = false; + + if (c == 'M' || c == 'm' || + c == 'L' || c == 'l' || + c == 'H' || c == 'h' || + c == 'V' || c == 'v' || + c == 'C' || c == 'c' || // beziers + c == 'S' || c == 's' || + c == 'Q' || c == 'q' || // quadratic beziers + c == 'T' || c == 't' || + c == 'Z' || c == 'z' || // closepath + c == ',') { + separate = true; + if (i != 0) { + pathBuffer.append("|"); + } + } + if (c == 'Z' || c == 'z') { + separate = false; + } + if (c == '-' && !lastSeparate) { + // allow for 'e' notation in numbers, e.g. 2.10e-9 + // http://dev.processing.org/bugs/show_bug.cgi?id=1408 + if (i == 0 || pathDataChars[i-1] != 'e') { + pathBuffer.append("|"); + } + } + if (c != ',') { + pathBuffer.append(c); //"" + pathDataBuffer.charAt(i)); + } + if (separate && c != ',' && c != '-') { + pathBuffer.append("|"); + } + lastSeparate = separate; + } + + // use whitespace constant to get rid of extra spaces and CR or LF + String[] pathDataKeys = + PApplet.splitTokens(pathBuffer.toString(), "|" + WHITESPACE); + vertices = new float[pathDataKeys.length][2]; + vertexCodes = new int[pathDataKeys.length]; + + float cx = 0; + float cy = 0; + int i = 0; + + char implicitCommand = '\0'; + + while (i < pathDataKeys.length) { + char c = pathDataKeys[i].charAt(0); + if(((c >= '0' && c <= '9') || (c == '-')) && implicitCommand != '\0') { + c = implicitCommand; + i--; + } else { + implicitCommand = c; + } + switch (c) { + + case 'M': // M - move to (absolute) + cx = PApplet.parseFloat(pathDataKeys[i + 1]); + cy = PApplet.parseFloat(pathDataKeys[i + 2]); + parsePathMoveto(cx, cy); + implicitCommand = 'L'; + i += 3; + break; + + case 'm': // m - move to (relative) + cx = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + cy = cy + PApplet.parseFloat(pathDataKeys[i + 2]); + parsePathMoveto(cx, cy); + implicitCommand = 'l'; + i += 3; + break; + + case 'L': + cx = PApplet.parseFloat(pathDataKeys[i + 1]); + cy = PApplet.parseFloat(pathDataKeys[i + 2]); + parsePathLineto(cx, cy); + i += 3; + break; + + case 'l': + cx = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + cy = cy + PApplet.parseFloat(pathDataKeys[i + 2]); + parsePathLineto(cx, cy); + i += 3; + break; + + // horizontal lineto absolute + case 'H': + cx = PApplet.parseFloat(pathDataKeys[i + 1]); + parsePathLineto(cx, cy); + i += 2; + break; + + // horizontal lineto relative + case 'h': + cx = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + parsePathLineto(cx, cy); + i += 2; + break; + + case 'V': + cy = PApplet.parseFloat(pathDataKeys[i + 1]); + parsePathLineto(cx, cy); + i += 2; + break; + + case 'v': + cy = cy + PApplet.parseFloat(pathDataKeys[i + 1]); + parsePathLineto(cx, cy); + i += 2; + break; + + // C - curve to (absolute) + case 'C': { + float ctrlX1 = PApplet.parseFloat(pathDataKeys[i + 1]); + float ctrlY1 = PApplet.parseFloat(pathDataKeys[i + 2]); + float ctrlX2 = PApplet.parseFloat(pathDataKeys[i + 3]); + float ctrlY2 = PApplet.parseFloat(pathDataKeys[i + 4]); + float endX = PApplet.parseFloat(pathDataKeys[i + 5]); + float endY = PApplet.parseFloat(pathDataKeys[i + 6]); + parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); + cx = endX; + cy = endY; + i += 7; + } + break; + + // c - curve to (relative) + case 'c': { + float ctrlX1 = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + float ctrlY1 = cy + PApplet.parseFloat(pathDataKeys[i + 2]); + float ctrlX2 = cx + PApplet.parseFloat(pathDataKeys[i + 3]); + float ctrlY2 = cy + PApplet.parseFloat(pathDataKeys[i + 4]); + float endX = cx + PApplet.parseFloat(pathDataKeys[i + 5]); + float endY = cy + PApplet.parseFloat(pathDataKeys[i + 6]); + parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); + cx = endX; + cy = endY; + i += 7; + } + break; + + // S - curve to shorthand (absolute) + case 'S': { + float ppx = vertices[vertexCount-2][X]; + float ppy = vertices[vertexCount-2][Y]; + float px = vertices[vertexCount-1][X]; + float py = vertices[vertexCount-1][Y]; + float ctrlX1 = px + (px - ppx); + float ctrlY1 = py + (py - ppy); + float ctrlX2 = PApplet.parseFloat(pathDataKeys[i + 1]); + float ctrlY2 = PApplet.parseFloat(pathDataKeys[i + 2]); + float endX = PApplet.parseFloat(pathDataKeys[i + 3]); + float endY = PApplet.parseFloat(pathDataKeys[i + 4]); + parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); + cx = endX; + cy = endY; + i += 5; + } + break; + + // s - curve to shorthand (relative) + case 's': { + float ppx = vertices[vertexCount-2][X]; + float ppy = vertices[vertexCount-2][Y]; + float px = vertices[vertexCount-1][X]; + float py = vertices[vertexCount-1][Y]; + float ctrlX1 = px + (px - ppx); + float ctrlY1 = py + (py - ppy); + float ctrlX2 = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + float ctrlY2 = cy + PApplet.parseFloat(pathDataKeys[i + 2]); + float endX = cx + PApplet.parseFloat(pathDataKeys[i + 3]); + float endY = cy + PApplet.parseFloat(pathDataKeys[i + 4]); + parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); + cx = endX; + cy = endY; + i += 5; + } + break; + + // Q - quadratic curve to (absolute) + case 'Q': { + float ctrlX = PApplet.parseFloat(pathDataKeys[i + 1]); + float ctrlY = PApplet.parseFloat(pathDataKeys[i + 2]); + float endX = PApplet.parseFloat(pathDataKeys[i + 3]); + float endY = PApplet.parseFloat(pathDataKeys[i + 4]); + parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); + cx = endX; + cy = endY; + i += 5; + } + break; + + // q - quadratic curve to (relative) + case 'q': { + float ctrlX = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + float ctrlY = cy + PApplet.parseFloat(pathDataKeys[i + 2]); + float endX = cx + PApplet.parseFloat(pathDataKeys[i + 3]); + float endY = cy + PApplet.parseFloat(pathDataKeys[i + 4]); + parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); + cx = endX; + cy = endY; + i += 5; + } + break; + + // T - quadratic curve to shorthand (absolute) + // The control point is assumed to be the reflection of the + // control point on the previous command relative to the + // current point. (If there is no previous command or if the + // previous command was not a Q, q, T or t, assume the control + // point is coincident with the current point.) + case 'T': { + float ppx = vertices[vertexCount-2][X]; + float ppy = vertices[vertexCount-2][Y]; + float px = vertices[vertexCount-1][X]; + float py = vertices[vertexCount-1][Y]; + float ctrlX = px + (px - ppx); + float ctrlY = py + (py - ppy); + float endX = PApplet.parseFloat(pathDataKeys[i + 1]); + float endY = PApplet.parseFloat(pathDataKeys[i + 2]); + parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); + cx = endX; + cy = endY; + i += 3; + } + break; + + // t - quadratic curve to shorthand (relative) + case 't': { + float ppx = vertices[vertexCount-2][X]; + float ppy = vertices[vertexCount-2][Y]; + float px = vertices[vertexCount-1][X]; + float py = vertices[vertexCount-1][Y]; + float ctrlX = px + (px - ppx); + float ctrlY = py + (py - ppy); + float endX = cx + PApplet.parseFloat(pathDataKeys[i + 1]); + float endY = cy + PApplet.parseFloat(pathDataKeys[i + 2]); + parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); + cx = endX; + cy = endY; + i += 3; + } + break; + + case 'Z': + case 'z': + close = true; + i++; + break; + + default: + String parsed = + PApplet.join(PApplet.subset(pathDataKeys, 0, i), ","); + String unparsed = + PApplet.join(PApplet.subset(pathDataKeys, i), ","); + System.err.println("parsed: " + parsed); + System.err.println("unparsed: " + unparsed); + if (pathDataKeys[i].equals("a") || pathDataKeys[i].equals("A")) { + String msg = "Sorry, elliptical arc support for SVG files " + + "is not yet implemented (See bug #996 for details)"; + throw new RuntimeException(msg); + } + throw new RuntimeException("shape command not handled: " + pathDataKeys[i]); + } + } + } + + +// private void parsePathCheck(int num) { +// if (vertexCount + num-1 >= vertices.length) { +// //vertices = (float[][]) PApplet.expand(vertices); +// float[][] temp = new float[vertexCount << 1][2]; +// System.arraycopy(vertices, 0, temp, 0, vertexCount); +// vertices = temp; +// } +// } + + private void parsePathVertex(float x, float y) { + if (vertexCount == vertices.length) { + //vertices = (float[][]) PApplet.expand(vertices); + float[][] temp = new float[vertexCount << 1][2]; + System.arraycopy(vertices, 0, temp, 0, vertexCount); + vertices = temp; + } + vertices[vertexCount][X] = x; + vertices[vertexCount][Y] = y; + vertexCount++; + } + + + private void parsePathCode(int what) { + if (vertexCodeCount == vertexCodes.length) { + vertexCodes = PApplet.expand(vertexCodes); + } + vertexCodes[vertexCodeCount++] = what; + } + + + private void parsePathMoveto(float px, float py) { + if (vertexCount > 0) { + parsePathCode(BREAK); + } + parsePathCode(VERTEX); + parsePathVertex(px, py); + } + + + private void parsePathLineto(float px, float py) { + parsePathCode(VERTEX); + parsePathVertex(px, py); + } + + + private void parsePathCurveto(float x1, float y1, + float x2, float y2, + float x3, float y3) { + parsePathCode(BEZIER_VERTEX); + parsePathVertex(x1, y1); + parsePathVertex(x2, y2); + parsePathVertex(x3, y3); + } + + private void parsePathQuadto(float x1, float y1, + float cx, float cy, + float x2, float y2) { + parsePathCode(BEZIER_VERTEX); + // x1/y1 already covered by last moveto, lineto, or curveto + parsePathVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f)); + parsePathVertex(x2 + ((cx-x2)*2/3.0f), y2 + ((cy-y2)*2/3.0f)); + parsePathVertex(x2, y2); + } + + + /** + * Parse the specified SVG matrix into a PMatrix2D. Note that PMatrix2D + * is rotated relative to the SVG definition, so parameters are rearranged + * here. More about the transformation matrices in + * this section + * of the SVG documentation. + * @param matrixStr text of the matrix param. + * @return a good old-fashioned PMatrix2D + */ + static protected PMatrix2D parseMatrix(String matrixStr) { + String[] pieces = PApplet.match(matrixStr, "\\s*(\\w+)\\((.*)\\)"); + if (pieces == null) { + System.err.println("Could not parse transform " + matrixStr); + return null; + } + float[] m = PApplet.parseFloat(PApplet.splitTokens(pieces[2], ", ")); + if (pieces[1].equals("matrix")) { + return new PMatrix2D(m[0], m[2], m[4], m[1], m[3], m[5]); + + } else if (pieces[1].equals("translate")) { + float tx = m[0]; + float ty = (m.length == 2) ? m[1] : m[0]; + //return new float[] { 1, 0, tx, 0, 1, ty }; + return new PMatrix2D(1, 0, tx, 0, 1, ty); + + } else if (pieces[1].equals("scale")) { + float sx = m[0]; + float sy = (m.length == 2) ? m[1] : m[0]; + //return new float[] { sx, 0, 0, 0, sy, 0 }; + return new PMatrix2D(sx, 0, 0, 0, sy, 0); + + } else if (pieces[1].equals("rotate")) { + float angle = m[0]; + + if (m.length == 1) { + float c = PApplet.cos(angle); + float s = PApplet.sin(angle); + // SVG version is cos(a) sin(a) -sin(a) cos(a) 0 0 + return new PMatrix2D(c, -s, 0, s, c, 0); + + } else if (m.length == 3) { + PMatrix2D mat = new PMatrix2D(0, 1, m[1], 1, 0, m[2]); + mat.rotate(m[0]); + mat.translate(-m[1], -m[2]); + return mat; //.get(null); + } + + } else if (pieces[1].equals("skewX")) { + return new PMatrix2D(1, 0, 1, PApplet.tan(m[0]), 0, 0); + + } else if (pieces[1].equals("skewY")) { + return new PMatrix2D(1, 0, 1, 0, PApplet.tan(m[0]), 0); + } + return null; + } + + + protected void parseColors(XMLElement properties) { + if (properties.hasAttribute("opacity")) { + String opacityText = properties.getString("opacity"); + setOpacity(opacityText); + } + + if (properties.hasAttribute("stroke")) { + String strokeText = properties.getString("stroke"); + setColor(strokeText, false); + } + + if (properties.hasAttribute("stroke-opacity")) { + String strokeOpacityText = properties.getString("stroke-opacity"); + setStrokeOpacity(strokeOpacityText); + } + + if (properties.hasAttribute("stroke-width")) { + // if NaN (i.e. if it's 'inherit') then default back to the inherit setting + String lineweight = properties.getString("stroke-width"); + setStrokeWeight(lineweight); + } + + if (properties.hasAttribute("stroke-linejoin")) { + String linejoin = properties.getString("stroke-linejoin"); + setStrokeJoin(linejoin); + } + + if (properties.hasAttribute("stroke-linecap")) { + String linecap = properties.getString("stroke-linecap"); + setStrokeCap(linecap); + } + + // fill defaults to black (though stroke defaults to "none") + // http://www.w3.org/TR/SVG/painting.html#FillProperties + if (properties.hasAttribute("fill")) { + String fillText = properties.getString("fill"); + setColor(fillText, true); + } + + if (properties.hasAttribute("fill-opacity")) { + String fillOpacityText = properties.getString("fill-opacity"); + setFillOpacity(fillOpacityText); + } + + if (properties.hasAttribute("style")) { + String styleText = properties.getString("style"); + String[] styleTokens = PApplet.splitTokens(styleText, ";"); + + //PApplet.println(styleTokens); + for (int i = 0; i < styleTokens.length; i++) { + String[] tokens = PApplet.splitTokens(styleTokens[i], ":"); + //PApplet.println(tokens); + + tokens[0] = PApplet.trim(tokens[0]); + + if (tokens[0].equals("fill")) { + setColor(tokens[1], true); + + } else if(tokens[0].equals("fill-opacity")) { + setFillOpacity(tokens[1]); + + } else if(tokens[0].equals("stroke")) { + setColor(tokens[1], false); + + } else if(tokens[0].equals("stroke-width")) { + setStrokeWeight(tokens[1]); + + } else if(tokens[0].equals("stroke-linecap")) { + setStrokeCap(tokens[1]); + + } else if(tokens[0].equals("stroke-linejoin")) { + setStrokeJoin(tokens[1]); + + } else if(tokens[0].equals("stroke-opacity")) { + setStrokeOpacity(tokens[1]); + + } else if(tokens[0].equals("opacity")) { + setOpacity(tokens[1]); + + } else { + // Other attributes are not yet implemented + } + } + } + } + + + void setOpacity(String opacityText) { + opacity = PApplet.parseFloat(opacityText); + strokeColor = ((int) (opacity * 255)) << 24 | strokeColor & 0xFFFFFF; + fillColor = ((int) (opacity * 255)) << 24 | fillColor & 0xFFFFFF; + } + + + void setStrokeWeight(String lineweight) { + strokeWeight = parseUnitSize(lineweight); + } + + + void setStrokeOpacity(String opacityText) { + strokeOpacity = PApplet.parseFloat(opacityText); + strokeColor = ((int) (strokeOpacity * 255)) << 24 | strokeColor & 0xFFFFFF; + } + + + void setStrokeJoin(String linejoin) { + if (linejoin.equals("inherit")) { + // do nothing, will inherit automatically + + } else if (linejoin.equals("miter")) { + strokeJoin = PConstants.MITER; + + } else if (linejoin.equals("round")) { + strokeJoin = PConstants.ROUND; + + } else if (linejoin.equals("bevel")) { + strokeJoin = PConstants.BEVEL; + } + } + + + void setStrokeCap(String linecap) { + if (linecap.equals("inherit")) { + // do nothing, will inherit automatically + + } else if (linecap.equals("butt")) { + strokeCap = PConstants.SQUARE; + + } else if (linecap.equals("round")) { + strokeCap = PConstants.ROUND; + + } else if (linecap.equals("square")) { + strokeCap = PConstants.PROJECT; + } + } + + + void setFillOpacity(String opacityText) { + fillOpacity = PApplet.parseFloat(opacityText); + fillColor = ((int) (fillOpacity * 255)) << 24 | fillColor & 0xFFFFFF; + } + + + void setColor(String colorText, boolean isFill) { + int opacityMask = fillColor & 0xFF000000; + boolean visible = true; + int color = 0; + String name = ""; + Gradient gradient = null; + Paint paint = null; + if (colorText.equals("none")) { + visible = false; + } else if (colorText.equals("black")) { + color = opacityMask; + } else if (colorText.equals("white")) { + color = opacityMask | 0xFFFFFF; + } else if (colorText.startsWith("#")) { + if (colorText.length() == 4) { + // Short form: #ABC, transform to long form #AABBCC + colorText = colorText.replaceAll("^#(.)(.)(.)$", "#$1$1$2$2$3$3"); + } + color = opacityMask | + (Integer.parseInt(colorText.substring(1), 16)) & 0xFFFFFF; + //System.out.println("hex for fill is " + PApplet.hex(fillColor)); + } else if (colorText.startsWith("rgb")) { + color = opacityMask | parseRGB(colorText); + } else if (colorText.startsWith("url(#")) { + name = colorText.substring(5, colorText.length() - 1); +// PApplet.println("looking for " + name); + Object object = findChild(name); + //PApplet.println("found " + fillObject); + if (object instanceof Gradient) { + gradient = (Gradient) object; + paint = calcGradientPaint(gradient); //, opacity); + //PApplet.println("got filla " + fillObject); + } else { +// visible = false; + System.err.println("url " + name + " refers to unexpected data: " + object); + } + } + if (isFill) { + fill = visible; + fillColor = color; + fillName = name; + fillGradient = gradient; + fillGradientPaint = paint; + } else { + stroke = visible; + strokeColor = color; + strokeName = name; + strokeGradient = gradient; + strokeGradientPaint = paint; + } + } + + + static protected int parseRGB(String what) { + int leftParen = what.indexOf('(') + 1; + int rightParen = what.indexOf(')'); + String sub = what.substring(leftParen, rightParen); + int[] values = PApplet.parseInt(PApplet.splitTokens(sub, ", ")); + return (values[0] << 16) | (values[1] << 8) | (values[2]); + } + + + static protected HashMap parseStyleAttributes(String style) { + HashMap table = new HashMap(); + String[] pieces = style.split(";"); + for (int i = 0; i < pieces.length; i++) { + String[] parts = pieces[i].split(":"); + table.put(parts[0], parts[1]); + } + return table; + } + + + /** + * Used in place of element.getFloatAttribute(a) because we can + * have a unit suffix (length or coordinate). + * @param element what to parse + * @param attribute name of the attribute to get + * @return unit-parsed version of the data + */ + static protected float getFloatWithUnit(XMLElement element, String attribute) { + String val = element.getString(attribute); + return (val == null) ? 0 : parseUnitSize(val); + } + + + /** + * Parse a size that may have a suffix for its units. + * Ignoring cases where this could also be a percentage. + * The units spec: + *
    + *
  • "1pt" equals "1.25px" (and therefore 1.25 user units) + *
  • "1pc" equals "15px" (and therefore 15 user units) + *
  • "1mm" would be "3.543307px" (3.543307 user units) + *
  • "1cm" equals "35.43307px" (and therefore 35.43307 user units) + *
  • "1in" equals "90px" (and therefore 90 user units) + *
+ */ + static protected float parseUnitSize(String text) { + int len = text.length() - 2; + + if (text.endsWith("pt")) { + return PApplet.parseFloat(text.substring(0, len)) * 1.25f; + } else if (text.endsWith("pc")) { + return PApplet.parseFloat(text.substring(0, len)) * 15; + } else if (text.endsWith("mm")) { + return PApplet.parseFloat(text.substring(0, len)) * 3.543307f; + } else if (text.endsWith("cm")) { + return PApplet.parseFloat(text.substring(0, len)) * 35.43307f; + } else if (text.endsWith("in")) { + return PApplet.parseFloat(text.substring(0, len)) * 90; + } else if (text.endsWith("px")) { + return PApplet.parseFloat(text.substring(0, len)); + } else { + return PApplet.parseFloat(text); + } + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + static class Gradient extends PShapeSVG { + AffineTransform transform; + + float[] offset; + int[] color; + int count; + + public Gradient(PShapeSVG parent, XMLElement properties) { + super(parent, properties); + + XMLElement elements[] = properties.getChildren(); + offset = new float[elements.length]; + color = new int[elements.length]; + + // + for (int i = 0; i < elements.length; i++) { + XMLElement elem = elements[i]; + String name = elem.getName(); + if (name.equals("stop")) { + String offsetAttr = elem.getString("offset"); + float div = 1.0f; + if (offsetAttr.endsWith("%")) { + div = 100.0f; + offsetAttr = offsetAttr.substring(0, offsetAttr.length() - 1); + } + offset[count] = PApplet.parseFloat(offsetAttr) / div; + String style = elem.getString("style"); + HashMap styles = parseStyleAttributes(style); + + String colorStr = styles.get("stop-color"); + if (colorStr == null) colorStr = "#000000"; + String opacityStr = styles.get("stop-opacity"); + if (opacityStr == null) opacityStr = "1"; + int tupacity = (int) (PApplet.parseFloat(opacityStr) * 255); + color[count] = (tupacity << 24) | + Integer.parseInt(colorStr.substring(1), 16); + count++; + } + } + offset = PApplet.subset(offset, 0, count); + color = PApplet.subset(color, 0, count); + } + } + + + class LinearGradient extends Gradient { + float x1, y1, x2, y2; + + public LinearGradient(PShapeSVG parent, XMLElement properties) { + super(parent, properties); + + this.x1 = getFloatWithUnit(properties, "x1"); + this.y1 = getFloatWithUnit(properties, "y1"); + this.x2 = getFloatWithUnit(properties, "x2"); + this.y2 = getFloatWithUnit(properties, "y2"); + + String transformStr = + properties.getString("gradientTransform"); + + if (transformStr != null) { + float t[] = parseMatrix(transformStr).get(null); + this.transform = new AffineTransform(t[0], t[3], t[1], t[4], t[2], t[5]); + + Point2D t1 = transform.transform(new Point2D.Float(x1, y1), null); + Point2D t2 = transform.transform(new Point2D.Float(x2, y2), null); + + this.x1 = (float) t1.getX(); + this.y1 = (float) t1.getY(); + this.x2 = (float) t2.getX(); + this.y2 = (float) t2.getY(); + } + } + } + + + class RadialGradient extends Gradient { + float cx, cy, r; + + public RadialGradient(PShapeSVG parent, XMLElement properties) { + super(parent, properties); + + this.cx = getFloatWithUnit(properties, "cx"); + this.cy = getFloatWithUnit(properties, "cy"); + this.r = getFloatWithUnit(properties, "r"); + + String transformStr = + properties.getString("gradientTransform"); + + if (transformStr != null) { + float t[] = parseMatrix(transformStr).get(null); + this.transform = new AffineTransform(t[0], t[3], t[1], t[4], t[2], t[5]); + + Point2D t1 = transform.transform(new Point2D.Float(cx, cy), null); + Point2D t2 = transform.transform(new Point2D.Float(cx + r, cy), null); + + this.cx = (float) t1.getX(); + this.cy = (float) t1.getY(); + this.r = (float) (t2.getX() - t1.getX()); + } + } + } + + + + class LinearGradientPaint implements Paint { + float x1, y1, x2, y2; + float[] offset; + int[] color; + int count; + float opacity; + + public LinearGradientPaint(float x1, float y1, float x2, float y2, + float[] offset, int[] color, int count, + float opacity) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + this.offset = offset; + this.color = color; + this.count = count; + this.opacity = opacity; + } + + public PaintContext createContext(ColorModel cm, + Rectangle deviceBounds, Rectangle2D userBounds, + AffineTransform xform, RenderingHints hints) { + Point2D t1 = xform.transform(new Point2D.Float(x1, y1), null); + Point2D t2 = xform.transform(new Point2D.Float(x2, y2), null); + return new LinearGradientContext((float) t1.getX(), (float) t1.getY(), + (float) t2.getX(), (float) t2.getY()); + } + + public int getTransparency() { + return TRANSLUCENT; // why not.. rather than checking each color + } + + public class LinearGradientContext implements PaintContext { + int ACCURACY = 2; + float tx1, ty1, tx2, ty2; + + public LinearGradientContext(float tx1, float ty1, float tx2, float ty2) { + this.tx1 = tx1; + this.ty1 = ty1; + this.tx2 = tx2; + this.ty2 = ty2; + } + + public void dispose() { } + + public ColorModel getColorModel() { return ColorModel.getRGBdefault(); } + + public Raster getRaster(int x, int y, int w, int h) { + WritableRaster raster = + getColorModel().createCompatibleWritableRaster(w, h); + + int[] data = new int[w * h * 4]; + + // make normalized version of base vector + float nx = tx2 - tx1; + float ny = ty2 - ty1; + float len = (float) Math.sqrt(nx*nx + ny*ny); + if (len != 0) { + nx /= len; + ny /= len; + } + + int span = (int) PApplet.dist(tx1, ty1, tx2, ty2) * ACCURACY; + if (span <= 0) { + //System.err.println("span is too small"); + // annoying edge case where the gradient isn't legit + int index = 0; + for (int j = 0; j < h; j++) { + for (int i = 0; i < w; i++) { + data[index++] = 0; + data[index++] = 0; + data[index++] = 0; + data[index++] = 255; + } + } + + } else { + int[][] interp = new int[span][4]; + int prev = 0; + for (int i = 1; i < count; i++) { + int c0 = color[i-1]; + int c1 = color[i]; + int last = (int) (offset[i] * (span-1)); + //System.out.println("last is " + last); + for (int j = prev; j <= last; j++) { + float btwn = PApplet.norm(j, prev, last); + interp[j][0] = (int) PApplet.lerp((c0 >> 16) & 0xff, (c1 >> 16) & 0xff, btwn); + interp[j][1] = (int) PApplet.lerp((c0 >> 8) & 0xff, (c1 >> 8) & 0xff, btwn); + interp[j][2] = (int) PApplet.lerp(c0 & 0xff, c1 & 0xff, btwn); + interp[j][3] = (int) (PApplet.lerp((c0 >> 24) & 0xff, (c1 >> 24) & 0xff, btwn) * opacity); + //System.out.println(j + " " + interp[j][0] + " " + interp[j][1] + " " + interp[j][2]); + } + prev = last; + } + + int index = 0; + for (int j = 0; j < h; j++) { + for (int i = 0; i < w; i++) { + //float distance = 0; //PApplet.dist(cx, cy, x + i, y + j); + //int which = PApplet.min((int) (distance * ACCURACY), interp.length-1); + float px = (x + i) - tx1; + float py = (y + j) - ty1; + // distance up the line is the dot product of the normalized + // vector of the gradient start/stop by the point being tested + int which = (int) ((px*nx + py*ny) * ACCURACY); + if (which < 0) which = 0; + if (which > interp.length-1) which = interp.length-1; + //if (which > 138) System.out.println("grabbing " + which); + + data[index++] = interp[which][0]; + data[index++] = interp[which][1]; + data[index++] = interp[which][2]; + data[index++] = interp[which][3]; + } + } + } + raster.setPixels(0, 0, w, h, data); + + return raster; + } + } + } + + + class RadialGradientPaint implements Paint { + float cx, cy, radius; + float[] offset; + int[] color; + int count; + float opacity; + + public RadialGradientPaint(float cx, float cy, float radius, + float[] offset, int[] color, int count, + float opacity) { + this.cx = cx; + this.cy = cy; + this.radius = radius; + this.offset = offset; + this.color = color; + this.count = count; + this.opacity = opacity; + } + + public PaintContext createContext(ColorModel cm, + Rectangle deviceBounds, Rectangle2D userBounds, + AffineTransform xform, RenderingHints hints) { + return new RadialGradientContext(); + } + + public int getTransparency() { + return TRANSLUCENT; + } + + public class RadialGradientContext implements PaintContext { + int ACCURACY = 5; + + public void dispose() {} + + public ColorModel getColorModel() { return ColorModel.getRGBdefault(); } + + public Raster getRaster(int x, int y, int w, int h) { + WritableRaster raster = + getColorModel().createCompatibleWritableRaster(w, h); + + int span = (int) radius * ACCURACY; + int[][] interp = new int[span][4]; + int prev = 0; + for (int i = 1; i < count; i++) { + int c0 = color[i-1]; + int c1 = color[i]; + int last = (int) (offset[i] * (span - 1)); + for (int j = prev; j <= last; j++) { + float btwn = PApplet.norm(j, prev, last); + interp[j][0] = (int) PApplet.lerp((c0 >> 16) & 0xff, (c1 >> 16) & 0xff, btwn); + interp[j][1] = (int) PApplet.lerp((c0 >> 8) & 0xff, (c1 >> 8) & 0xff, btwn); + interp[j][2] = (int) PApplet.lerp(c0 & 0xff, c1 & 0xff, btwn); + interp[j][3] = (int) (PApplet.lerp((c0 >> 24) & 0xff, (c1 >> 24) & 0xff, btwn) * opacity); + } + prev = last; + } + + int[] data = new int[w * h * 4]; + int index = 0; + for (int j = 0; j < h; j++) { + for (int i = 0; i < w; i++) { + float distance = PApplet.dist(cx, cy, x + i, y + j); + int which = PApplet.min((int) (distance * ACCURACY), interp.length-1); + + data[index++] = interp[which][0]; + data[index++] = interp[which][1]; + data[index++] = interp[which][2]; + data[index++] = interp[which][3]; + } + } + raster.setPixels(0, 0, w, h, data); + + return raster; + } + } + } + + + protected Paint calcGradientPaint(Gradient gradient) { + if (gradient instanceof LinearGradient) { + LinearGradient grad = (LinearGradient) gradient; + return new LinearGradientPaint(grad.x1, grad.y1, grad.x2, grad.y2, + grad.offset, grad.color, grad.count, + opacity); + + } else if (gradient instanceof RadialGradient) { + RadialGradient grad = (RadialGradient) gradient; + return new RadialGradientPaint(grad.cx, grad.cy, grad.r, + grad.offset, grad.color, grad.count, + opacity); + } + return null; + } + + +// protected Paint calcGradientPaint(Gradient gradient, +// float x1, float y1, float x2, float y2) { +// if (gradient instanceof LinearGradient) { +// LinearGradient grad = (LinearGradient) gradient; +// return new LinearGradientPaint(x1, y1, x2, y2, +// grad.offset, grad.color, grad.count, +// opacity); +// } +// throw new RuntimeException("Not a linear gradient."); +// } + + +// protected Paint calcGradientPaint(Gradient gradient, +// float cx, float cy, float r) { +// if (gradient instanceof RadialGradient) { +// RadialGradient grad = (RadialGradient) gradient; +// return new RadialGradientPaint(cx, cy, r, +// grad.offset, grad.color, grad.count, +// opacity); +// } +// throw new RuntimeException("Not a radial gradient."); +// } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + protected void styles(PGraphics g) { + super.styles(g); + + if (g instanceof PGraphicsJava2D) { + PGraphicsJava2D p2d = (PGraphicsJava2D) g; + + if (strokeGradient != null) { + p2d.strokeGradient = true; + p2d.strokeGradientObject = strokeGradientPaint; + } else { + // need to shut off, in case parent object has a gradient applied + //p2d.strokeGradient = false; + } + if (fillGradient != null) { + p2d.fillGradient = true; + p2d.fillGradientObject = fillGradientPaint; + } else { + // need to shut off, in case parent object has a gradient applied + //p2d.fillGradient = false; + } + } + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + //public void drawImpl(PGraphics g) { + // do nothing + //} + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + /** + * Get a particular element based on its SVG ID. When editing SVG by hand, + * this is the id="" tag on any SVG element. When editing from Illustrator, + * these IDs can be edited by expanding the layers palette. The names used + * in the layers palette, both for the layers or the shapes and groups + * beneath them can be used here. + *
+   * // This code grabs "Layer 3" and the shapes beneath it.
+   * PShape layer3 = svg.getChild("Layer 3");
+   * 
+ */ + public PShape getChild(String name) { + PShape found = super.getChild(name); + if (found == null) { + // Otherwise try with underscores instead of spaces + // (this is how Illustrator handles spaces in the layer names). + found = super.getChild(name.replace(' ', '_')); + } + // Set bounding box based on the parent bounding box + if (found != null) { +// found.x = this.x; +// found.y = this.y; + found.width = this.width; + found.height = this.height; + } + return found; + } + + + /** + * Prints out the SVG document. Useful for parsing. + */ + public void print() { + PApplet.println(element.toString()); + } +} diff --git a/support/Processing_core_src/processing/core/PSmoothTriangle.java b/support/Processing_core_src/processing/core/PSmoothTriangle.java new file mode 100644 index 0000000..ba692fe --- /dev/null +++ b/support/Processing_core_src/processing/core/PSmoothTriangle.java @@ -0,0 +1,968 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-08 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + + +/** + * Smoothed triangle renderer for P3D. + * + * Based off of the PPolygon class in old versions of Processing. + * Name and location of this class will change in a future release. + */ +public class PSmoothTriangle implements PConstants { + + // really this is "debug" but.. + private static final boolean EWJORDAN = false; + private static final boolean FRY = false; + + // identical to the constants from PGraphics + + static final int X = 0; // transformed xyzw + static final int Y = 1; // formerly SX SY SZ + static final int Z = 2; + + static final int R = 3; // actual rgb, after lighting + static final int G = 4; // fill stored here, transform in place + static final int B = 5; + static final int A = 6; + + static final int U = 7; // texture + static final int V = 8; + + static final int DEFAULT_SIZE = 64; // this is needed for spheres + float vertices[][] = new float[DEFAULT_SIZE][PGraphics.VERTEX_FIELD_COUNT]; + int vertexCount; + + + // after some fiddling, this seems to produce the best results + static final int ZBUFFER_MIN_COVERAGE = 204; + + float r[] = new float[DEFAULT_SIZE]; // storage used by incrementalize + float dr[] = new float[DEFAULT_SIZE]; + float l[] = new float[DEFAULT_SIZE]; // more storage for incrementalize + float dl[] = new float[DEFAULT_SIZE]; + float sp[] = new float[DEFAULT_SIZE]; // temporary storage for scanline + float sdp[] = new float[DEFAULT_SIZE]; + + // color and xyz are always interpolated + boolean interpX; + boolean interpZ; + boolean interpUV; // is this necessary? could just check timage != null + boolean interpARGB; + + int rgba; + int r2, g2, b2, a2, a2orig; + + boolean noDepthTest; + + PGraphics3D parent; + int pixels[]; + float[] zbuffer; + + // the parent's width/height, + // or if smooth is enabled, parent's w/h scaled + // up by the smooth dimension + int width, height; + int width1, height1; + + PImage timage; + int tpixels[]; + int theight, twidth; + int theight1, twidth1; + int tformat; + + // temp fix to behave like SMOOTH_IMAGES + // TODO ewjordan: can probably remove this variable + boolean texture_smooth; + + // for anti-aliasing + static final int SUBXRES = 8; + static final int SUBXRES1 = 7; + static final int SUBYRES = 8; + static final int SUBYRES1 = 7; + static final int MAX_COVERAGE = SUBXRES * SUBYRES; + + boolean smooth; + int firstModY; + int lastModY; + int lastY; + int aaleft[] = new int[SUBYRES]; + int aaright[] = new int[SUBYRES]; + int aaleftmin, aarightmin; + int aaleftmax, aarightmax; + int aaleftfull, aarightfull; + + /* Variables needed for accurate texturing. */ + //private PMatrix textureMatrix = new PMatrix3D(); + private float[] camX = new float[3]; + private float[] camY = new float[3]; + private float[] camZ = new float[3]; + private float ax,ay,az; + private float bx,by,bz; + private float cx,cy,cz; + private float nearPlaneWidth, nearPlaneHeight, nearPlaneDepth; + //private float newax, newbx, newcx; + private float xmult, ymult; + + + final private int MODYRES(int y) { + return (y & SUBYRES1); + } + + + public PSmoothTriangle(PGraphics3D iparent) { + parent = iparent; + reset(0); + } + + + public void reset(int count) { + vertexCount = count; + interpX = true; + interpZ = true; + interpUV = false; + interpARGB = true; + timage = null; + } + + + public float[] nextVertex() { + if (vertexCount == vertices.length) { + //parent.message(CHATTER, "re-allocating for " + + // (vertexCount*2) + " vertices"); + float temp[][] = new float[vertexCount<<1][PGraphics.VERTEX_FIELD_COUNT]; + System.arraycopy(vertices, 0, temp, 0, vertexCount); + vertices = temp; + + r = new float[vertices.length]; + dr = new float[vertices.length]; + l = new float[vertices.length]; + dl = new float[vertices.length]; + sp = new float[vertices.length]; + sdp = new float[vertices.length]; + } + return vertices[vertexCount++]; // returns v[0], sets vc to 1 + } + + + public void texture(PImage image) { + this.timage = image; + this.tpixels = image.pixels; + this.twidth = image.width; + this.theight = image.height; + this.tformat = image.format; + + twidth1 = twidth - 1; + theight1 = theight - 1; + interpUV = true; + } + + public void render() { + if (vertexCount < 3) return; + + smooth = true;//TODO + // these may have changed due to a resize() + // so they should be refreshed here + pixels = parent.pixels; + zbuffer = parent.zbuffer; + + noDepthTest = false;//parent.hints[DISABLE_DEPTH_TEST]; + + // In 0148+, should always be true if this code is called at all + //smooth = parent.smooth; + + // by default, text turns on smooth for the textures + // themselves. but this should be shut off if the hint + // for DISABLE_TEXT_SMOOTH is set. + texture_smooth = true; + + width = smooth ? parent.width*SUBXRES : parent.width; + height = smooth ? parent.height*SUBYRES : parent.height; + + width1 = width - 1; + height1 = height - 1; + + if (!interpARGB) { + r2 = (int) (vertices[0][R] * 255); + g2 = (int) (vertices[0][G] * 255); + b2 = (int) (vertices[0][B] * 255); + a2 = (int) (vertices[0][A] * 255); + a2orig = a2; // save an extra copy + rgba = 0xff000000 | (r2 << 16) | (g2 << 8) | b2; + } + + for (int i = 0; i < vertexCount; i++) { + r[i] = 0; dr[i] = 0; l[i] = 0; dl[i] = 0; + } + + if (smooth) { + for (int i = 0; i < vertexCount; i++) { + vertices[i][X] *= SUBXRES; + vertices[i][Y] *= SUBYRES; + } + firstModY = -1; + } + + // find top vertex (y is zero at top, higher downwards) + int topi = 0; + float ymin = vertices[0][Y]; + float ymax = vertices[0][Y]; // fry 031001 + for (int i = 1; i < vertexCount; i++) { + if (vertices[i][Y] < ymin) { + ymin = vertices[i][Y]; + topi = i; + } + if (vertices[i][Y] > ymax) ymax = vertices[i][Y]; + } + + // the last row is an exceptional case, because there won't + // necessarily be 8 rows of subpixel lines that will force + // the final line to render. so instead, the algo keeps track + // of the lastY (in subpixel resolution) that will be rendered + // and that will force a scanline to happen the same as + // every eighth in the other situations + //lastY = -1; // fry 031001 + lastY = (int) (ymax - 0.5f); // global to class bc used by other fxns + + int lefti = topi; // li, index of left vertex + int righti = topi; // ri, index of right vertex + int y = (int) (ymin + 0.5f); // current scan line + int lefty = y - 1; // lower end of left edge + int righty = y - 1; // lower end of right edge + + interpX = true; + + int remaining = vertexCount; + + // scan in y, activating new edges on left & right + // as scan line passes over new vertices + while (remaining > 0) { + // advance left edge? + while ((lefty <= y) && (remaining > 0)) { + remaining--; + // step ccw down left side + int i = (lefti != 0) ? (lefti-1) : (vertexCount-1); + incrementalize_y(vertices[lefti], vertices[i], l, dl, y); + lefty = (int) (vertices[i][Y] + 0.5f); + lefti = i; + } + + // advance right edge? + while ((righty <= y) && (remaining > 0)) { + remaining--; + // step cw down right edge + int i = (righti != vertexCount-1) ? (righti + 1) : 0; + incrementalize_y(vertices[righti], vertices[i], r, dr, y); + righty = (int) (vertices[i][Y] + 0.5f); + righti = i; + } + + // do scanlines till end of l or r edge + while (y < lefty && y < righty) { + // this doesn't work because it's not always set here + //if (remaining == 0) { + //lastY = (lefty < righty) ? lefty-1 : righty-1; + //System.out.println("lastY is " + lastY); + //} + + if ((y >= 0) && (y < height)) { + //try { // hopefully this bug is fixed + if (l[X] <= r[X]) scanline(y, l, r); + else scanline(y, r, l); + //} catch (ArrayIndexOutOfBoundsException e) { + //e.printStackTrace(); + //} + } + y++; + // this increment probably needs to be different + // UV and RGB shouldn't be incremented until line is emitted + increment(l, dl); + increment(r, dr); + } + } + //if (smooth) { + //System.out.println("y/lasty/lastmody = " + y + " " + lastY + " " + lastModY); + //} + } + + + public void unexpand() { + if (smooth) { + for (int i = 0; i < vertexCount; i++) { + vertices[i][X] /= SUBXRES; + vertices[i][Y] /= SUBYRES; + } + } + } + + + private void scanline(int y, float l[], float r[]) { + //System.out.println("scanline " + y); + for (int i = 0; i < vertexCount; i++) { // should be moved later + sp[i] = 0; sdp[i] = 0; + } + + // this rounding doesn't seem to be relevant with smooth + int lx = (int) (l[X] + 0.49999f); // ceil(l[X]-.5); + if (lx < 0) lx = 0; + int rx = (int) (r[X] - 0.5f); + if (rx > width1) rx = width1; + + if (lx > rx) return; + + if (smooth) { + int mody = MODYRES(y); + + aaleft[mody] = lx; + aaright[mody] = rx; + + if (firstModY == -1) { + firstModY = mody; + aaleftmin = lx; aaleftmax = lx; + aarightmin = rx; aarightmax = rx; + + } else { + if (aaleftmin > aaleft[mody]) aaleftmin = aaleft[mody]; + if (aaleftmax < aaleft[mody]) aaleftmax = aaleft[mody]; + if (aarightmin > aaright[mody]) aarightmin = aaright[mody]; + if (aarightmax < aaright[mody]) aarightmax = aaright[mody]; + } + + lastModY = mody; // moved up here (before the return) 031001 + // not the eighth (or lastY) line, so not scanning this time + if ((mody != SUBYRES1) && (y != lastY)) return; + //lastModY = mody; // eeK! this was missing + //return; + + //if (y == lastY) { + //System.out.println("y is lasty"); + //} + //lastModY = mody; + aaleftfull = aaleftmax/SUBXRES + 1; + aarightfull = aarightmin/SUBXRES - 1; + } + + // this is the setup, based on lx + incrementalize_x(l, r, sp, sdp, lx); + //System.out.println(l[V] + " " + r[V] + " " +sp[V] + " " +sdp[V]); + + // scan in x, generating pixels + // using parent.width to get actual pixel index + // rather than scaled by smooth factor + int offset = smooth ? parent.width * (y / SUBYRES) : parent.width*y; + + int truelx = 0, truerx = 0; + if (smooth) { + truelx = lx / SUBXRES; + truerx = (rx + SUBXRES1) / SUBXRES; + + lx = aaleftmin / SUBXRES; + rx = (aarightmax + SUBXRES1) / SUBXRES; + if (lx < 0) lx = 0; + if (rx > parent.width1) rx = parent.width1; + } + +// System.out.println("P3D interp uv " + interpUV + " " + +// vertices[2][U] + " " + vertices[2][V]); + + interpX = false; + int tr, tg, tb, ta; + //System.out.println("lx: "+lx + "\nrx: "+rx); + for (int x = lx; x <= rx; x++) { + + // added == because things on same plane weren't replacing each other + // makes for strangeness in 3D [ewj: yup!], but totally necessary for 2D + //if (noDepthTest || (sp[Z] < zbuffer[offset+x])) { + if (noDepthTest || (sp[Z] <= zbuffer[offset+x])) { + //if (true) { + + // map texture based on U, V coords in sp[U] and sp[V] + if (interpUV) { + int tu = (int)sp[U]; + int tv = (int)sp[V]; + + if (tu > twidth1) tu = twidth1; + if (tv > theight1) tv = theight1; + if (tu < 0) tu = 0; + if (tv < 0) tv = 0; + + int txy = tv*twidth + tu; + //System.out.println("tu: "+tu+" ; tv: "+tv+" ; txy: "+txy); + float[] uv = new float[2]; + txy = getTextureIndex(x, y*1.0f/SUBYRES, uv); + // txy = getTextureIndex(x* 1.0f/SUBXRES, y*1.0f/SUBYRES, uv); + + tu = (int)uv[0]; tv = (int)uv[1]; + // if (tu > twidth1) tu = twidth1; + // if (tv > theight1) tv = theight1; + // if (tu < 0) tu = 0; + // if (tv < 0) tv = 0; + txy = twidth*tv + tu; + // if (EWJORDAN) System.out.println("x/y/txy:"+x + " " + y + " " +txy); + //PApplet.println(sp); + + //smooth = true; + if (smooth || texture_smooth) { + //if (FRY) System.out.println("sp u v = " + sp[U] + " " + sp[V]); + //System.out.println("sp u v = " + sp[U] + " " + sp[V]); + // tuf1/tvf1 is the amount of coverage for the adjacent + // pixel, which is the decimal percentage. + // int tuf1 = (int) (255f * (sp[U] - (float)tu)); + // int tvf1 = (int) (255f * (sp[V] - (float)tv)); + + int tuf1 = (int) (255f * (uv[0] - tu)); + int tvf1 = (int) (255f * (uv[1] - tv)); + + // the closer sp[U or V] is to the decimal being zero + // the more coverage it should get of the original pixel + int tuf = 255 - tuf1; + int tvf = 255 - tvf1; + + // this code sucks! filled with bugs and slow as hell! + int pixel00 = tpixels[txy]; + int pixel01 = (tv < theight1) ? tpixels[txy + twidth] : tpixels[txy]; + int pixel10 = (tu < twidth1) ? tpixels[txy + 1] : tpixels[txy]; + int pixel11 = ((tv < theight1) && (tu < twidth1)) ? tpixels[txy + twidth + 1] : tpixels[txy]; + //System.out.println("1: "+pixel00); + //check + int p00, p01, p10, p11; + int px0, px1; //, pxy; + + if (tformat == ALPHA) { + px0 = (pixel00*tuf + pixel10*tuf1) >> 8; + px1 = (pixel01*tuf + pixel11*tuf1) >> 8; + ta = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[A]*255)) : a2orig)) >> 8; + } else if (tformat == ARGB) { + p00 = (pixel00 >> 24) & 0xff; + p01 = (pixel01 >> 24) & 0xff; + p10 = (pixel10 >> 24) & 0xff; + p11 = (pixel11 >> 24) & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + ta = (((px0*tvf + px1*tvf1) >> 8) * + (interpARGB ? ((int) (sp[A]*255)) : a2orig)) >> 8; + } else { // RGB image, no alpha + //ACCTEX: Getting here when smooth is on + ta = interpARGB ? ((int) (sp[A]*255)) : a2orig; + //System.out.println("4: "+ta + " " +interpARGB + " " + sp[A] + " " + a2orig); + //check + } + + if ((tformat == RGB) || (tformat == ARGB)) { + p00 = (pixel00 >> 16) & 0xff; // red + p01 = (pixel01 >> 16) & 0xff; + p10 = (pixel10 >> 16) & 0xff; + p11 = (pixel11 >> 16) & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + tr = (((px0*tvf + px1*tvf1) >> 8) * (interpARGB ? ((int) (sp[R]*255)) : r2)) >> 8; + + p00 = (pixel00 >> 8) & 0xff; // green + p01 = (pixel01 >> 8) & 0xff; + p10 = (pixel10 >> 8) & 0xff; + p11 = (pixel11 >> 8) & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + tg = (((px0*tvf + px1*tvf1) >> 8) * (interpARGB ? ((int) (sp[G]*255)) : g2)) >> 8; + + + p00 = pixel00 & 0xff; // blue + p01 = pixel01 & 0xff; + p10 = pixel10 & 0xff; + p11 = pixel11 & 0xff; + + px0 = (p00*tuf + p10*tuf1) >> 8; + px1 = (p01*tuf + p11*tuf1) >> 8; + tb = (((px0*tvf + px1*tvf1) >> 8) * (interpARGB ? ((int) (sp[B]*255)) : b2)) >> 8; + //System.out.println("5: "+tr + " " + tg + " " +tb); + //check + } else { // alpha image, only use current fill color + if (interpARGB) { + tr = (int) (sp[R] * 255); + tg = (int) (sp[G] * 255); + tb = (int) (sp[B] * 255); + } else { + tr = r2; + tg = g2; + tb = b2; + } + } + + // get coverage for pixel if smooth + // checks smooth again here because of + // hints[SMOOTH_IMAGES] used up above + int weight = smooth ? coverage(x) : 255; + if (weight != 255) ta = (ta*weight) >> 8; + //System.out.println(ta); + //System.out.println("8"); + //check + } else { // no smooth, just get the pixels + int tpixel = tpixels[txy]; + // TODO i doubt splitting these guys really gets us + // all that much speed.. is it worth it? + if (tformat == ALPHA) { + ta = tpixel; + if (interpARGB) { + tr = (int) (sp[R]*255); + tg = (int) (sp[G]*255); + tb = (int) (sp[B]*255); + if (sp[A] != 1) { + ta = (((int) (sp[A]*255)) * ta) >> 8; + } + } else { + tr = r2; + tg = g2; + tb = b2; + ta = (a2orig * ta) >> 8; + } + + } else { // RGB or ARGB + ta = (tformat == RGB) ? 255 : (tpixel >> 24) & 0xff; + if (interpARGB) { + tr = (((int) (sp[R]*255)) * ((tpixel >> 16) & 0xff)) >> 8; + tg = (((int) (sp[G]*255)) * ((tpixel >> 8) & 0xff)) >> 8; + tb = (((int) (sp[B]*255)) * ((tpixel) & 0xff)) >> 8; + ta = (((int) (sp[A]*255)) * ta) >> 8; + } else { + tr = (r2 * ((tpixel >> 16) & 0xff)) >> 8; + tg = (g2 * ((tpixel >> 8) & 0xff)) >> 8; + tb = (b2 * ((tpixel) & 0xff)) >> 8; + ta = (a2orig * ta) >> 8; + } + } + } + + if ((ta == 254) || (ta == 255)) { // if (ta & 0xf8) would be good + // no need to blend + pixels[offset+x] = 0xff000000 | (tr << 16) | (tg << 8) | tb; + zbuffer[offset+x] = sp[Z]; + } else { + // blend with pixel on screen + int a1 = 255-ta; + int r1 = (pixels[offset+x] >> 16) & 0xff; + int g1 = (pixels[offset+x] >> 8) & 0xff; + int b1 = (pixels[offset+x]) & 0xff; + + + pixels[offset+x] = + 0xff000000 | + (((tr*ta + r1*a1) >> 8) << 16) | + ((tg*ta + g1*a1) & 0xff00) | + ((tb*ta + b1*a1) >> 8); + + //System.out.println("17"); + //check + if (ta > ZBUFFER_MIN_COVERAGE) zbuffer[offset+x] = sp[Z]; + } + + //System.out.println("18"); + //check + } else { // no image applied + int weight = smooth ? coverage(x) : 255; + + if (interpARGB) { + r2 = (int) (sp[R] * 255); + g2 = (int) (sp[G] * 255); + b2 = (int) (sp[B] * 255); + if (sp[A] != 1) weight = (weight * ((int) (sp[A] * 255))) >> 8; + if (weight == 255) { + rgba = 0xff000000 | (r2 << 16) | (g2 << 8) | b2; + } + } else { + if (a2orig != 255) weight = (weight * a2orig) >> 8; + } + + if (weight == 255) { + // no blend, no aa, just the rgba + pixels[offset+x] = rgba; + zbuffer[offset+x] = sp[Z]; + + } else { + int r1 = (pixels[offset+x] >> 16) & 0xff; + int g1 = (pixels[offset+x] >> 8) & 0xff; + int b1 = (pixels[offset+x]) & 0xff; + a2 = weight; + + int a1 = 255 - a2; + pixels[offset+x] = (0xff000000 | + ((r1*a1 + r2*a2) >> 8) << 16 | + // use & instead of >> and << below + ((g1*a1 + g2*a2) >> 8) << 8 | + ((b1*a1 + b2*a2) >> 8)); + + if (a2 > ZBUFFER_MIN_COVERAGE) zbuffer[offset+x] = sp[Z]; + } + } + } + // if smooth enabled, don't increment values + // for the pixel in the stretch out version + // of the scanline used to get smooth edges. + if (!smooth || ((x >= truelx) && (x <= truerx))) { + //if (!smooth) + increment(sp, sdp); + } + } + firstModY = -1; + interpX = true; + } + + + // x is in screen, not huge 8x coordinates + private int coverage(int x) { + if ((x >= aaleftfull) && (x <= aarightfull) && + // important since not all SUBYRES lines may have been covered + (firstModY == 0) && (lastModY == SUBYRES1)) { + return 255; + } + + int pixelLeft = x*SUBXRES; // huh? + int pixelRight = pixelLeft + 8; + + int amt = 0; + for (int i = firstModY; i <= lastModY; i++) { + if ((aaleft[i] > pixelRight) || (aaright[i] < pixelLeft)) { + continue; + } + // does this need a +1 ? + amt += ((aaright[i] < pixelRight ? aaright[i] : pixelRight) - + (aaleft[i] > pixelLeft ? aaleft[i] : pixelLeft)); + } + amt <<= 2; + return (amt == 256) ? 255 : amt; + } + + + private void incrementalize_y(float p1[], float p2[], + float p[], float dp[], int y) { + float delta = p2[Y] - p1[Y]; + if (delta == 0) delta = 1; + float fraction = y + 0.5f - p1[Y]; + + if (interpX) { + dp[X] = (p2[X] - p1[X]) / delta; + p[X] = p1[X] + dp[X] * fraction; + } + if (interpZ) { + dp[Z] = (p2[Z] - p1[Z]) / delta; + p[Z] = p1[Z] + dp[Z] * fraction; + } + + if (interpARGB) { + dp[R] = (p2[R] - p1[R]) / delta; + dp[G] = (p2[G] - p1[G]) / delta; + dp[B] = (p2[B] - p1[B]) / delta; + dp[A] = (p2[A] - p1[A]) / delta; + p[R] = p1[R] + dp[R] * fraction; + p[G] = p1[G] + dp[G] * fraction; + p[B] = p1[B] + dp[B] * fraction; + p[A] = p1[A] + dp[A] * fraction; + } + + if (interpUV) { + dp[U] = (p2[U] - p1[U]) / delta; + dp[V] = (p2[V] - p1[V]) / delta; + + //if (smooth) { + //p[U] = p1[U]; //+ dp[U] * fraction; + //p[V] = p1[V]; //+ dp[V] * fraction; + + //} else { + p[U] = p1[U] + dp[U] * fraction; + p[V] = p1[V] + dp[V] * fraction; + //} + if (FRY) System.out.println("inc y p[U] p[V] = " + p[U] + " " + p[V]); + } + } + + //incrementalize_x(l, r, sp, sdp, lx); + private void incrementalize_x(float p1[], float p2[], + float p[], float dp[], int x) { + float delta = p2[X] - p1[X]; + if (delta == 0) delta = 1; + float fraction = x + 0.5f - p1[X]; + if (smooth) { + delta /= SUBXRES; + fraction /= SUBXRES; + } + + if (interpX) { + dp[X] = (p2[X] - p1[X]) / delta; + p[X] = p1[X] + dp[X] * fraction; + } + if (interpZ) { + dp[Z] = (p2[Z] - p1[Z]) / delta; + p[Z] = p1[Z] + dp[Z] * fraction; + //System.out.println(p2[Z]+" " +p1[Z]+" " +dp[Z]); + } + + if (interpARGB) { + dp[R] = (p2[R] - p1[R]) / delta; + dp[G] = (p2[G] - p1[G]) / delta; + dp[B] = (p2[B] - p1[B]) / delta; + dp[A] = (p2[A] - p1[A]) / delta; + p[R] = p1[R] + dp[R] * fraction; + p[G] = p1[G] + dp[G] * fraction; + p[B] = p1[B] + dp[B] * fraction; + p[A] = p1[A] + dp[A] * fraction; + } + + if (interpUV) { + if (FRY) System.out.println("delta, frac = " + delta + ", " + fraction); + dp[U] = (p2[U] - p1[U]) / delta; + dp[V] = (p2[V] - p1[V]) / delta; + + //if (smooth) { + //p[U] = p1[U]; + // offset for the damage that will be done by the + // 8 consecutive calls to scanline + // agh.. this won't work b/c not always 8 calls before render + // maybe lastModY - firstModY + 1 instead? + if (FRY) System.out.println("before inc x p[V] = " + p[V] + " " + p1[V] + " " + p2[V]); + //p[V] = p1[V] - SUBXRES1 * fraction; + + //} else { + p[U] = p1[U] + dp[U] * fraction; + p[V] = p1[V] + dp[V] * fraction; + //} + } + } + + private void increment(float p[], float dp[]) { + if (interpX) p[X] += dp[X]; + if (interpZ) p[Z] += dp[Z]; + + if (interpARGB) { + p[R] += dp[R]; + p[G] += dp[G]; + p[B] += dp[B]; + p[A] += dp[A]; + } + + if (interpUV) { + if (FRY) System.out.println("increment() " + p[V] + " " + dp[V]); + p[U] += dp[U]; + p[V] += dp[V]; + } + } + + + /** + * Pass camera-space coordinates for the triangle. + * Needed to render if hint(ENABLE_ACCURATE_TEXTURES) enabled. + * Generally this will not need to be called manually, + * currently called from PGraphics3D.render_triangles() + */ + public void setCamVertices(float x0, float y0, float z0, + float x1, float y1, float z1, + float x2, float y2, float z2) { + camX[0] = x0; + camX[1] = x1; + camX[2] = x2; + + camY[0] = y0; + camY[1] = y1; + camY[2] = y2; + + camZ[0] = z0; + camZ[1] = z1; + camZ[2] = z2; + } + + public void setVertices(float x0, float y0, float z0, + float x1, float y1, float z1, + float x2, float y2, float z2) { + vertices[0][X] = x0; + vertices[1][X] = x1; + vertices[2][X] = x2; + + vertices[0][Y] = y0; + vertices[1][Y] = y1; + vertices[2][Y] = y2; + + vertices[0][Z] = z0; + vertices[1][Z] = z1; + vertices[2][Z] = z2; + } + + + + /** + * Precompute a bunch of variables needed to perform + * texture mapping. + * @return True unless texture mapping is degenerate + */ + boolean precomputeAccurateTexturing() { + int o0 = 0; + int o1 = 1; + int o2 = 2; + + PMatrix3D myMatrix = new PMatrix3D(vertices[o0][U], vertices[o0][V], 1, 0, + vertices[o1][U], vertices[o1][V], 1, 0, + vertices[o2][U], vertices[o2][V], 1, 0, + 0, 0, 0, 1); + + // A 3x3 inversion would be more efficient here, + // given that the fourth r/c are unity + boolean invertSuccess = myMatrix.invert();// = myMatrix.invert(); + + // If the matrix inversion had trouble, let the caller know. + // Note that this does not catch everything that could go wrong + // here, like if the renderer is in ortho() mode (which really + // must be caught in PGraphics3D instead of here). + if (!invertSuccess) return false; + + float m00, m01, m02, m10, m11, m12, m20, m21, m22; + m00 = myMatrix.m00*camX[o0]+myMatrix.m01*camX[o1]+myMatrix.m02*camX[o2]; + m01 = myMatrix.m10*camX[o0]+myMatrix.m11*camX[o1]+myMatrix.m12*camX[o2]; + m02 = myMatrix.m20*camX[o0]+myMatrix.m21*camX[o1]+myMatrix.m22*camX[o2]; + m10 = myMatrix.m00*camY[o0]+myMatrix.m01*camY[o1]+myMatrix.m02*camY[o2]; + m11 = myMatrix.m10*camY[o0]+myMatrix.m11*camY[o1]+myMatrix.m12*camY[o2]; + m12 = myMatrix.m20*camY[o0]+myMatrix.m21*camY[o1]+myMatrix.m22*camY[o2]; + m20 = -(myMatrix.m00*camZ[o0]+myMatrix.m01*camZ[o1]+myMatrix.m02*camZ[o2]); + m21 = -(myMatrix.m10*camZ[o0]+myMatrix.m11*camZ[o1]+myMatrix.m12*camZ[o2]); + m22 = -(myMatrix.m20*camZ[o0]+myMatrix.m21*camZ[o1]+myMatrix.m22*camZ[o2]); + + float px = m02; + float py = m12; + float pz = m22; + + float TEX_WIDTH = this.twidth; + float TEX_HEIGHT = this.theight; + + float resultT0x = m00*TEX_WIDTH+m02; + float resultT0y = m10*TEX_WIDTH+m12; + float resultT0z = m20*TEX_WIDTH+m22; + float result0Tx = m01*TEX_HEIGHT+m02; + float result0Ty = m11*TEX_HEIGHT+m12; + float result0Tz = m21*TEX_HEIGHT+m22; + float mx = resultT0x-m02; + float my = resultT0y-m12; + float mz = resultT0z-m22; + float nx = result0Tx-m02; + float ny = result0Ty-m12; + float nz = result0Tz-m22; + + //avec = p x n + ax = (py*nz-pz*ny)*TEX_WIDTH; //F_TEX_WIDTH/HEIGHT? + ay = (pz*nx-px*nz)*TEX_WIDTH; + az = (px*ny-py*nx)*TEX_WIDTH; + //bvec = m x p + bx = (my*pz-mz*py)*TEX_HEIGHT; + by = (mz*px-mx*pz)*TEX_HEIGHT; + bz = (mx*py-my*px)*TEX_HEIGHT; + //cvec = n x m + cx = ny*mz-nz*my; + cy = nz*mx-nx*mz; + cz = nx*my-ny*mx; + + //System.out.println("a/b/c: "+ax+" " + ay + " " + az + " " + bx + " " + by + " " + bz + " " + cx + " " + cy + " " + cz); + + nearPlaneWidth = (parent.rightScreen-parent.leftScreen); + nearPlaneHeight = (parent.topScreen-parent.bottomScreen); + nearPlaneDepth = parent.nearPlane; + + // one pixel width in nearPlane coordinates + xmult = nearPlaneWidth / parent.width; + ymult = nearPlaneHeight / parent.height; + // Extra scalings to map screen plane units to pixel units +// newax = ax*xmult; +// newbx = bx*xmult; +// newcx = cx*xmult; + + + // System.out.println("nearplane: "+ nearPlaneWidth + " " + nearPlaneHeight + " " + nearPlaneDepth); + // System.out.println("mults: "+ xmult + " " + ymult); + // System.out.println("news: "+ newax + " " + newbx + " " + newcx); + return true; + } + + /** + * Get the texture map location based on the current screen + * coordinates. Assumes precomputeAccurateTexturing() has + * been called already for this texture mapping. + * @param sx + * @param sy + * @return + */ + private int getTextureIndex(float sx, float sy, float[] uv) { + if (EWJORDAN) System.out.println("Getting texel at "+sx + ", "+sy); + //System.out.println("Screen: "+ sx + " " + sy); + sx = xmult*(sx-(parent.width/2.0f) +.5f);//+.5f) + sy = ymult*(sy-(parent.height/2.0f)+.5f);//+.5f) + //sx /= SUBXRES; + //sy /= SUBYRES; + float sz = nearPlaneDepth; + float a = sx * ax + sy * ay + sz * az; + float b = sx * bx + sy * by + sz * bz; + float c = sx * cx + sy * cy + sz * cz; + int u = (int)(a / c); + int v = (int)(b / c); + uv[0] = a / c; + uv[1] = b / c; + if (uv[0] < 0) { + uv[0] = u = 0; + } + if (uv[1] < 0) { + uv[1] = v = 0; + } + if (uv[0] >= twidth) { + uv[0] = twidth-1; + u = twidth-1; + } + if (uv[1] >= theight) { + uv[1] = theight-1; + v = theight-1; + } + int result = v*twidth + u; + //System.out.println("a/b/c: "+a + " " + b + " " + c); + //System.out.println("cx/y/z: "+cx + " " + cy + " " + cz); + //if (result < 0) result = 0; + //if (result >= timage.pixels.length-2) result = timage.pixels.length - 2; + if (EWJORDAN) System.out.println("Got texel "+result); + return result; + } + + + public void setIntensities(float ar, float ag, float ab, float aa, + float br, float bg, float bb, float ba, + float cr, float cg, float cb, float ca) { + vertices[0][R] = ar; + vertices[0][G] = ag; + vertices[0][B] = ab; + vertices[0][A] = aa; + vertices[1][R] = br; + vertices[1][G] = bg; + vertices[1][B] = bb; + vertices[1][A] = ba; + vertices[2][R] = cr; + vertices[2][G] = cg; + vertices[2][B] = cb; + vertices[2][A] = ca; + } +} diff --git a/support/Processing_core_src/processing/core/PStyle.java b/support/Processing_core_src/processing/core/PStyle.java new file mode 100644 index 0000000..ccea03a --- /dev/null +++ b/support/Processing_core_src/processing/core/PStyle.java @@ -0,0 +1,61 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2008 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA +*/ + +package processing.core; + + +public class PStyle implements PConstants { + public int imageMode; + public int rectMode; + public int ellipseMode; + public int shapeMode; + + public int colorMode; + public float colorModeX; + public float colorModeY; + public float colorModeZ; + public float colorModeA; + + public boolean tint; + public int tintColor; + public boolean fill; + public int fillColor; + public boolean stroke; + public int strokeColor; + public float strokeWeight; + public int strokeCap; + public int strokeJoin; + + // TODO these fellas are inconsistent, and may need to go elsewhere + public float ambientR, ambientG, ambientB; + public float specularR, specularG, specularB; + public float emissiveR, emissiveG, emissiveB; + public float shininess; + + public PFont textFont; + public int textAlign; + public int textAlignY; + public int textMode; + public float textSize; + public float textLeading; +} diff --git a/support/Processing_core_src/processing/core/PTriangle.java b/support/Processing_core_src/processing/core/PTriangle.java new file mode 100644 index 0000000..97c4fed --- /dev/null +++ b/support/Processing_core_src/processing/core/PTriangle.java @@ -0,0 +1,3850 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2004-07 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + */ + +package processing.core; + +/** + * Handles rendering of single (tesselated) triangles in 3D. + *

+ * Originally written by sami (www.sumea.com) + */ +public class PTriangle implements PConstants +{ + static final float PIXEL_CENTER = 0.5f; // for polygon aa + + static final int R_GOURAUD = 0x1; + static final int R_TEXTURE8 = 0x2; + static final int R_TEXTURE24 = 0x4; + static final int R_TEXTURE32 = 0x8; + static final int R_ALPHA = 0x10; + + private int[] m_pixels; + private int[] m_texture; + //private int[] m_stencil; + private float[] m_zbuffer; + + private int SCREEN_WIDTH; + private int SCREEN_HEIGHT; + //private int SCREEN_WIDTH1; + //private int SCREEN_HEIGHT1; + + private int TEX_WIDTH; + private int TEX_HEIGHT; + private float F_TEX_WIDTH; + private float F_TEX_HEIGHT; + + public boolean INTERPOLATE_UV; + public boolean INTERPOLATE_RGB; + public boolean INTERPOLATE_ALPHA; + + // the power of 2 that tells how many pixels to interpolate + // for between exactly computed texture coordinates + private static final int DEFAULT_INTERP_POWER = 3; + private static int TEX_INTERP_POWER = DEFAULT_INTERP_POWER; + + // Vertex coordinates + private float[] x_array; + private float[] y_array; + private float[] z_array; + + private float[] camX; + private float[] camY; + private float[] camZ; + + // U,V coordinates + private float[] u_array; + private float[] v_array; + + // Vertex Intensity + private float[] r_array; + private float[] g_array; + private float[] b_array; + private float[] a_array; + + // vertex offsets + private int o0; + private int o1; + private int o2; + + /* rgb & a */ + private float r0; + private float r1; + private float r2; + private float g0; + private float g1; + private float g2; + private float b0; + private float b1; + private float b2; + private float a0; + private float a1; + private float a2; + + /* accurate texture uv coordinates */ + private float u0; + private float u1; + private float u2; + private float v0; + private float v1; + private float v2; + + /* deltas */ + //private float dx0; + //private float dx1; + private float dx2; + private float dy0; + private float dy1; + private float dy2; + private float dz0; + //private float dz1; + private float dz2; + + /* texture deltas */ + private float du0; + //private float du1; + private float du2; + private float dv0; + //private float dv1; + private float dv2; + + /* rgba deltas */ + private float dr0; + //private float dr1; + private float dr2; + private float dg0; + //private float dg1; + private float dg2; + private float db0; + //private float db1; + private float db2; + private float da0; + //private float da1; + private float da2; + + /* */ + private float uleft; + private float vleft; + private float uleftadd; + private float vleftadd; + + /* polyedge positions & adds */ + private float xleft; + private float xrght; + private float xadd1; + private float xadd2; + private float zleft; + private float zleftadd; + + /* rgba positions & adds */ + private float rleft; + private float gleft; + private float bleft; + private float aleft; + private float rleftadd; + private float gleftadd; + private float bleftadd; + private float aleftadd; + + /* other somewhat useful variables :) */ + private float dta; + //private float dta2; + private float temp; + private float width; + + /* integer poly UV adds */ + private int iuadd; + private int ivadd; + private int iradd; + private int igadd; + private int ibadd; + private int iaadd; + private float izadd; + + /* fill color */ + private int m_fill; + + /* draw flags */ + public int m_drawFlags; + + /* current poly number */ +// private int m_index; + + /** */ + private PGraphics3D parent; + + private boolean noDepthTest; + //private boolean argbSurface; + + /** */ + private boolean m_culling; + + /** */ + private boolean m_singleRight; + + /** + * True if using bilinear interpolation for textures. + * Always set to true. If this is ever changed (maybe with a hint()?) + * will need to write code for texture8/24/32 et al that will handle mixing + * the m_fill color in with the texture color. + */ + private boolean m_bilinear = true; // always set to true + + + // Vectors needed in accurate texture code + // We store them as class members to avoid too much code duplication + private float ax,ay,az; + private float bx,by,bz; + private float cx,cy,cz; + private float nearPlaneWidth; + private float nearPlaneHeight; + private float nearPlaneDepth; + private float xmult; + private float ymult; + // optimization vars...not pretty, but save a couple mults per pixel + private float newax,newbx,newcx; + // are we currently drawing the first piece of the triangle, + // or have we already done so? + private boolean firstSegment; + + + public PTriangle(PGraphics3D g) { + x_array = new float[3]; + y_array = new float[3]; + z_array = new float[3]; + u_array = new float[3]; + v_array = new float[3]; + r_array = new float[3]; + g_array = new float[3]; + b_array = new float[3]; + a_array = new float[3]; + + camX = new float[3]; + camY = new float[3]; + camZ = new float[3]; + + this.parent = g; + reset(); + } + + + /** + * Resets polygon attributes + */ + public void reset() { + // reset these in case PGraphics was resized + + SCREEN_WIDTH = parent.width; + SCREEN_HEIGHT = parent.height; + //SCREEN_WIDTH1 = SCREEN_WIDTH-1; + //SCREEN_HEIGHT1 = SCREEN_HEIGHT-1; + + m_pixels = parent.pixels; +// m_stencil = parent.stencil; + m_zbuffer = parent.zbuffer; + + noDepthTest = parent.hints[DISABLE_DEPTH_TEST]; + //argbSurface = parent.format == PConstants.ARGB; + + // other things to reset + + INTERPOLATE_UV = false; + INTERPOLATE_RGB = false; + INTERPOLATE_ALPHA = false; + //m_tImage = null; + m_texture = null; + m_drawFlags = 0; + } + + + /** + * Sets backface culling on/off + */ + public void setCulling(boolean tf) { + m_culling = tf; + } + + + /** + * Sets vertex coordinates for the triangle + */ + public void setVertices(float x0, float y0, float z0, + float x1, float y1, float z1, + float x2, float y2, float z2) { + x_array[0] = x0; + x_array[1] = x1; + x_array[2] = x2; + + y_array[0] = y0; + y_array[1] = y1; + y_array[2] = y2; + + z_array[0] = z0; + z_array[1] = z1; + z_array[2] = z2; + } + + + /** + * Pass camera-space coordinates for the triangle. + * Needed to render if hint(ENABLE_ACCURATE_TEXTURES) enabled. + * Generally this will not need to be called manually, + * currently called from PGraphics3D.render_triangles() + */ + public void setCamVertices(float x0, float y0, float z0, + float x1, float y1, float z1, + float x2, float y2, float z2) { + camX[0] = x0; + camX[1] = x1; + camX[2] = x2; + + camY[0] = y0; + camY[1] = y1; + camY[2] = y2; + + camZ[0] = z0; + camZ[1] = z1; + camZ[2] = z2; + } + + + /** + * Sets the UV coordinates of the texture + */ + public void setUV(float u0, float v0, + float u1, float v1, + float u2, float v2) { + // sets & scales uv texture coordinates to center of the pixel + u_array[0] = (u0 * F_TEX_WIDTH + 0.5f) * 65536f; + u_array[1] = (u1 * F_TEX_WIDTH + 0.5f) * 65536f; + u_array[2] = (u2 * F_TEX_WIDTH + 0.5f) * 65536f; + v_array[0] = (v0 * F_TEX_HEIGHT + 0.5f) * 65536f; + v_array[1] = (v1 * F_TEX_HEIGHT + 0.5f) * 65536f; + v_array[2] = (v2 * F_TEX_HEIGHT + 0.5f) * 65536f; + } + + + /** + * Sets vertex intensities in 0xRRGGBBAA format + */ + public void setIntensities(float r0, float g0, float b0, float a0, + float r1, float g1, float b1, float a1, + float r2, float g2, float b2, float a2) { + // Check if we need alpha or not? + if ((a0 != 1.0f) || (a1 != 1.0f) || (a2 != 1.0f)) { + INTERPOLATE_ALPHA = true; + a_array[0] = (a0 * 253f + 1.0f) * 65536f; + a_array[1] = (a1 * 253f + 1.0f) * 65536f; + a_array[2] = (a2 * 253f + 1.0f) * 65536f; + m_drawFlags|=R_ALPHA; + } else { + INTERPOLATE_ALPHA = false; + m_drawFlags&=~R_ALPHA; + } + + // Check if we need to interpolate the intensity values + if ((r0 != r1) || (r1 != r2)) { + INTERPOLATE_RGB = true; + m_drawFlags |= R_GOURAUD; + } else if ((g0 != g1) || (g1 != g2)) { + INTERPOLATE_RGB = true; + m_drawFlags |= R_GOURAUD; + } else if ((b0 != b1) || (b1 != b2)) { + INTERPOLATE_RGB = true; + m_drawFlags |= R_GOURAUD; + } else { + //m_fill = parent.filli; + m_drawFlags &=~ R_GOURAUD; + } + + // push values to arrays.. some extra scaling is added + // to prevent possible color "overflood" due to rounding errors + r_array[0] = (r0 * 253f + 1.0f) * 65536f; + r_array[1] = (r1 * 253f + 1.0f) * 65536f; + r_array[2] = (r2 * 253f + 1.0f) * 65536f; + + g_array[0] = (g0 * 253f + 1.0f) * 65536f; + g_array[1] = (g1 * 253f + 1.0f) * 65536f; + g_array[2] = (g2 * 253f + 1.0f) * 65536f; + + b_array[0] = (b0 * 253f + 1.0f) * 65536f; + b_array[1] = (b1 * 253f + 1.0f) * 65536f; + b_array[2] = (b2 * 253f + 1.0f) * 65536f; + + // for plain triangles + m_fill = 0xFF000000 | + ((int)(255*r0) << 16) | ((int)(255*g0) << 8) | (int)(255*b0); + } + + + /** + * Sets texture image used for the polygon + */ + public void setTexture(PImage image) { + //m_tImage = image; + m_texture = image.pixels; + TEX_WIDTH = image.width; + TEX_HEIGHT = image.height; + F_TEX_WIDTH = TEX_WIDTH-1; + F_TEX_HEIGHT = TEX_HEIGHT-1; + INTERPOLATE_UV = true; + + if (image.format == ARGB) { + m_drawFlags |= R_TEXTURE32; + } else if (image.format == RGB) { + m_drawFlags |= R_TEXTURE24; + } else if (image.format == ALPHA) { + m_drawFlags |= R_TEXTURE8; + } + } + + + /** + * + */ + public void setUV(float[] u, float[] v) { + if (m_bilinear) { + // sets & scales uv texture coordinates to edges of pixels + u_array[0] = (u[0] * F_TEX_WIDTH) * 65500f; + u_array[1] = (u[1] * F_TEX_WIDTH) * 65500f; + u_array[2] = (u[2] * F_TEX_WIDTH) * 65500f; + v_array[0] = (v[0] * F_TEX_HEIGHT) * 65500f; + v_array[1] = (v[1] * F_TEX_HEIGHT) * 65500f; + v_array[2] = (v[2] * F_TEX_HEIGHT) * 65500f; + } else { + // sets & scales uv texture coordinates to center of the pixel + u_array[0] = (u[0] * TEX_WIDTH) * 65500f; + u_array[1] = (u[1] * TEX_WIDTH) * 65500f; + u_array[2] = (u[2] * TEX_WIDTH) * 65500f; + v_array[0] = (v[0] * TEX_HEIGHT) * 65500f; + v_array[1] = (v[1] * TEX_HEIGHT) * 65500f; + v_array[2] = (v[2] * TEX_HEIGHT) * 65500f; + } + } + + +// public void setIndex(int index) { +// m_index = index; +// } + + + /** + * Renders the polygon + */ + public void render() { + float x0, x1, x2; + float z0, z1, z2; + + float y0 = y_array[0]; + float y1 = y_array[1]; + float y2 = y_array[2]; + + //System.out.println(PApplet.hex(m_drawFlags)); + + // For accurate texture interpolation, need to mark whether + // we've already pre-calculated for the triangle + firstSegment = true; + + // do backface culling? + if (m_culling) { + x0 = x_array[0]; + if ((x_array[2]-x0)*(y1-y0) < (x_array[1]-x0)*(y2-y0)) + return; + } + + /* get vertex order from top -> down */ + if (y0 < y1) { + if (y2 < y1) { + if (y2 < y0) { // 2,0,1 + o0 = 2; + o1 = 0; + o2 = 1; + } else { // 0,2,1 + o0 = 0; + o1 = 2; + o2 = 1; + } + } else { // 0,1,2 + o0 = 0; + o1 = 1; + o2 = 2; + } + } else { + if (y2 > y1) { + if (y2 < y0) { // 1,2,0 + o0 = 1; + o1 = 2; + o2 = 0; + } else { // 1,0,2 + o0 = 1; + o1 = 0; + o2 = 2; + } + } else { // 2,1,0 + o0 = 2; + o1 = 1; + o2 = 0; + } + } + + /** + * o0 = "top" vertex offset + * o1 = "mid" vertex offset + * o2 = "bot" vertex offset + */ + + y0 = y_array[o0]; + int yi0 = (int) (y0 + PIXEL_CENTER); + if (yi0 > SCREEN_HEIGHT) { + return; + } else if (yi0 < 0) { + yi0 = 0; + } + + y2 = y_array[o2]; + int yi2 = (int) (y2 + PIXEL_CENTER); + if (yi2 < 0) { + return; + } else if (yi2 > SCREEN_HEIGHT) { + yi2 = SCREEN_HEIGHT; + } + + // Does the poly actually cross a scanline? + if (yi2 > yi0) { + x0 = x_array[o0]; + x1 = x_array[o1]; + x2 = x_array[o2]; + + // get mid Y and clip it + y1 = y_array[o1]; + int yi1 = (int) (y1 + PIXEL_CENTER); + if (yi1 < 0) + yi1 = 0; + if (yi1 > SCREEN_HEIGHT) + yi1 = SCREEN_HEIGHT; + + // calculate deltas etc. + dx2 = x2 - x0; + dy0 = y1 - y0; + dy2 = y2 - y0; + xadd2 = dx2 / dy2; // xadd for "single" edge + temp = dy0 / dy2; + width = temp * dx2 + x0 - x1; + + // calculate alpha blend interpolation + if (INTERPOLATE_ALPHA) { + a0 = a_array[o0]; + a1 = a_array[o1]; + a2 = a_array[o2]; + da0 = a1-a0; + da2 = a2-a0; + iaadd = (int) ((temp * da2 - da0) / width); // alpha add + } + + // calculate intensity interpolation + if (INTERPOLATE_RGB) { + r0 = r_array[o0]; + r1 = r_array[o1]; + r2 = r_array[o2]; + + g0 = g_array[o0]; + g1 = g_array[o1]; + g2 = g_array[o2]; + + b0 = b_array[o0]; + b1 = b_array[o1]; + b2 = b_array[o2]; + + dr0 = r1-r0; + dg0 = g1-g0; + db0 = b1-b0; + + dr2 = r2-r0; + dg2 = g2-g0; + db2 = b2-b0; + + iradd = (int) ((temp * dr2 - dr0) / width); // r add + igadd = (int) ((temp * dg2 - dg0) / width); // g add + ibadd = (int) ((temp * db2 - db0) / width); // b add + } + + // calculate UV interpolation + if (INTERPOLATE_UV) { + u0 = u_array[o0]; + u1 = u_array[o1]; + u2 = u_array[o2]; + v0 = v_array[o0]; + v1 = v_array[o1]; + v2 = v_array[o2]; + du0 = u1-u0; + dv0 = v1-v0; + du2 = u2-u0; + dv2 = v2-v0; + iuadd = (int) ((temp * du2 - du0) / width); // u add + ivadd = (int) ((temp * dv2 - dv0) / width); // v add + } + + z0 = z_array[o0]; + z1 = z_array[o1]; + z2 = z_array[o2]; + dz0 = z1-z0; + dz2 = z2-z0; + izadd = (temp * dz2 - dz0) / width; + + // draw the upper poly segment if it's visible + if (yi1 > yi0) { + dta = (yi0 + PIXEL_CENTER) - y0; + xadd1 = (x1 - x0) / dy0; + + // we can determine which side is "single" side + // by comparing left/right edge adds + if (xadd2 > xadd1) { + xleft = x0 + dta * xadd1; + xrght = x0 + dta * xadd2; + zleftadd = dz0 / dy0; + zleft = dta*zleftadd+z0; + + if (INTERPOLATE_UV) { + uleftadd = du0 / dy0; + vleftadd = dv0 / dy0; + uleft = dta*uleftadd+u0; + vleft = dta*vleftadd+v0; + } + + if (INTERPOLATE_RGB) { + rleftadd = dr0 / dy0; + gleftadd = dg0 / dy0; + bleftadd = db0 / dy0; + rleft = dta*rleftadd+r0; + gleft = dta*gleftadd+g0; + bleft = dta*bleftadd+b0; + } + + if (INTERPOLATE_ALPHA) { + aleftadd = da0 / dy0; + aleft = dta*aleftadd+a0; + + if (m_drawFlags == R_ALPHA) { + drawsegment_plain_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) { + drawsegment_gouraud_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) { + drawsegment_texture8_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) { + drawsegment_texture24_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) { + drawsegment_texture32_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) { + drawsegment_gouraud_texture8_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) { + drawsegment_gouraud_texture24_alpha(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) { + drawsegment_gouraud_texture32_alpha(xadd1,xadd2, yi0,yi1); + } + } else { + if (m_drawFlags == 0) { + drawsegment_plain(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == R_GOURAUD) { + drawsegment_gouraud(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == R_TEXTURE8) { + drawsegment_texture8(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == R_TEXTURE24) { + drawsegment_texture24(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == R_TEXTURE32) { + drawsegment_texture32(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) { + drawsegment_gouraud_texture8(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) { + drawsegment_gouraud_texture24(xadd1,xadd2, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) { + drawsegment_gouraud_texture32(xadd1,xadd2, yi0,yi1); + } + } + m_singleRight = true; + } else { + xleft = x0 + dta * xadd2; + xrght = x0 + dta * xadd1; + zleftadd = dz2 / dy2; + zleft = dta*zleftadd+z0; + // + if (INTERPOLATE_UV) { + uleftadd = du2 / dy2; + vleftadd = dv2 / dy2; + uleft = dta*uleftadd+u0; + vleft = dta*vleftadd+v0; + } + + // + if (INTERPOLATE_RGB) { + rleftadd = dr2 / dy2; + gleftadd = dg2 / dy2; + bleftadd = db2 / dy2; + rleft = dta*rleftadd+r0; + gleft = dta*gleftadd+g0; + bleft = dta*bleftadd+b0; + } + + + if (INTERPOLATE_ALPHA) { + aleftadd = da2 / dy2; + aleft = dta*aleftadd+a0; + + if (m_drawFlags == R_ALPHA) { + drawsegment_plain_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) { + drawsegment_gouraud_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) { + drawsegment_texture8_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) { + drawsegment_texture24_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) { + drawsegment_texture32_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) { + drawsegment_gouraud_texture8_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) { + drawsegment_gouraud_texture24_alpha(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) { + drawsegment_gouraud_texture32_alpha(xadd2, xadd1, yi0,yi1); + } + } else { + if (m_drawFlags == 0) { + drawsegment_plain(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == R_GOURAUD) { + drawsegment_gouraud(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == R_TEXTURE8) { + drawsegment_texture8(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == R_TEXTURE24) { + drawsegment_texture24(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == R_TEXTURE32) { + drawsegment_texture32(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) { + drawsegment_gouraud_texture8(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) { + drawsegment_gouraud_texture24(xadd2, xadd1, yi0,yi1); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) { + drawsegment_gouraud_texture32(xadd2, xadd1, yi0,yi1); + } + } + m_singleRight = false; + } + + // if bottom segment height is zero, return + if (yi2 == yi1) return; + + // calculate xadd 1 + dy1 = y2 - y1; + xadd1 = (x2 - x1) / dy1; + + } else { + // top seg height was zero, calculate & clip single edge X + dy1 = y2 - y1; + xadd1 = (x2 - x1) / dy1; + + // which edge is left? + if (xadd2 < xadd1) { + xrght = ((yi1 + PIXEL_CENTER) - y0) * xadd2 + x0; + m_singleRight = true; + } else { + dta = (yi1 + PIXEL_CENTER) - y0; + xleft = dta * xadd2 + x0; + zleftadd = dz2 / dy2; + zleft = dta * zleftadd + z0; + + if (INTERPOLATE_UV) { + uleftadd = du2 / dy2; + vleftadd = dv2 / dy2; + uleft = dta * uleftadd + u0; + vleft = dta * vleftadd + v0; + } + + if (INTERPOLATE_RGB) { + rleftadd = dr2 / dy2; + gleftadd = dg2 / dy2; + bleftadd = db2 / dy2; + rleft = dta * rleftadd + r0; + gleft = dta * gleftadd + g0; + bleft = dta * bleftadd + b0; + } + + // + if (INTERPOLATE_ALPHA) { + aleftadd = da2 / dy2; + aleft = dta * aleftadd + a0; + } + m_singleRight = false; + } + } + + // draw the lower segment + if (m_singleRight) { + dta = (yi1 + PIXEL_CENTER) - y1; + xleft = dta * xadd1 + x1; + zleftadd = (z2 - z1) / dy1; + zleft = dta * zleftadd + z1; + + if (INTERPOLATE_UV) { + uleftadd = (u2 - u1) / dy1; + vleftadd = (v2 - v1) / dy1; + uleft = dta * uleftadd + u1; + vleft = dta * vleftadd + v1; + } + + if (INTERPOLATE_RGB) { + rleftadd = (r2 - r1) / dy1; + gleftadd = (g2 - g1) / dy1; + bleftadd = (b2 - b1) / dy1; + rleft = dta * rleftadd + r1; + gleft = dta * gleftadd + g1; + bleft = dta * bleftadd + b1; + } + + if (INTERPOLATE_ALPHA) { + aleftadd = (a2 - a1) / dy1; + aleft = dta * aleftadd + a1; + + if (m_drawFlags == R_ALPHA) { + drawsegment_plain_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) { + drawsegment_gouraud_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) { + drawsegment_texture8_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) { + drawsegment_texture24_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) { + drawsegment_texture32_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) { + drawsegment_gouraud_texture8_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) { + drawsegment_gouraud_texture24_alpha(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) { + drawsegment_gouraud_texture32_alpha(xadd1, xadd2, yi1,yi2); + } + } else { + if (m_drawFlags == 0) { + drawsegment_plain(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == R_GOURAUD) { + drawsegment_gouraud(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == R_TEXTURE8) { + drawsegment_texture8(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == R_TEXTURE24) { + drawsegment_texture24(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == R_TEXTURE32) { + drawsegment_texture32(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) { + drawsegment_gouraud_texture8(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) { + drawsegment_gouraud_texture24(xadd1, xadd2, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) { + drawsegment_gouraud_texture32(xadd1, xadd2, yi1,yi2); + } + } + } else { + xrght = ((yi1 + PIXEL_CENTER)- y1) * xadd1 + x1; + + if (INTERPOLATE_ALPHA) { + if (m_drawFlags == R_ALPHA) { + drawsegment_plain_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) { + drawsegment_gouraud_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) { + drawsegment_texture8_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) { + drawsegment_texture24_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) { + drawsegment_texture32_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) { + drawsegment_gouraud_texture8_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) { + drawsegment_gouraud_texture24_alpha(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) { + drawsegment_gouraud_texture32_alpha(xadd2, xadd1, yi1,yi2); + } + } else { + if (m_drawFlags == 0) { + drawsegment_plain(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == R_GOURAUD) { + drawsegment_gouraud(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == R_TEXTURE8) { + drawsegment_texture8(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == R_TEXTURE24) { + drawsegment_texture24(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == R_TEXTURE32) { + drawsegment_texture32(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) { + drawsegment_gouraud_texture8(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) { + drawsegment_gouraud_texture24(xadd2, xadd1, yi1,yi2); + } else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) { + drawsegment_gouraud_texture32(xadd2, xadd1, yi1,yi2); + } + } + } + } + } + + + /** + * Accurate texturing code by ewjordan@gmail.com, April 14, 2007 + * The getColorFromTexture() function should be inlined and optimized + * so that most of the heavy lifting happens outside the per-pixel loop. + * The unoptimized generic algorithm looks like this (unless noted, + * all of these variables are vectors, so the actual code will look messier): + * + * p = camera space vector where u == 0, v == 0; + * m = vector from p to location where u == TEX_WIDTH; + * n = vector from p to location where v == TEX_HEIGHT; + * + * A = p cross n; + * B = m cross p; + * C = n cross m; + * A *= texture.width; + * B *= texture.height; + * + * for (scanlines in triangle){ + * float a = S * A; + * float b = S * B; + * float c = S * C; + * for (pixels in scanline){ + * int u = a/c; + * int v = b/c; + * color = texture[v * texture.width + u]; + * a += A.x; + * b += B.x; + * c += C.x; + * } + * } + * + * We don't use this exact algorithm here, however, because of the extra + * overhead from the divides. Instead we compute the exact u and v (labelled + * iu and iv in the code) at the start of each scanline and we perform a + * linear interpolation for every linearInterpLength = 1 << TEX_INTERP_POWER + * pixels. This means that we only perform the true calculation once in a + * while, and the rest of the time the algorithm functions exactly as in the + * fast inaccurate case, at least in theory. In practice, even if we set + * linearInterpLength very high we still incur some speed penalty due to the + * preprocessing that must take place per-scanline. A similar method could + * be applied per scanline to avoid this, but it would only be worthwhile in + * the case that we never compute more than one exact calculation per + * scanline. If we want something like this, however, it would be best to + * create another mode of calculation called "constant-z" interpolation, + * which could be used for things like floors and ceilings where the + * distance from the camera plane never changes over the course of a + * scanline. We could also add the vertical analogue for drawing vertical + * walls. In any case, these are not critical as the current algorithm runs + * fairly well, perhaps ~10% slower than the default perspective-less one. + */ + + /** + * Solve for camera space coordinates of critical texture points and + * set up per-triangle variables for accurate texturing. + * Sets all class variables relevant to accurate texture computation + * Should be called once per triangle - checks firstSegment to see if + * we've already called. + */ + private boolean precomputeAccurateTexturing() { + // rescale u/v_array values when inverting matrix and performing other calcs + float myFact = 65500.0f; + float myFact2 = 65500.0f; + + //Matrix inversion to find affine transform between (u,v,(1)) -> (x,y,z) + + // OPTIMIZE: There should be a way to avoid the inversion here, which is + // quite expensive (~150 mults). Also it might crap out due to loss of + // precision depending on the scaling of the u/v_arrays. Nothing clever + // currently happens if the inversion fails, since this means the + // transformation is degenerate - we just pass false back to the caller + // and let it handle the situation. [There is no good solution to this + // case from within this function, since the way the calculation proceeds + // presumes a non-degenerate transformation matrix between camera space + // and uv space] + + // Obvious optimization: if the vertices are actually at the appropriate + // texture coordinates (e.g. (0,0), (TEX_WIDTH,0), and (0,TEX_HEIGHT)) + // then we can immediately return the right solution without the inversion. + // This is fairly common, so could speed up many cases of drawing. + // [not implemented] + + // Furthermore, we could cache the p,resultT0,result0T vectors in the + // triangle's basis, since we could then do a look-up and generate the + // resulting coordinates very simply. This would include the above + // optimization as a special case - we could pre-populate the cache with + // special cases like that and dynamically add more. The idea here is that + // most people simply paste textures onto triangles and move the triangles + // from frame to frame, so any per-triangle-per-frame code is likely + // wasted effort. [not implemented] + + // Note: o0, o1, and o2 vary depending on view angle to triangle, + // but p, n, and m should not depend on ordering differences + + if (firstSegment){ + PMatrix3D myMatrix = + new PMatrix3D(u_array[o0]/myFact, v_array[o0]/myFact2, 1, 0, + u_array[o1]/myFact, v_array[o1]/myFact2, 1, 0, + u_array[o2]/myFact, v_array[o2]/myFact2, 1, 0, + 0, 0, 0, 1); + // A 3x3 inversion would be more efficient here, + // given that the fourth r/c are unity + myMatrix.invert(); + // if the matrix inversion had trouble, let the caller know + if (myMatrix == null) return false; + + float m00, m01, m02, m10, m11, m12, m20, m21, m22; + m00 = myMatrix.m00*camX[o0]+myMatrix.m01*camX[o1]+myMatrix.m02*camX[o2]; + m01 = myMatrix.m10*camX[o0]+myMatrix.m11*camX[o1]+myMatrix.m12*camX[o2]; + m02 = myMatrix.m20*camX[o0]+myMatrix.m21*camX[o1]+myMatrix.m22*camX[o2]; + m10 = myMatrix.m00*camY[o0]+myMatrix.m01*camY[o1]+myMatrix.m02*camY[o2]; + m11 = myMatrix.m10*camY[o0]+myMatrix.m11*camY[o1]+myMatrix.m12*camY[o2]; + m12 = myMatrix.m20*camY[o0]+myMatrix.m21*camY[o1]+myMatrix.m22*camY[o2]; + m20 = -(myMatrix.m00*camZ[o0]+myMatrix.m01*camZ[o1]+myMatrix.m02*camZ[o2]); + m21 = -(myMatrix.m10*camZ[o0]+myMatrix.m11*camZ[o1]+myMatrix.m12*camZ[o2]); + m22 = -(myMatrix.m20*camZ[o0]+myMatrix.m21*camZ[o1]+myMatrix.m22*camZ[o2]); + + float px = m02; + float py = m12; + float pz = m22; + // Bugfix: possibly we should use F_TEX_WIDTH/HEIGHT instead? + // Seems to read off end of array in that case, though... + float resultT0x = m00*TEX_WIDTH+m02; + float resultT0y = m10*TEX_WIDTH+m12; + float resultT0z = m20*TEX_WIDTH+m22; + float result0Tx = m01*TEX_HEIGHT+m02; + float result0Ty = m11*TEX_HEIGHT+m12; + float result0Tz = m21*TEX_HEIGHT+m22; + float mx = resultT0x-m02; + float my = resultT0y-m12; + float mz = resultT0z-m22; + float nx = result0Tx-m02; + float ny = result0Ty-m12; + float nz = result0Tz-m22; + + //avec = p x n + ax = (py*nz-pz*ny)*TEX_WIDTH; //F_TEX_WIDTH/HEIGHT? + ay = (pz*nx-px*nz)*TEX_WIDTH; + az = (px*ny-py*nx)*TEX_WIDTH; + //bvec = m x p + bx = (my*pz-mz*py)*TEX_HEIGHT; + by = (mz*px-mx*pz)*TEX_HEIGHT; + bz = (mx*py-my*px)*TEX_HEIGHT; + //cvec = n x m + cx = ny*mz-nz*my; + cy = nz*mx-nx*mz; + cz = nx*my-ny*mx; + } + + nearPlaneWidth = parent.rightScreen-parent.leftScreen; + nearPlaneHeight = parent.topScreen-parent.bottomScreen; + nearPlaneDepth = parent.nearPlane; + // one pixel width in nearPlane coordinates + xmult = nearPlaneWidth / SCREEN_WIDTH; + ymult = nearPlaneHeight / SCREEN_HEIGHT; + // Extra scalings to map screen plane units to pixel units + newax = ax*xmult; + newbx = bx*xmult; + newcx = cx*xmult; + return true; + } + + + /** + * Set the power of two used for linear interpolation of texture coordinates. + * A true texture coordinate is computed every 2^pwr pixels along a scanline. + */ + static public void setInterpPower(int pwr) { + //Currently must be invoked from P5 as PTriangle.setInterpPower(...) + TEX_INTERP_POWER = pwr; + } + + + /** + * Plain color + */ + private void drawsegment_plain(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int f = m_fill; +// int p = m_index; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + float iz = izadd * xdiff + zleft; + xstart+=ytop; + xend+=ytop; + + for ( ; xstart < xend; xstart++ ) { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + m_zbuffer[xstart] = iz; + m_pixels[xstart] = m_fill; +// m_stencil[xstart] = p; + } + iz+=izadd; + } + + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + zleft+=zleftadd; + } + } + + + /** + * Plain color, interpolated alpha + */ + private void drawsegment_plain_alpha(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; + + int pr = m_fill & 0xFF0000; + int pg = m_fill & 0xFF00; + int pb = m_fill & 0xFF; + +// int p = m_index; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + float iz = izadd * xdiff + zleft; + int ia = (int) (iaf * xdiff + aleft); + xstart += ytop; + xend += ytop; + + //int ma0 = 0xFF000000; + + for ( ; xstart < xend; xstart++ ) { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + // don't set zbuffer when not fully opaque + //m_zbuffer[xstart] = iz; + + int alpha = ia >> 16; + int mr0 = m_pixels[xstart]; + /* + if (argbSurface) { + ma0 = (((mr0 >>> 24) * alpha) << 16) & 0xFF000000; + if (ma0 == 0) ma0 = alpha << 24; + } + */ + int mg0 = mr0 & 0xFF00; + int mb0 = mr0 & 0xFF; + mr0 &= 0xFF0000; + + mr0 = mr0 + (((pr - mr0) * alpha) >> 8); + mg0 = mg0 + (((pg - mg0) * alpha) >> 8); + mb0 = mb0 + (((pb - mb0) * alpha) >> 8); + + m_pixels[xstart] = 0xFF000000 | + (mr0 & 0xFF0000) | (mg0 & 0xFF00) | (mb0 & 0xFF); + +// m_stencil[xstart] = p; + } + iz += izadd; + ia += iaadd; + } + ytop += SCREEN_WIDTH; + xleft += leftadd; + xrght += rghtadd; + zleft += zleftadd; + } + } + + + /** + * RGB gouraud + */ + private void drawsegment_gouraud(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + for ( ; xstart < xend; xstart++ ) { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + m_zbuffer[xstart] = iz; + m_pixels[xstart] = 0xFF000000 | + ((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16)); +// m_stencil[xstart] = p; + } + + ir+=iradd; + ig+=igadd; + ib+=ibadd; + iz+=izadd; + } + + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + zleft+=zleftadd; + } + } + + + /** + * RGB gouraud + interpolated alpha + */ + private void drawsegment_gouraud_alpha(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + for ( ; xstart < xend; xstart++ ) { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + // + int red = (ir & 0xFF0000); + int grn = (ig >> 8) & 0xFF00; + int blu = (ib >> 16); + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + + // blend alpha + int al = ia >> 16; + + // + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); +// m_stencil[xstart] = p; + } + + // + ir+=iradd; + ig+=igadd; + ib+=ibadd; + ia+=iaadd; + iz+=izadd; + } + + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + aleft+=aleftadd; + zleft+=zleftadd; + } + } + + + /** + * 8-bit plain texture + */ + + //THIS IS MESSED UP, NEED TO GRAB ORIGINAL VERSION!!! + private void drawsegment_texture8(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + // Accurate texture mode added - comments stripped from dupe code, + // see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode) { + // see if the precomputation goes well, if so finish the setup + if (precomputeAccurateTexturing()) { + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + // if the matrix inversion screwed up, revert to normal rendering + // (something is degenerate) + accurateMode = false; + } + } + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + + int red = m_fill & 0xFF0000; + int grn = m_fill & 0xFF00; + int blu = m_fill & 0xFF; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode && goingIn) { + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; + iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else { + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + for ( ; xstart < xend; xstart++ ) { + if (accurateMode) { + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else { + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + // try-catch just in case pixel offset it out of range + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + int al0; + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = iu & 0xFFFF; + al0 = m_texture[ofs] & 0xFF; + int al1 = m_texture[ofs + 1] & 0xFF; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int al2 = m_texture[ofs] & 0xFF; + int al3 = m_texture[ofs + 1] & 0xFF; + al0 = al0 + (((al1-al0) * iui) >> 16); + al2 = al2 + (((al3-al2) * iui) >> 16); + al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16); + } else { + al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF; + } + + int br = m_pixels[xstart]; + int bg = (br & 0xFF00); + int bb = (br & 0xFF); + br = (br & 0xFF0000); + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al0) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al0) >> 8)) & 0xFF); +// m_stencil[xstart] = p; + } + } + catch (Exception e) { + } + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + iz+=izadd; + } + ypixel++;//accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + zleft+=zleftadd; + } + } + + + + /** + * 8-bit texutre + alpha + */ + private void drawsegment_texture8_alpha(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + // Accurate texture mode added - comments stripped from dupe code, + // see drawsegment_texture24() for details + + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode) { + // see if the precomputation goes well, if so finish the setup + if (precomputeAccurateTexturing()) { + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else { + // if the matrix inversion screwed up, + // revert to normal rendering (something is degenerate) + accurateMode = false; + } + } + ytop*=SCREEN_WIDTH; + ybottom*=SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float iaf = iaadd; + + int red = m_fill & 0xFF0000; + int grn = m_fill & 0xFF00; + int blu = m_fill & 0xFF; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + // try-catch just in case pixel offset it out of range + try + { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + int al0; + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = iu & 0xFFFF; + al0 = m_texture[ofs] & 0xFF; + int al1 = m_texture[ofs + 1] & 0xFF; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int al2 = m_texture[ofs] & 0xFF; + int al3 = m_texture[ofs + 1] & 0xFF; + al0 = al0 + (((al1-al0) * iui) >> 16); + al2 = al2 + (((al3-al2) * iui) >> 16); + al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16); + } else { + al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF; + } + al0 = (al0 * (ia >> 16)) >> 8; + + int br = m_pixels[xstart]; + int bg = (br & 0xFF00); + int bb = (br & 0xFF); + br = (br & 0xFF0000); + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al0) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al0) >> 8)) & 0xFF); +// m_stencil[xstart] = p; + } + } + catch (Exception e) { + } + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + iz+=izadd; + ia+=iaadd; + } + ypixel++;//accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + zleft+=zleftadd; + aleft+=aleftadd; + } + } + + /** + * Plain 24-bit texture + */ + private void drawsegment_texture24(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + float iuf = iuadd; + float ivf = ivadd; + + boolean tint = (m_fill & 0xFFFFFF) != 0xFFFFFF; + int rtint = (m_fill >> 16) & 0xff; + int gtint = (m_fill >> 8) & 0xff; + int btint = m_fill & 0xFF; + + int ypixel = ytop/SCREEN_WIDTH;//ACCTEX + int lastRowStart = m_texture.length - TEX_WIDTH - 2;//If we're past this index, we can't shift down a row w/o throwing an exception + // int exCount = 0;//counter for exceptions caught + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; //bring this local since it will be accessed often + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + + //Interpolation length of 16 tends to look good except at a small angle; 8 looks okay then, except for the + //above issue. When viewing close to flat, as high as 32 is often acceptable. Could add dynamic interpolation + //settings based on triangle angle - currently we just pick a value and leave it (by default I have the + //power set at 3, so every 8 pixels a true coordinate is calculated, which seems a decent compromise). + + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion gave us garbage, revert to normal rendering (something is degenerate) + } + } + + + while (ytop < ybottom) {//scanline loop + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0){ xstart = 0; } + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH){ xend = SCREEN_WIDTH; } + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + float iz = izadd * xdiff + zleft; + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + //off by one (half, I guess) hack, w/o it the first rows are outside the texture - maybe a mistake somewhere? + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az;//OPT - some of this could be brought out of the y-loop since + b = screenx*bx+screeny*by+screenz*bz;//xpixel and ypixel just increment by the same numbers each iteration. + c = screenx*cx+screeny*cy+screenz*cz;//Probably not a big bottleneck, though. + } + + //Figure out whether triangle is going further into the screen or not as we move along scanline + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + + //Set up linear interpolation between calculated texture points + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + //float fdeltaU = 0; float fdeltaV = 0;//vars for floating point interpolating version of algorithm + //float fiu = 0; float fiv = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + + //Bugfix (done): it's a Really Bad Thing to interpolate along a scanline when the triangle goes deeper into the screen, + //because if the angle is severe enough the last control point for interpolation may cross the vanishing + //point. This leads to some pretty nasty artifacts, and ideally we should scan from right to left if the + //triangle is better served that way, or (what we do now) precompute the offset that we'll need so that we end up + //with a control point exactly at the furthest edge of the triangle. + + if (accurateMode&&goingIn){ + //IMPORTANT!!! Results are horrid without this hack! + //If polygon goes into the screen along scan line, we want to match the control point to the furthest point drawn + //since the control points are less meaningful the closer you are to the vanishing point. + //We'll do this by making the first control point lie before the start of the scanline (safe since it's closer to us) + + int rightOffset = (xend-xstart-1)%linearInterpLength; //"off by one" hack...probably means there's a small bug somewhere + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + + //Take step to control point to the left of start pixel + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + + //Now step to right control point + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + + //Get deltas for interpolation + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + //Otherwise the left edge is further, and we pin the first control point to it + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + for ( ; xstart < xend; xstart++ ) {//pixel loop - keep trim, can execute thousands of times per frame + //boolean drawBlack = false; //used to display control points + if(accurateMode){ + /* //Non-interpolating algorithm - slowest version, calculates exact coordinate for each pixel, + //and casts from float->int + float oneoverc = 65536.0f/c; //a bit faster to pre-divide for next two steps + iu = (int)(a*oneoverc); + iv = (int)(b*oneoverc); + a += newax; + b += newbx; + c += newcx; + */ + + //Float while calculating, int while interpolating + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + //drawBlack = true; + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; //ints are used for interpolation, not actual computation + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ //race through using linear interpolation if we're not at a control point + iu += deltaU; + iv += deltaV; + } + interpCounter++; + + /* //Floating point interpolating version - slower than int thanks to casts during interpolation steps + if (interpCounter == 0) { + interpCounter = linearInterpLength; + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; + oldfv = fv; + fu = (a*oneoverc); + fv = (b*oneoverc); + //oldu = u; oldv = v; + fiu = oldfu; + fiv = oldfv; + fdeltaU = (fu-oldfu)/linearInterpLength; + fdeltaV = (fv-oldfv)/linearInterpLength; + } + else{ + fiu += fdeltaU; + fiv += fdeltaV; + } + interpCounter--; + iu = (int)(fiu); iv = (int)(fiv);*/ + + } + + // try-catch just in case pixel offset is out of range + try{ + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + m_zbuffer[xstart] = iz; + if (m_bilinear) { + //We could (should?) add bounds checking on iu and iv here (keep in mind the 16 bit shift!). + //This would also be the place to add looping texture mode (bounds check == clamped). + //For looping/clamped textures, we'd also need to change PGraphics.textureVertex() to remove + //the texture range check there (it constrains normalized texture coordinates from 0->1). + + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + //if(ofs < 0) { ofs += TEX_WIDTH; } + //if(ofs > m_texture.length-2) {ofs -= TEX_WIDTH; } + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; //quick hack to thwart exceptions + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + int red = up + (((dn-up) * ivi) >> 7); + if (tint) red = ((red * rtint) >> 8) & 0xFF0000; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + int grn = up + (((dn-up) * ivi) >> 7); + if (tint) grn = ((grn * gtint) >> 8) & 0xFF00; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + int blu = up + (((dn-up) * ivi) >> 7); + if (tint) blu = ((blu * btint) >> 8) & 0xFF; + + //m_pixels[xstart] = (red & 0xFF0000) | (grn & 0xFF00) | (blu & 0xFF); + m_pixels[xstart] = 0xFF000000 | + (red & 0xFF0000) | (grn & 0xFF00) | (blu & 0xFF); + + } else { + m_pixels[xstart] = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + } +// m_stencil[xstart] = p; + } + } catch (Exception e) {/*exCount++;*/} + iz+=izadd; + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + } + ypixel++; //accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + zleft+=zleftadd; + uleft+=uleftadd; + vleft+=vleftadd; + } + //if (exCount>0) System.out.println(exCount+" exceptions in this segment"); + } + + + /** + * Alpha 24-bit texture + */ + private void drawsegment_texture24_alpha(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + boolean tint = (m_fill & 0xFFFFFF) != 0xFFFFFF; + int rtint = (m_fill >> 16) & 0xff; + int gtint = (m_fill >> 8) & 0xff; + int btint = m_fill & 0xFF; + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + // get alpha + int al = ia >> 16; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + int red = up + (((dn-up) * ivi) >> 7); + if (tint) red = ((red * rtint) >> 8) & 0xFF0000; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + int grn = up + (((dn-up) * ivi) >> 7); + if (tint) grn = ((grn * gtint) >> 8) & 0xFF00; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + int blu = up + (((dn-up) * ivi) >> 7); + if (tint) blu = ((blu * btint) >> 8) & 0xFF; + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + + } else { + int red = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + int grn = red & 0xFF00; + int blu = red & 0xFF; + red&=0xFF0000; + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + } +// m_stencil[xstart] = p; + } + } catch (Exception e) { } + + xpixel++; // accurate mode + if (!accurateMode){ + iu += iuadd; + iv += ivadd; + } + ia+=iaadd; + iz+=izadd; + } + ypixel++; // accurate mode + + ytop+=SCREEN_WIDTH; + + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + zleft+=zleftadd; + aleft+=aleftadd; + } + } + + /** + * Plain 32-bit texutre + */ + private void drawsegment_texture32(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop*=SCREEN_WIDTH; + ybottom*=SCREEN_WIDTH; +// int p = m_index; + + boolean tint = m_fill != 0xFFFFFFFF; + int rtint = (m_fill >> 16) & 0xff; + int gtint = (m_fill >> 8) & 0xff; + int btint = m_fill & 0xFF; + + float iuf = iuadd; + float ivf = ivadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + // try-catch just in case pixel offset it out of range + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + int red = up + (((dn-up) * ivi) >> 7); + if (tint) red = ((red * rtint) >> 8) & 0xFF0000; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + int grn = up + (((dn-up) * ivi) >> 7); + if (tint) grn = ((grn * gtint) >> 8) & 0xFF00; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + int blu = up + (((dn-up) * ivi) >> 7); + if (tint) blu = ((blu * btint) >> 8) & 0xFF; + + // alpha + pix0>>>=24; + pix2>>>=24; + up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7); + dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7); + int al = up + (((dn-up) * ivi) >> 7); + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + } else { + int red = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + int al = red >>> 24; + int grn = red & 0xFF00; + int blu = red & 0xFF; + red&=0xFF0000; + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + } +// m_stencil[xstart] = p; + } + } catch (Exception e) { } + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + iz+=izadd; + } + ypixel++;//accurate mode + + ytop+=SCREEN_WIDTH; + + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + zleft+=zleftadd; + aleft+=aleftadd; + } + + + } + + /** + * Alpha 32-bit texutre + */ + private void drawsegment_texture32_alpha(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + boolean tint = (m_fill & 0xFFFFFF) != 0xFFFFFF; + int rtint = (m_fill >> 16) & 0xff; + int gtint = (m_fill >> 8) & 0xff; + int btint = m_fill & 0xFF; + + float iuf = iuadd; + float ivf = ivadd; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + + float xdiff = (xstart + PIXEL_CENTER) - xleft; + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + // try-catch just in case pixel offset it out of range + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + // get alpha + int al = ia >> 16; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + int red = up + (((dn-up) * ivi) >> 7); + if (tint) red = ((red * rtint) >> 8) & 0xFF0000; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + int grn = up + (((dn-up) * ivi) >> 7); + if (tint) grn = ((grn * gtint) >> 8) & 0xFF00; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + int blu = up + (((dn-up) * ivi) >> 7); + if (tint) blu = ((blu * btint) >> 8) & 0xFF; + + // alpha + pix0>>>=24; + pix2>>>=24; + up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7); + dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7); + al = al * (up + (((dn-up) * ivi) >> 7)) >> 8; + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + } else { + int red = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + al = al * (red >>> 24) >> 8; + int grn = red & 0xFF00; + int blu = red & 0xFF; + red&=0xFF0000; + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + } +// m_stencil[xstart] = p; + } + } catch (Exception e) { } + + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ia+=iaadd; + iz+=izadd; + } + ypixel++;//accurate mode + + ytop+=SCREEN_WIDTH; + + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + zleft+=zleftadd; + aleft+=aleftadd; + } + + + } + + + /** + * Gouraud blended with 8-bit alpha texture + */ + private void drawsegment_gouraud_texture8(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + try + { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + int al0; + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = iu & 0xFFFF; + al0 = m_texture[ofs] & 0xFF; + int al1 = m_texture[ofs + 1] & 0xFF; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int al2 = m_texture[ofs] & 0xFF; + int al3 = m_texture[ofs + 1] & 0xFF; + al0 = al0 + (((al1-al0) * iui) >> 16); + al2 = al2 + (((al3-al2) * iui) >> 16); + al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16); + } else { + al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF; + } + + // get RGB colors + int red = ir & 0xFF0000; + int grn = (ig >> 8) & 0xFF00; + int blu = (ib >> 16); + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al0) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al0) >> 8)) & 0xFF); + + // write stencil +// m_stencil[xstart] = p; + } + } + catch (Exception e) { + + } + + // + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ir+=iradd; + ig+=igadd; + ib+=ibadd; + iz+=izadd; + } + ypixel++;//accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + + uleft+=uleftadd; + vleft+=vleftadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + zleft+=zleftadd; + } + } + + + /** + * Texture multiplied with gouraud + */ + private void drawsegment_gouraud_texture8_alpha(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + // Accurate texture mode added - comments stripped from dupe code, + // see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode) { + // see if the precomputation goes well, if so finish the setup + if (precomputeAccurateTexturing()) { + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + // if the matrix inversion screwed up, + // revert to normal rendering (something is degenerate) + accurateMode = false; + } + } + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + int al0; + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = iu & 0xFFFF; + al0 = m_texture[ofs] & 0xFF; + int al1 = m_texture[ofs + 1] & 0xFF; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int al2 = m_texture[ofs] & 0xFF; + int al3 = m_texture[ofs + 1] & 0xFF; + al0 = al0 + (((al1-al0) * iui) >> 16); + al2 = al2 + (((al3-al2) * iui) >> 16); + al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16); + } else { + al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF; + } + al0 = (al0 * (ia >> 16)) >> 8; + + // get RGB colors + int red = ir & 0xFF0000; + int grn = (ig >> 8) & 0xFF00; + int blu = (ib >> 16); + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al0) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al0) >> 8)) & 0xFF); + + // write stencil +// m_stencil[xstart] = p; + } + } catch (Exception e) { } + + // + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ir+=iradd; + ig+=igadd; + ib+=ibadd; + ia+=iaadd; + iz+=izadd; + } + ypixel++;//accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + aleft+=aleftadd; + zleft+=zleftadd; + } + } + + + /** + * Texture multiplied with gouraud + */ + private void drawsegment_gouraud_texture24(float leftadd, + float rghtadd, + int ytop, + int ybottom) { + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + m_zbuffer[xstart] = iz; + + int red; + int grn; + int blu; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + red = up + (((dn-up) * ivi) >> 7); + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + grn = up + (((dn-up) * ivi) >> 7); + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + blu = up + (((dn-up) * ivi) >> 7); + } else { + // get texture pixel color + blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + red = (blu & 0xFF0000); + grn = (blu & 0xFF00); + blu = blu & 0xFF; + } + + // + int r = (ir >> 16); + int g = (ig >> 16); + // oops, namespace collision with accurate + // texture vector b...sorry [ewjordan] + int bb2 = (ib >> 16); + + m_pixels[xstart] = 0xFF000000 | + ((((red * r) & 0xFF000000) | ((grn * g) & 0xFF0000) | (blu * bb2)) >> 8); +// m_stencil[xstart] = p; + } + } catch (Exception e) { } + + // + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ir+=iradd; + ig+=igadd; + ib+=ibadd; + iz+=izadd; + } + ypixel++;//accurate mode + + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + zleft+=zleftadd; + } + } + + + /** + * Gouraud*texture blended with interpolating alpha + */ + private void drawsegment_gouraud_texture24_alpha + ( + float leftadd, + float rghtadd, + int ytop, + int ybottom + ) { + + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + for ( ;xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + // get texture pixel color + try + { + //if (iz < m_zbuffer[xstart]) { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { // [fry 041114] + //m_zbuffer[xstart] = iz; + + // blend + int al = ia >> 16; + + int red; + int grn; + int blu; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + red = (up + (((dn-up) * ivi) >> 7)) >> 16; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + grn = (up + (((dn-up) * ivi) >> 7)) >> 8; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + blu = up + (((dn-up) * ivi) >> 7); + } else { + blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + red = (blu & 0xFF0000) >> 16; // 0 - 255 + grn = (blu & 0xFF00) >> 8; // 0 - 255 + blu = (blu & 0xFF); // 0 - 255 + } + + // multiply with gouraud color + red = (red * ir) >>> 8; // 0x00FF???? + grn = (grn * ig) >>> 16; // 0x0000FF?? + blu = (blu * ib) >>> 24; // 0x000000FF + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + + // + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); +// m_stencil[xstart] = p; + } + } + catch (Exception e) { + } + + // + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ir+=iradd; + ig+=igadd; + ib+=ibadd; + ia+=iaadd; + iz+=izadd; + } + + ypixel++;//accurate mode + + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + aleft+=aleftadd; + zleft+=zleftadd; + } + } + + + /** + * Gouraud*texture blended with interpolating alpha + */ + private void drawsegment_gouraud_texture32 + ( + float leftadd, + float rghtadd, + int ytop, + int ybottom + ) { + + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop*=SCREEN_WIDTH; + ybottom*=SCREEN_WIDTH; + //int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + + for ( ; xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + try { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { + //m_zbuffer[xstart] = iz; + + int red; + int grn; + int blu; + int al; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + red = (up + (((dn-up) * ivi) >> 7)) >> 16; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + grn = (up + (((dn-up) * ivi) >> 7)) >> 8; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + blu = up + (((dn-up) * ivi) >> 7); + + // alpha + pix0>>>=24; + pix2>>>=24; + up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7); + dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7); + al = up + (((dn-up) * ivi) >> 7); + } else { + // get texture pixel color + blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + al = (blu >>> 24); + red = (blu & 0xFF0000) >> 16; + grn = (blu & 0xFF00) >> 8; + blu = blu & 0xFF; + } + + // multiply with gouraud color + red = (red * ir) >>> 8; // 0x00FF???? + grn = (grn * ig) >>> 16; // 0x0000FF?? + blu = (blu * ib) >>> 24; // 0x000000FF + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + + // + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); + } + } catch (Exception e) { } + + // + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ir+=iradd; + ig+=igadd; + ib+=ibadd; + iz+=izadd; + } + ypixel++;//accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + zleft+=zleftadd; + } + } + + + /** + * Gouraud*texture blended with interpolating alpha + */ + private void drawsegment_gouraud_texture32_alpha + ( + float leftadd, + float rghtadd, + int ytop, + int ybottom + ) { + //Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details + int ypixel = ytop; + int lastRowStart = m_texture.length - TEX_WIDTH - 2; + boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; + float screenx = 0; float screeny = 0; float screenz = 0; + float a = 0; float b = 0; float c = 0; + int linearInterpPower = TEX_INTERP_POWER; + int linearInterpLength = 1 << linearInterpPower; + if (accurateMode){ + if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup + newax *= linearInterpLength; + newbx *= linearInterpLength; + newcx *= linearInterpLength; + screenz = nearPlaneDepth; + firstSegment = false; + } else{ + accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate) + } + } + + ytop *= SCREEN_WIDTH; + ybottom *= SCREEN_WIDTH; +// int p = m_index; + + float iuf = iuadd; + float ivf = ivadd; + float irf = iradd; + float igf = igadd; + float ibf = ibadd; + float iaf = iaadd; + + while (ytop < ybottom) { + int xstart = (int) (xleft + PIXEL_CENTER); + if (xstart < 0) + xstart = 0; + + int xpixel = xstart;//accurate mode + + int xend = (int) (xrght + PIXEL_CENTER); + if (xend > SCREEN_WIDTH) + xend = SCREEN_WIDTH; + float xdiff = (xstart + PIXEL_CENTER) - xleft; + + int iu = (int) (iuf * xdiff + uleft); + int iv = (int) (ivf * xdiff + vleft); + int ir = (int) (irf * xdiff + rleft); + int ig = (int) (igf * xdiff + gleft); + int ib = (int) (ibf * xdiff + bleft); + int ia = (int) (iaf * xdiff + aleft); + float iz = izadd * xdiff + zleft; + + xstart+=ytop; + xend+=ytop; + if (accurateMode){ + screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f)); + screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f)); + a = screenx*ax+screeny*ay+screenz*az; + b = screenx*bx+screeny*by+screenz*bz; + c = screenx*cx+screeny*cy+screenz*cz; + } + boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true; + int interpCounter = 0; + int deltaU = 0; int deltaV = 0; + float fu = 0; float fv = 0; + float oldfu = 0; float oldfv = 0; + + if (accurateMode&&goingIn){ + int rightOffset = (xend-xstart-1)%linearInterpLength; + int leftOffset = linearInterpLength-rightOffset; + float rightOffset2 = rightOffset / ((float)linearInterpLength); + float leftOffset2 = leftOffset / ((float)linearInterpLength); + interpCounter = leftOffset; + float ao = a-leftOffset2*newax; + float bo = b-leftOffset2*newbx; + float co = c-leftOffset2*newcx; + float oneoverc = 65536.0f/co; + oldfu = (ao*oneoverc); oldfv = (bo*oneoverc); + a += rightOffset2*newax; + b += rightOffset2*newbx; + c += rightOffset2*newcx; + oneoverc = 65536.0f/c; + fu = a*oneoverc; fv = b*oneoverc; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack + } else{ + float preoneoverc = 65536.0f/c; + fu = (a*preoneoverc); + fv = (b*preoneoverc); + } + + for ( ;xstart < xend; xstart++ ) { + if(accurateMode){ + if (interpCounter == linearInterpLength) interpCounter = 0; + if (interpCounter == 0){ + a += newax; + b += newbx; + c += newcx; + float oneoverc = 65536.0f/c; + oldfu = fu; oldfv = fv; + fu = (a*oneoverc); fv = (b*oneoverc); + iu = (int)oldfu; iv = (int)oldfv; + deltaU = ((int)(fu - oldfu)) >> linearInterpPower; + deltaV = ((int)(fv - oldfv)) >> linearInterpPower; + } else{ + iu += deltaU; + iv += deltaV; + } + interpCounter++; + } + + // get texture pixel color + try { + //if (iz < m_zbuffer[xstart]) { + if (noDepthTest || (iz <= m_zbuffer[xstart])) { // [fry 041114] + //m_zbuffer[xstart] = iz; + + // blend + int al = ia >> 16; + + int red; + int grn; + int blu; + + if (m_bilinear) { + int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16); + int iui = (iu & 0xFFFF) >> 9; + int ivi = (iv & 0xFFFF) >> 9; + + // get texture pixels + int pix0 = m_texture[ofs]; + int pix1 = m_texture[ofs + 1]; + if (ofs < lastRowStart) ofs+=TEX_WIDTH; + int pix2 = m_texture[ofs]; + int pix3 = m_texture[ofs + 1]; + + // red + int red0 = (pix0 & 0xFF0000); + int red2 = (pix2 & 0xFF0000); + int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7); + int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7); + red = (up + (((dn-up) * ivi) >> 7)) >> 16; + + // grn + red0 = (pix0 & 0xFF00); + red2 = (pix2 & 0xFF00); + up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7); + grn = (up + (((dn-up) * ivi) >> 7)) >> 8; + + // blu + red0 = (pix0 & 0xFF); + red2 = (pix2 & 0xFF); + up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7); + dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7); + blu = up + (((dn-up) * ivi) >> 7); + + // alpha + pix0>>>=24; + pix2>>>=24; + up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7); + dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7); + al = al * (up + (((dn-up) * ivi) >> 7)) >> 8; + } else { + blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)]; + al = al * (blu >>> 24) >> 8; + red = (blu & 0xFF0000) >> 16; // 0 - 255 + grn = (blu & 0xFF00) >> 8; // 0 - 255 + blu = (blu & 0xFF); // 0 - 255 + } + + // multiply with gouraud color + red = (red * ir) >>> 8; // 0x00FF???? + grn = (grn * ig) >>> 16; // 0x0000FF?? + blu = (blu * ib) >>> 24; // 0x000000FF + + // get buffer pixels + int bb = m_pixels[xstart]; + int br = (bb & 0xFF0000); // 0x00FF0000 + int bg = (bb & 0xFF00); // 0x0000FF00 + bb = (bb & 0xFF); // 0x000000FF + + // + m_pixels[xstart] = 0xFF000000 | + ((br + (((red - br) * al) >> 8)) & 0xFF0000) | + ((bg + (((grn - bg) * al) >> 8)) & 0xFF00) | + ((bb + (((blu - bb) * al) >> 8)) & 0xFF); +// m_stencil[xstart] = p; + } + } catch (Exception e) { } + + // + xpixel++;//accurate mode + if (!accurateMode){ + iu+=iuadd; + iv+=ivadd; + } + ir+=iradd; + ig+=igadd; + ib+=ibadd; + ia+=iaadd; + iz+=izadd; + } + ypixel++;//accurate mode + ytop+=SCREEN_WIDTH; + xleft+=leftadd; + xrght+=rghtadd; + uleft+=uleftadd; + vleft+=vleftadd; + rleft+=rleftadd; + gleft+=gleftadd; + bleft+=bleftadd; + aleft+=aleftadd; + zleft+=zleftadd; + } + } +} diff --git a/support/Processing_core_src/processing/core/PVector.java b/support/Processing_core_src/processing/core/PVector.java new file mode 100644 index 0000000..1fb4f1f --- /dev/null +++ b/support/Processing_core_src/processing/core/PVector.java @@ -0,0 +1,565 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 200X Dan Shiffman + Copyright (c) 2008 Ben Fry and Casey Reas + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + */ + +package processing.core; + +/** + * A class to describe a two or three dimensional vector. + *

+ * The result of all functions are applied to the vector itself, with the + * exception of cross(), which returns a new PVector (or writes to a specified + * 'target' PVector). That is, add() will add the contents of one vector to + * this one. Using add() with additional parameters allows you to put the + * result into a new PVector. Functions that act on multiple vectors also + * include static versions. Because creating new objects can be computationally + * expensive, most functions include an optional 'target' PVector, so that a + * new PVector object is not created with each operation. + *

+ * Initially based on the Vector3D class by Dan Shiffman. + */ +public class PVector { + + /** The x component of the vector. */ + public float x; + + /** The y component of the vector. */ + public float y; + + /** The z component of the vector. */ + public float z; + + /** Array so that this can be temporarily used in an array context */ + protected float[] array; + + + /** + * Constructor for an empty vector: x, y, and z are set to 0. + */ + public PVector() { + } + + + /** + * Constructor for a 3D vector. + * + * @param x the x coordinate. + * @param y the y coordinate. + * @param z the y coordinate. + */ + public PVector(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + + /** + * Constructor for a 2D vector: z coordinate is set to 0. + * + * @param x the x coordinate. + * @param y the y coordinate. + */ + public PVector(float x, float y) { + this.x = x; + this.y = y; + this.z = 0; + } + + + /** + * Set x, y, and z coordinates. + * + * @param x the x coordinate. + * @param y the y coordinate. + * @param z the z coordinate. + */ + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + + /** + * Set x, y, and z coordinates from a Vector3D object. + * + * @param v the PVector object to be copied + */ + public void set(PVector v) { + x = v.x; + y = v.y; + z = v.z; + } + + + /** + * Set the x, y (and maybe z) coordinates using a float[] array as the source. + * @param source array to copy from + */ + public void set(float[] source) { + if (source.length >= 2) { + x = source[0]; + y = source[1]; + } + if (source.length >= 3) { + z = source[2]; + } + } + + + /** + * Get a copy of this vector. + */ + public PVector get() { + return new PVector(x, y, z); + } + + + public float[] get(float[] target) { + if (target == null) { + return new float[] { x, y, z }; + } + if (target.length >= 2) { + target[0] = x; + target[1] = y; + } + if (target.length >= 3) { + target[2] = z; + } + return target; + } + + + /** + * Calculate the magnitude (length) of the vector + * @return the magnitude of the vector + */ + public float mag() { + return (float) Math.sqrt(x*x + y*y + z*z); + } + + + /** + * Add a vector to this vector + * @param v the vector to be added + */ + public void add(PVector v) { + x += v.x; + y += v.y; + z += v.z; + } + + + public void add(float x, float y, float z) { + this.x += x; + this.y += y; + this.z += z; + } + + + /** + * Add two vectors + * @param v1 a vector + * @param v2 another vector + * @return a new vector that is the sum of v1 and v2 + */ + static public PVector add(PVector v1, PVector v2) { + return add(v1, v2, null); + } + + + /** + * Add two vectors into a target vector + * @param v1 a vector + * @param v2 another vector + * @param target the target vector (if null, a new vector will be created) + * @return a new vector that is the sum of v1 and v2 + */ + static public PVector add(PVector v1, PVector v2, PVector target) { + if (target == null) { + target = new PVector(v1.x + v2.x,v1.y + v2.y, v1.z + v2.z); + } else { + target.set(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); + } + return target; + } + + + /** + * Subtract a vector from this vector + * @param v the vector to be subtracted + */ + public void sub(PVector v) { + x -= v.x; + y -= v.y; + z -= v.z; + } + + + public void sub(float x, float y, float z) { + this.x -= x; + this.y -= y; + this.z -= z; + } + + + /** + * Subtract one vector from another + * @param v1 a vector + * @param v2 another vector + * @return a new vector that is v1 - v2 + */ + static public PVector sub(PVector v1, PVector v2) { + return sub(v1, v2, null); + } + + + static public PVector sub(PVector v1, PVector v2, PVector target) { + if (target == null) { + target = new PVector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); + } else { + target.set(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); + } + return target; + } + + + /** + * Multiply this vector by a scalar + * @param n the value to multiply by + */ + public void mult(float n) { + x *= n; + y *= n; + z *= n; + } + + + /** + * Multiply a vector by a scalar + * @param v a vector + * @param n scalar + * @return a new vector that is v1 * n + */ + static public PVector mult(PVector v, float n) { + return mult(v, n, null); + } + + + /** + * Multiply a vector by a scalar, and write the result into a target PVector. + * @param v a vector + * @param n scalar + * @param target PVector to store the result + * @return the target vector, now set to v1 * n + */ + static public PVector mult(PVector v, float n, PVector target) { + if (target == null) { + target = new PVector(v.x*n, v.y*n, v.z*n); + } else { + target.set(v.x*n, v.y*n, v.z*n); + } + return target; + } + + + /** + * Multiply each element of one vector by the elements of another vector. + * @param v the vector to multiply by + */ + public void mult(PVector v) { + x *= v.x; + y *= v.y; + z *= v.z; + } + + + /** + * Multiply each element of one vector by the individual elements of another + * vector, and return the result as a new PVector. + */ + static public PVector mult(PVector v1, PVector v2) { + return mult(v1, v2, null); + } + + + /** + * Multiply each element of one vector by the individual elements of another + * vector, and write the result into a target vector. + * @param v1 the first vector + * @param v2 the second vector + * @param target PVector to store the result + */ + static public PVector mult(PVector v1, PVector v2, PVector target) { + if (target == null) { + target = new PVector(v1.x*v2.x, v1.y*v2.y, v1.z*v2.z); + } else { + target.set(v1.x*v2.x, v1.y*v2.y, v1.z*v2.z); + } + return target; + } + + + /** + * Divide this vector by a scalar + * @param n the value to divide by + */ + public void div(float n) { + x /= n; + y /= n; + z /= n; + } + + + /** + * Divide a vector by a scalar and return the result in a new vector. + * @param v a vector + * @param n scalar + * @return a new vector that is v1 / n + */ + static public PVector div(PVector v, float n) { + return div(v, n, null); + } + + + static public PVector div(PVector v, float n, PVector target) { + if (target == null) { + target = new PVector(v.x/n, v.y/n, v.z/n); + } else { + target.set(v.x/n, v.y/n, v.z/n); + } + return target; + } + + + /** + * Divide each element of one vector by the elements of another vector. + */ + public void div(PVector v) { + x /= v.x; + y /= v.y; + z /= v.z; + } + + + /** + * Multiply each element of one vector by the individual elements of another + * vector, and return the result as a new PVector. + */ + static public PVector div(PVector v1, PVector v2) { + return div(v1, v2, null); + } + + + /** + * Divide each element of one vector by the individual elements of another + * vector, and write the result into a target vector. + * @param v1 the first vector + * @param v2 the second vector + * @param target PVector to store the result + */ + static public PVector div(PVector v1, PVector v2, PVector target) { + if (target == null) { + target = new PVector(v1.x/v2.x, v1.y/v2.y, v1.z/v2.z); + } else { + target.set(v1.x/v2.x, v1.y/v2.y, v1.z/v2.z); + } + return target; + } + + + /** + * Calculate the Euclidean distance between two points (considering a point as a vector object) + * @param v another vector + * @return the Euclidean distance between + */ + public float dist(PVector v) { + float dx = x - v.x; + float dy = y - v.y; + float dz = z - v.z; + return (float) Math.sqrt(dx*dx + dy*dy + dz*dz); + } + + + /** + * Calculate the Euclidean distance between two points (considering a point as a vector object) + * @param v1 a vector + * @param v2 another vector + * @return the Euclidean distance between v1 and v2 + */ + static public float dist(PVector v1, PVector v2) { + float dx = v1.x - v2.x; + float dy = v1.y - v2.y; + float dz = v1.z - v2.z; + return (float) Math.sqrt(dx*dx + dy*dy + dz*dz); + } + + + /** + * Calculate the dot product with another vector + * @return the dot product + */ + public float dot(PVector v) { + return x*v.x + y*v.y + z*v.z; + } + + + public float dot(float x, float y, float z) { + return this.x*x + this.y*y + this.z*z; + } + + + static public float dot(PVector v1, PVector v2) { + return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; + } + + + /** + * Return a vector composed of the cross product between this and another. + */ + public PVector cross(PVector v) { + return cross(v, null); + } + + + /** + * Perform cross product between this and another vector, and store the + * result in 'target'. If target is null, a new vector is created. + */ + public PVector cross(PVector v, PVector target) { + float crossX = y * v.z - v.y * z; + float crossY = z * v.x - v.z * x; + float crossZ = x * v.y - v.x * y; + + if (target == null) { + target = new PVector(crossX, crossY, crossZ); + } else { + target.set(crossX, crossY, crossZ); + } + return target; + } + + + static public PVector cross(PVector v1, PVector v2, PVector target) { + float crossX = v1.y * v2.z - v2.y * v1.z; + float crossY = v1.z * v2.x - v2.z * v1.x; + float crossZ = v1.x * v2.y - v2.x * v1.y; + + if (target == null) { + target = new PVector(crossX, crossY, crossZ); + } else { + target.set(crossX, crossY, crossZ); + } + return target; + } + + + /** + * Normalize the vector to length 1 (make it a unit vector) + */ + public void normalize() { + float m = mag(); + if (m != 0 && m != 1) { + div(m); + } + } + + + /** + * Normalize this vector, storing the result in another vector. + * @param target Set to null to create a new vector + * @return a new vector (if target was null), or target + */ + public PVector normalize(PVector target) { + if (target == null) { + target = new PVector(); + } + float m = mag(); + if (m > 0) { + target.set(x/m, y/m, z/m); + } else { + target.set(x, y, z); + } + return target; + } + + + /** + * Limit the magnitude of this vector + * @param max the maximum length to limit this vector + */ + public void limit(float max) { + if (mag() > max) { + normalize(); + mult(max); + } + } + + + /** + * Calculate the angle of rotation for this vector (only 2D vectors) + * @return the angle of rotation + */ + public float heading2D() { + float angle = (float) Math.atan2(-y, x); + return -1*angle; + } + + + /** + * Calculate the angle between two vectors, using the dot product + * @param v1 a vector + * @param v2 another vector + * @return the angle between the vectors + */ + static public float angleBetween(PVector v1, PVector v2) { + double dot = v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; + double v1mag = Math.sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z); + double v2mag = Math.sqrt(v2.x * v2.x + v2.y * v2.y + v2.z * v2.z); + return (float) Math.acos(dot / (v1mag * v2mag)); + } + + + public String toString() { + return "[ " + x + ", " + y + ", " + z + " ]"; + } + + + /** + * Return a representation of this vector as a float array. This is only for + * temporary use. If used in any other fashion, the contents should be copied + * by using the get() command to copy into your own array. + */ + public float[] array() { + if (array == null) { + array = new float[3]; + } + array[0] = x; + array[1] = y; + array[2] = z; + return array; + } +} + + diff --git a/support/Processing_core_src/processing/xml/CDATAReader.java b/support/Processing_core_src/processing/xml/CDATAReader.java new file mode 100644 index 0000000..11b6849 --- /dev/null +++ b/support/Processing_core_src/processing/xml/CDATAReader.java @@ -0,0 +1,193 @@ +/* CDATAReader.java NanoXML/Java + * + * $Revision: 1.3 $ + * $Date: 2002/01/04 21:03:28 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.io.Reader; +import java.io.IOException; + + +/** + * This reader reads data from another reader until the end of a CDATA section + * (]]>) has been encountered. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.3 $ + */ +class CDATAReader + extends Reader +{ + + /** + * The encapsulated reader. + */ + private StdXMLReader reader; + + + /** + * Saved char. + */ + private char savedChar; + + + /** + * True if the end of the stream has been reached. + */ + private boolean atEndOfData; + + + /** + * Creates the reader. + * + * @param reader the encapsulated reader + */ + CDATAReader(StdXMLReader reader) + { + this.reader = reader; + this.savedChar = 0; + this.atEndOfData = false; + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.reader = null; + super.finalize(); + } + + + /** + * Reads a block of data. + * + * @param buffer where to put the read data + * @param offset first position in buffer to put the data + * @param size maximum number of chars to read + * + * @return the number of chars read, or -1 if at EOF + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + public int read(char[] buffer, + int offset, + int size) + throws IOException + { + int charsRead = 0; + + if (this.atEndOfData) { + return -1; + } + + if ((offset + size) > buffer.length) { + size = buffer.length - offset; + } + + while (charsRead < size) { + char ch = this.savedChar; + + if (ch == 0) { + ch = this.reader.read(); + } else { + this.savedChar = 0; + } + + if (ch == ']') { + char ch2 = this.reader.read(); + + if (ch2 == ']') { + char ch3 = this.reader.read(); + + if (ch3 == '>') { + this.atEndOfData = true; + break; + } + + this.savedChar = ch2; + this.reader.unread(ch3); + } else { + this.reader.unread(ch2); + } + } + buffer[charsRead] = ch; + charsRead++; + } + + if (charsRead == 0) { + charsRead = -1; + } + + return charsRead; + } + + + /** + * Skips remaining data and closes the stream. + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + public void close() + throws IOException + { + while (! this.atEndOfData) { + char ch = this.savedChar; + + if (ch == 0) { + ch = this.reader.read(); + } else { + this.savedChar = 0; + } + + if (ch == ']') { + char ch2 = this.reader.read(); + + if (ch2 == ']') { + char ch3 = this.reader.read(); + + if (ch3 == '>') { + break; + } + + this.savedChar = ch2; + this.reader.unread(ch3); + } else { + this.reader.unread(ch2); + } + } + } + + this.atEndOfData = true; + } + +} diff --git a/support/Processing_core_src/processing/xml/ContentReader.java b/support/Processing_core_src/processing/xml/ContentReader.java new file mode 100644 index 0000000..66430c0 --- /dev/null +++ b/support/Processing_core_src/processing/xml/ContentReader.java @@ -0,0 +1,212 @@ +/* ContentReader.java NanoXML/Java + * + * $Revision: 1.4 $ + * $Date: 2002/01/04 21:03:28 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.io.Reader; +import java.io.IOException; + + +/** + * This reader reads data from another reader until a new element has + * been encountered. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.4 $ + */ +class ContentReader + extends Reader +{ + + /** + * The encapsulated reader. + */ + private StdXMLReader reader; + + + /** + * Buffer. + */ + private String buffer; + + + /** + * Pointer into the buffer. + */ + private int bufferIndex; + + + /** + * The entity resolver. + */ + private XMLEntityResolver resolver; + + + /** + * Creates the reader. + * + * @param reader the encapsulated reader + * @param resolver the entity resolver + * @param buffer data that has already been read from reader + */ + ContentReader(StdXMLReader reader, + XMLEntityResolver resolver, + String buffer) + { + this.reader = reader; + this.resolver = resolver; + this.buffer = buffer; + this.bufferIndex = 0; + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.reader = null; + this.resolver = null; + this.buffer = null; + super.finalize(); + } + + + /** + * Reads a block of data. + * + * @param outputBuffer where to put the read data + * @param offset first position in buffer to put the data + * @param size maximum number of chars to read + * + * @return the number of chars read, or -1 if at EOF + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + public int read(char[] outputBuffer, + int offset, + int size) + throws IOException + { + try { + int charsRead = 0; + int bufferLength = this.buffer.length(); + + if ((offset + size) > outputBuffer.length) { + size = outputBuffer.length - offset; + } + + while (charsRead < size) { + String str = ""; + char ch; + + if (this.bufferIndex >= bufferLength) { + str = XMLUtil.read(this.reader, '&'); + ch = str.charAt(0); + } else { + ch = this.buffer.charAt(this.bufferIndex); + this.bufferIndex++; + outputBuffer[charsRead] = ch; + charsRead++; + continue; // don't interprete chars in the buffer + } + + if (ch == '<') { + this.reader.unread(ch); + break; + } + + if ((ch == '&') && (str.length() > 1)) { + if (str.charAt(1) == '#') { + ch = XMLUtil.processCharLiteral(str); + } else { + XMLUtil.processEntity(str, this.reader, this.resolver); + continue; + } + } + + outputBuffer[charsRead] = ch; + charsRead++; + } + + if (charsRead == 0) { + charsRead = -1; + } + + return charsRead; + } catch (XMLParseException e) { + throw new IOException(e.getMessage()); + } + } + + + /** + * Skips remaining data and closes the stream. + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + public void close() + throws IOException + { + try { + int bufferLength = this.buffer.length(); + + for (;;) { + String str = ""; + char ch; + + if (this.bufferIndex >= bufferLength) { + str = XMLUtil.read(this.reader, '&'); + ch = str.charAt(0); + } else { + ch = this.buffer.charAt(this.bufferIndex); + this.bufferIndex++; + continue; // don't interprete chars in the buffer + } + + if (ch == '<') { + this.reader.unread(ch); + break; + } + + if ((ch == '&') && (str.length() > 1)) { + if (str.charAt(1) != '#') { + XMLUtil.processEntity(str, this.reader, this.resolver); + } + } + } + } catch (XMLParseException e) { + throw new IOException(e.getMessage()); + } + } + +} diff --git a/support/Processing_core_src/processing/xml/PIReader.java b/support/Processing_core_src/processing/xml/PIReader.java new file mode 100644 index 0000000..d6a2bf2 --- /dev/null +++ b/support/Processing_core_src/processing/xml/PIReader.java @@ -0,0 +1,157 @@ +/* PIReader.java NanoXML/Java + * + * $Revision: 1.3 $ + * $Date: 2002/01/04 21:03:28 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.io.Reader; +import java.io.IOException; + + +/** + * This reader reads data from another reader until the end of a processing + * instruction (?>) has been encountered. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.3 $ + */ +class PIReader + extends Reader +{ + + /** + * The encapsulated reader. + */ + private StdXMLReader reader; + + + /** + * True if the end of the stream has been reached. + */ + private boolean atEndOfData; + + + /** + * Creates the reader. + * + * @param reader the encapsulated reader + */ + PIReader(StdXMLReader reader) + { + this.reader = reader; + this.atEndOfData = false; + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.reader = null; + super.finalize(); + } + + + /** + * Reads a block of data. + * + * @param buffer where to put the read data + * @param offset first position in buffer to put the data + * @param size maximum number of chars to read + * + * @return the number of chars read, or -1 if at EOF + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + public int read(char[] buffer, + int offset, + int size) + throws IOException + { + if (this.atEndOfData) { + return -1; + } + + int charsRead = 0; + + if ((offset + size) > buffer.length) { + size = buffer.length - offset; + } + + while (charsRead < size) { + char ch = this.reader.read(); + + if (ch == '?') { + char ch2 = this.reader.read(); + + if (ch2 == '>') { + this.atEndOfData = true; + break; + } + + this.reader.unread(ch2); + } + + buffer[charsRead] = ch; + charsRead++; + } + + if (charsRead == 0) { + charsRead = -1; + } + + return charsRead; + } + + + /** + * Skips remaining data and closes the stream. + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + public void close() + throws IOException + { + while (! this.atEndOfData) { + char ch = this.reader.read(); + + if (ch == '?') { + char ch2 = this.reader.read(); + + if (ch2 == '>') { + this.atEndOfData = true; + } + } + } + } + +} diff --git a/support/Processing_core_src/processing/xml/StdXMLBuilder.java b/support/Processing_core_src/processing/xml/StdXMLBuilder.java new file mode 100644 index 0000000..b66f7f4 --- /dev/null +++ b/support/Processing_core_src/processing/xml/StdXMLBuilder.java @@ -0,0 +1,330 @@ +/* StdXMLBuilder.java NanoXML/Java + * + * $Revision: 1.3 $ + * $Date: 2002/01/04 21:03:28 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + +import java.io.IOException; +import java.io.Reader; +import java.util.Stack; + + +/** + * StdXMLBuilder creates a tree of XML elements from a data source. + * + * @see processing.xml.XMLElement + * + * @author Marc De Scheemaecker + */ +public class StdXMLBuilder { + /** + * This stack contains the current element and its parents. + */ + private Stack stack; + + + /** + * The root element of the parsed XML tree. + */ + private XMLElement root; + + private XMLElement parent; + + /** + * Creates the builder. + */ + public StdXMLBuilder() { + this(new XMLElement()); + this.stack = null; + this.root = null; + } + + + public StdXMLBuilder(XMLElement parent) { + this.parent = parent; + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + //this.prototype = null; + this.root = null; + this.stack.clear(); + this.stack = null; + super.finalize(); + } + + + /** + * This method is called before the parser starts processing its input. + * + * @param systemID the system ID of the XML data source. + * @param lineNr the line on which the parsing starts. + */ + public void startBuilding(String systemID, + int lineNr) + { + this.stack = new Stack(); + this.root = null; + } + + + /** + * This method is called when a processing instruction is encountered. + * PIs with target "xml" are handled by the parser. + * + * @param target the PI target. + * @param reader to read the data from the PI. + */ + public void newProcessingInstruction(String target, + Reader reader) + { + // nothing to do + } + + + /** + * This method is called when a new XML element is encountered. + * + * @see #endElement + * + * @param name the name of the element. + * @param nsPrefix the prefix used to identify the namespace. If no + * namespace has been specified, this parameter is null. + * @param nsURI the URI associated with the namespace. If no + * namespace has been specified, or no URI is + * associated with nsPrefix, this parameter is null. + * @param systemID the system ID of the XML data source. + * @param lineNr the line in the source where the element starts. + */ + public void startElement(String name, + String nsPrefix, + String nsURI, + String systemID, + int lineNr) + { + String fullName = name; + + if (nsPrefix != null) { + fullName = nsPrefix + ':' + name; + } + + //XMLElement elt = this.prototype.createElement(fullName, nsURI, + // systemID, lineNr); + +// XMLElement elt = new XMLElement(fullName, nsURI, systemID, lineNr); +// +// if (this.stack.empty()) { +// this.root = elt; +// } else { +// XMLElement top = (XMLElement) this.stack.peek(); +// top.addChild(elt); +// } +// stack.push(elt); + + if (this.stack.empty()) { + //System.out.println("setting root"); + parent.init(fullName, nsURI, systemID, lineNr); + stack.push(parent); + root = parent; + } else { + XMLElement top = (XMLElement) this.stack.peek(); + //System.out.println("stack has " + top.getName()); + XMLElement elt = new XMLElement(fullName, nsURI, systemID, lineNr); + top.addChild(elt); + stack.push(elt); + } + } + + + /** + * This method is called when the attributes of an XML element have been + * processed. + * + * @see #startElement + * @see #addAttribute + * + * @param name the name of the element. + * @param nsPrefix the prefix used to identify the namespace. If no + * namespace has been specified, this parameter is null. + * @param nsURI the URI associated with the namespace. If no + * namespace has been specified, or no URI is + * associated with nsPrefix, this parameter is null. + */ + public void elementAttributesProcessed(String name, + String nsPrefix, + String nsURI) + { + // nothing to do + } + + + /** + * This method is called when the end of an XML elemnt is encountered. + * + * @see #startElement + * + * @param name the name of the element. + * @param nsPrefix the prefix used to identify the namespace. If no + * namespace has been specified, this parameter is null. + * @param nsURI the URI associated with the namespace. If no + * namespace has been specified, or no URI is + * associated with nsPrefix, this parameter is null. + */ + public void endElement(String name, + String nsPrefix, + String nsURI) + { + XMLElement elt = (XMLElement) this.stack.pop(); + + if (elt.getChildCount() == 1) { + XMLElement child = elt.getChild(0); + + if (child.getLocalName() == null) { + elt.setContent(child.getContent()); + elt.removeChild(0); + } + } + } + + + /** + * This method is called when a new attribute of an XML element is + * encountered. + * + * @param key the key (name) of the attribute. + * @param nsPrefix the prefix used to identify the namespace. If no + * namespace has been specified, this parameter is null. + * @param nsURI the URI associated with the namespace. If no + * namespace has been specified, or no URI is + * associated with nsPrefix, this parameter is null. + * @param value the value of the attribute. + * @param type the type of the attribute. If no type is known, + * "CDATA" is returned. + * + * @throws java.lang.Exception + * If an exception occurred while processing the event. + */ + public void addAttribute(String key, + String nsPrefix, + String nsURI, + String value, + String type) + throws Exception + { + String fullName = key; + + if (nsPrefix != null) { + fullName = nsPrefix + ':' + key; + } + + XMLElement top = (XMLElement) this.stack.peek(); + + if (top.hasAttribute(fullName)) { + throw new XMLParseException(top.getSystemID(), + top.getLine(), + "Duplicate attribute: " + key); + } + +// if (nsPrefix != null) { +// top.setAttribute(fullName, nsURI, value); +// } else { + top.setString(fullName, value); +// } + } + + + /** + * This method is called when a PCDATA element is encountered. A Java + * reader is supplied from which you can read the data. The reader will + * only read the data of the element. You don't need to check for + * boundaries. If you don't read the full element, the rest of the data + * is skipped. You also don't have to care about entities; they are + * resolved by the parser. + * + * @param reader the Java reader from which you can retrieve the data. + * @param systemID the system ID of the XML data source. + * @param lineNr the line in the source where the element starts. + */ + public void addPCData(Reader reader, + String systemID, + int lineNr) + { + int bufSize = 2048; + int sizeRead = 0; + StringBuffer str = new StringBuffer(bufSize); + char[] buf = new char[bufSize]; + + for (;;) { + if (sizeRead >= bufSize) { + bufSize *= 2; + str.ensureCapacity(bufSize); + } + + int size; + + try { + size = reader.read(buf); + } catch (IOException e) { + break; + } + + if (size < 0) { + break; + } + + str.append(buf, 0, size); + sizeRead += size; + } + + //XMLElement elt = this.prototype.createElement(null, systemID, lineNr); + XMLElement elt = new XMLElement(null, null, systemID, lineNr); + elt.setContent(str.toString()); + + if (! this.stack.empty()) { + XMLElement top = (XMLElement) this.stack.peek(); + top.addChild(elt); + } + } + + + /** + * Returns the result of the building process. This method is called just + * before the parse method of StdXMLParser returns. + * + * @return the result of the building process. + */ + public Object getResult() + { + return this.root; + } + +} diff --git a/support/Processing_core_src/processing/xml/StdXMLParser.java b/support/Processing_core_src/processing/xml/StdXMLParser.java new file mode 100644 index 0000000..b38f9d7 --- /dev/null +++ b/support/Processing_core_src/processing/xml/StdXMLParser.java @@ -0,0 +1,685 @@ +/* StdXMLParser.java NanoXML/Java + * + * $Revision: 1.5 $ + * $Date: 2002/03/24 11:37:00 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.io.Reader; +import java.util.Enumeration; +import java.util.Properties; +import java.util.Vector; + + +/** + * StdXMLParser is the core parser of NanoXML. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.5 $ + */ +public class StdXMLParser { + + /** + * The builder which creates the logical structure of the XML data. + */ + private StdXMLBuilder builder; + + + /** + * The reader from which the parser retrieves its data. + */ + private StdXMLReader reader; + + + /** + * The entity resolver. + */ + private XMLEntityResolver entityResolver; + + + /** + * The validator that will process entity references and validate the XML + * data. + */ + private XMLValidator validator; + + + /** + * Creates a new parser. + */ + public StdXMLParser() + { + this.builder = null; + this.validator = null; + this.reader = null; + this.entityResolver = new XMLEntityResolver(); + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.builder = null; + this.reader = null; + this.entityResolver = null; + this.validator = null; + super.finalize(); + } + + + /** + * Sets the builder which creates the logical structure of the XML data. + * + * @param builder the non-null builder + */ + public void setBuilder(StdXMLBuilder builder) + { + this.builder = builder; + } + + + /** + * Returns the builder which creates the logical structure of the XML data. + * + * @return the builder + */ + public StdXMLBuilder getBuilder() + { + return this.builder; + } + + + /** + * Sets the validator that validates the XML data. + * + * @param validator the non-null validator + */ + public void setValidator(XMLValidator validator) + { + this.validator = validator; + } + + + /** + * Returns the validator that validates the XML data. + * + * @return the validator + */ + public XMLValidator getValidator() + { + return this.validator; + } + + + /** + * Sets the entity resolver. + * + * @param resolver the non-null resolver + */ + public void setResolver(XMLEntityResolver resolver) + { + this.entityResolver = resolver; + } + + + /** + * Returns the entity resolver. + * + * @return the non-null resolver + */ + public XMLEntityResolver getResolver() + { + return this.entityResolver; + } + + + /** + * Sets the reader from which the parser retrieves its data. + * + * @param reader the reader + */ + public void setReader(StdXMLReader reader) + { + this.reader = reader; + } + + + /** + * Returns the reader from which the parser retrieves its data. + * + * @return the reader + */ + public StdXMLReader getReader() + { + return this.reader; + } + + + /** + * Parses the data and lets the builder create the logical data structure. + * + * @return the logical structure built by the builder + * + * @throws net.n3.nanoxml.XMLException + * if an error occurred reading or parsing the data + */ + public Object parse() + throws XMLException + { + try { + this.builder.startBuilding(this.reader.getSystemID(), + this.reader.getLineNr()); + this.scanData(); + return this.builder.getResult(); + } catch (XMLException e) { + throw e; + } catch (Exception e) { + throw new XMLException(e); + } + } + + + /** + * Scans the XML data for elements. + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void scanData() throws Exception { + while ((! this.reader.atEOF()) && (this.builder.getResult() == null)) { + String str = XMLUtil.read(this.reader, '&'); + char ch = str.charAt(0); + if (ch == '&') { + XMLUtil.processEntity(str, this.reader, this.entityResolver); + continue; + } + + switch (ch) { + case '<': + this.scanSomeTag(false, // don't allow CDATA + null, // no default namespace + new Properties()); + break; + + case ' ': + case '\t': + case '\r': + case '\n': + // skip whitespace + break; + + default: + XMLUtil.errorInvalidInput(reader.getSystemID(), + reader.getLineNr(), + "`" + ch + "' (0x" + + Integer.toHexString((int) ch) + + ')'); + } + } + } + + + /** + * Scans an XML tag. + * + * @param allowCDATA true if CDATA sections are allowed at this point + * @param defaultNamespace the default namespace URI (or null) + * @param namespaces list of defined namespaces + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void scanSomeTag(boolean allowCDATA, + String defaultNamespace, + Properties namespaces) + throws Exception + { + String str = XMLUtil.read(this.reader, '&'); + char ch = str.charAt(0); + + if (ch == '&') { + XMLUtil.errorUnexpectedEntity(reader.getSystemID(), + reader.getLineNr(), + str); + } + + switch (ch) { + case '?': + this.processPI(); + break; + + case '!': + this.processSpecialTag(allowCDATA); + break; + + default: + this.reader.unread(ch); + this.processElement(defaultNamespace, namespaces); + } + } + + + /** + * Processes a "processing instruction". + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void processPI() + throws Exception + { + XMLUtil.skipWhitespace(this.reader, null); + String target = XMLUtil.scanIdentifier(this.reader); + XMLUtil.skipWhitespace(this.reader, null); + Reader r = new PIReader(this.reader); + + if (!target.equalsIgnoreCase("xml")) { + this.builder.newProcessingInstruction(target, r); + } + + r.close(); + } + + + /** + * Processes a tag that starts with a bang (<!...>). + * + * @param allowCDATA true if CDATA sections are allowed at this point + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void processSpecialTag(boolean allowCDATA) + throws Exception + { + String str = XMLUtil.read(this.reader, '&'); + char ch = str.charAt(0); + + if (ch == '&') { + XMLUtil.errorUnexpectedEntity(reader.getSystemID(), + reader.getLineNr(), + str); + } + + switch (ch) { + case '[': + if (allowCDATA) { + this.processCDATA(); + } else { + XMLUtil.errorUnexpectedCDATA(reader.getSystemID(), + reader.getLineNr()); + } + + return; + + case 'D': + this.processDocType(); + return; + + case '-': + XMLUtil.skipComment(this.reader); + return; + } + } + + + /** + * Processes a CDATA section. + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void processCDATA() throws Exception { + if (! XMLUtil.checkLiteral(this.reader, "CDATA[")) { + XMLUtil.errorExpectedInput(reader.getSystemID(), + reader.getLineNr(), + "') { + XMLUtil.errorExpectedInput(reader.getSystemID(), + reader.getLineNr(), + "`>'"); + } + + // TODO DTD checking is currently disabled, because it breaks + // applications that don't have access to a net connection + // (since it insists on going and checking out the DTD). + if (false) { + if (systemID != null) { + Reader r = this.reader.openStream(publicID.toString(), systemID); + this.reader.startNewStream(r); + this.reader.setSystemID(systemID); + this.reader.setPublicID(publicID.toString()); + this.validator.parseDTD(publicID.toString(), + this.reader, + this.entityResolver, + true); + } + } + } + + + /** + * Processes a regular element. + * + * @param defaultNamespace the default namespace URI (or null) + * @param namespaces list of defined namespaces + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void processElement(String defaultNamespace, + Properties namespaces) + throws Exception + { + String fullName = XMLUtil.scanIdentifier(this.reader); + String name = fullName; + XMLUtil.skipWhitespace(this.reader, null); + String prefix = null; + int colonIndex = name.indexOf(':'); + + if (colonIndex > 0) { + prefix = name.substring(0, colonIndex); + name = name.substring(colonIndex + 1); + } + + Vector attrNames = new Vector(); + Vector attrValues = new Vector(); + Vector attrTypes = new Vector(); + + this.validator.elementStarted(fullName, + this.reader.getSystemID(), + this.reader.getLineNr()); + char ch; + + for (;;) { + ch = this.reader.read(); + + if ((ch == '/') || (ch == '>')) { + break; + } + + this.reader.unread(ch); + this.processAttribute(attrNames, attrValues, attrTypes); + XMLUtil.skipWhitespace(this.reader, null); + } + + Properties extraAttributes = new Properties(); + this.validator.elementAttributesProcessed(fullName, + extraAttributes, + this.reader.getSystemID(), + this.reader.getLineNr()); + Enumeration en = extraAttributes.keys(); + + while (en.hasMoreElements()) { + String key = (String) en.nextElement(); + String value = extraAttributes.getProperty(key); + attrNames.addElement(key); + attrValues.addElement(value); + attrTypes.addElement("CDATA"); + } + + // post 1.2.1, just treat namespaces like any other attribute +// for (int i = 0; i < attrNames.size(); i++) { +// String key = (String) attrNames.elementAt(i); +// String value = (String) attrValues.elementAt(i); +// //String type = (String) attrTypes.elementAt(i); + +// if (key.equals("xmlns")) { +// defaultNamespace = value; +// } else if (key.startsWith("xmlns:")) { +// namespaces.put(key.substring(6), value); +// } +// } + + if (prefix == null) { + this.builder.startElement(name, prefix, defaultNamespace, + this.reader.getSystemID(), + this.reader.getLineNr()); + } else { + this.builder.startElement(name, prefix, + namespaces.getProperty(prefix), + this.reader.getSystemID(), + this.reader.getLineNr()); + } + + for (int i = 0; i < attrNames.size(); i++) { + String key = (String) attrNames.elementAt(i); + +// if (key.startsWith("xmlns")) { +// continue; +// } + + String value = (String) attrValues.elementAt(i); + String type = (String) attrTypes.elementAt(i); + colonIndex = key.indexOf(':'); + + if (colonIndex > 0) { + String attPrefix = key.substring(0, colonIndex); + key = key.substring(colonIndex + 1); + this.builder.addAttribute(key, attPrefix, + namespaces.getProperty(attPrefix), + value, type); + } else { + this.builder.addAttribute(key, null, null, value, type); + } + } + + if (prefix == null) { + this.builder.elementAttributesProcessed(name, prefix, + defaultNamespace); + } else { + this.builder.elementAttributesProcessed(name, prefix, + namespaces + .getProperty(prefix)); + } + + if (ch == '/') { + if (this.reader.read() != '>') { + XMLUtil.errorExpectedInput(reader.getSystemID(), + reader.getLineNr(), + "`>'"); + } + + this.validator.elementEnded(name, + this.reader.getSystemID(), + this.reader.getLineNr()); + + if (prefix == null) { + this.builder.endElement(name, prefix, defaultNamespace); + } else { + this.builder.endElement(name, prefix, + namespaces.getProperty(prefix)); + } + + return; + } + + StringBuffer buffer = new StringBuffer(16); + + for (;;) { + buffer.setLength(0); + String str; + + for (;;) { + XMLUtil.skipWhitespace(this.reader, buffer); + str = XMLUtil.read(this.reader, '&'); + + if ((str.charAt(0) == '&') && (str.charAt(1) != '#')) { + XMLUtil.processEntity(str, this.reader, + this.entityResolver); + } else { + break; + } + } + + if (str.charAt(0) == '<') { + str = XMLUtil.read(this.reader, '\0'); + + if (str.charAt(0) == '/') { + XMLUtil.skipWhitespace(this.reader, null); + str = XMLUtil.scanIdentifier(this.reader); + + if (! str.equals(fullName)) { + XMLUtil.errorWrongClosingTag(reader.getSystemID(), + reader.getLineNr(), + name, str); + } + + XMLUtil.skipWhitespace(this.reader, null); + + if (this.reader.read() != '>') { + XMLUtil.errorClosingTagNotEmpty(reader.getSystemID(), + reader.getLineNr()); + } + + this.validator.elementEnded(fullName, + this.reader.getSystemID(), + this.reader.getLineNr()); + if (prefix == null) { + this.builder.endElement(name, prefix, defaultNamespace); + } else { + this.builder.endElement(name, prefix, + namespaces.getProperty(prefix)); + } + break; + } else { // <[^/] + this.reader.unread(str.charAt(0)); + this.scanSomeTag(true, //CDATA allowed + defaultNamespace, + (Properties) namespaces.clone()); + } + } else { // [^<] + if (str.charAt(0) == '&') { + ch = XMLUtil.processCharLiteral(str); + buffer.append(ch); + } else { + reader.unread(str.charAt(0)); + } + this.validator.PCDataAdded(this.reader.getSystemID(), + this.reader.getLineNr()); + Reader r = new ContentReader(this.reader, + this.entityResolver, + buffer.toString()); + this.builder.addPCData(r, this.reader.getSystemID(), + this.reader.getLineNr()); + r.close(); + } + } + } + + + /** + * Processes an attribute of an element. + * + * @param attrNames contains the names of the attributes. + * @param attrValues contains the values of the attributes. + * @param attrTypes contains the types of the attributes. + * + * @throws java.lang.Exception + * if something went wrong + */ + protected void processAttribute(Vector attrNames, + Vector attrValues, + Vector attrTypes) + throws Exception + { + String key = XMLUtil.scanIdentifier(this.reader); + XMLUtil.skipWhitespace(this.reader, null); + + if (! XMLUtil.read(this.reader, '&').equals("=")) { + XMLUtil.errorExpectedInput(reader.getSystemID(), + reader.getLineNr(), + "`='"); + } + + XMLUtil.skipWhitespace(this.reader, null); + String value = XMLUtil.scanString(this.reader, '&', + this.entityResolver); + attrNames.addElement(key); + attrValues.addElement(value); + attrTypes.addElement("CDATA"); + this.validator.attributeAdded(key, value, + this.reader.getSystemID(), + this.reader.getLineNr()); + } + +} diff --git a/support/Processing_core_src/processing/xml/StdXMLReader.java b/support/Processing_core_src/processing/xml/StdXMLReader.java new file mode 100644 index 0000000..e2d97a5 --- /dev/null +++ b/support/Processing_core_src/processing/xml/StdXMLReader.java @@ -0,0 +1,626 @@ +/* StdXMLReader.java NanoXML/Java + * + * $Revision: 1.4 $ + * $Date: 2002/01/04 21:03:28 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +//import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.LineNumberReader; +import java.io.PushbackReader; +import java.io.PushbackInputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Stack; + + +/** + * StdXMLReader reads the data to be parsed. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.4 $ + */ +public class StdXMLReader +{ + + /** + * A stacked reader. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.4 $ + */ + private class StackedReader + { + + PushbackReader pbReader; + + LineNumberReader lineReader; + + URL systemId; + + String publicId; + + } + + + /** + * The stack of readers. + */ + private Stack readers; + + + /** + * The current push-back reader. + */ + private StackedReader currentReader; + + + /** + * Creates a new reader using a string as input. + * + * @param str the string containing the XML data + */ + public static StdXMLReader stringReader(String str) + { + return new StdXMLReader(new StringReader(str)); + } + + + /** + * Creates a new reader using a file as input. + * + * @param filename the name of the file containing the XML data + * + * @throws java.io.FileNotFoundException + * if the file could not be found + * @throws java.io.IOException + * if an I/O error occurred + */ + public static StdXMLReader fileReader(String filename) + throws FileNotFoundException, + IOException + { + StdXMLReader r = new StdXMLReader(new FileInputStream(filename)); + r.setSystemID(filename); + + for (int i = 0; i < r.readers.size(); i++) { + StackedReader sr = (StackedReader) r.readers.elementAt(i); + sr.systemId = r.currentReader.systemId; + } + + return r; + } + + + /** + * Initializes the reader from a system and public ID. + * + * @param publicID the public ID which may be null. + * @param systemID the non-null system ID. + * + * @throws MalformedURLException + * if the system ID does not contain a valid URL + * @throws FileNotFoundException + * if the system ID refers to a local file which does not exist + * @throws IOException + * if an error occurred opening the stream + */ + public StdXMLReader(String publicID, + String systemID) + throws MalformedURLException, + FileNotFoundException, + IOException + { + URL systemIDasURL = null; + + try { + systemIDasURL = new URL(systemID); + } catch (MalformedURLException e) { + systemID = "file:" + systemID; + + try { + systemIDasURL = new URL(systemID); + } catch (MalformedURLException e2) { + throw e; + } + } + + this.currentReader = new StackedReader(); + this.readers = new Stack(); + Reader reader = this.openStream(publicID, systemIDasURL.toString()); + this.currentReader.lineReader = new LineNumberReader(reader); + this.currentReader.pbReader + = new PushbackReader(this.currentReader.lineReader, 2); + } + + + /** + * Initializes the XML reader. + * + * @param reader the input for the XML data. + */ + public StdXMLReader(Reader reader) + { + this.currentReader = new StackedReader(); + this.readers = new Stack(); + this.currentReader.lineReader = new LineNumberReader(reader); + this.currentReader.pbReader + = new PushbackReader(this.currentReader.lineReader, 2); + this.currentReader.publicId = ""; + + try { + this.currentReader.systemId = new URL("file:."); + } catch (MalformedURLException e) { + // never happens + } + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.currentReader.lineReader = null; + this.currentReader.pbReader = null; + this.currentReader.systemId = null; + this.currentReader.publicId = null; + this.currentReader = null; + this.readers.clear(); + super.finalize(); + } + + + /** + * Scans the encoding from an <?xml...?> tag. + * + * @param str the first tag in the XML data. + * + * @return the encoding, or null if no encoding has been specified. + */ + protected String getEncoding(String str) + { + if (! str.startsWith("= 'a') + && (str.charAt(index) <= 'z')) { + key.append(str.charAt(index)); + index++; + } + + while ((index < str.length()) && (str.charAt(index) <= ' ')) { + index++; + } + + if ((index >= str.length()) || (str.charAt(index) != '=')) { + break; + } + + while ((index < str.length()) && (str.charAt(index) != '\'') + && (str.charAt(index) != '"')) { + index++; + } + + if (index >= str.length()) { + break; + } + + char delimiter = str.charAt(index); + index++; + int index2 = str.indexOf(delimiter, index); + + if (index2 < 0) { + break; + } + + if (key.toString().equals("encoding")) { + return str.substring(index, index2); + } + + index = index2 + 1; + } + + return null; + } + + + /** + * Converts a stream to a reader while detecting the encoding. + * + * @param stream the input for the XML data. + * @param charsRead buffer where to put characters that have been read + * + * @throws java.io.IOException + * if an I/O error occurred + */ + protected Reader stream2reader(InputStream stream, + StringBuffer charsRead) + throws IOException + { + PushbackInputStream pbstream = new PushbackInputStream(stream); + int b = pbstream.read(); + + switch (b) { + case 0x00: + case 0xFE: + case 0xFF: + pbstream.unread(b); + return new InputStreamReader(pbstream, "UTF-16"); + + case 0xEF: + for (int i = 0; i < 2; i++) { + pbstream.read(); + } + + return new InputStreamReader(pbstream, "UTF-8"); + + case 0x3C: + b = pbstream.read(); + charsRead.append('<'); + + while ((b > 0) && (b != 0x3E)) { + charsRead.append((char) b); + b = pbstream.read(); + } + + if (b > 0) { + charsRead.append((char) b); + } + + String encoding = this.getEncoding(charsRead.toString()); + + if (encoding == null) { + return new InputStreamReader(pbstream, "UTF-8"); + } + + charsRead.setLength(0); + + try { + return new InputStreamReader(pbstream, encoding); + } catch (UnsupportedEncodingException e) { + return new InputStreamReader(pbstream, "UTF-8"); + } + + default: + charsRead.append((char) b); + return new InputStreamReader(pbstream, "UTF-8"); + } + } + + + /** + * Initializes the XML reader. + * + * @param stream the input for the XML data. + * + * @throws java.io.IOException + * if an I/O error occurred + */ + public StdXMLReader(InputStream stream) + throws IOException + { + // unused? + //PushbackInputStream pbstream = new PushbackInputStream(stream); + StringBuffer charsRead = new StringBuffer(); + Reader reader = this.stream2reader(stream, charsRead); + this.currentReader = new StackedReader(); + this.readers = new Stack(); + this.currentReader.lineReader = new LineNumberReader(reader); + this.currentReader.pbReader + = new PushbackReader(this.currentReader.lineReader, 2); + this.currentReader.publicId = ""; + + try { + this.currentReader.systemId = new URL("file:."); + } catch (MalformedURLException e) { + // never happens + } + + this.startNewStream(new StringReader(charsRead.toString())); + } + + + /** + * Reads a character. + * + * @return the character + * + * @throws java.io.IOException + * if no character could be read + */ + public char read() + throws IOException + { + int ch = this.currentReader.pbReader.read(); + + while (ch < 0) { + if (this.readers.empty()) { + throw new IOException("Unexpected EOF"); + } + + this.currentReader.pbReader.close(); + this.currentReader = (StackedReader) this.readers.pop(); + ch = this.currentReader.pbReader.read(); + } + + return (char) ch; + } + + + /** + * Returns true if the current stream has no more characters left to be + * read. + * + * @throws java.io.IOException + * if an I/O error occurred + */ + public boolean atEOFOfCurrentStream() + throws IOException + { + int ch = this.currentReader.pbReader.read(); + + if (ch < 0) { + return true; + } else { + this.currentReader.pbReader.unread(ch); + return false; + } + } + + + /** + * Returns true if there are no more characters left to be read. + * + * @throws java.io.IOException + * if an I/O error occurred + */ + public boolean atEOF() + throws IOException + { + int ch = this.currentReader.pbReader.read(); + + while (ch < 0) { + if (this.readers.empty()) { + return true; + } + + this.currentReader.pbReader.close(); + this.currentReader = (StackedReader) this.readers.pop(); + ch = this.currentReader.pbReader.read(); + } + + this.currentReader.pbReader.unread(ch); + return false; + } + + + /** + * Pushes the last character read back to the stream. + * + * @param ch the character to push back. + * + * @throws java.io.IOException + * if an I/O error occurred + */ + public void unread(char ch) + throws IOException + { + this.currentReader.pbReader.unread(ch); + } + + + /** + * Opens a stream from a public and system ID. + * + * @param publicID the public ID, which may be null + * @param systemID the system ID, which is never null + * + * @throws java.net.MalformedURLException + * if the system ID does not contain a valid URL + * @throws java.io.FileNotFoundException + * if the system ID refers to a local file which does not exist + * @throws java.io.IOException + * if an error occurred opening the stream + */ + public Reader openStream(String publicID, + String systemID) + throws MalformedURLException, + FileNotFoundException, + IOException + { + URL url = new URL(this.currentReader.systemId, systemID); + + if (url.getRef() != null) { + String ref = url.getRef(); + + if (url.getFile().length() > 0) { + url = new URL(url.getProtocol(), url.getHost(), url.getPort(), + url.getFile()); + url = new URL("jar:" + url + '!' + ref); + } else { + url = StdXMLReader.class.getResource(ref); + } + } + + this.currentReader.publicId = publicID; + this.currentReader.systemId = url; + StringBuffer charsRead = new StringBuffer(); + Reader reader = this.stream2reader(url.openStream(), charsRead); + + if (charsRead.length() == 0) { + return reader; + } + + String charsReadStr = charsRead.toString(); + PushbackReader pbreader = new PushbackReader(reader, + charsReadStr.length()); + + for (int i = charsReadStr.length() - 1; i >= 0; i--) { + pbreader.unread(charsReadStr.charAt(i)); + } + + return pbreader; + } + + + /** + * Starts a new stream from a Java reader. The new stream is used + * temporary to read data from. If that stream is exhausted, control + * returns to the parent stream. + * + * @param reader the non-null reader to read the new data from + */ + public void startNewStream(Reader reader) + { + this.startNewStream(reader, false); + } + + + /** + * Starts a new stream from a Java reader. The new stream is used + * temporary to read data from. If that stream is exhausted, control + * returns to the parent stream. + * + * @param reader the non-null reader to read the new data from + * @param isInternalEntity true if the reader is produced by resolving + * an internal entity + */ + public void startNewStream(Reader reader, + boolean isInternalEntity) + { + StackedReader oldReader = this.currentReader; + this.readers.push(this.currentReader); + this.currentReader = new StackedReader(); + + if (isInternalEntity) { + this.currentReader.lineReader = null; + this.currentReader.pbReader = new PushbackReader(reader, 2); + } else { + this.currentReader.lineReader = new LineNumberReader(reader); + this.currentReader.pbReader + = new PushbackReader(this.currentReader.lineReader, 2); + } + + this.currentReader.systemId = oldReader.systemId; + this.currentReader.publicId = oldReader.publicId; + } + + + /** + * Returns the current "level" of the stream on the stack of streams. + */ + public int getStreamLevel() + { + return this.readers.size(); + } + + + /** + * Returns the line number of the data in the current stream. + */ + public int getLineNr() + { + if (this.currentReader.lineReader == null) { + StackedReader sr = (StackedReader) this.readers.peek(); + + if (sr.lineReader == null) { + return 0; + } else { + return sr.lineReader.getLineNumber() + 1; + } + } + + return this.currentReader.lineReader.getLineNumber() + 1; + } + + + /** + * Sets the system ID of the current stream. + * + * @param systemID the system ID + * + * @throws java.net.MalformedURLException + * if the system ID does not contain a valid URL + */ + public void setSystemID(String systemID) + throws MalformedURLException + { + this.currentReader.systemId = new URL(this.currentReader.systemId, + systemID); + } + + + /** + * Sets the public ID of the current stream. + * + * @param publicID the public ID + */ + public void setPublicID(String publicID) + { + this.currentReader.publicId = publicID; + } + + + /** + * Returns the current system ID. + */ + public String getSystemID() + { + return this.currentReader.systemId.toString(); + } + + + /** + * Returns the current public ID. + */ + public String getPublicID() + { + return this.currentReader.publicId; + } + +} diff --git a/support/Processing_core_src/processing/xml/XMLAttribute.java b/support/Processing_core_src/processing/xml/XMLAttribute.java new file mode 100644 index 0000000..ebb71d1 --- /dev/null +++ b/support/Processing_core_src/processing/xml/XMLAttribute.java @@ -0,0 +1,153 @@ +/* XMLAttribute.java NanoXML/Java + * + * $Revision: 1.4 $ + * $Date: 2002/01/04 21:03:29 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +/** + * An attribute in an XML element. This is an internal class. + * + * @see net.n3.nanoxml.XMLElement + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.4 $ + */ +class XMLAttribute +{ + + /** + * The full name of the attribute. + */ + private String name; + + + /** + * The short name of the attribute. + */ + private String localName; + + + /** + * The namespace URI of the attribute. + */ + private String namespace; + + + /** + * The value of the attribute. + */ + private String value; + + + /** + * The type of the attribute. + */ + private String type; + + + /** + * Creates a new attribute. + * + * @param fullName the non-null full name + * @param name the non-null short name + * @param namespace the namespace URI, which may be null + * @param value the value of the attribute + * @param type the type of the attribute + */ + XMLAttribute(String fullName, + String name, + String namespace, + String value, + String type) + { + this.name = fullName; + this.localName = name; + this.namespace = namespace; + this.value = value; + this.type = type; + } + + + /** + * Returns the full name of the attribute. + */ + String getName() + { + return this.name; + } + + + /** + * Returns the short name of the attribute. + */ + String getLocalName() + { + return this.localName; + } + + + /** + * Returns the namespace of the attribute. + */ + String getNamespace() + { + return this.namespace; + } + + + /** + * Returns the value of the attribute. + */ + String getValue() + { + return this.value; + } + + + /** + * Sets the value of the attribute. + * + * @param value the new value. + */ + void setValue(String value) + { + this.value = value; + } + + + /** + * Returns the type of the attribute. + * + * @param type the new type. + */ + String getType() + { + return this.type; + } + +} diff --git a/support/Processing_core_src/processing/xml/XMLElement.java b/support/Processing_core_src/processing/xml/XMLElement.java new file mode 100644 index 0000000..737daf6 --- /dev/null +++ b/support/Processing_core_src/processing/xml/XMLElement.java @@ -0,0 +1,1512 @@ +/* XMLElement.java NanoXML/Java + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + +import java.io.*; +import java.util.*; + +import processing.core.PApplet; + + +/** + * XMLElement is a representation of an XML object. The object is able to parse XML code. The methods described here are the most basic. More are documented in the Developer's Reference. + *

+ * The encoding parameter inside XML files is ignored, only UTF-8 (or plain ASCII) are parsed properly. + * =advanced + * XMLElement is an XML element. This is the base class used for the + * Processing XML library, representing a single node of an XML tree. + * + * This code is based on a modified version of NanoXML by Marc De Scheemaecker. + * + * @author Marc De Scheemaecker + * @author processing.org + * + * @webref data:composite + * @usage Web & Application + * @instanceName xml any variable of type XMLElement + */ +public class XMLElement implements Serializable { + /** No line number defined. */ + public static final int NO_LINE = -1; + + /** The sketch creating this element. */ + private PApplet sketch; + + /** The parent element. */ + private XMLElement parent; + + /** The attributes of the element. */ + private Vector attributes; + + /** The child elements. */ + private Vector children; + + /** The name of the element. */ + private String name; + + /** The full name of the element (includes the namespace). */ + private String fullName; + + /** The namespace URI. */ + private String namespace; + + /** The content of the element. */ + private String content; + + /** The system ID of the source data where this element is located. */ + private String systemID; + + /** The line in the source data where this element starts. */ + private int line; + + + /** + * Creates an empty element to be used for #PCDATA content. + * @nowebref + */ + public XMLElement() { + this(null, null, null, NO_LINE); + } + + + /** + * Creates an empty element. + * + * @param fullName the name of the element. + */ + public XMLElement(String fullName) { + this(fullName, null, null, NO_LINE); + } + + +// /** +// * Creates an empty element. +// * +// * @param fullName the name of the element. +// * @param systemID the system ID of the XML data where the element starts. +// * @param lineNr the line in the XML data where the element starts. +// */ +// public XMLElement(String fullName, +// String systemID, +// int lineNr) { +// this(fullName, null, systemID, lineNr); +// } + + +// /** +// * Creates an empty element. +// * +// * @param fullName the full name of the element +// * @param namespace the namespace URI. +// */ +// public XMLElement(String fullName, +// String namespace) { +// this(fullName, namespace, null, NO_LINE); +// } + + + /** + * Creates an empty element. (Used internally for parsing/building.) + * + * @param fullName the full name of the element + * @param namespace the namespace URI. + * @param systemID the system ID of the XML data where the element starts. + * @param lineNr the line in the XML data where the element starts. + * @nowebref + */ + public XMLElement(String fullName, + String namespace, + String systemID, + int lineNr) { + this.attributes = new Vector(); + this.children = new Vector(8); + this.fullName = fullName; + if (namespace == null) { + this.name = fullName; + } else { + int index = fullName.indexOf(':'); + if (index >= 0) { + this.name = fullName.substring(index + 1); + } else { + this.name = fullName; + } + } + this.namespace = namespace; + this.content = null; + this.line = lineNr; + this.systemID = systemID; + this.parent = null; + } + + + /** + * Begin parsing XML data passed in from a PApplet. This code + * wraps exception handling, for more advanced exception handling, + * use the constructor that takes a Reader or InputStream. + * @author processing.org + * @param filename name of the XML file to load + * @param parent typically use "this" + */ + public XMLElement(PApplet sketch, String filename) { + this(); + this.sketch = sketch; + init(sketch.createReader(filename)); + } + + + public XMLElement(Reader reader) { + this(); + init(reader); + } + + + static public XMLElement parse(String xml) { + return parse(new StringReader(xml)); + } + + + static public XMLElement parse(Reader r) { + try { + StdXMLParser parser = new StdXMLParser(); + parser.setBuilder(new StdXMLBuilder()); + parser.setValidator(new XMLValidator()); + parser.setReader(new StdXMLReader(r)); + return (XMLElement) parser.parse(); + } catch (XMLException e) { + e.printStackTrace(); + return null; + } + } + + + protected void init(String fullName, + String namespace, + String systemID, + int lineNr) { + this.fullName = fullName; + if (namespace == null) { + this.name = fullName; + } else { + int index = fullName.indexOf(':'); + if (index >= 0) { + this.name = fullName.substring(index + 1); + } else { + this.name = fullName; + } + } + this.namespace = namespace; + this.line = lineNr; + this.systemID = systemID; + } + + + protected void init(Reader r) { + try { + StdXMLParser parser = new StdXMLParser(); + parser.setBuilder(new StdXMLBuilder(this)); + parser.setValidator(new XMLValidator()); + parser.setReader(new StdXMLReader(r)); + parser.parse(); + } catch (XMLException e) { + e.printStackTrace(); + } + } + + +// /** +// * Creates an element to be used for #PCDATA content. +// */ +// public XMLElement createPCDataElement() { +// return new XMLElement(); +// } + + +// /** +// * Creates an empty element. +// * +// * @param fullName the name of the element. +// */ +// public XMLElement createElement(String fullName) { +// return new XMLElement(fullName); +// } + + +// /** +// * Creates an empty element. +// * +// * @param fullName the name of the element. +// * @param systemID the system ID of the XML data where the element starts. +// * @param lineNr the line in the XML data where the element starts. +// */ +// public XMLElement createElement(String fullName, +// String systemID, +// int lineNr) { +// //return new XMLElement(fullName, systemID, lineNr); +// return new XMLElement(fullName, null, systemID, lineNr); +// } + + +// /** +// * Creates an empty element. +// * +// * @param fullName the full name of the element +// * @param namespace the namespace URI. +// */ +// public XMLElement createElement(String fullName, +// String namespace) { +// //return new XMLElement(fullName, namespace); +// return new XMLElement(fullName, namespace, null, NO_LINE); +// } + + +// /** +// * Creates an empty element. +// * +// * @param fullName the full name of the element +// * @param namespace the namespace URI. +// * @param systemID the system ID of the XML data where the element starts. +// * @param lineNr the line in the XML data where the element starts. +// */ +// public XMLElement createElement(String fullName, +// String namespace, +// String systemID, +// int lineNr) { +// return new XMLElement(fullName, namespace, systemID, lineNr); +// } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() throws Throwable { + this.attributes.clear(); + this.attributes = null; + this.children = null; + this.fullName = null; + this.name = null; + this.namespace = null; + this.content = null; + this.systemID = null; + this.parent = null; + super.finalize(); + } + + + /** + * Returns the parent element. This method returns null for the root + * element. + */ + public XMLElement getParent() { + return this.parent; + } + + + /** + * Returns the full name (i.e. the name including an eventual namespace + * prefix) of the element. + * + * @webref + * @brief Returns the name of the element. + * @return the name, or null if the element only contains #PCDATA. + */ + public String getName() { + return this.fullName; + } + + + /** + * Returns the name of the element without its namespace. + * + * @return the name, or null if the element only contains #PCDATA. + */ + public String getLocalName() { + return this.name; + } + + + /** + * Returns the namespace of the element. + * + * @return the namespace, or null if no namespace is associated with the + * element. + */ + public String getNamespace() { + return this.namespace; + } + + + /** + * Sets the full name. This method also sets the short name and clears the + * namespace URI. + * + * @param name the non-null name. + */ + public void setName(String name) { + this.name = name; + this.fullName = name; + this.namespace = null; + } + + + /** + * Sets the name. + * + * @param fullName the non-null full name. + * @param namespace the namespace URI, which may be null. + */ + public void setName(String fullName, String namespace) { + int index = fullName.indexOf(':'); + if ((namespace == null) || (index < 0)) { + this.name = fullName; + } else { + this.name = fullName.substring(index + 1); + } + this.fullName = fullName; + this.namespace = namespace; + } + + + /** + * Adds a child element. + * + * @param child the non-null child to add. + */ + public void addChild(XMLElement child) { + if (child == null) { + throw new IllegalArgumentException("child must not be null"); + } + if ((child.getLocalName() == null) && (! this.children.isEmpty())) { + XMLElement lastChild = (XMLElement) this.children.lastElement(); + + if (lastChild.getLocalName() == null) { + lastChild.setContent(lastChild.getContent() + + child.getContent()); + return; + } + } + ((XMLElement)child).parent = this; + this.children.addElement(child); + } + + + /** + * Inserts a child element. + * + * @param child the non-null child to add. + * @param index where to put the child. + */ + public void insertChild(XMLElement child, int index) { + if (child == null) { + throw new IllegalArgumentException("child must not be null"); + } + if ((child.getLocalName() == null) && (! this.children.isEmpty())) { + XMLElement lastChild = (XMLElement) this.children.lastElement(); + if (lastChild.getLocalName() == null) { + lastChild.setContent(lastChild.getContent() + + child.getContent()); + return; + } + } + ((XMLElement) child).parent = this; + this.children.insertElementAt(child, index); + } + + + /** + * Removes a child element. + * + * @param child the non-null child to remove. + */ + public void removeChild(XMLElement child) { + if (child == null) { + throw new IllegalArgumentException("child must not be null"); + } + this.children.removeElement(child); + } + + + /** + * Removes the child located at a certain index. + * + * @param index the index of the child, where the first child has index 0. + */ + public void removeChild(int index) { + children.removeElementAt(index); + } + + +// /** +// * Returns an enumeration of all child elements. +// * +// * @return the non-null enumeration +// */ +// public Enumeration enumerateChildren() { +// return this.children.elements(); +// } + + + /** + * Returns whether the element is a leaf element. + * + * @return true if the element has no children. + */ + public boolean isLeaf() { + return children.isEmpty(); + } + + + /** + * Returns whether the element has children. + * + * @return true if the element has children. + */ + public boolean hasChildren() { + return (!children.isEmpty()); + } + + + /** + * Returns the number of children for the element. + * + * @return the count. + * @webref + * @see processing.xml.XMLElement#getChild(int) + * @see processing.xml.XMLElement#getChildren(String) + */ + public int getChildCount() { + return this.children.size(); + } + + + /** + * Returns a vector containing all the child elements. + * + * @return the vector. + */ +// public Vector getChildren() { +// return this.children; +// } + + + /** + * Put the names of all children into an array. Same as looping through + * each child and calling getName() on each XMLElement. + */ + public String[] listChildren() { + int childCount = getChildCount(); + String[] outgoing = new String[childCount]; + for (int i = 0; i < childCount; i++) { + outgoing[i] = getChild(i).getName(); + } + return outgoing; + } + + + /** + * Returns an array containing all the child elements. + */ + public XMLElement[] getChildren() { + int childCount = getChildCount(); + XMLElement[] kids = new XMLElement[childCount]; + children.copyInto(kids); + return kids; + } + + + /** + * Quick accessor for an element at a particular index. + * @author processing.org + * @param index the element + */ + public XMLElement getChild(int index) { + return (XMLElement) children.elementAt(index); + } + + + /** + * Returns the child XMLElement as specified by the index parameter. The value of the index parameter must be less than the total number of children to avoid going out of the array storing the child elements. + * When the path parameter is specified, then it will return all children that match that path. The path is a series of elements and sub-elements, separated by slashes. + * + * @return the element + * @author processing.org + * + * @webref + * @see processing.xml.XMLElement#getChildCount() + * @see processing.xml.XMLElement#getChildren(String) + * @brief Get a child by its name or path. + * @param path path to a particular element + */ + public XMLElement getChild(String path) { + if (path.indexOf('/') != -1) { + return getChildRecursive(PApplet.split(path, '/'), 0); + } + int childCount = getChildCount(); + for (int i = 0; i < childCount; i++) { + XMLElement kid = getChild(i); + String kidName = kid.getName(); + if (kidName != null && kidName.equals(path)) { + return kid; + } + } + return null; + } + + + /** + * Internal helper function for getChild(String). + * @param items result of splitting the query on slashes + * @param offset where in the items[] array we're currently looking + * @return matching element or null if no match + * @author processing.org + */ + protected XMLElement getChildRecursive(String[] items, int offset) { + // if it's a number, do an index instead + if (Character.isDigit(items[offset].charAt(0))) { + XMLElement kid = getChild(Integer.parseInt(items[offset])); + if (offset == items.length-1) { + return kid; + } else { + return kid.getChildRecursive(items, offset+1); + } + } + int childCount = getChildCount(); + for (int i = 0; i < childCount; i++) { + XMLElement kid = getChild(i); + String kidName = kid.getName(); + if (kidName != null && kidName.equals(items[offset])) { + if (offset == items.length-1) { + return kid; + } else { + return kid.getChildRecursive(items, offset+1); + } + } + } + return null; + } + + +// /** +// * Returns the child at a specific index. +// * +// * @param index the index of the child +// * +// * @return the non-null child +// * +// * @throws java.lang.ArrayIndexOutOfBoundsException +// * if the index is out of bounds. +// */ +// public XMLElement getChildAtIndex(int index) throws ArrayIndexOutOfBoundsException { +// return (XMLElement) this.children.elementAt(index); +// } + + + /** + * Returns all of the children as an XMLElement array. + * When the path parameter is specified, then it will return all children that match that path. + * The path is a series of elements and sub-elements, separated by slashes. + * + * @param path element name or path/to/element + * @return array of child elements that match + * @author processing.org + * + * @webref + * @brief Returns all of the children as an XMLElement array. + * @see processing.xml.XMLElement#getChildCount() + * @see processing.xml.XMLElement#getChild(int) + */ + public XMLElement[] getChildren(String path) { + if (path.indexOf('/') != -1) { + return getChildrenRecursive(PApplet.split(path, '/'), 0); + } + // if it's a number, do an index instead + // (returns a single element array, since this will be a single match + if (Character.isDigit(path.charAt(0))) { + return new XMLElement[] { getChild(Integer.parseInt(path)) }; + } + int childCount = getChildCount(); + XMLElement[] matches = new XMLElement[childCount]; + int matchCount = 0; + for (int i = 0; i < childCount; i++) { + XMLElement kid = getChild(i); + String kidName = kid.getName(); + if (kidName != null && kidName.equals(path)) { + matches[matchCount++] = kid; + } + } + return (XMLElement[]) PApplet.subset(matches, 0, matchCount); + } + + + protected XMLElement[] getChildrenRecursive(String[] items, int offset) { + if (offset == items.length-1) { + return getChildren(items[offset]); + } + XMLElement[] matches = getChildren(items[offset]); + XMLElement[] outgoing = new XMLElement[0]; + for (int i = 0; i < matches.length; i++) { + XMLElement[] kidMatches = matches[i].getChildrenRecursive(items, offset+1); + outgoing = (XMLElement[]) PApplet.concat(outgoing, kidMatches); + } + return outgoing; + } + + + /** + * Searches an attribute. + * + * @param fullName the non-null full name of the attribute. + * + * @return the attribute, or null if the attribute does not exist. + */ + private XMLAttribute findAttribute(String fullName) { + Enumeration en = this.attributes.elements(); + while (en.hasMoreElements()) { + XMLAttribute attr = (XMLAttribute) en.nextElement(); + if (attr.getName().equals(fullName)) { + return attr; + } + } + return null; + } + + +// /** +// * Searches an attribute. +// * +// * @param name the non-null short name of the attribute. +// * @param namespace the name space, which may be null. +// * +// * @return the attribute, or null if the attribute does not exist. +// */ +// private XMLAttribute findAttribute(String name, +// String namespace) { +// Enumeration en = this.attributes.elements(); +// while (en.hasMoreElements()) { +// XMLAttribute attr = (XMLAttribute) en.nextElement(); +// boolean found = attr.getName().equals(name); +// if (namespace == null) { +// found &= (attr.getNamespace() == null); +// } else { +// found &= namespace.equals(attr.getNamespace()); +// } +// +// if (found) { +// return attr; +// } +// } +// return null; +// } + + + /** + * Returns the number of attributes. + */ + public int getAttributeCount() { + return attributes.size(); + } + + + public String[] listAttributes() { + String[] outgoing = new String[attributes.size()]; + for (int i = 0; i < attributes.size(); i++) { + outgoing[i] = attributes.get(i).getName(); + } + return outgoing; + } + + + /** + * Returns the value of an attribute. + * @param name the non-null name of the attribute. + * @return the value, or null if the attribute does not exist. + */ +// public String getAttribute(String name) { +// return getAttribute(name, null); +// } + + + /** + * Returns the value of an attribute. + * + * @param name the non-null full name of the attribute. + * @param defaultValue the default value of the attribute. + * + * @return the value, or defaultValue if the attribute does not exist. + */ +// public String getAttribute(String name, String defaultValue) { +// XMLAttribute attr = this.findAttribute(name); +// if (attr == null) { +// return defaultValue; +// } else { +// return attr.getValue(); +// } +// } + + +// /** +// * Returns the value of an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI, which may be null. +// * @param defaultValue the default value of the attribute. +// * +// * @return the value, or defaultValue if the attribute does not exist. +// * @deprecated namespace code is more trouble than it's worth +// */ +// public String getAttribute(String name, +// String namespace, +// String defaultValue) { +// XMLAttribute attr = this.findAttribute(name, namespace); +// if (attr == null) { +// return defaultValue; +// } else { +// return attr.getValue(); +// } +// } + + + /** + * @deprecated use getString() or getAttribute() + */ + public String getStringAttribute(String name) { + return getString(name); + } + + + /** + * Returns a String attribute of the element. + * If the default parameter is used and the attribute doesn't exist, the default value is returned. + * When using the version of the method without the default parameter, if the attribute doesn't exist, the value 0 is returned. + * + * @webref + * @param name the name of the attribute + * @param default Value value returned if the attribute is not found + * + * @brief Returns a String attribute of the element. + * @deprecated use getString() or getAttribute() + */ + public String getStringAttribute(String name, String defaultValue) { + return getString(name, defaultValue); + } + + +// /** +// * @deprecated namespace code is more trouble than it's worth +// */ +// public String getStringAttribute(String name, +// String namespace, +// String defaultValue) { +// return getAttribute(name, namespace, defaultValue); +// } + + + public String getString(String name) { + return getString(name, null); + } + + + public String getString(String name, String defaultValue) { + XMLAttribute attr = this.findAttribute(name); + if (attr == null) { + return defaultValue; + } else { + return attr.getValue(); + } + } + + + /** + * Returns a boolean attribute of the element. + */ + public boolean getBoolean(String name) { + return getBoolean(name, false); + } + + + /** + * Returns a boolean attribute of the element. + * If the defaultValue parameter is used and the attribute doesn't exist, the defaultValue is returned. + * When using the version of the method without the defaultValue parameter, if the attribute doesn't exist, the value false is returned. + * + * @param name the name of the attribute + * @param defaultValue value returned if the attribute is not found + * + * @webref + * @brief Returns a boolean attribute of the element. + * @return the value, or defaultValue if the attribute does not exist. + */ + public boolean getBoolean(String name, boolean defaultValue) { + String value = getString(name); + if (value == null) { + return defaultValue; + } + return (value.equals("1") || value.toLowerCase().equals("true")); + } + + +// /** +// * Returns the value of an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI, which may be null. +// * @param defaultValue the default value of the attribute. +// * +// * @return the value, or defaultValue if the attribute does not exist. +// */ +// public boolean getBooleanAttribute(String name, +// String namespace, +// boolean defaultValue) { +// String value = this.getAttribute(name, namespace, +// Boolean.toString(defaultValue)); +// return value.equals("1") || value.toLowerCase().equals("true"); +// } + + + /** + * @deprecated use getInt() instead + */ + public int getIntAttribute(String name) { + return getInt(name, 0); + } + + + /** + * @deprecated use getInt() instead + */ + public int getIntAttribute(String name, int defaultValue) { + return getInt(name, defaultValue); + } + + + /** + * Returns an integer attribute of the element. + */ + public int getInt(String name) { + return getInt(name, 0); + } + + + /** + * Returns an integer attribute of the element. + * If the default parameter is used and the attribute doesn't exist, the default value is returned. + * When using the version of the method without the default parameter, if the attribute doesn't exist, the value 0 is returned. + * + * @param name the name of the attribute + * @param defaultValue value returned if the attribute is not found + * + * @webref + * @brief Returns an integer attribute of the element. + * @return the value, or defaultValue if the attribute does not exist. + */ + public int getInt(String name, int defaultValue) { + String value = getString(name); + return (value == null) ? defaultValue : PApplet.parseInt(value, defaultValue); + } + + +// /** +// * Returns the value of an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI, which may be null. +// * @param defaultValue the default value of the attribute. +// * +// * @return the value, or defaultValue if the attribute does not exist. +// * @deprecated namespace code is more trouble than it's worth +// */ +// public int getIntAttribute(String name, +// String namespace, +// int defaultValue) { +// String value = this.getAttribute(name, namespace, +// Integer.toString(defaultValue)); +// return Integer.parseInt(value); +// } + + + /** + * @deprecated use getFloat() instead + */ + public float getFloatAttribute(String name) { + return getFloat(name, 0); + } + + + /** + * @deprecated use getFloat() instead + */ + public float getFloatAttribute(String name, float defaultValue) { + return getFloat(name, 0); + } + + + public float getFloat(String name) { + return getFloat(name, 0); + } + + + /** + * Returns a float attribute of the element. + * If the default parameter is used and the attribute doesn't exist, the default value is returned. + * When using the version of the method without the default parameter, if the attribute doesn't exist, the value 0 is returned. + * + * @param name the name of the attribute + * @param defaultValue value returned if the attribute is not found + * + * @return the value, or defaultValue if the attribute does not exist. + * + * @webref + * @brief Returns a float attribute of the element. + */ + public float getFloat(String name, float defaultValue) { + String value = getString(name); + if (value == null) { + return defaultValue; + } + return PApplet.parseFloat(value, defaultValue); +// String value = this.getAttribute(name, Float.toString(defaultValue)); +// return Float.parseFloat(value); + } + + +// /** +// * Returns the value of an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI, which may be null. +// * @param defaultValue the default value of the attribute. +// * +// * @return the value, or defaultValue if the attribute does not exist. +// * @nowebref +// * @deprecated namespace code is more trouble than it's worth +// */ +// public float getFloatAttribute(String name, +// String namespace, +// float defaultValue) { +// String value = this.getAttribute(name, namespace, +// Float.toString(defaultValue)); +// return Float.parseFloat(value); +// } + + + public double getDouble(String name) { + return getDouble(name, 0); + } + + + /** + * Returns the value of an attribute. + * + * @param name the non-null full name of the attribute. + * @param defaultValue the default value of the attribute. + * + * @return the value, or defaultValue if the attribute does not exist. + */ + public double getDouble(String name, double defaultValue) { + String value = getString(name); + return (value == null) ? defaultValue : Double.parseDouble(value); + } + + +// /** +// * Returns the value of an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI, which may be null. +// * @param defaultValue the default value of the attribute. +// * +// * @return the value, or defaultValue if the attribute does not exist. +// */ +// public double getDoubleAttribute(String name, +// String namespace, +// double defaultValue) { +// String value = this.getAttribute(name, namespace, +// Double.toString(defaultValue)); +// return Double.parseDouble(value); +// } + + +// /** +// * Returns the type of an attribute. +// * +// * @param name the non-null full name of the attribute. +// * +// * @return the type, or null if the attribute does not exist. +// */ +// public String getAttributeType(String name) { +// XMLAttribute attr = this.findAttribute(name); +// if (attr == null) { +// return null; +// } else { +// return attr.getType(); +// } +// } + + +// /** +// * Returns the namespace of an attribute. +// * +// * @param name the non-null full name of the attribute. +// * +// * @return the namespace, or null if there is none associated. +// */ +// public String getAttributeNamespace(String name) { +// XMLAttribute attr = this.findAttribute(name); +// if (attr == null) { +// return null; +// } else { +// return attr.getNamespace(); +// } +// } + + +// /** +// * Returns the type of an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI, which may be null. +// * +// * @return the type, or null if the attribute does not exist. +// */ +// public String getAttributeType(String name, +// String namespace) { +// XMLAttribute attr = this.findAttribute(name, namespace); +// if (attr == null) { +// return null; +// } else { +// return attr.getType(); +// } +// } + + +// /** +// * @deprecated use set() +// */ +// public void setAttribute(String name, String value) { +// set(name, value); +// } + + + /** + * Sets an attribute. + * + * @param name the non-null full name of the attribute. + * @param value the non-null value of the attribute. + */ + public void setString(String name, String value) { + XMLAttribute attr = this.findAttribute(name); + if (attr == null) { + attr = new XMLAttribute(name, name, null, value, "CDATA"); + this.attributes.addElement(attr); + } else { + attr.setValue(value); + } + } + + + public void setBoolean(String name, boolean value) { + setString(name, String.valueOf(value)); + } + + + public void setInt(String name, int value) { + setString(name, String.valueOf(value)); + } + + + public void setFloat(String name, float value) { + setString(name, String.valueOf(value)); + } + + + public void setDouble(String name, double value) { + setString(name, String.valueOf(value)); + } + + +// /** +// * Sets an attribute. +// * +// * @param fullName the non-null full name of the attribute. +// * @param namespace the namespace URI of the attribute, which may be null. +// * @param value the non-null value of the attribute. +// */ +// public void setAttribute(String fullName, +// String namespace, +// String value) { +// int index = fullName.indexOf(':'); +// String vorname = fullName.substring(index + 1); +// XMLAttribute attr = this.findAttribute(vorname, namespace); +// if (attr == null) { +// attr = new XMLAttribute(fullName, vorname, namespace, value, "CDATA"); +// this.attributes.addElement(attr); +// } else { +// attr.setValue(value); +// } +// } + + + /** + * Removes an attribute. Formerly removeAttribute(). + * + * @param name the non-null name of the attribute. + */ + public void remove(String name) { + for (int i = 0; i < this.attributes.size(); i++) { + XMLAttribute attr = (XMLAttribute) this.attributes.elementAt(i); + if (attr.getName().equals(name)) { + this.attributes.removeElementAt(i); + return; + } + } + } + + +// /** +// * Removes an attribute. +// * +// * @param name the non-null name of the attribute. +// * @param namespace the namespace URI of the attribute, which may be null. +// */ +// public void removeAttribute(String name, +// String namespace) { +// for (int i = 0; i < this.attributes.size(); i++) { +// XMLAttribute attr = (XMLAttribute) this.attributes.elementAt(i); +// boolean found = attr.getName().equals(name); +// if (namespace == null) { +// found &= (attr.getNamespace() == null); +// } else { +// found &= attr.getNamespace().equals(namespace); +// } +// +// if (found) { +// this.attributes.removeElementAt(i); +// return; +// } +// } +// } + + +// /** +// * Returns an enumeration of all attribute names. +// * +// * @return the non-null enumeration. +// */ +// public Enumeration enumerateAttributeNames() { +// Vector result = new Vector(); +// Enumeration en = this.attributes.elements(); +// while (en.hasMoreElements()) { +// XMLAttribute attr = (XMLAttribute) en.nextElement(); +// result.addElement(attr.getFullName()); +// } +// return result.elements(); +// } + + + /** + * Returns whether an attribute exists. + * + * @return true if the attribute exists. + */ + public boolean hasAttribute(String name) { + return this.findAttribute(name) != null; + } + + +// /** +// * Returns whether an attribute exists. +// * +// * @return true if the attribute exists. +// */ +// public boolean hasAttribute(String name, +// String namespace) { +// return this.findAttribute(name, namespace) != null; +// } + + +// /** +// * Returns all attributes as a Properties object. +// * +// * @return the non-null set. +// */ +// public Properties getAttributes() { +// Properties result = new Properties(); +// Enumeration en = this.attributes.elements(); +// while (en.hasMoreElements()) { +// XMLAttribute attr = (XMLAttribute) en.nextElement(); +// result.put(attr.getFullName(), attr.getValue()); +// } +// return result; +// } + + +// /** +// * Returns all attributes in a specific namespace as a Properties object. +// * +// * @param namespace the namespace URI of the attributes, which may be null. +// * +// * @return the non-null set. +// */ +// public Properties getAttributesInNamespace(String namespace) { +// Properties result = new Properties(); +// Enumeration en = this.attributes.elements(); +// while (en.hasMoreElements()) { +// XMLAttribute attr = (XMLAttribute) en.nextElement(); +// if (namespace == null) { +// if (attr.getNamespace() == null) { +// result.put(attr.getName(), attr.getValue()); +// } +// } else { +// if (namespace.equals(attr.getNamespace())) { +// result.put(attr.getName(), attr.getValue()); +// } +// } +// } +// return result; +// } + + + /** + * Returns the system ID of the data where the element started. + * + * @return the system ID, or null if unknown. + * + * @see #getLineNr + */ + public String getSystemID() { + return this.systemID; + } + + + /** + * Returns the line number in the data where the element started. + * + * @return the line number, or NO_LINE if unknown. + * + * @see #NO_LINE + * @see #getSystemID + */ + public int getLine() { + return this.line; + } + + + /** + * Returns the content of an element. If there is no such content, null is returned. + * =advanced + * Return the #PCDATA content of the element. If the element has a + * combination of #PCDATA content and child elements, the #PCDATA + * sections can be retrieved as unnamed child objects. In this case, + * this method returns null. + * + * @webref + * @brief Returns the content of an element + * @return the content. + */ + public String getContent() { + return this.content; + } + + + /** + * Sets the #PCDATA content. It is an error to call this method with a + * non-null value if there are child objects. + * + * @param content the (possibly null) content. + */ + public void setContent(String content) { + this.content = content; + } + + + /** + * Returns true if the element equals another element. + * + * @param rawElement the element to compare to + */ + public boolean equals(Object object) { + if (!(object instanceof XMLElement)) { + return false; + } + XMLElement rawElement = (XMLElement) object; + + if (! this.name.equals(rawElement.getLocalName())) { + return false; + } + if (this.attributes.size() != rawElement.getAttributeCount()) { + return false; + } + Enumeration en = this.attributes.elements(); + while (en.hasMoreElements()) { + XMLAttribute attr = (XMLAttribute) en.nextElement(); + // if (! rawElement.hasAttribute(attr.getName(), attr.getNamespace())) { + if (!rawElement.hasAttribute(attr.getName())) { + return false; + } + // String value = rawElement.getAttribute(attr.getName(), + // attr.getNamespace(), + // null); + String value = rawElement.getString(attr.getName(), null); + if (! attr.getValue().equals(value)) { + return false; + } + // String type = + // rawElement.getAttributeType(attr.getName(), attr.getNamespace()); + // if (!attr.getType().equals(type)) { + // return false; + // } + } + if (this.children.size() != rawElement.getChildCount()) { + return false; + } + for (int i = 0; i < this.children.size(); i++) { + XMLElement child1 = this.getChild(i); + XMLElement child2 = rawElement.getChild(i); + + if (!child1.equals(child2)) { + return false; + } + } + return true; + } + +// /** +// * Returns true if the element equals another element. +// * +// * @param rawElement the element to compare to +// */ +// public boolean equals(Object rawElement) { +// if (!(rawElement instanceof XMLElement)) { +// return false; +// } +// try { +// return this.equalsXMLElement((XMLElement) rawElement); +// } catch (ClassCastException e) { +// return false; +// } +// } + + +// /** +// * Returns true if the element equals another element. +// * +// * @param rawElement the element to compare to +// */ +// public boolean equalsXMLElement(XMLElement rawElement) { +// if (! this.name.equals(rawElement.getLocalName())) { +// return false; +// } +// if (this.attributes.size() != rawElement.getAttributeCount()) { +// return false; +// } +// Enumeration en = this.attributes.elements(); +// while (en.hasMoreElements()) { +// XMLAttribute attr = (XMLAttribute) en.nextElement(); +//// if (! rawElement.hasAttribute(attr.getName(), attr.getNamespace())) { +// if (!rawElement.hasAttribute(attr.getFullName())) { +// return false; +// } +//// String value = rawElement.getAttribute(attr.getName(), +//// attr.getNamespace(), +//// null); +// String value = rawElement.getAttribute(attr.getFullName(), null); +// if (! attr.getValue().equals(value)) { +// return false; +// } +//// String type = +//// rawElement.getAttributeType(attr.getName(), attr.getNamespace()); +//// if (!attr.getType().equals(type)) { +//// return false; +//// } +// } +// if (this.children.size() != rawElement.getChildCount()) { +// return false; +// } +// for (int i = 0; i < this.children.size(); i++) { +// XMLElement child1 = this.getChildAtIndex(i); +// XMLElement child2 = rawElement.getChildAtIndex(i); +// +// if (! child1.equalsXMLElement(child2)) { +// return false; +// } +// } +// return true; +// } + + + public String toString() { + return toString(true); + } + + + public String toString(boolean pretty) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(baos); + XMLWriter writer = new XMLWriter(osw); + try { + writer.write(this, pretty); + } catch (IOException e) { + e.printStackTrace(); + } + return baos.toString(); + } + + + private PApplet findSketch() { + if (sketch != null) { + return sketch; + } + if (parent != null) { + return parent.findSketch(); + } + return null; + } + + + public boolean save(String filename) { + if (sketch == null) { + sketch = findSketch(); + } + if (sketch == null) { + System.err.println("save() can only be used on elements loaded by a sketch"); + throw new RuntimeException("no sketch found, use write(PrintWriter) instead."); + } + return write(sketch.createWriter(filename)); + } + + + public boolean write(PrintWriter writer) { + writer.println(XMLWriter.HEADER); + XMLWriter xmlw = new XMLWriter(writer); + try { + xmlw.write(this, true); + writer.flush(); + return true; + + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/support/Processing_core_src/processing/xml/XMLEntityResolver.java b/support/Processing_core_src/processing/xml/XMLEntityResolver.java new file mode 100644 index 0000000..f12c4c0 --- /dev/null +++ b/support/Processing_core_src/processing/xml/XMLEntityResolver.java @@ -0,0 +1,173 @@ +/* XMLEntityResolver.java NanoXML/Java + * + * $Revision: 1.4 $ + * $Date: 2002/01/04 21:03:29 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.util.Hashtable; +import java.io.Reader; +import java.io.StringReader; + + +/** + * An XMLEntityResolver resolves entities. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.4 $ + */ +public class XMLEntityResolver +{ + + /** + * The entities. + */ + private Hashtable entities; + + + /** + * Initializes the resolver. + */ + public XMLEntityResolver() + { + this.entities = new Hashtable(); + this.entities.put("amp", "&"); + this.entities.put("quot", """); + this.entities.put("apos", "'"); + this.entities.put("lt", "<"); + this.entities.put("gt", ">"); + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.entities.clear(); + this.entities = null; + super.finalize(); + } + + + /** + * Adds an internal entity. + * + * @param name the name of the entity. + * @param value the value of the entity. + */ + public void addInternalEntity(String name, + String value) + { + if (! this.entities.containsKey(name)) { + this.entities.put(name, value); + } + } + + + /** + * Adds an external entity. + * + * @param name the name of the entity. + * @param publicID the public ID of the entity, which may be null. + * @param systemID the system ID of the entity. + */ + public void addExternalEntity(String name, + String publicID, + String systemID) + { + if (! this.entities.containsKey(name)) { + this.entities.put(name, new String[] { publicID, systemID } ); + } + } + + + /** + * Returns a Java reader containing the value of an entity. + * + * @param xmlReader the current XML reader + * @param name the name of the entity. + * + * @return the reader, or null if the entity could not be resolved. + */ + public Reader getEntity(StdXMLReader xmlReader, + String name) + throws XMLParseException + { + Object obj = this.entities.get(name); + + if (obj == null) { + return null; + } else if (obj instanceof java.lang.String) { + return new StringReader((String)obj); + } else { + String[] id = (String[]) obj; + return this.openExternalEntity(xmlReader, id[0], id[1]); + } + } + + + /** + * Returns true if an entity is external. + * + * @param name the name of the entity. + */ + public boolean isExternalEntity(String name) + { + Object obj = this.entities.get(name); + return ! (obj instanceof java.lang.String); + } + + + /** + * Opens an external entity. + * + * @param xmlReader the current XML reader + * @param publicID the public ID, which may be null + * @param systemID the system ID + * + * @return the reader, or null if the reader could not be created/opened + */ + protected Reader openExternalEntity(StdXMLReader xmlReader, + String publicID, + String systemID) + throws XMLParseException + { + String parentSystemID = xmlReader.getSystemID(); + + try { + return xmlReader.openStream(publicID, systemID); + } catch (Exception e) { + throw new XMLParseException(parentSystemID, + xmlReader.getLineNr(), + "Could not open external entity " + + "at system ID: " + systemID); + } + } + +} diff --git a/support/Processing_core_src/processing/xml/XMLException.java b/support/Processing_core_src/processing/xml/XMLException.java new file mode 100644 index 0000000..8515d48 --- /dev/null +++ b/support/Processing_core_src/processing/xml/XMLException.java @@ -0,0 +1,286 @@ +/* XMLException.java NanoXML/Java + * + * $Revision: 1.4 $ + * $Date: 2002/01/04 21:03:29 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + +import java.io.PrintStream; +import java.io.PrintWriter; + + +/** + * An XMLException is thrown when an exception occurred while processing the + * XML data. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.4 $ + */ +public class XMLException + extends Exception +{ + + /** + * The message of the exception. + */ + private String msg; + + + /** + * The system ID of the XML data where the exception occurred. + */ + private String systemID; + + + /** + * The line number in the XML data where the exception occurred. + */ + private int lineNr; + + + /** + * Encapsulated exception. + */ + private Exception encapsulatedException; + + + /** + * Creates a new exception. + * + * @param msg the message of the exception. + */ + public XMLException(String msg) + { + this(null, -1, null, msg, false); + } + + + /** + * Creates a new exception. + * + * @param e the encapsulated exception. + */ + public XMLException(Exception e) + { + this(null, -1, e, "Nested Exception", false); + } + + + /** + * Creates a new exception. + * + * @param systemID the system ID of the XML data where the exception + * occurred + * @param lineNr the line number in the XML data where the exception + * occurred. + * @param e the encapsulated exception. + */ + public XMLException(String systemID, + int lineNr, + Exception e) + { + this(systemID, lineNr, e, "Nested Exception", true); + } + + + /** + * Creates a new exception. + * + * @param systemID the system ID of the XML data where the exception + * occurred + * @param lineNr the line number in the XML data where the exception + * occurred. + * @param msg the message of the exception. + */ + public XMLException(String systemID, + int lineNr, + String msg) + { + this(systemID, lineNr, null, msg, true); + } + + + /** + * Creates a new exception. + * + * @param systemID the system ID from where the data came + * @param lineNr the line number in the XML data where the exception + * occurred. + * @param e the encapsulated exception. + * @param msg the message of the exception. + * @param reportParams true if the systemID, lineNr and e params need to be + * appended to the message + */ + public XMLException(String systemID, + int lineNr, + Exception e, + String msg, + boolean reportParams) + { + super(XMLException.buildMessage(systemID, lineNr, e, msg, + reportParams)); + this.systemID = systemID; + this.lineNr = lineNr; + this.encapsulatedException = e; + this.msg = XMLException.buildMessage(systemID, lineNr, e, msg, + reportParams); + } + + + /** + * Builds the exception message + * + * @param systemID the system ID from where the data came + * @param lineNr the line number in the XML data where the exception + * occurred. + * @param e the encapsulated exception. + * @param msg the message of the exception. + * @param reportParams true if the systemID, lineNr and e params need to be + * appended to the message + */ + private static String buildMessage(String systemID, + int lineNr, + Exception e, + String msg, + boolean reportParams) + { + String str = msg; + + if (reportParams) { + if (systemID != null) { + str += ", SystemID='" + systemID + "'"; + } + + if (lineNr >= 0) { + str += ", Line=" + lineNr; + } + + if (e != null) { + str += ", Exception: " + e; + } + } + + return str; + } + + + /** + * Cleans up the object when it's destroyed. + */ + protected void finalize() + throws Throwable + { + this.systemID = null; + this.encapsulatedException = null; + super.finalize(); + } + + + /** + * Returns the system ID of the XML data where the exception occurred. + * If there is no system ID known, null is returned. + */ + public String getSystemID() + { + return this.systemID; + } + + + /** + * Returns the line number in the XML data where the exception occurred. + * If there is no line number known, -1 is returned. + */ + public int getLineNr() + { + return this.lineNr; + } + + + /** + * Returns the encapsulated exception, or null if no exception is + * encapsulated. + */ + public Exception getException() + { + return this.encapsulatedException; + } + + + /** + * Dumps the exception stack to a print writer. + * + * @param writer the print writer + */ + public void printStackTrace(PrintWriter writer) + { + super.printStackTrace(writer); + + if (this.encapsulatedException != null) { + writer.println("*** Nested Exception:"); + this.encapsulatedException.printStackTrace(writer); + } + } + + + /** + * Dumps the exception stack to an output stream. + * + * @param stream the output stream + */ + public void printStackTrace(PrintStream stream) + { + super.printStackTrace(stream); + + if (this.encapsulatedException != null) { + stream.println("*** Nested Exception:"); + this.encapsulatedException.printStackTrace(stream); + } + } + + + /** + * Dumps the exception stack to System.err. + */ + public void printStackTrace() + { + super.printStackTrace(); + + if (this.encapsulatedException != null) { + System.err.println("*** Nested Exception:"); + this.encapsulatedException.printStackTrace(); + } + } + + + /** + * Returns a string representation of the exception. + */ + public String toString() + { + return this.msg; + } + +} diff --git a/support/Processing_core_src/processing/xml/XMLParseException.java b/support/Processing_core_src/processing/xml/XMLParseException.java new file mode 100644 index 0000000..aa7915d --- /dev/null +++ b/support/Processing_core_src/processing/xml/XMLParseException.java @@ -0,0 +1,69 @@ +/* XMLParseException.java NanoXML/Java + * + * $Revision: 1.3 $ + * $Date: 2002/01/04 21:03:29 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +/** + * An XMLParseException is thrown when the XML passed to the XML parser is not + * well-formed. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.3 $ + */ +public class XMLParseException + extends XMLException +{ + + /** + * Creates a new exception. + * + * @param msg the message of the exception. + */ + public XMLParseException(String msg) + { + super(msg); + } + + + /** + * Creates a new exception. + * + * @param systemID the system ID from where the data came + * @param lineNr the line number in the XML data where the exception + * occurred. + * @param msg the message of the exception. + */ + public XMLParseException(String systemID, + int lineNr, + String msg) + { + super(systemID, lineNr, null, msg, true); + } + +} diff --git a/support/Processing_core_src/processing/xml/XMLUtil.java b/support/Processing_core_src/processing/xml/XMLUtil.java new file mode 100644 index 0000000..6adad79 --- /dev/null +++ b/support/Processing_core_src/processing/xml/XMLUtil.java @@ -0,0 +1,758 @@ +/* XMLUtil.java NanoXML/Java + * + * $Revision: 1.5 $ + * $Date: 2002/02/03 21:19:38 $ + * $Name: RELEASE_2_2_1 $ + * + * This file is part of NanoXML 2 for Java. + * Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved. + * + * This software is provided 'as-is', without any express or implied warranty. + * In no event will the authors be held liable for any damages arising from the + * use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software in + * a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source distribution. + */ + +package processing.xml; + + +import java.io.IOException; +import java.io.Reader; + + +/** + * Utility methods for NanoXML. + * + * @author Marc De Scheemaecker + * @version $Name: RELEASE_2_2_1 $, $Revision: 1.5 $ + */ +class XMLUtil +{ + + /** + * Skips the remainder of a comment. + * It is assumed that <!- is already read. + * + * @param reader the reader + * + * @throws java.io.IOException + * if an error occurred reading the data + */ + static void skipComment(StdXMLReader reader) + throws IOException, + XMLParseException + { + if (reader.read() != '-') { + XMLUtil.errorExpectedInput(reader.getSystemID(), + reader.getLineNr(), + "