From 34579ae440a7bf68ea5ef962b8793b7607589b70 Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Wed, 21 Apr 2010 01:58:57 +0000 Subject: [PATCH] Initial sync with Processing 6406. Compiles and runs (on Mac OS X) but probably very buggy. --- app/src/processing/app/Base.java | 252 +- app/src/processing/app/Editor.java | 432 +- app/src/processing/app/EditorConsole.java | 20 +- app/src/processing/app/EditorListener.java | 11 + app/src/processing/app/EditorToolbar.java | 220 +- app/src/processing/app/Platform.java | 33 + app/src/processing/app/Preferences.java | 5 + app/src/processing/app/Sketch.java | 229 +- .../processing/app/StreamRedirectThread.java | 95 + app/src/processing/app/WebServer.java | 8 +- ...tThread.java => EventThread.java.disabled} | 5 +- .../processing/app/debug/MessageSiphon.java | 7 +- .../{Runner.java => Runner.java.disabled} | 604 +- .../processing/app/debug/RunnerException.java | 10 +- .../processing/app/debug/RunnerListener.java | 2 + app/src/processing/app/linux/Platform.java | 15 +- app/src/processing/app/macosx/Platform.java | 62 +- .../processing/app/macosx/ThinkDifferent.java | 3 +- .../app/preproc/PdePreprocessor.java | 108 +- .../processing/app/syntax/InputHandler.java | 36 +- .../processing/app/syntax/JEditTextArea.java | 15 +- .../app/syntax/PdeTextAreaDefaults.java | 29 +- .../app/syntax/TextAreaPainter.java | 28 +- .../app/syntax/im/CompositionTextManager.java | 187 + .../app/syntax/im/CompositionTextPainter.java | 124 + .../app/syntax/im/InputMethodSupport.java | 105 + .../processing/app/tools/ColorSelector.java | 27 +- app/src/processing/app/tools/CreateFont.java | 582 +- app/src/processing/app/windows/Platform.java | 39 +- build/macosx/make.sh | 1 + build/shared/lib/preferences.txt | 32 +- core/.project | 34 +- core/.settings/org.eclipse.jdt.core.prefs | 532 +- core/.settings/org.eclipse.jdt.ui.prefs | 4 +- core/build.xml | 26 + core/done.txt | 55 + core/methods/.classpath | 7 + core/methods/.project | 17 + core/methods/build.xml | 28 + core/methods/demo/PApplet.java | 9483 +++++++++++++++++ core/methods/demo/PGraphics.java | 5075 +++++++++ core/methods/demo/PImage.java | 2862 +++++ core/methods/methods.jar | Bin 0 -> 3725 bytes core/methods/src/PAppletMethods.java | 272 + core/src/processing/core/PApplet.java | 689 +- core/src/processing/core/PConstants.java | 45 +- core/src/processing/core/PFont.java | 938 +- core/src/processing/core/PGraphics.java | 964 +- core/src/processing/core/PGraphics3D.java | 45 +- core/src/processing/core/PGraphicsJava2D.java | 10 + core/src/processing/core/PImage.java | 278 +- core/src/processing/core/PPolygon.java | 2 +- core/src/processing/core/PShape.java | 145 +- core/src/processing/core/PShapeSVG.java | 6 +- core/src/processing/core/PVector.java | 4 +- core/src/processing/xml/XMLElement.java | 122 +- core/todo.txt | 162 +- 57 files changed, 22913 insertions(+), 2218 deletions(-) create mode 100644 app/src/processing/app/StreamRedirectThread.java rename app/src/processing/app/debug/{EventThread.java => EventThread.java.disabled} (98%) rename app/src/processing/app/debug/{Runner.java => Runner.java.disabled} (52%) create mode 100644 app/src/processing/app/syntax/im/CompositionTextManager.java create mode 100644 app/src/processing/app/syntax/im/CompositionTextPainter.java create mode 100644 app/src/processing/app/syntax/im/InputMethodSupport.java create mode 100644 core/build.xml create mode 100644 core/methods/.classpath create mode 100644 core/methods/.project create mode 100644 core/methods/build.xml create mode 100644 core/methods/demo/PApplet.java create mode 100644 core/methods/demo/PGraphics.java create mode 100644 core/methods/demo/PImage.java create mode 100644 core/methods/methods.jar create mode 100644 core/methods/src/PAppletMethods.java diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java index 0c62a8b32..e2a92b819 100644 --- a/app/src/processing/app/Base.java +++ b/app/src/processing/app/Base.java @@ -3,7 +3,7 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2004-09 Ben Fry and Casey Reas + Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify @@ -42,7 +42,10 @@ import processing.core.*; */ public class Base { public static final int REVISION = 18; + /** This might be replaced by main() if there's a lib/version.txt file. */ static String VERSION_NAME = "0018"; + /** Set true if this a proper release rather than a numbered revision. */ + static public boolean RELEASE = false; static HashMap platformNames = new HashMap(); static { @@ -101,31 +104,16 @@ public class Base { // ArrayList editors = Collections.synchronizedList(new ArrayList()); Editor activeEditor; -// int nextEditorX; -// int nextEditorY; - -// import com.sun.jna.Library; -// import com.sun.jna.Native; - -// public interface CLibrary extends Library { -// CLibrary INSTANCE = (CLibrary)Native.loadLibrary("c", CLibrary.class); -// int setenv(String name, String value, int overwrite); -// String getenv(String name); -// int unsetenv(String name); -// int putenv(String string); -// } - static public void main(String args[]) { -// /Users/fry/coconut/sketchbook/libraries/gsvideo/library -// CLibrary clib = CLibrary.INSTANCE; -// clib.setenv("DYLD_LIBRARY_PATH", "/Users/fry/coconut/sketchbook/libraries/gsvideo/library", 1); -// System.out.println("env is now " + clib.getenv("DYLD_LIBRARY_PATH")); - try { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { - VERSION_NAME = PApplet.loadStrings(versionFile)[0]; + String version = PApplet.loadStrings(versionFile)[0]; + if (!version.equals(VERSION_NAME)) { + VERSION_NAME = version; + RELEASE = true; + } } } catch (Exception e) { e.printStackTrace(); @@ -187,10 +175,12 @@ public class Base { try { platform.setLookAndFeel(); } catch (Exception e) { - System.err.println("Non-fatal error while setting the Look & Feel."); - System.err.println("The error message follows, however Arduino should run fine."); - System.err.println(e.getMessage()); - //e.printStackTrace(); + String mess = e.getMessage(); + if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) { + System.err.println("Non-fatal error while setting the Look & Feel."); + System.err.println("The error message follows, however Arduino should run fine."); + System.err.println(mess); + } } // Create a location for untitled sketches @@ -213,7 +203,7 @@ public class Base { static protected void initPlatform() { try { - Class platformClass = Class.forName("processing.app.Platform"); + Class platformClass = Class.forName("processing.app.Platform"); if (Base.isMacOS()) { platformClass = Class.forName("processing.app.macosx.Platform"); } else if (Base.isWindows()) { @@ -270,7 +260,7 @@ public class Base { } } - // If not path is set, get the default sketchbook folder for this platform + // If no path is set, get the default sketchbook folder for this platform if (sketchbookPath == null) { File defaultFolder = getDefaultSketchbookFolder(); Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath()); @@ -456,8 +446,8 @@ public class Base { protected int[] nextEditorLocation() { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - int defaultWidth = Preferences.getInteger("default.window.width"); - int defaultHeight = Preferences.getInteger("default.window.height"); + int defaultWidth = Preferences.getInteger("editor.window.width.default"); + int defaultHeight = Preferences.getInteger("editor.window.height.default"); if (activeEditor == null) { // If no current active editor, use default placement @@ -584,7 +574,7 @@ public class Base { * Replace the sketch in the current window with a new untitled document. */ public void handleNewReplace() { - if (!activeEditor.checkModified(true)) { + if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches @@ -616,7 +606,7 @@ public class Base { * @param path Location of the primary pde file for the sketch. */ public void handleOpenReplace(String path) { - if (!activeEditor.checkModified(true)) { + if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches @@ -758,8 +748,8 @@ public class Base { */ public boolean handleClose(Editor editor) { // Check if modified - boolean immediate = editors.size() == 1; - if (!editor.checkModified(immediate)) { +// boolean immediate = editors.size() == 1; + if (!editor.checkModified()) { return false; } @@ -862,7 +852,7 @@ public class Base { protected boolean handleQuitEach() { int index = 0; for (Editor editor : editors) { - if (editor.checkModified(true)) { + if (editor.checkModified()) { // Update to the new/final sketch path for this fella storeSketchPath(editor, index); index++; @@ -914,7 +904,8 @@ public class Base { // Add a list of all sketches and subfolders try { - boolean sketches = addSketches(menu, getSketchbookFolder(), true); + //boolean sketches = addSketches(menu, getSketchbookFolder(), true); + boolean sketches = addSketches(menu, getSketchbookFolder()); if (sketches) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); @@ -923,11 +914,11 @@ public class Base { //System.out.println("rebuilding examples menu"); // Add each of the subfolders of examples directly to the menu try { - boolean found = addSketches(menu, examplesFolder, true); + boolean found = addSketches(menu, examplesFolder); if (found) menu.addSeparator(); - found = addSketches(menu, getSketchbookLibrariesFolder(), true); + found = addSketches(menu, getSketchbookLibrariesFolder()); if (found) menu.addSeparator(); - addSketches(menu, librariesFolder, true); + addSketches(menu, librariesFolder); } catch (IOException e) { e.printStackTrace(); } @@ -939,7 +930,8 @@ public class Base { //new Exception().printStackTrace(); try { menu.removeAll(); - addSketches(menu, getSketchbookFolder(), false); + //addSketches(menu, getSketchbookFolder(), false); + addSketches(menu, getSketchbookFolder()); } catch (IOException e) { e.printStackTrace(); } @@ -983,11 +975,11 @@ public class Base { //System.out.println("rebuilding examples menu"); try { menu.removeAll(); - boolean found = addSketches(menu, examplesFolder, false); + boolean found = addSketches(menu, examplesFolder); if (found) menu.addSeparator(); - found = addSketches(menu, getSketchbookLibrariesFolder(), false); + found = addSketches(menu, getSketchbookLibrariesFolder()); if (found) menu.addSeparator(); - addSketches(menu, librariesFolder, false); + addSketches(menu, librariesFolder); } catch (IOException e) { e.printStackTrace(); } @@ -1050,8 +1042,7 @@ public class Base { * should replace the sketch in the current window, or false when the * sketch should open in a new window. */ - protected boolean addSketches(JMenu menu, File folder, - final boolean openReplaces) throws IOException { + protected boolean addSketches(JMenu menu, File folder) throws IOException { // skip .DS_Store files, etc (this shouldn't actually be necessary) if (!folder.isDirectory()) return false; @@ -1068,7 +1059,8 @@ public class Base { public void actionPerformed(ActionEvent e) { String path = e.getActionCommand(); if (new File(path).exists()) { - if (openReplaces) { +// if (openReplaces) { + if ((e.getModifiers() & ActionEvent.SHIFT_MASK) == 0) { handleOpenReplace(path); } else { handleOpen(path); @@ -1121,14 +1113,15 @@ public class Base { } else { // don't create an extra menu level for a folder named "examples" if (subfolder.getName().equals("examples")) { - boolean found = addSketches(menu, subfolder, openReplaces); //, false); + boolean found = addSketches(menu, subfolder); if (found) ifound = true; } else { // not a sketch folder, but maybe a subfolder containing sketches JMenu submenu = new JMenu(list[i]); // needs to be separate var // otherwise would set ifound to false - boolean found = addSketches(submenu, subfolder, openReplaces); //, false); + //boolean found = addSketches(submenu, subfolder, openReplaces); //, false); + boolean found = addSketches(submenu, subfolder); //, false); if (found) { menu.add(submenu); ifound = true; @@ -1319,6 +1312,11 @@ public class Base { // } + static public Platform getPlatform() { + return platform; + } + + static public String getPlatformName() { String osname = System.getProperty("os.name"); @@ -1714,12 +1712,11 @@ public class Base { } */ - /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ - static public void registerWindowCloseKeys(JRootPane root, //Window window, + static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, @@ -1836,6 +1833,129 @@ public class Base { // ................................................................... + + // incomplete + static public int showYesNoCancelQuestion(Editor editor, String title, + String primary, String secondary) { + if (!Base.isMacOS()) { + int result = + JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title, + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); + return result; +// if (result == JOptionPane.YES_OPTION) { +// +// } else if (result == JOptionPane.NO_OPTION) { +// return true; // ok to continue +// +// } else if (result == JOptionPane.CANCEL_OPTION) { +// return false; +// +// } else { +// throw new IllegalStateException(); +// } + + } else { + // Pane formatting adapted from the Quaqua guide + // http://www.randelshofer.ch/quaqua/guide/joptionpane.html + JOptionPane pane = + new JOptionPane(" " + + " " + + "Do you want to save changes to this sketch
" + + " before closing?
" + + "

If you don't save, your changes will be lost.", + JOptionPane.QUESTION_MESSAGE); + + String[] options = new String[] { + "Save", "Cancel", "Don't Save" + }; + pane.setOptions(options); + + // highlight the safest option ala apple hig + pane.setInitialValue(options[0]); + + // on macosx, setting the destructive property places this option + // away from the others at the lefthand side + pane.putClientProperty("Quaqua.OptionPane.destructiveOption", + new Integer(2)); + + JDialog dialog = pane.createDialog(editor, null); + dialog.setVisible(true); + + Object result = pane.getValue(); + if (result == options[0]) { + return JOptionPane.YES_OPTION; + } else if (result == options[1]) { + return JOptionPane.CANCEL_OPTION; + } else if (result == options[2]) { + return JOptionPane.NO_OPTION; + } else { + return JOptionPane.CLOSED_OPTION; + } + } + } + + +//if (result == JOptionPane.YES_OPTION) { + // +// } else if (result == JOptionPane.NO_OPTION) { +// return true; // ok to continue + // +// } else if (result == JOptionPane.CANCEL_OPTION) { +// return false; + // +// } else { +// throw new IllegalStateException(); +// } + + static public int showYesNoQuestion(Frame editor, String title, + String primary, String secondary) { + if (!Base.isMacOS()) { + return JOptionPane.showConfirmDialog(editor, + "" + + "" + primary + "" + + "
" + secondary, title, + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + } else { + // Pane formatting adapted from the Quaqua guide + // http://www.randelshofer.ch/quaqua/guide/joptionpane.html + JOptionPane pane = + new JOptionPane(" " + + " " + + "" + primary + "" + + "

" + secondary + "

", + JOptionPane.QUESTION_MESSAGE); + + String[] options = new String[] { + "Yes", "No" + }; + pane.setOptions(options); + + // highlight the safest option ala apple hig + pane.setInitialValue(options[0]); + + JDialog dialog = pane.createDialog(editor, null); + dialog.setVisible(true); + + Object result = pane.getValue(); + if (result == options[0]) { + return JOptionPane.YES_OPTION; + } else if (result == options[1]) { + return JOptionPane.NO_OPTION; + } else { + return JOptionPane.CLOSED_OPTION; + } + } + } + + /** * Retrieve a path to something in the Processing folder. Eventually this * may refer to the Contents subfolder of Processing.app, if we bundle things @@ -1959,6 +2079,36 @@ public class Base { } + + /** + * Read from a file with a bunch of attribute/value pairs + * that are separated by = and ignore comments with #. + */ + static public HashMap readSettings(File inputFile) { + HashMap outgoing = new HashMap(); + if (!inputFile.exists()) return outgoing; // return empty hash + + String lines[] = PApplet.loadStrings(inputFile); + for (int i = 0; i < lines.length; i++) { + int hash = lines[i].indexOf('#'); + String line = (hash == -1) ? + lines[i].trim() : lines[i].substring(0, hash).trim(); + if (line.length() == 0) continue; + + int equals = line.indexOf('='); + if (equals == -1) { + System.err.println("ignoring illegal line in " + inputFile); + System.err.println(" " + line); + continue; + } + String attr = line.substring(0, equals).trim(); + String valu = line.substring(equals + 1).trim(); + outgoing.put(attr, valu); + } + return outgoing; + } + + static public void copyFile(File sourceFile, File targetFile) throws IOException { InputStream from = @@ -2116,7 +2266,7 @@ public class Base { static public String[] listFiles(File folder, boolean relative) { String path = folder.getAbsolutePath(); - Vector vector = new Vector(); + Vector vector = new Vector(); listFiles(relative ? (path + File.separator) : "", path, vector); String outgoing[] = new String[vector.size()]; vector.copyInto(outgoing); @@ -2125,7 +2275,7 @@ public class Base { static protected void listFiles(String basePath, - String path, Vector vector) { + String path, Vector vector) { File folder = new File(path); String list[] = folder.list(); if (list == null) return; diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java index 30ceb6b2b..831f02f80 100644 --- a/app/src/processing/app/Editor.java +++ b/app/src/processing/app/Editor.java @@ -43,7 +43,6 @@ import javax.swing.undo.*; import gnu.io.*; - /** * Main editor panel for the Processing Development Environment. */ @@ -114,7 +113,6 @@ public class Editor extends JFrame implements RunnerListener { EditorLineStatus lineStatus; - boolean newEditor = true; JEditorPane editorPane; JEditTextArea textarea; @@ -122,14 +120,14 @@ public class Editor extends JFrame implements RunnerListener { // runtime information and window placement Point sketchWindowLocation; - Runner runtime; + //Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; boolean running; - boolean presenting; + //boolean presenting; boolean uploading; // undo fellers @@ -142,6 +140,12 @@ public class Editor extends JFrame implements RunnerListener { FindReplace find; + Runnable runHandler; + Runnable presentHandler; + Runnable stopHandler; + Runnable exportHandler; + Runnable exportAppHandler; + public Editor(Base ibase, String path, int[] location) { super("Arduino"); @@ -149,6 +153,9 @@ public class Editor extends JFrame implements RunnerListener { //Base.setIcon(this); + // Install default actions for Run, Present, etc. + resetHandlers(); + // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { @@ -232,22 +239,7 @@ public class Editor extends JFrame implements RunnerListener { lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); -// if (newEditor) { -// try { -// setupEditorPane(); -// upper.add(editorPane); -// } catch (Exception e1) { -// PrintWriter w = PApplet.createWriter(new File("/Users/fry/Desktop/blah.txt")); -// w.println(e1.getMessage()); -// e1.printStackTrace(w); -// w.flush(); -// w.close(); -//// e1.printStackTrace()); -//// e1.printStackTrace(System.out); -// } -// } else { upper.add(textarea); -// } splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); @@ -276,64 +268,10 @@ public class Editor extends JFrame implements RunnerListener { listener = new EditorListener(this, textarea); pain.add(box); - pain.setTransferHandler(new TransferHandler() { + // get shift down/up events so we can show the alt version of toolbar buttons + textarea.addKeyListener(toolbar); - public boolean canImport(JComponent dest, DataFlavor[] flavors) { - return true; - } - - public boolean importData(JComponent src, Transferable transferable) { - int successful = 0; - - try { - DataFlavor uriListFlavor = - new DataFlavor("text/uri-list;class=java.lang.String"); - - if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { - java.util.List list = (java.util.List) - transferable.getTransferData(DataFlavor.javaFileListFlavor); - for (int i = 0; i < list.size(); i++) { - File file = (File) list.get(i); - if (sketch.addFile(file)) { - successful++; - } - } - } else if (transferable.isDataFlavorSupported(uriListFlavor)) { - //System.out.println("uri list"); - String data = (String)transferable.getTransferData(uriListFlavor); - String[] pieces = PApplet.splitTokens(data, "\r\n"); - //PApplet.println(pieces); - for (int i = 0; i < pieces.length; i++) { - if (pieces[i].startsWith("#")) continue; - - String path = null; - if (pieces[i].startsWith("file:///")) { - path = pieces[i].substring(7); - } else if (pieces[i].startsWith("file:/")) { - path = pieces[i].substring(5); - } - if (sketch.addFile(new File(path))) { - successful++; - } - } - } - } catch (Exception e) { - e.printStackTrace(); - return false; - } - - if (successful == 0) { - statusError("No files were added to the sketch."); - - } else if (successful == 1) { - statusNotice("One file added to the sketch."); - - } else { - statusNotice(successful + " files added to the sketch."); - } - return true; - } - }); + pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); @@ -345,6 +283,20 @@ public class Editor extends JFrame implements RunnerListener { // Set the window bounds and the divider location before setting it visible setPlacement(location); + + // If the window is resized too small this will resize it again to the + // minimums. Adapted by Chris Lonnen from comments here: + // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4320050 + // as a fix for http://dev.processing.org/bugs/show_bug.cgi?id=25 + final int minW = Preferences.getInteger("editor.window.width.min"); + final int minH = Preferences.getInteger("editor.window.height.min"); + addComponentListener(new java.awt.event.ComponentAdapter() { + public void componentResized(ComponentEvent event) { + setSize((getWidth() < minW) ? minW : getWidth(), + (getHeight() < minH) ? minH : getHeight()); + } + }); + // System.out.println("t3"); // Bring back the general options for the editor @@ -363,46 +315,71 @@ public class Editor extends JFrame implements RunnerListener { } - /* - // http://wiki.netbeans.org/DevFaqEditorCodeCompletionAnyJEditorPane - void setupEditorPane() throws IOException { - editorPane = new JEditorPane(); + /** + * Handles files dragged & dropped from the desktop and into the editor + * window. Dragging files into the editor window is the same as using + * "Sketch → Add File" for each file. + */ + class FileDropHandler extends TransferHandler { + public boolean canImport(JComponent dest, DataFlavor[] flavors) { + return true; + } - // This will find the Java editor kit and associate it with - // our editor pane. But that does not give us code completion - // just yet because we have no Java context (i.e. no class path, etc.). - // However, this does give us syntax coloring. - EditorKit kit = CloneableEditorSupport.getEditorKit("text/x-java"); - editorPane.setEditorKit(kit); - - // You can specify any ".java" file. - // If the file does not exist, it will be created. - // The contents of the file does not matter. - // The extension must be ".java", however. -// String newSourcePath = "/Users/fry/Desktop/tmp.java"; + @SuppressWarnings("unchecked") + public boolean importData(JComponent src, Transferable transferable) { + int successful = 0; -// File tmpFile = new File(newSourcePath); -// System.out.println(tmpFile.getParent() + " " + tmpFile.getName()); -// FileObject fob = FileUtil.createData(tmpFile); - File tmpFile = File.createTempFile("temp", ".java"); - FileObject fob = FileUtil.toFileObject(FileUtil.normalizeFile(tmpFile)); + try { + DataFlavor uriListFlavor = + new DataFlavor("text/uri-list;class=java.lang.String"); - DataObject dob = DataObject.find(fob); - editorPane.getDocument().putProperty(Document.StreamDescriptionProperty, dob); + if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + java.util.List list = (java.util.List) + transferable.getTransferData(DataFlavor.javaFileListFlavor); + for (int i = 0; i < list.size(); i++) { + File file = (File) list.get(i); + if (sketch.addFile(file)) { + successful++; + } + } + } else if (transferable.isDataFlavorSupported(uriListFlavor)) { + // Some platforms (Mac OS X and Linux, when this began) preferred + // this method of moving files. + String data = (String)transferable.getTransferData(uriListFlavor); + String[] pieces = PApplet.splitTokens(data, "\r\n"); + for (int i = 0; i < pieces.length; i++) { + if (pieces[i].startsWith("#")) continue; - // This sets up a default class path for us so that - // we can find all the JDK classes via code completion. - DialogBinding.bindComponentToFile(fob, 0, 0, editorPane); + String path = null; + if (pieces[i].startsWith("file:///")) { + path = pieces[i].substring(7); + } else if (pieces[i].startsWith("file:/")) { + path = pieces[i].substring(5); + } + if (sketch.addFile(new File(path))) { + successful++; + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } - // Last but not least, we need to fill the editor pane with - // some initial dummy code - as it seems somehow required to - // kick-start code completion. - // A simple dummy package declaration will do. - editorPane.setText("package dummy;"); + if (successful == 0) { + statusError("No files were added to the sketch."); + + } else if (successful == 1) { + statusNotice("One file added to the sketch."); + + } else { + statusNotice(successful + " files added to the sketch."); + } + return true; + } } - */ - - + + protected void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { @@ -434,10 +411,10 @@ public class Editor extends JFrame implements RunnerListener { * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ - public Dimension getMinimumSize() { - //System.out.println("getting minimum size"); - return new Dimension(500, 550); - } +// public Dimension getMinimumSize() { +// //System.out.println("getting minimum size"); +// return new Dimension(500, 550); +// } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @@ -737,7 +714,7 @@ public class Editor extends JFrame implements RunnerListener { protected void addTools(JMenu menu, File sourceFolder) { - HashMap toolItems = new HashMap(); + HashMap toolItems = new HashMap(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { @@ -807,7 +784,7 @@ public class Editor extends JFrame implements RunnerListener { // If no class name found, just move on. if (className == null) continue; - Class toolClass = Class.forName(className, true, loader); + Class toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); @@ -817,6 +794,7 @@ public class Editor extends JFrame implements RunnerListener { item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); + //new Thread(tool).start(); } }); //menu.add(item); @@ -826,7 +804,7 @@ public class Editor extends JFrame implements RunnerListener { e.printStackTrace(); } } - ArrayList toolList = new ArrayList(toolItems.keySet()); + ArrayList toolList = new ArrayList(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); @@ -843,7 +821,7 @@ public class Editor extends JFrame implements RunnerListener { try { ZipFile zipFile = new ZipFile(file); - Enumeration entries = zipFile.entries(); + Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); @@ -869,7 +847,7 @@ public class Editor extends JFrame implements RunnerListener { protected JMenuItem createToolMenuItem(String className) { try { - Class toolClass = Class.forName(className); + Class toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); @@ -903,12 +881,14 @@ public class Editor extends JFrame implements RunnerListener { menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); - /* - //menu.add(createToolMenuItem("processing.app.tools.android.Build")); - item = createToolMenuItem("processing.app.tools.android.Build"); - item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers)); - menu.add(item); - */ +// // These are temporary entries while Android mode is being worked out. +// // The mode will not be in the tools menu, and won't involve a cmd-key +// if (!Base.RELEASE) { +// item = createToolMenuItem("processing.app.tools.android.AndroidTool"); +// item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers)); +// menu.add(item); +// menu.add(createToolMenuItem("processing.app.tools.android.Reset")); +// } return menu; } @@ -1363,6 +1343,35 @@ public class Editor extends JFrame implements RunnerListener { // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + // these will be done in a more generic way soon, more like: + // setHandler("action name", Runnable); + // but for the time being, working out the kinks of how many things to + // abstract from the editor in this fashion. + + + public void setHandlers(Runnable runHandler, Runnable presentHandler, + Runnable stopHandler, + Runnable exportHandler, Runnable exportAppHandler) { + this.runHandler = runHandler; + this.presentHandler = presentHandler; + this.stopHandler = stopHandler; + this.exportHandler = exportHandler; + this.exportAppHandler = exportAppHandler; + } + + + public void resetHandlers() { + runHandler = new DefaultRunHandler(); + presentHandler = new DefaultPresentHandler(); + stopHandler = new DefaultStopHandler(); + exportHandler = new DefaultExportHandler(); + exportAppHandler = new DefaultExportAppHandler(); + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + /** * Gets the current sketch object. */ @@ -1799,26 +1808,50 @@ public class Editor extends JFrame implements RunnerListener { console.clear(); } - //presenting = present; - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - try { - sketch.compile(verbose); - statusNotice("Done compiling."); - } catch (RunnerException e) { - //statusError("Error compiling..."); - statusError(e); - - } catch (Exception e) { - e.printStackTrace(); - } - - toolbar.deactivate(EditorToolbar.RUN); - } - }); + // Cannot use invokeLater() here, otherwise it gets + // placed on the event thread and causes a hang--bad idea all around. + new Thread(verbose ? presentHandler : runHandler).start(); } + // DAM: in Arduino, this is compile + class DefaultRunHandler implements Runnable { + public void run() { + try { + sketch.prepare(); + String appletClassName = sketch.build(false); + statusNotice("Done compiling."); + } catch (Exception e) { + statusError(e); + } + + toolbar.deactivate(EditorToolbar.RUN); + } + } + + // DAM: in Arduino, this is compile (with verbose output) + class DefaultPresentHandler implements Runnable { + public void run() { + try { + sketch.prepare(); + String appletClassName = sketch.build(true); + statusNotice("Done compiling."); + } catch (Exception e) { + statusError(e); + } + + toolbar.deactivate(EditorToolbar.RUN); + } + } + + class DefaultStopHandler implements Runnable { + public void run() { + try { + // DAM: we should try to kill the compilation or upload process here. + } catch (Exception e) { + statusError(e); + } + } + } /** * Set the location of the sketch run window. Used by Runner to update the @@ -1855,8 +1888,10 @@ public class Editor extends JFrame implements RunnerListener { /** - * Called by Runner to notify that the sketch has stopped running. - * Tools should not call this function, use handleStop() instead. + * Deactivate the Run button. This is called by Runner to notify that the + * sketch has stopped running, usually in response to an error (or maybe + * the sketch completing and exiting?) Tools should not call this function. + * To initiate a "stop" action, call handleStop() instead. */ public void internalRunnerClosed() { running = false; @@ -1870,11 +1905,9 @@ public class Editor extends JFrame implements RunnerListener { public void internalCloseRunner() { running = false; + if (stopHandler != null) try { - if (runtime != null) { - runtime.close(); // kills the window - runtime = null; // will this help? - } + stopHandler.run(); } catch (Exception e) { } sketch.cleanup(); @@ -1883,13 +1916,14 @@ public class Editor extends JFrame implements RunnerListener { /** * Check if the sketch is modified and ask user to save changes. - * Immediately should be set true when quitting, or when the save should - * not happen asynchronously. Come to think of it, that's always now? * @return false if canceling the close/quit operation */ - protected boolean checkModified(boolean immediately) { + protected boolean checkModified() { if (!sketch.isModified()) return true; + // As of Processing 1.0.10, this always happens immediately. + // http://dev.processing.org/bugs/show_bug.cgi?id=1456 + String prompt = "Save changes to " + sketch.getName() + "? "; if (!Base.isMacOS()) { @@ -1899,13 +1933,14 @@ public class Editor extends JFrame implements RunnerListener { JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { - return handleSave(immediately); + return handleSave(true); } else if (result == JOptionPane.NO_OPTION) { return true; // ok to continue } else if (result == JOptionPane.CANCEL_OPTION) { return false; + } else { throw new IllegalStateException(); } @@ -1950,7 +1985,7 @@ public class Editor extends JFrame implements RunnerListener { Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) - return handleSave(immediately); + return handleSave(true); } else if (result == options[2]) { // don't save (still close/quit) return true; @@ -2203,39 +2238,69 @@ public class Editor extends JFrame implements RunnerListener { synchronized public void handleExport(final boolean verbose) { //if (!handleExportCheckModified()) return; toolbar.activate(EditorToolbar.EXPORT); - console.clear(); statusNotice("Uploading to I/O Board..."); - //SwingUtilities.invokeLater(new Runnable() { - Thread t = new Thread(new Runnable() { - public void run() { - try { - serialMonitor.closeSerialPort(); - serialMonitor.setVisible(false); - - uploading = true; - - boolean success = sketch.exportApplet(verbose); - if (success) { - statusNotice("Done uploading."); - } else { - // error message will already be visible - } - } catch (RunnerException e) { - //statusError("Error during upload."); - //e.printStackTrace(); - statusError(e); - } catch (Exception e) { - e.printStackTrace(); - } - uploading = false; - //toolbar.clear(); - toolbar.deactivate(EditorToolbar.EXPORT); - }}); - t.start(); + new Thread(verbose ? exportAppHandler : exportHandler).start(); } + // DAM: in Arduino, this is upload + class DefaultExportHandler implements Runnable { + public void run() { + + try { + serialMonitor.closeSerialPort(); + serialMonitor.setVisible(false); + + uploading = true; + + boolean success = sketch.exportApplet(false); + if (success) { + statusNotice("Done uploading."); + } else { + // error message will already be visible + } + } catch (RunnerException e) { + //statusError("Error during upload."); + //e.printStackTrace(); + statusError(e); + } catch (Exception e) { + e.printStackTrace(); + } + uploading = false; + //toolbar.clear(); + toolbar.deactivate(EditorToolbar.EXPORT); + } + } + + // DAM: in Arduino, this is upload (with verbose output) + class DefaultExportAppHandler implements Runnable { + public void run() { + + try { + serialMonitor.closeSerialPort(); + serialMonitor.setVisible(false); + + uploading = true; + + boolean success = sketch.exportApplet(true); + if (success) { + statusNotice("Done uploading."); + } else { + // error message will already be visible + } + } catch (RunnerException e) { + //statusError("Error during upload."); + //e.printStackTrace(); + statusError(e); + } catch (Exception e) { + e.printStackTrace(); + } + uploading = false; + //toolbar.clear(); + toolbar.deactivate(EditorToolbar.EXPORT); + } + } /** * Checks to see if the sketch has been modified, and if so, @@ -2418,7 +2483,7 @@ public class Editor extends JFrame implements RunnerListener { } statusError(mess); } - e.printStackTrace(); +// e.printStackTrace(); } @@ -2563,4 +2628,3 @@ public class Editor extends JFrame implements RunnerListener { } } } - diff --git a/app/src/processing/app/EditorConsole.java b/app/src/processing/app/EditorConsole.java index 002fb3edd..38cf00fc2 100644 --- a/app/src/processing/app/EditorConsole.java +++ b/app/src/processing/app/EditorConsole.java @@ -28,6 +28,7 @@ import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.text.*; + import java.util.*; @@ -47,8 +48,6 @@ public class EditorConsole extends JScrollPane { MutableAttributeSet stdStyle; MutableAttributeSet errStyle; - boolean cerror; - int maxLineCount; static File errFile; @@ -221,18 +220,9 @@ public class EditorConsole extends JScrollPane { public void write(byte b[], int offset, int length, boolean err) { - if (err != cerror) { - // advance the line because switching between err/out streams - // potentially, could check whether we're already on a new line - message("", cerror, true); - } - // we could do some cross platform CR/LF mangling here before outputting - // add text to output document message(new String(b, offset, length), err, false); - // set last error state - cerror = err; } @@ -291,10 +281,10 @@ public class EditorConsole extends JScrollPane { // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - class EditorConsoleStream extends OutputStream { + private static class EditorConsoleStream extends OutputStream { //static EditorConsole current; - boolean err; // whether stderr or stdout - byte single[] = new byte[1]; + final boolean err; // whether stderr or stdout + final byte single[] = new byte[1]; public EditorConsoleStream(boolean err) { this.err = err; @@ -389,7 +379,7 @@ public class EditorConsole extends JScrollPane { * swing event thread, so they need to be synchronized */ class BufferedStyledDocument extends DefaultStyledDocument { - ArrayList elements = new ArrayList(); + ArrayList elements = new ArrayList(); int maxLineLength, maxLineCount; int currentLineLength = 0; boolean needLineBreak = false; diff --git a/app/src/processing/app/EditorListener.java b/app/src/processing/app/EditorListener.java index ffd05b022..58c3fc9a1 100644 --- a/app/src/processing/app/EditorListener.java +++ b/app/src/processing/app/EditorListener.java @@ -103,6 +103,10 @@ public class EditorListener { char c = event.getKeyChar(); int code = event.getKeyCode(); +// if (code == KeyEvent.VK_SHIFT) { +// editor.toolbar.setShiftPressed(true); +// } + //System.out.println((int)c + " " + code + " " + event); //System.out.println(); @@ -457,6 +461,13 @@ public class EditorListener { } +// public boolean keyReleased(KeyEvent event) { +// if (code == KeyEvent.VK_SHIFT) { +// editor.toolbar.setShiftPressed(false); +// } +// } + + public boolean keyTyped(KeyEvent event) { char c = event.getKeyChar(); diff --git a/app/src/processing/app/EditorToolbar.java b/app/src/processing/app/EditorToolbar.java index 6a5fe2214..74ef71f94 100644 --- a/app/src/processing/app/EditorToolbar.java +++ b/app/src/processing/app/EditorToolbar.java @@ -3,7 +3,7 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2004-08 Ben Fry and Casey Reas + Copyright (c) 2004-09 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify @@ -25,6 +25,7 @@ package processing.app; import java.awt.*; import java.awt.event.*; + import javax.swing.*; import javax.swing.event.*; @@ -32,12 +33,18 @@ import javax.swing.event.*; /** * run/stop/etc buttons for the ide */ -public class EditorToolbar extends JComponent implements MouseInputListener { +public class EditorToolbar extends JComponent implements MouseInputListener, KeyListener { + /** Rollover titles for each button. */ static final String title[] = { "Verify", "Stop", "New", "Open", "Save", "Upload", "Serial Monitor" }; + /** Titles for each button when the shift key is pressed. */ + static final String titleShift[] = { + "Verify (w/ Verbose Output)", "Stop", "New Editor Window", "Open in Another Window", "Save", "Upload (w/ Verbose Output)", "Serial Monitor" + }; + static final int BUTTON_COUNT = title.length; /** Width of each toolbar button. */ static final int BUTTON_WIDTH = 27; @@ -45,6 +52,9 @@ public class EditorToolbar extends JComponent implements MouseInputListener { static final int BUTTON_HEIGHT = 32; /** The amount of space between groups of buttons on the toolbar. */ static final int BUTTON_GAP = 5; + /** Size of the button image being chopped up. */ + static final int BUTTON_IMAGE_SIZE = 33; + static final int RUN = 0; static final int STOP = 1; @@ -61,45 +71,35 @@ public class EditorToolbar extends JComponent implements MouseInputListener { static final int ACTIVE = 2; Editor editor; - //boolean disableRun; // this was for library - //Label status; Image offscreen; int width, height; Color bgcolor; - static Image buttons; - static Image inactive[]; - static Image rollover[]; - static Image active[]; + static Image[][] buttonImages; int currentRollover; - //int currentSelection; JPopupMenu popup; JMenu menu; int buttonCount; - int state[] = new int[BUTTON_COUNT]; - Image stateImage[]; + int[] state = new int[BUTTON_COUNT]; + Image[] stateImage; int which[]; // mapping indices to implementation int x1[], x2[]; int y1, y2; - String status; Font statusFont; Color statusColor; + boolean shiftPressed; public EditorToolbar(Editor editor, JMenu menu) { this.editor = editor; this.menu = menu; - if (buttons == null) { - buttons = Base.getThemeImage("buttons.gif", this); - } - buttonCount = 0; which = new int[BUTTON_COUNT]; @@ -115,9 +115,6 @@ public class EditorToolbar extends JComponent implements MouseInputListener { currentRollover = -1; bgcolor = Theme.getColor("buttons.bgcolor"); - - status = ""; - statusFont = Theme.getFont("buttons.status.font"); statusColor = Theme.getColor("buttons.status.color"); @@ -125,30 +122,28 @@ public class EditorToolbar extends JComponent implements MouseInputListener { addMouseMotionListener(this); } - - public void paintComponent(Graphics screen) { - // this data is shared by all EditorToolbar instances - if (inactive == null) { - inactive = new Image[BUTTON_COUNT]; - rollover = new Image[BUTTON_COUNT]; - active = new Image[BUTTON_COUNT]; - - int IMAGE_SIZE = 33; + protected void loadButtons() { + Image allButtons = Base.getThemeImage("buttons.gif", this); + buttonImages = new Image[BUTTON_COUNT][3]; for (int i = 0; i < BUTTON_COUNT; i++) { - inactive[i] = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); - Graphics g = inactive[i].getGraphics(); - g.drawImage(buttons, -(i*IMAGE_SIZE) - 3, -2*IMAGE_SIZE, null); - - rollover[i] = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); - g = rollover[i].getGraphics(); - g.drawImage(buttons, -(i*IMAGE_SIZE) - 3, -1*IMAGE_SIZE, null); - - active[i] = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); - g = active[i].getGraphics(); - g.drawImage(buttons, -(i*IMAGE_SIZE) - 3, -0*IMAGE_SIZE, null); + for (int state = 0; state < 3; state++) { + Image image = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); + Graphics g = image.getGraphics(); + g.drawImage(allButtons, + -(i*BUTTON_IMAGE_SIZE) - 3, + (-2 + state)*BUTTON_IMAGE_SIZE, null); + buttonImages[i][state] = image; } } + } + + @Override + public void paintComponent(Graphics screen) { + // this data is shared by all EditorToolbar instances + if (buttonImages == null) { + loadButtons(); + } // this happens once per instance of EditorToolbar if (stateImage == null) { @@ -191,21 +186,34 @@ public class EditorToolbar extends JComponent implements MouseInputListener { /* // if i ever find the guy who wrote the java2d api, i will hurt him. + * + * whereas I love the Java2D API. --jdf. lol. + * Graphics2D g2 = (Graphics2D) g; FontRenderContext frc = g2.getFontRenderContext(); float statusW = (float) statusFont.getStringBounds(status, frc).getWidth(); float statusX = (getSize().width - statusW) / 2; g2.drawString(status, statusX, statusY); */ - //int statusY = (BUTTON_HEIGHT + statusFont.getAscent()) / 2; + if (currentRollover != -1) { int statusY = (BUTTON_HEIGHT + g.getFontMetrics().getAscent()) / 2; + String status = shiftPressed ? titleShift[currentRollover] : title[currentRollover]; g.drawString(status, buttonCount * BUTTON_WIDTH + 3 * BUTTON_GAP, statusY); + } screen.drawImage(offscreen, 0, 0, null); + + if (!isEnabled()) { + screen.setColor(new Color(0,0,0,100)); + screen.fillRect(0, 0, getWidth(), getHeight()); + } } public void mouseMoved(MouseEvent e) { + if (!isEnabled()) + return; + // mouse events before paint(); if (state == null) return; @@ -213,16 +221,17 @@ public class EditorToolbar extends JComponent implements MouseInputListener { // avoid flicker, since there will probably be an update event setState(OPEN, INACTIVE, false); } - //System.out.println(e); - //mouseMove(e); - handleMouse(e.getX(), e.getY()); + handleMouse(e); } public void mouseDragged(MouseEvent e) { } - public void handleMouse(int x, int y) { + public void handleMouse(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + if (currentRollover != -1) { if ((x > x1[currentRollover]) && (y > y1) && (x < x2[currentRollover]) && (y < y2)) { @@ -230,7 +239,6 @@ public class EditorToolbar extends JComponent implements MouseInputListener { } else { setState(currentRollover, INACTIVE, true); - messageClear(title[currentRollover]); currentRollover = -1; } } @@ -238,10 +246,8 @@ public class EditorToolbar extends JComponent implements MouseInputListener { if (sel == -1) return; if (state[sel] != ACTIVE) { - //if (!(disableRun && ((sel == RUN) || (sel == STOP)))) { setState(sel, ROLLOVER, true); currentRollover = sel; - //} } } @@ -263,32 +269,16 @@ public class EditorToolbar extends JComponent implements MouseInputListener { private void setState(int slot, int newState, boolean updateAfter) { - //if (inactive == null) return; state[slot] = newState; - switch (newState) { - case INACTIVE: - stateImage[slot] = inactive[which[slot]]; - break; - case ACTIVE: - stateImage[slot] = active[which[slot]]; - break; - case ROLLOVER: - stateImage[slot] = rollover[which[slot]]; - message(title[which[slot]]); - break; - } + stateImage[slot] = buttonImages[which[slot]][newState]; if (updateAfter) { - //System.out.println("trying to update " + slot + " " + state[slot]); - //new Exception("setting slot " + slot + " to " + state[slot]).printStackTrace(); - repaint(); // changed for swing from update(); - //Toolkit.getDefaultToolkit().sync(); + repaint(); } } public void mouseEntered(MouseEvent e) { - //mouseMove(e); - handleMouse(e.getX(), e.getY()); + handleMouse(e); } @@ -300,14 +290,18 @@ public class EditorToolbar extends JComponent implements MouseInputListener { if (state[OPEN] != INACTIVE) { setState(OPEN, INACTIVE, true); } - status = ""; - handleMouse(e.getX(), e.getY()); + handleMouse(e); } int wasDown = -1; public void mousePressed(MouseEvent e) { + + // jdf + if (!isEnabled()) + return; + final int x = e.getX(); final int y = e.getY(); @@ -331,8 +325,11 @@ public class EditorToolbar extends JComponent implements MouseInputListener { break; case NEW: - //editor.base.handleNew(e.isShiftDown()); + if (shiftPressed) { + editor.base.handleNew(); + } else { editor.base.handleNewReplace(); + } break; case SAVE: @@ -353,84 +350,26 @@ public class EditorToolbar extends JComponent implements MouseInputListener { public void mouseClicked(MouseEvent e) { } - public void mouseReleased(MouseEvent e) { - /* - switch (currentSelection) { - - case OPEN: - setState(OPEN, INACTIVE, true); - break; - } - currentSelection = -1; - */ - } - - - //public void disableRun(boolean what) { - //disableRun = what; - //} - - - /* - public void run() { - if (inactive == null) return; - clear(); - setState(RUN, ACTIVE, true); - } - */ - -// public void running(boolean yesno) { -// setState(RUN, yesno ? ACTIVE : INACTIVE, true); -// } + public void mouseReleased(MouseEvent e) { } /** * Set a particular button to be active. */ public void activate(int what) { - //System.out.println("activating " + what); - if (inactive == null) return; + if (buttonImages != null) { setState(what, ACTIVE, true); } - - //public void clearRun() { - //if (inactive == null) return; - //setState(RUN, INACTIVE, true); - //} + } /** * Set a particular button to be active. */ public void deactivate(int what) { - if (inactive == null) return; // don't draw if not ready + if (buttonImages != null) { setState(what, INACTIVE, true); } - - /** - * Clear all the state of all buttons. - */ -// public void clear() { // (int button) { -// if (inactive == null) return; -// -// System.out.println("clearing state of buttons"); -// // skip the run button, do the others -// for (int i = 1; i < buttonCount; i++) { -// setState(i, INACTIVE, false); -// } -// repaint(); // changed for swing from update(); -// } - - - public void message(String msg) { - //status.setText(msg + " "); // don't mind the hack - status = msg; - } - - - public void messageClear(String msg) { - //if (status.getText().equals(msg + " ")) status.setText(Editor.EMPTY); - if (status.equals(msg)) status = ""; } @@ -447,4 +386,23 @@ public class EditorToolbar extends JComponent implements MouseInputListener { public Dimension getMaximumSize() { return new Dimension(3000, BUTTON_HEIGHT); } + + + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_SHIFT) { + shiftPressed = true; + repaint(); +} + } + + + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_SHIFT) { + shiftPressed = false; + repaint(); + } + } + + + public void keyTyped(KeyEvent e) { } } diff --git a/app/src/processing/app/Platform.java b/app/src/processing/app/Platform.java index 28fe66c99..9fd0fd972 100644 --- a/app/src/processing/app/Platform.java +++ b/app/src/processing/app/Platform.java @@ -26,6 +26,9 @@ import java.io.File; import javax.swing.UIManager; +import com.sun.jna.Library; +import com.sun.jna.Native; + /** * Used by Base for platform-specific tweaking, for instance finding the @@ -129,6 +132,36 @@ public class Platform { // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + public interface CLibrary extends Library { + CLibrary INSTANCE = (CLibrary)Native.loadLibrary("c", CLibrary.class); + int setenv(String name, String value, int overwrite); + String getenv(String name); + int unsetenv(String name); + int putenv(String string); + } + + + public void setenv(String variable, String value) { + CLibrary clib = CLibrary.INSTANCE; + clib.setenv(variable, value, 1); + } + + + public String getenv(String variable) { + CLibrary clib = CLibrary.INSTANCE; + return clib.getenv(variable); + } + + + public int unsetenv(String variable) { + CLibrary clib = CLibrary.INSTANCE; + return clib.unsetenv(variable); + } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + protected void showLauncherWarning() { Base.showWarning("No launcher available", "Unspecified platform, no launcher available.\n" + diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java index a2b790bba..ffc63f7ae 100644 --- a/app/src/processing/app/Preferences.java +++ b/app/src/processing/app/Preferences.java @@ -626,6 +626,11 @@ public class Preferences { } + static public void unset(String attribute) { + table.remove(attribute); + } + + static public boolean getBoolean(String attribute) { String value = get(attribute); //, null); return (new Boolean(value)).booleanValue(); diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java index 29c2c3976..34b76d8d0 100644 --- a/app/src/processing/app/Sketch.java +++ b/app/src/processing/app/Sketch.java @@ -3,7 +3,7 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2004-09 Ben Fry and Casey Reas + Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify @@ -95,6 +95,9 @@ public class Sketch { * DLLs or JNILIBs. */ private String libraryPath; + /** + * List of library folders. + */ private ArrayList importedLibraries; /** @@ -1165,11 +1168,14 @@ public class Sketch { * X. afterwards, some of these steps need a cleanup function * */ - protected String compile(boolean verbose) - throws RunnerException { - - String name; - + //protected String compile() throws RunnerException { + + + /** + * When running from the editor, take care of preparations before running + * the build. + */ + public void prepare() { // make sure the user didn't hide the sketch folder ensureExistence(); @@ -1199,11 +1205,8 @@ public class Sketch { // better connected to the dataFolder stuff below. cleanup(); - // handle preprocessing the main file's code - name = build(tempBuildFolder.getAbsolutePath(), verbose); - size(tempBuildFolder.getAbsolutePath(), name); - - return name; +// // handle preprocessing the main file's code +// return build(tempBuildFolder.getAbsolutePath()); } @@ -1255,14 +1258,6 @@ public class Sketch { // 1. concatenate all .pde files to the 'main' pde // store line number for starting point of each code bit - // Unfortunately, the header has to be written on a single line, because - // there's no way to determine how long it will be until the code has - // already been preprocessed. The header will vary in length based on - // the programming mode (STATIC, ACTIVE, or JAVA), which is determined - // by the preprocessor. So the preprocOffset for the primary class remains - // zero, even though it'd be nice to have a legitimate offset, and be able - // to remove the 'pretty' boolean for preproc.write(). - StringBuffer bigCode = new StringBuffer(); int bigCount = 0; for (SketchCode sc : code) { @@ -1271,29 +1266,9 @@ public class Sketch { bigCode.append(sc.getProgram()); bigCode.append('\n'); bigCount += sc.getLineCount(); -// if (sc != code[0]) { -// sc.setPreprocName(null); // don't compile me -// } } } - /* - String program = code[0].getProgram(); - StringBuffer bigCode = new StringBuffer(program); - int bigCount = code[0].getLineCount(); - bigCode.append('\n'); - - for (int i = 1; i < codeCount; i++) { - if (code[i].isExtension("pde")) { - code[i].setPreprocOffset(bigCount); - bigCode.append(code[i].getProgram()); - bigCode.append('\n'); - bigCount += code[i].getLineCount(); - code[i].setPreprocName(null); // don't compile me - } - } - */ - // Note that the headerOffset isn't applied until compile and run, because // it only applies to the code after it's been written to the .java file. int headerOffset = 0; @@ -1391,6 +1366,134 @@ public class Sketch { } + public ArrayList getImportedLibraries() { + return importedLibraries; + } + + + /** + * Map an error from a set of processed .java files back to its location + * in the actual sketch. + * @param message The error message. + * @param filename The .java file where the exception was found. + * @param line Line number of the .java file for the exception (1-indexed) + * @return A RunnerException to be sent to the editor, or null if it wasn't + * possible to place the exception to the sketch code. + */ +// public RunnerException placeExceptionAlt(String message, +// String filename, int line) { +// String appletJavaFile = appletClassName + ".java"; +// SketchCode errorCode = null; +// if (filename.equals(appletJavaFile)) { +// for (SketchCode code : getCode()) { +// if (code.isExtension("pde")) { +// if (line >= code.getPreprocOffset()) { +// errorCode = code; +// } +// } +// } +// } else { +// for (SketchCode code : getCode()) { +// if (code.isExtension("java")) { +// if (filename.equals(code.getFileName())) { +// errorCode = code; +// } +// } +// } +// } +// int codeIndex = getCodeIndex(errorCode); +// +// if (codeIndex != -1) { +// //System.out.println("got line num " + lineNumber); +// // in case this was a tab that got embedded into the main .java +// line -= getCode(codeIndex).getPreprocOffset(); +// +// // lineNumber is 1-indexed, but editor wants zero-indexed +// line--; +// +// // getMessage() will be what's shown in the editor +// RunnerException exception = +// new RunnerException(message, codeIndex, line, -1); +// exception.hideStackTrace(); +// return exception; +// } +// return null; +// } + + + /** + * Map an error from a set of processed .java files back to its location + * in the actual sketch. + * @param message The error message. + * @param filename The .java file where the exception was found. + * @param line Line number of the .java file for the exception (0-indexed!) + * @return A RunnerException to be sent to the editor, or null if it wasn't + * possible to place the exception to the sketch code. + */ + public RunnerException placeException(String message, + String dotJavaFilename, + int dotJavaLine) { + int codeIndex = 0; //-1; + int codeLine = -1; + +// System.out.println("placing " + dotJavaFilename + " " + dotJavaLine); +// System.out.println("code count is " + getCodeCount()); + + // first check to see if it's a .java file + for (int i = 0; i < getCodeCount(); i++) { + SketchCode code = getCode(i); + if (code.isExtension("java")) { + if (dotJavaFilename.equals(code.getFileName())) { + codeIndex = i; + codeLine = dotJavaLine; + return new RunnerException(message, codeIndex, codeLine); + } + } + } + + // If not the preprocessed file at this point, then need to get out + if (!dotJavaFilename.equals(name + ".java")) { + return null; + } + + // if it's not a .java file, codeIndex will still be 0 + // this section searches through the list of .pde files + codeIndex = 0; + for (int i = 0; i < getCodeCount(); i++) { + SketchCode code = getCode(i); + + if (code.isExtension("pde")) { +// System.out.println("preproc offset is " + code.getPreprocOffset()); +// System.out.println("looking for line " + dotJavaLine); + if (code.getPreprocOffset() <= dotJavaLine) { + codeIndex = i; +// System.out.println("i'm thinkin file " + i); + codeLine = dotJavaLine - code.getPreprocOffset(); + } + } + } + // could not find a proper line number, so deal with this differently. + // but if it was in fact the .java file we're looking for, though, + // send the error message through. + // this is necessary because 'import' statements will be at a line + // that has a lower number than the preproc offset, for instance. +// if (codeLine == -1 && !dotJavaFilename.equals(name + ".java")) { +// return null; +// } + return new RunnerException(message, codeIndex, codeLine); + } + + + /** + * Run the build inside the temporary build folder. + * @return null if compilation failed, main class name if not + * @throws RunnerException + */ + public String build(boolean verbose) throws RunnerException { + return build(tempBuildFolder.getAbsolutePath(), verbose); + } + + /** * Preprocess and compile all the code for this sketch. * @@ -1410,6 +1513,7 @@ public class Sketch { // that will bubble up to whomever called build(). Compiler compiler = new Compiler(); if (compiler.compile(this, buildPath, primaryClassName, verbose)) { + size(buildPath, primaryClassName); return primaryClassName; } return null; @@ -1500,7 +1604,7 @@ public class Sketch { verbose); return success ? suggestedClassName : null; - } + } /** * Replace all commented portions of a given String as spaces. @@ -1538,7 +1642,8 @@ public class Sketch { break; } else { - index++; + // continue blanking this area + p[index++] = ' '; } } if (!endOfRainbow) { @@ -1562,8 +1667,8 @@ public class Sketch { * Export to application via GUI. */ protected boolean exportApplication() throws IOException, RunnerException { - return false; - } + return false; + } /** @@ -1571,8 +1676,8 @@ public class Sketch { */ public boolean exportApplication(String destPath, int exportPlatform) throws IOException, RunnerException { - return false; - } + return false; + } protected void addManifest(ZipOutputStream zos) throws IOException { @@ -1588,35 +1693,6 @@ public class Sketch { } - /** - * Read from a file with a bunch of attribute/value pairs - * that are separated by = and ignore comments with #. - */ - protected HashMap readSettings(File inputFile) { - HashMap outgoing = new HashMap(); - if (!inputFile.exists()) return outgoing; // return empty hash - - String lines[] = PApplet.loadStrings(inputFile); - for (int i = 0; i < lines.length; i++) { - int hash = lines[i].indexOf('#'); - String line = (hash == -1) ? - lines[i].trim() : lines[i].substring(0, hash).trim(); - if (line.length() == 0) continue; - - int equals = line.indexOf('='); - if (equals == -1) { - System.err.println("ignoring illegal line in " + inputFile); - System.err.println(" " + line); - continue; - } - String attr = line.substring(0, equals).trim(); - String valu = line.substring(equals + 1).trim(); - outgoing.put(attr, valu); - } - return outgoing; - } - - /** * Slurps up .class files from a colon (or semicolon on windows) * separated list of paths and adds them to a ZipOutputStream. @@ -1923,11 +1999,6 @@ public class Sketch { } - public ArrayList getImportedLibraries() { - return importedLibraries; - } - - public String getClassPath() { return classPath; } diff --git a/app/src/processing/app/StreamRedirectThread.java b/app/src/processing/app/StreamRedirectThread.java new file mode 100644 index 000000000..0d27a56e6 --- /dev/null +++ b/app/src/processing/app/StreamRedirectThread.java @@ -0,0 +1,95 @@ +/* + + * @(#)StreamRedirectThread.java 1.4 03/01/23 + * + * Copyright 2003 Sun Microsystems, Inc. All rights reserved. + * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. + */ +/* + * Copyright (c) 1997-2001 by Sun Microsystems, Inc. All Rights Reserved. + * + * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use, + * modify and redistribute this software in source and binary code form, + * provided that i) this copyright notice and license appear on all copies of + * the software; and ii) Licensee does not utilize the software in a manner + * which is disparaging to Sun. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY + * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR + * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE + * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING + * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS + * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, + * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER + * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF + * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * This software is not designed or intended for use in on-line control of + * aircraft, air traffic, aircraft navigation or aircraft communications; or in + * the design, construction, operation or maintenance of any nuclear + * facility. Licensee represents and warrants that it will not use or + * redistribute the Software for such purposes. + */ +package processing.app; + +import java.io.*; + +/** + * StreamRedirectThread is a thread which copies it's input to + * it's output and terminates when it completes. + * + * @version @(#) StreamRedirectThread.java 1.4 03/01/23 23:33:38 + * @author Robert Field + */ +public class StreamRedirectThread extends Thread { + + private final Reader in; + private final Writer out; + + private static final int BUFFER_SIZE = 2048; + + + /** + * Set up for copy. + * @param name Name of the thread + * @param in Stream to copy from + * @param out Stream to copy to + */ + public StreamRedirectThread(String name, InputStream in, OutputStream out) { + super(name); + this.in = new InputStreamReader(in); + this.out = new OutputStreamWriter(out); + setPriority(Thread.MAX_PRIORITY-1); + } + + + public StreamRedirectThread(String name, Reader in, Writer out) { + super(name); + this.in = in; + this.out = out; + setPriority(Thread.MAX_PRIORITY-1); + } + + + /** + * Copy. + */ + public void run() { + try { + char[] cbuf = new char[BUFFER_SIZE]; + int count; + //System.out.println("opening streamredirectthread"); + while ((count = in.read(cbuf, 0, BUFFER_SIZE)) >= 0) { + out.write(cbuf, 0, count); + // had to add the flush() here.. maybe shouldn't be using writer? [fry] + out.flush(); + } + //System.out.println("exiting streamredirectthread"); + out.flush(); + } catch(IOException exc) { + System.err.println("Child I/O Transfer - " + exc); + } + } +} diff --git a/app/src/processing/app/WebServer.java b/app/src/processing/app/WebServer.java index 01f6cc39e..fc2089d8e 100644 --- a/app/src/processing/app/WebServer.java +++ b/app/src/processing/app/WebServer.java @@ -8,8 +8,12 @@ import java.util.zip.*; //import javax.swing.SwingUtilities; /** - * An example of a very simple, multi-threaded HTTP server. - * Taken from this article on java.sun.com. + * This code is placed here in anticipation of running the reference from an + * internal web server that reads the docs from a zip file, instead of using + * thousands of .html files on the disk, which is really inefficient. + *

+ * This is a very simple, multi-threaded HTTP server, originally based on + * this article on java.sun.com. */ public class WebServer implements HttpConstants { diff --git a/app/src/processing/app/debug/EventThread.java b/app/src/processing/app/debug/EventThread.java.disabled similarity index 98% rename from app/src/processing/app/debug/EventThread.java rename to app/src/processing/app/debug/EventThread.java.disabled index d4f93d503..4c68eeb47 100644 --- a/app/src/processing/app/debug/EventThread.java +++ b/app/src/processing/app/debug/EventThread.java.disabled @@ -65,7 +65,8 @@ public class EventThread extends Thread { // Maps ThreadReference to ThreadTrace instances private Map traceMap = new HashMap(); - EventThread(Runner parent, VirtualMachine vm, String[] excludes, PrintWriter writer) { + + public EventThread(Runner parent, VirtualMachine vm, String[] excludes, PrintWriter writer) { super("event-handler"); this.parent = parent; this.vm = vm; @@ -103,7 +104,7 @@ public class EventThread extends Thread { * @param excludes Class patterns for which we don't want events * @param watchFields Do we want to watch assignments to fields */ - void setEventRequests(boolean watchFields) { + public void setEventRequests(boolean watchFields) { EventRequestManager mgr = vm.eventRequestManager(); // VMDeathRequest deathReq = mgr.createVMDeathRequest(); diff --git a/app/src/processing/app/debug/MessageSiphon.java b/app/src/processing/app/debug/MessageSiphon.java index 970fc4c8a..79a0920d5 100644 --- a/app/src/processing/app/debug/MessageSiphon.java +++ b/app/src/processing/app/debug/MessageSiphon.java @@ -29,7 +29,7 @@ import java.io.*; /** * Slurps up messages from compiler. */ -class MessageSiphon implements Runnable { +public class MessageSiphon implements Runnable { BufferedReader streamReader; Thread thread; MessageConsumer consumer; @@ -84,4 +84,9 @@ class MessageSiphon implements Runnable { thread = null; } } + + + public Thread getThread() { + return thread; +} } diff --git a/app/src/processing/app/debug/Runner.java b/app/src/processing/app/debug/Runner.java.disabled similarity index 52% rename from app/src/processing/app/debug/Runner.java rename to app/src/processing/app/debug/Runner.java.disabled index f439eeb98..e6af3f48d 100644 --- a/app/src/processing/app/debug/Runner.java +++ b/app/src/processing/app/debug/Runner.java.disabled @@ -24,6 +24,7 @@ package processing.app.debug; import processing.app.*; +import processing.app.preproc.PdePreprocessor; import processing.core.*; import java.awt.Point; @@ -49,60 +50,54 @@ public class Runner implements MessageConsumer { private boolean presenting; // Object that listens for error messages or exceptions. - private RunnerListener listener; + protected RunnerListener listener; // Running remote VM - private VirtualMachine vm; + protected VirtualMachine vm; // Thread transferring remote error stream to our error stream - private Thread errThread = null; + protected Thread errThread = null; // Thread transferring remote output stream to our output stream - private Thread outThread = null; + protected Thread outThread = null; // Mode for tracing the Trace program (default= 0 off) - private int debugTraceMode = 0; + protected int debugTraceMode = 0; // Do we want to watch assignments to fields - private boolean watchFields = false; + protected boolean watchFields = false; // Class patterns for which we don't want events - private String[] excludes = { + protected String[] excludes = { "java.*", "javax.*", "sun.*", "com.sun.*", "apple.*", "processing.*" }; - private RunnerException exception; + protected RunnerException exception; //private PrintStream leechErr; - private Editor editor; - private Sketch sketch; + protected Editor editor; + protected Sketch sketch; private String appletClassName; -// private boolean newMessage; -// private int messageLineCount; -// private boolean foundMessageSource; -// -// private SystemOutSiphon processInput; -// private OutputStream processOutput; -// private MessageSiphon processError; - - public Runner(Sketch sketch, String appletClassName, - boolean presenting, RunnerListener listener) { - this.sketch = sketch; - this.appletClassName = appletClassName; - this.presenting = presenting; + public Runner(RunnerListener listener, Sketch sketch) { this.listener = listener; + this.sketch = sketch; if (listener instanceof Editor) { this.editor = (Editor) listener; +// } else { +// System.out.println("actually it's a " + listener.getClass().getName()); } } - public void launch() { + public void launch(String appletClassName, boolean presenting) { + this.appletClassName = appletClassName; + this.presenting = presenting; + // TODO entire class is a total mess as of release 0136. // This will be cleaned up significantly over the next couple months. @@ -132,7 +127,7 @@ public class Runner implements MessageConsumer { protected String[] getMachineParams() { - ArrayList params = new ArrayList(); + ArrayList params = new ArrayList(); //params.add("-Xint"); // interpreted mode //params.add("-Xprof"); // profiler @@ -203,6 +198,13 @@ public class Runner implements MessageConsumer { protected String[] getSketchParams() { ArrayList params = new ArrayList(); + // It's dangerous to add your own main() to your code, + // but if you've done it, we'll respect your right to hang yourself. + // http://dev.processing.org/bugs/show_bug.cgi?id=1446 + if (PdePreprocessor.foundMain) { + params.add(appletClassName); + + } else { params.add("processing.core.PApplet"); // If there was a saved location (this guy has been run more than once) @@ -242,6 +244,7 @@ public class Runner implements MessageConsumer { } params.add(appletClassName); + } // String outgoing[] = new String[params.size()]; // params.toArray(outgoing); @@ -250,121 +253,11 @@ public class Runner implements MessageConsumer { } - /* - protected VirtualMachine launchVirtualMachine_sun(String[] vmParams, String[] classParams) { - //vm = launchTarget(sb.toString()); - LaunchingConnector connector = - findLaunchingConnector("com.sun.jdi.CommandLineLaunch"); - //Map arguments = connectorArguments(connector, mainArgs); - - PApplet.println(connector); // gets the defaults - - Map arguments = connector.defaultArguments(); - //System.out.println(arguments); - -// for (Iterator itr = arguments.keySet().iterator(); itr.hasNext(); ) { -// Connector.Argument argument = -// (Connector.Argument) arguments.get(itr.next()); -// System.out.println(argument); -// } - - //connector.transport(). - - Connector.Argument mainArg = - (Connector.Argument)arguments.get("main"); - if (mainArg == null) { - throw new Error("Bad launching connector"); - } - String mainArgs = ""; - //mainArgs = addArgument(mainArgs, className); - if (classParams != null) { - for (int i = 0; i < classParams.length; i++) { - mainArgs = addArgument(mainArgs, classParams[i], ' '); - } - } - mainArg.setValue(mainArgs); - - //System.out.println("main args are: "); - //System.out.println(mainArgs); - -// if (watchFields) { -// // We need a VM that supports watchpoints -// Connector.Argument optionArg = -// (Connector.Argument)arguments.get("options"); -// if (optionArg == null) { -// throw new Error("Bad launching connector"); -// } -// optionArg.setValue("-classic"); -// } - String optionArgs = ""; - for (int i = 0; i < vmParams.length; i++) { - optionArgs = addArgument(optionArgs, vmParams[i], ' '); - } - // prevent any incorrect transport address b.s. from being added - // -Xrunjdwp:transport=dt_socket,address=cincinnati118.ipcorporate.com:55422,suspend=y - //optionArgs = addArgument(optionArgs, "-agentlib:jdwp=transport=dt_socket,address=localhost:12345,suspend=y", ' '); - //optionArgs += " -Xrunjdwp:transport=dt_socket,address=localhost:55422,suspend=y"; - //optionArgs = optionArgs + " -agentlib:jdwp=transport=dt_socket"; - //optionArgs = addArgument(optionArgs, "-Xrunjdwp:transport=dt_socket,address=localhost:55422,suspend=y", ' '); - - //optionArgs = addArgument(optionArgs, "address=127.0.0.1:54321", ' '); - //optionArgs = addArgument(optionArgs, "localAddress", ' '); - - Connector.Argument optionArg = - (Connector.Argument)arguments.get("options"); - optionArg.setValue(optionArgs); - -// Connector.Argument addressArg = -// (Connector.Argument)arguments.get("address"); - //arguments.put("raw.address", new Connector.Argument("blah")); - //PApplet.println("it's gonna be " + addressArg); - - //arguments.put("address", "localhost"); - -// Connector.Argument addressArg = -// (Connector.Argument)arguments.get("address"); -// addressArg.setValue("localhost"); - -// System.out.println("option args are: "); -// System.out.println(arguments.get("options")); - - System.out.println("args are " + arguments); - - // com.sun.tools.jdi.SunCommandLineLauncher - - // http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#sunlaunch - try { - return connector.launch(arguments); - } catch (IOException exc) { - throw new Error("Unable to launch target VM: " + exc); - } catch (IllegalConnectorArgumentsException exc) { - throw new Error("Internal error: " + exc); - } catch (VMStartException exc) { - exc.printStackTrace(); - System.err.println(); - System.err.println("Could not run the sketch."); - System.err.println("Make sure that you haven't set the maximum available memory too high."); - System.err.println("For more information, read revisions.txt and Help -> Troubleshooting."); - //System.err.println("Target VM failed to initialize:"); - //System.err.println("msg is " + exc.getMessage()); - //exc.printStackTrace(); - //throw new Error("Target VM failed to initialize: " + - //exc.getMessage()); - //throw new Error(exc.getMessage()); - //throw new RunnerException(exc.getMessage()); - //editor.error(exc); - editor.error("Could not run the sketch."); - return null; - } - } - */ - - protected VirtualMachine launchVirtualMachine(String[] vmParams, String[] classParams) { //vm = launchTarget(sb.toString()); - LaunchingConnector connector = - findLaunchingConnector("com.sun.jdi.RawCommandLineLaunch"); + LaunchingConnector connector = (LaunchingConnector) + findConnector("com.sun.jdi.RawCommandLineLaunch"); //PApplet.println(connector); // gets the defaults //Map arguments = connectorArguments(connector, mainArgs); @@ -447,9 +340,10 @@ public class Runner implements MessageConsumer { } System.err.println("For more information, read revisions.txt and Help \u2192 Troubleshooting."); } - if (editor != null) { + // changing this to separate editor and listener [091124] + //if (editor != null) { listener.statusError("Could not run the sketch."); - } + //} return null; } } @@ -493,7 +387,7 @@ public class Runner implements MessageConsumer { * start threads to forward remote error and output streams, * resume the remote VM, wait for the final event, and shutdown. */ - void generateTrace(PrintWriter writer) { + protected void generateTrace(PrintWriter writer) { vm.setDebugTraceMode(debugTraceMode); EventThread eventThread = null; @@ -515,7 +409,7 @@ public class Runner implements MessageConsumer { // process.getErrorStream(), // System.err); MessageSiphon ms = new MessageSiphon(process.getErrorStream(), this); - errThread = ms.thread; + errThread = ms.getThread(); outThread = new StreamRedirectThread("output reader", process.getInputStream(), @@ -545,7 +439,6 @@ public class Runner implements MessageConsumer { if (editor != null) { editor.internalRunnerClosed(); } - } catch (InterruptedException exc) { // we don't interrupt } @@ -554,20 +447,10 @@ public class Runner implements MessageConsumer { } - /** - * Find a com.sun.jdi.CommandLineLaunch connector - */ - LaunchingConnector findLaunchingConnector(String connectorName) { - //VirtualMachineManager mgr = Bootstrap.virtualMachineManager(); - - // Get the default connector. - // Not useful here since they all need different args. -// System.out.println(Bootstrap.virtualMachineManager().defaultConnector()); -// return Bootstrap.virtualMachineManager().defaultConnector(); - + protected Connector findConnector(String connectorName) { List connectors = Bootstrap.virtualMachineManager().allConnectors(); - // code to list available connectors + // debug: code to list available connectors // Iterator iter2 = connectors.iterator(); // while (iter2.hasNext()) { // Connector connector = (Connector)iter2.next(); @@ -578,10 +461,10 @@ public class Runner implements MessageConsumer { while (iter.hasNext()) { Connector connector = (Connector)iter.next(); if (connector.name().equals(connectorName)) { - return (LaunchingConnector)connector; + return connector; } } - throw new Error("No launching connector"); + throw new Error("No connector"); } @@ -611,7 +494,17 @@ public class Runner implements MessageConsumer { // System.out.println(or.referenceType().fields()); // if (name.startsWith("java.lang.")) { // name = name.substring(10); - if (exceptionName.equals("java.lang.OutOfMemoryError")) { + if (!handleCommonErrors(exceptionName, message, listener)) { + reportException(message, event.thread()); + } + if (editor != null) { + editor.internalRunnerClosed(); + } + } + + public static boolean handleCommonErrors(final String exceptionClass, final String message, final RunnerListener listener) + { + if (exceptionClass.equals("java.lang.OutOfMemoryError")) { listener.statusError("OutOfMemoryError: You may need to increase the memory setting in Preferences."); System.err.println("An OutOfMemoryError means that your code is either using up too much memory"); System.err.println("because of a bug (e.g. creating an array that's too large, or unintentionally"); @@ -619,96 +512,83 @@ public class Runner implements MessageConsumer { System.err.println("If your sketch uses a lot of memory (for instance if it loads a lot of data files)"); System.err.println("you can increase the memory available to your sketch using the Preferences window."); - } else if (exceptionName.equals("java.lang.StackOverflowError")) { + } else if (exceptionClass.equals("java.lang.StackOverflowError")) { listener.statusError("StackOverflowError: This sketch is attempting too much recursion."); System.err.println("A StackOverflowError means that you have a bug that's causing a function"); System.err.println("to be called recursively (it's calling itself and going in circles),"); System.err.println("or you're intentionally calling a recursive function too much,"); System.err.println("and your code should be rewritten in a more efficient manner."); - } else if (exceptionName.equals("java.lang.UnsupportedClassVersionError")) { + } else if (exceptionClass.equals("java.lang.UnsupportedClassVersionError")) { listener.statusError("UnsupportedClassVersionError: A library is using code compiled with an unsupported version of Java."); System.err.println("This version of Processing only supports libraries and JAR files compiled for Java 1.5."); System.err.println("A library used by this sketch was compiled for Java 1.6 or later, "); System.err.println("and needs to be recompiled to be compatible with Java 1.5."); - - } else if (exceptionName.equals("java.lang.NoSuchMethodError") || exceptionName.equals("java.lang.NoSuchFieldError")) { - listener.statusError(exceptionName.substring(10) + ": You're probably using a library that's incompatible with this version of Processing."); - - } else if (message.equals("ClassNotFoundException: quicktime.std.StdQTException")) { - listener.statusError("Could not find QuickTime, please reinstall QuickTime 7 or later."); - + } else if (exceptionClass.equals("java.lang.NoSuchMethodError") || exceptionClass.equals("java.lang.NoSuchFieldError")) { + listener.statusError(exceptionClass.substring(10) + ": You're probably using a library that's incompatible with this version of Processing."); + } else if (message!=null && + message.equals("ClassNotFoundException: quicktime.std.StdQTException")) { + listener + .statusError("Could not find QuickTime, please reinstall QuickTime 7 or later."); } else { - reportException(message, event.thread()); + return false; } - editor.internalRunnerClosed(); + return true; } - - // This may be called more than one time per error in the VM, + // TODO: This may be called more than one time per error in the VM, // presumably because exceptions might be wrapped inside others, // and this will fire for both. protected void reportException(String message, ThreadReference thread) { - try { - int codeIndex = -1; - int lineNumber = -1; + listener.statusError(findException(message, thread)); + } + + + /** + * Move through a list of stack frames, searching for references to code + * found in the current sketch. Return with a RunnerException that contains + * the location of the error, or if nothing is found, just return with a + * RunnerException that wraps the error message itself. + */ + RunnerException findException(String message, ThreadReference thread) { + try { + // use to dump the stack for debugging +// for (StackFrame frame : thread.frames()) { +// System.out.println("frame: " + frame); +// } - // Any of the thread.blah() methods can throw an AbsentInformationEx - // if that bit of data is missing. If so, just write out the error - // message to the console. List frames = thread.frames(); for (StackFrame frame : frames) { -// System.out.println("frame: " + frame); + try { Location location = frame.location(); String filename = null; filename = location.sourceName(); - lineNumber = location.lineNumber(); - - String appletJavaFile = appletClassName + ".java"; - SketchCode errorCode = null; - if (filename.equals(appletJavaFile)) { - for (SketchCode code : sketch.getCode()) { - if (code.isExtension("pde")) { - if (lineNumber >= code.getPreprocOffset()) { - errorCode = code; + int lineNumber = location.lineNumber() - 1; + RunnerException rex = + sketch.placeException(message, filename, lineNumber); + if (rex != null) { + return rex; } - } - } - } else { - for (SketchCode code : sketch.getCode()) { - if (code.isExtension("java")) { - if (filename.equals(code.getFileName())) { - errorCode = code; - } - } - } - } - codeIndex = sketch.getCodeIndex(errorCode); - - if (codeIndex != -1) { - //System.out.println("got line num " + lineNumber); - // in case this was a tab that got embedded into the main .java - lineNumber -= sketch.getCode(codeIndex).getPreprocOffset(); - - // lineNumber is 1-indexed, but editor wants zero-indexed - lineNumber--; - - // getMessage() will be what's shown in the editor - exception = new RunnerException(message, codeIndex, lineNumber, -1); - exception.hideStackTrace(); - listener.statusError(exception); - return; - } - } } catch (AbsentInformationException e) { + // Any of the thread.blah() methods can throw an AbsentInformationEx + // if that bit of data is missing. If so, just write out the error + // message to the console. //e.printStackTrace(); // not useful exception = new RunnerException(message); exception.hideStackTrace(); listener.statusError(exception); - + } + } } catch (IncompatibleThreadStateException e) { + // This shouldn't happen, but if it does, print the exception in case + // it's something that needs to be debugged separately. e.printStackTrace(); } + // Give up, nothing found inside the pile of stack frames + RunnerException rex = new RunnerException(message); + // exception is being created /here/, so stack trace is not useful + rex.hideStackTrace(); + return rex; } @@ -727,26 +607,7 @@ public class Runner implements MessageConsumer { } vm = null; } - - //if (window != null) window.hide(); -// if (window != null) { -// //System.err.println("disposing window"); -// window.dispose(); -// window = null; -// } - - /* - if (process != null) { - try { - process.destroy(); - } catch (Exception e) { - //System.err.println("(ignored) error while destroying"); - //e.printStackTrace(); } - process = null; - } - */ - } // made synchronized for rev 87 @@ -762,7 +623,10 @@ public class Runner implements MessageConsumer { // that signals that the applet has been quit. if (s.indexOf(PApplet.EXTERNAL_STOP) == 0) { //System.out.println("external: quit"); - editor.internalCloseRunner(); + if (editor != null) { + //editor.internalCloseRunner(); // [091124] + editor.handleStop(); + } return; } @@ -773,281 +637,23 @@ public class Runner implements MessageConsumer { int space = nums.indexOf(' '); int left = Integer.parseInt(nums.substring(0, space)); int top = Integer.parseInt(nums.substring(space + 1)); + // this is only fired when connected to an editor editor.setSketchLocation(new Point(left, top)); //System.out.println("external: move to " + left + " " + top); return; } - // Removed while doing cleaning for 0145, - // it seems that this is never actually printed out. - /* - // this is PApplet sending a message saying "i'm about to spew - // a stack trace because an error occurred during PApplet.run()" - if (s.indexOf(PApplet.LEECH_WAKEUP) == 0) { - // newMessage being set to 'true' means that the next time - // message() is called, expect the first line of the actual - // error message & stack trace to be sent from the applet. - newMessage = true; - return; // this line ignored - } - */ - // these are used for debugging, in case there are concerns // that some errors aren't coming through properly - /* - if (s.length() > 2) { - System.err.println(newMessage); - System.err.println("message " + s.length() + ":" + s); - } - */ +// if (s.length() > 2) { +// System.err.println(newMessage); +// System.err.println("message " + s.length() + ":" + s); +// } + // always shove out the mesage, since it might not fall under // the same setup as we're expecting System.err.print(s); //System.err.println("[" + s.length() + "] " + s); System.err.flush(); - -// // exit here because otherwise the exception name -// // may be titled with a blank string -// if (s.trim().length() == 0) return; -// -// // annoying, because it seems as though the terminators -// // aren't being sent properly -// //System.err.println(s); -// -// //if (newMessage && s.length() > 2) { -// if (newMessage) { -// exception = new RunnerException(s); // type of java ex -// exception.hideStackTrace(); -// //System.out.println("setting ex type to " + s); -// newMessage = false; -// foundMessageSource = false; -// messageLineCount = 0; -// -// } else { -// messageLineCount++; -// -// /* -//java.lang.NullPointerException -// at javatest.(javatest.java:5) -// at Temporary_2425_1153.draw(Temporary_2425_1153.java:11) -// at PApplet.nextFrame(PApplet.java:481) -// at PApplet.run(PApplet.java:428) -// at java.lang.Thread.run(Unknown Source) -// */ -// -// if (!foundMessageSource) { -// // " at javatest.(javatest.java:5)" -// // -> "javatest.(javatest.java:5)" -// int atIndex = s.indexOf("at "); -// if (atIndex == -1) { -// //System.err.println(s); // stop double-printing exceptions -// return; -// } -// s = s.substring(atIndex + 3); -// -// // added for 0124 to improve error handling -// // not highlighting lines if it's in the p5 code -// if (s.startsWith("processing.")) return; -// // no highlight if it's java.lang.whatever -// if (s.startsWith("java.")) return; -// -// // "javatest.(javatest.java:5)" -// // -> "javatest." and "(javatest.java:5)" -// int startParen = s.indexOf('('); -// // at javatest.(javatest.java:5) -// //String pkgClassFxn = null; -// //String fileLine = null; -// int codeIndex = -1; -// int lineNumber = -1; -// -// if (startParen == -1) { -// //pkgClassFxn = s; -// -// } else { -// //pkgClassFxn = s.substring(0, startParen); -// -// // "(javatest.java:5)" -// String fileAndLine = s.substring(startParen + 1); -// int stopParen = fileAndLine.indexOf(')'); -// //fileAndLine = fileAndLine.substring(0, fileAndLine.length() - 1); -// fileAndLine = fileAndLine.substring(0, stopParen); -// //System.out.println("file 'n line " + fileAndLine); -// -// //if (!fileAndLine.equals("Unknown Source")) { -// // "javatest.java:5" -// int colonIndex = fileAndLine.indexOf(':'); -// if (colonIndex != -1) { -// String filename = fileAndLine.substring(0, colonIndex); -// // "javatest.java" and "5" -// //System.out.println("filename = " + filename); -// //System.out.println("pre0 = " + sketch.code[0].preprocName); -// //for (int i = 0; i < sketch.codeCount; i++) { -// //System.out.println(i + " " + sketch.code[i].lineOffset + " " + -// // sketch.code[i].preprocName); -// //} -// lineNumber = -// Integer.parseInt(fileAndLine.substring(colonIndex + 1)) - 1; -// -// for (int i = 0; i < sketch.getCodeCount(); i++) { -// SketchCode code = sketch.getCode(i); -// //System.out.println(code.preprocName + " " + lineNumber + " " + -// // code.preprocOffset); -// if (((code.preprocName == null) && -// (lineNumber >= code.preprocOffset)) || -// ((code.preprocName != null) && -// code.preprocName.equals(filename))) { -// codeIndex = i; -// //System.out.println("got codeindex " + codeIndex); -// //break; -// //} else if ( -// } -// } -// -// if (codeIndex != -1) { -// //System.out.println("got line num " + lineNumber); -// // in case this was a tab that got embedded into the main .java -// lineNumber -= sketch.getCode(codeIndex).preprocOffset; -// -// // this may have a paren on the end, if so need to strip -// // down to just the digits -// /* -// int lastNumberIndex = colonIndex + 1; -// while ((lastNumberIndex < fileAndLine.length()) && -// Character.isDigit(fileAndLine.charAt(lastNumberIndex))) { -// lastNumberIndex++; -// } -// */ -// -// // lineNumber is 1-indexed, but editor wants zero-indexed -// // getMessage() will be what's shown in the editor -// exception = -// new RunnerException(exception.getMessage(), -// codeIndex, lineNumber, -1); -// exception.hideStackTrace(); -// foundMessageSource = true; -// } -// } -// } -// editor.error(exception); -// -// /* -// int index = s.indexOf(className + ".java"); -// if (index != -1) { -// int len = (className + ".java").length(); -// String lineNumberStr = s.substring(index + len + 1); -// index = lineNumberStr.indexOf(')'); -// lineNumberStr = lineNumberStr.substring(0, index); -// try { -// exception.line = Integer.parseInt(lineNumberStr) - 1; //2; -// } catch (NumberFormatException e) { } -// //e.printStackTrace(); // a recursive error waiting to happen? -// // if nfe occurs, who cares, still send the error on up -// editor.error(exception); -// */ -// -// /* -// // WARNING THESE ARE DISABLED!! -// } else if ((index = s.indexOf(className + ".class")) != -1) { -// // code to check for: -// // at Temporary_484_3845.loop(Compiled Code) -// // would also probably get: -// // at Temporary_484_3845.loop -// // which (i believe) is used by the mac and/or jview -// String functionStr = s.substring(index + -// (className + ".class").length() + 1); -// index = functionStr.indexOf('('); -// if (index != -1) { -// functionStr = functionStr.substring(0, index); -// } -// exception = new RunnerException(//"inside \"" + functionStr + "()\": " + -// exception.getMessage() + -// " inside " + functionStr + "() " + -// "[add Compiler.disable() to setup()]"); -// editor.error(exception); -// // this will fall through in tihs example: -// // at Temporary_4636_9696.pootie(Compiled Code) -// // at Temporary_4636_9696.loop(Temporary_4636_9696.java:24) -// // because pootie() (re)sets the exception title -// // and throws it, but then the line number gets set -// // because of the line that comes after -// */ -// -// } else if (messageLineCount > 10) { // 5 -> 10 for 0088 -// // this means the class name may not be mentioned -// // in the stack trace.. this is just a general purpose -// // error, but needs to make it through anyway. -// // so if five lines have gone past, might as well signal -// messageLineCount = -100; -// exception = new RunnerException(exception.getMessage()); -// exception.hideStackTrace(); -// editor.error(exception); -// -// } else { -// //System.err.print(s); -// } -// //System.out.println("got it " + s); -// } } - - - ////////////////////////////////////////////////////////////// - - - /** - * Siphons from an InputStream of System.out (from a Process) - * and sends it to the real System.out. - */ - class SystemOutSiphon implements Runnable { - InputStream input; - Thread thread; - - public SystemOutSiphon(InputStream input) { - this.input = input; - - thread = new Thread(this); - // unless this is set to min, it seems to hork the app - // since it's in charge of stuffing the editor console with strings - // maybe it's time to get rid of/fix that friggin console - // ...disabled for 0075, with 0074's fix for code folder hanging - // this only seems to make the console unresponsive - //thread.setPriority(Thread.MIN_PRIORITY); - thread.start(); } - - public void run() { - byte boofer[] = new byte[256]; - - while (Thread.currentThread() == thread) { - try { - // can't use a buffered reader here because incremental - // print statements are interesting too.. causes some - // disparity with how System.err gets spewed, oh well. - int count = input.read(boofer, 0, boofer.length); - if (count == -1) { - thread = null; - - } else { - System.out.print(new String(boofer, 0, count)); - //System.out.flush(); - } - - } catch (IOException e) { - // this is prolly because the app was quit & the stream broken - //e.printStackTrace(System.out); - //e.printStackTrace(); - thread = null; - - } catch (Exception e) { - //System.out.println("SystemOutSiphon: i just died in your arms tonight"); - // on mac os x, this will spew a "Bad File Descriptor" ex - // each time an external app is shut down. - //e.printStackTrace(); - thread = null; - //System.out.println(""); - } - //System.out.println("SystemOutSiphon: out"); - //thread = null; - } - } - } -} diff --git a/app/src/processing/app/debug/RunnerException.java b/app/src/processing/app/debug/RunnerException.java index 0b4e59154..97887ed7e 100644 --- a/app/src/processing/app/debug/RunnerException.java +++ b/app/src/processing/app/debug/RunnerException.java @@ -37,10 +37,18 @@ public class RunnerException extends Exception /*RuntimeException*/ { public RunnerException(String message) { - this(message, -1, -1, -1, true); + this(message, true); } + public RunnerException(String message, boolean showStackTrace) { + this(message, -1, -1, -1, showStackTrace); + } + public RunnerException(String message, int file, int line) { + this(message, file, line, -1, true); + } + + public RunnerException(String message, int file, int line, int column) { this(message, file, line, column, true); } diff --git a/app/src/processing/app/debug/RunnerListener.java b/app/src/processing/app/debug/RunnerListener.java index 1728d7972..b9505a510 100644 --- a/app/src/processing/app/debug/RunnerListener.java +++ b/app/src/processing/app/debug/RunnerListener.java @@ -28,4 +28,6 @@ public interface RunnerListener { public void statusError(String message); public void statusError(Exception exception); + + public void statusNotice(String message); } \ No newline at end of file diff --git a/app/src/processing/app/linux/Platform.java b/app/src/processing/app/linux/Platform.java index 496e926ae..ff89c813b 100644 --- a/app/src/processing/app/linux/Platform.java +++ b/app/src/processing/app/linux/Platform.java @@ -67,10 +67,18 @@ public class Platform extends processing.app.Platform { return true; } + // Attempt to use xdg-open + try { + Process p = Runtime.getRuntime().exec(new String[] { "xdg-open" }); + p.waitFor(); + Preferences.set("launcher", "xdg-open"); + return true; + } catch (Exception e) { } + // Attempt to use gnome-open try { Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" }); - /*int result =*/ p.waitFor(); + p.waitFor(); // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04) Preferences.set("launcher", "gnome-open"); return true; @@ -79,7 +87,7 @@ public class Platform extends processing.app.Platform { // Attempt with kde-open try { Process p = Runtime.getRuntime().exec(new String[] { "kde-open" }); - /*int result =*/ p.waitFor(); + p.waitFor(); Preferences.set("launcher", "kde-open"); return true; } catch (Exception e) { } @@ -100,7 +108,8 @@ public class Platform extends processing.app.Platform { e.printStackTrace(); } } else { - System.out.println("not available"); + System.out.println("No launcher set, cannot open " + + file.getAbsolutePath()); } } } diff --git a/app/src/processing/app/macosx/Platform.java b/app/src/processing/app/macosx/Platform.java index 6a156e8f0..06a8f5214 100644 --- a/app/src/processing/app/macosx/Platform.java +++ b/app/src/processing/app/macosx/Platform.java @@ -25,12 +25,15 @@ package processing.app.macosx; import java.awt.Insets; import java.io.File; import java.io.FileNotFoundException; +import java.lang.reflect.Method; +import java.net.URI; import javax.swing.UIManager; import com.apple.eio.FileManager; import processing.app.Base; +import processing.core.PApplet; /** @@ -103,36 +106,45 @@ public class Platform extends processing.app.Platform { public void openURL(String url) throws Exception { - if (!url.startsWith("http://")) { + if (PApplet.javaVersion < 1.6f) { + if (url.startsWith("http://")) { + // formerly com.apple.eio.FileManager.openURL(url); + // but due to deprecation, instead loading dynamically + try { + 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 { // Assume this is a file instead, and just open it. // Extension of http://dev.processing.org/bugs/show_bug.cgi?id=1010 processing.core.PApplet.open(url); - - /* - // prepend file:// on this guy since it's a file - url = "file://" + url; - - // replace spaces with %20 for the file url - // otherwise the mac doesn't like to open it - // can't just use URLEncoder, since that makes slashes into - // %2F characters, which is no good. some might say "useless" - if (url.indexOf(' ') != -1) { - StringBuffer sb = new StringBuffer(); - char c[] = url.toCharArray(); - for (int i = 0; i < c.length; i++) { - if (c[i] == ' ') { - sb.append("%20"); - } else { - sb.append(c[i]); - } - } - url = sb.toString(); } - */ + } else { + try { + Class desktopClass = Class.forName("java.awt.Desktop"); + Method getMethod = desktopClass.getMethod("getDesktop"); + Object desktop = getMethod.invoke(null, new Object[] { }); + + // for Java 1.6, replacing with java.awt.Desktop.browse() + // and java.awt.Desktop.open() + if (url.startsWith("http://")) { // browse to a location + Method browseMethod = + desktopClass.getMethod("browse", new Class[] { URI.class }); + browseMethod.invoke(desktop, new Object[] { new URI(url) }); + } else { // open a file + Method openMethod = + desktopClass.getMethod("open", new Class[] { File.class }); + openMethod.invoke(desktop, new Object[] { new File(url) }); + } + } catch (Exception e) { + e.printStackTrace(); + } + } } - // for Java 1.6, replace with java.awt.Desktop.browse() and java.awt.Desktop.open() - com.apple.eio.FileManager.openURL(url); - } public boolean openFolderAvailable() { diff --git a/app/src/processing/app/macosx/ThinkDifferent.java b/app/src/processing/app/macosx/ThinkDifferent.java index 1d292b399..f0c13cbba 100644 --- a/app/src/processing/app/macosx/ThinkDifferent.java +++ b/app/src/processing/app/macosx/ThinkDifferent.java @@ -50,7 +50,8 @@ public class ThinkDifferent implements ApplicationListener { static protected void init(Base base) { if (application == null) { - application = new com.apple.eawt.Application(); + //application = new com.apple.eawt.Application(); + application = com.apple.eawt.Application.getApplication(); } if (adapter == null) { adapter = new ThinkDifferent(base); diff --git a/app/src/processing/app/preproc/PdePreprocessor.java b/app/src/processing/app/preproc/PdePreprocessor.java index b00b7cb03..10b940536 100644 --- a/app/src/processing/app/preproc/PdePreprocessor.java +++ b/app/src/processing/app/preproc/PdePreprocessor.java @@ -51,15 +51,9 @@ public class PdePreprocessor { List prototypes; - - - - String[] defaultImports; - // these ones have the .* at the end, since a class name might be at the end // instead of .* which would make trouble other classes using this can lop // off the . and anything after it to produce a package name consistently. - //public String extraImports[]; ArrayList programImports; // imports just from the code folder, treated differently @@ -71,24 +65,24 @@ public class PdePreprocessor { PrintStream stream; String program; String buildPath; + // starts as sketch name, ends as main class name String name; /** * Setup a new preprocessor. */ - public PdePreprocessor() { } - - public int writePrefix(String program, String buildPath, - String name, String codeFolderPackages[]) - throws FileNotFoundException { - this.buildPath = buildPath; - this.name = name; - + public PdePreprocessor() { int tabSize = Preferences.getInteger("editor.tabs.size"); char[] indentChars = new char[tabSize]; Arrays.fill(indentChars, ' '); indent = new String(indentChars); + } + + public int writePrefix(String program, String buildPath, + String sketchName, String codeFolderPackages[]) throws FileNotFoundException { + this.buildPath = buildPath; + this.name = sketchName; // if the program ends with no CR or LF an OutOfMemoryError will happen. // not gonna track down the bug now, so here's a hack for it: @@ -99,52 +93,13 @@ public class PdePreprocessor { // an OutOfMemoryError or NullPointerException will happen. // again, not gonna bother tracking this down, but here's a hack. // http://dev.processing.org/bugs/show_bug.cgi?id=16 - Sketch.scrubComments(program); - // this returns the scrubbed version, but more important for this - // function, it'll check to see if there are errors with the comments. + String scrubbed = Sketch.scrubComments(program); + // If there are errors, an exception is thrown and this fxn exits. if (Preferences.getBoolean("preproc.substitute_unicode")) { - // check for non-ascii chars (these will be/must be in unicode format) - char p[] = program.toCharArray(); - int unicodeCount = 0; - for (int i = 0; i < p.length; i++) { - if (p[i] > 127) unicodeCount++; - } - // if non-ascii chars are in there, convert to unicode escapes - if (unicodeCount != 0) { - // add unicodeCount * 5.. replacing each unicode char - // with six digit uXXXX sequence (xxxx is in hex) - // (except for nbsp chars which will be a replaced with a space) - int index = 0; - char p2[] = new char[p.length + unicodeCount*5]; - for (int i = 0; i < p.length; i++) { - if (p[i] < 128) { - p2[index++] = p[i]; - - } else if (p[i] == 160) { // unicode for non-breaking space - p2[index++] = ' '; - - } else { - int c = p[i]; - p2[index++] = '\\'; - p2[index++] = 'u'; - char str[] = Integer.toHexString(c).toCharArray(); - // add leading zeros, so that the length is 4 - //for (int i = 0; i < 4 - str.length; i++) p2[index++] = '0'; - for (int m = 0; m < 4 - str.length; m++) p2[index++] = '0'; - System.arraycopy(str, 0, p2, index, str.length); - index += str.length; - } - } - program = new String(p2, 0, index); - } + program = substituteUnicode(program); } - // These may change in-between (if the prefs panel adds this option) - // so grab them here on construction. - String prefsLine = Preferences.get("preproc.imports"); - defaultImports = PApplet.splitTokens(prefsLine, ", "); - //String importRegexp = "(?:^|\\s|;)(import\\s+)(\\S+)(\\s*;)"; String importRegexp = "^\\s*#include\\s+[<\"](\\S+)[\">]"; programImports = new ArrayList(); @@ -184,8 +139,47 @@ public class PdePreprocessor { return headerCount + prototypeCount; } + + static String substituteUnicode(String program) { + // check for non-ascii chars (these will be/must be in unicode format) + char p[] = program.toCharArray(); + int unicodeCount = 0; + for (int i = 0; i < p.length; i++) { + if (p[i] > 127) unicodeCount++; + } + // if non-ascii chars are in there, convert to unicode escapes + if (unicodeCount != 0) { + // add unicodeCount * 5.. replacing each unicode char + // with six digit uXXXX sequence (xxxx is in hex) + // (except for nbsp chars which will be a replaced with a space) + int index = 0; + char p2[] = new char[p.length + unicodeCount*5]; + for (int i = 0; i < p.length; i++) { + if (p[i] < 128) { + p2[index++] = p[i]; + + } else if (p[i] == 160) { // unicode for non-breaking space + p2[index++] = ' '; + + } else { + int c = p[i]; + p2[index++] = '\\'; + p2[index++] = 'u'; + char str[] = Integer.toHexString(c).toCharArray(); + // add leading zeros, so that the length is 4 + //for (int i = 0; i < 4 - str.length; i++) p2[index++] = '0'; + for (int m = 0; m < 4 - str.length; m++) p2[index++] = '0'; + System.arraycopy(str, 0, p2, index, str.length); + index += str.length; + } + } + program = new String(p2, 0, index); + } + return program; + } + /** - * preprocesses a pde file and write out a java file + * preprocesses a pde file and writes out a java file * @return the classname of the exported Java */ //public String write(String program, String buildPath, String name, diff --git a/app/src/processing/app/syntax/InputHandler.java b/app/src/processing/app/syntax/InputHandler.java index db7260da5..9a11d3866 100644 --- a/app/src/processing/app/syntax/InputHandler.java +++ b/app/src/processing/app/syntax/InputHandler.java @@ -24,7 +24,7 @@ import java.util.*; * to the implementations of this class to do so. * * @author Slava Pestov - * @version $Id: InputHandler.java 4168 2008-08-09 17:24:37Z fry $ + * @version $Id: InputHandler.java 6126 2010-02-16 23:43:53Z fry $ */ public abstract class InputHandler extends KeyAdapter { @@ -70,6 +70,9 @@ public abstract class InputHandler extends KeyAdapter public static final ActionListener SELECT_PREV_WORD = new prev_word(true); public static final ActionListener REPEAT = new repeat(); public static final ActionListener TOGGLE_RECT = new toggle_rect(); + public static final ActionListener CLIPBOARD_CUT = new clipboard_cut(); // [fry] + public static final ActionListener CLIPBOARD_COPY = new clipboard_copy(); + public static final ActionListener CLIPBOARD_PASTE = new clipboard_paste(); // Default action public static final ActionListener INSERT_CHAR = new insert_char(); @@ -113,6 +116,9 @@ public abstract class InputHandler extends KeyAdapter actions.put("repeat",REPEAT); actions.put("toggle-rect",TOGGLE_RECT); actions.put("insert-char",INSERT_CHAR); + actions.put("clipboard-cut",CLIPBOARD_CUT); + actions.put("clipboard-copy",CLIPBOARD_COPY); + actions.put("clipboard-paste",CLIPBOARD_PASTE); } /** @@ -1077,6 +1083,34 @@ public abstract class InputHandler extends KeyAdapter } } + + public static class clipboard_cut implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + getTextArea(evt).cut(); + } + } + + + public static class clipboard_copy implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + getTextArea(evt).copy(); + } + } + + + public static class clipboard_paste implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + getTextArea(evt).paste(); + } + } + + public static class insert_char implements ActionListener, InputHandler.NonRepeatable { diff --git a/app/src/processing/app/syntax/JEditTextArea.java b/app/src/processing/app/syntax/JEditTextArea.java index 0cc9e0146..d5c01c48a 100644 --- a/app/src/processing/app/syntax/JEditTextArea.java +++ b/app/src/processing/app/syntax/JEditTextArea.java @@ -22,6 +22,9 @@ import java.awt.event.*; import java.awt.*; import java.util.Enumeration; import java.util.Vector; +import java.awt.im.InputMethodRequests; + +import processing.app.syntax.im.InputMethodSupport; /** * jEdit's text area component. It is more suited for editing program @@ -51,7 +54,7 @@ import java.util.Vector; * + "}"); * * @author Slava Pestov - * @version $Id: JEditTextArea.java 5625 2009-06-07 21:08:59Z fry $ + * @version $Id: JEditTextArea.java 6123 2010-02-16 21:43:44Z fry $ */ public class JEditTextArea extends JComponent { @@ -127,6 +130,16 @@ public class JEditTextArea extends JComponent }); } + /** + * Inline Input Method Support for Japanese. + */ + private InputMethodSupport inputMethodSupport = null; + public InputMethodRequests getInputMethodRequests() { + if (inputMethodSupport == null) { + inputMethodSupport = new InputMethodSupport(this); + } + return inputMethodSupport; + } /** * Get current position of the vertical scroll bar. [fry] diff --git a/app/src/processing/app/syntax/PdeTextAreaDefaults.java b/app/src/processing/app/syntax/PdeTextAreaDefaults.java index a2dda2b78..b715255be 100644 --- a/app/src/processing/app/syntax/PdeTextAreaDefaults.java +++ b/app/src/processing/app/syntax/PdeTextAreaDefaults.java @@ -34,18 +34,22 @@ public class PdeTextAreaDefaults extends TextAreaDefaults { inputHandler = new DefaultInputHandler(); //inputHandler.addDefaultKeyBindings(); // 0122 - // use option on mac for things that are ctrl on windows/linux + // use option on mac for text edit controls that are ctrl on windows/linux String mod = Base.isMacOS() ? "A" : "C"; // right now, ctrl-up/down is select up/down, but mod should be // used instead, because the mac expects it to be option(alt) inputHandler.addKeyBinding("BACK_SPACE", InputHandler.BACKSPACE); + // for 0122, shift-backspace is delete, for 0176, it's now a preference, + // to prevent holy warriors from attacking me for it. + if (Preferences.getBoolean("editor.keys.shift_backspace_is_delete")) { + inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.DELETE); + } else { + inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.BACKSPACE); + } + inputHandler.addKeyBinding("DELETE", InputHandler.DELETE); - - //inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.BACKSPACE); - // for 0122, shift-backspace is delete - inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.DELETE); inputHandler.addKeyBinding("S+DELETE", InputHandler.DELETE); // the following two were changing for 0122 for better mac/pc compatability @@ -57,12 +61,23 @@ public class PdeTextAreaDefaults extends TextAreaDefaults { //inputHandler.addKeyBinding("TAB", InputHandler.INSERT_TAB); inputHandler.addKeyBinding("INSERT", InputHandler.OVERWRITE); + + // http://dev.processing.org/bugs/show_bug.cgi?id=162 + // added for 0176, though the bindings do not appear relevant for osx + if (Preferences.getBoolean("editor.keys.alternative_cut_copy_paste")) { + inputHandler.addKeyBinding("C+INSERT", InputHandler.CLIPBOARD_COPY); + inputHandler.addKeyBinding("S+INSERT", InputHandler.CLIPBOARD_PASTE); + inputHandler.addKeyBinding("S+DELETE", InputHandler.CLIPBOARD_CUT); + } + // disabling for 0122, not sure what this does //inputHandler.addKeyBinding("C+\\", InputHandler.TOGGLE_RECT); - // for 0122, these have been changed for better compatability + // for 0122, these have been changed for better compatibility // HOME and END now mean the beginning/end of the document - if (Base.isMacOS()) { + // for 0176 changed this to a preference so that the Mac OS X people + // can get the "normal" behavior as well if they prefer. + if (Preferences.getBoolean("editor.keys.home_and_end_travel_far")) { inputHandler.addKeyBinding("HOME", InputHandler.DOCUMENT_HOME); inputHandler.addKeyBinding("END", InputHandler.DOCUMENT_END); inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_DOC_HOME); diff --git a/app/src/processing/app/syntax/TextAreaPainter.java b/app/src/processing/app/syntax/TextAreaPainter.java index 229df09b7..cc93aeded 100644 --- a/app/src/processing/app/syntax/TextAreaPainter.java +++ b/app/src/processing/app/syntax/TextAreaPainter.java @@ -12,6 +12,7 @@ package processing.app.syntax; import processing.app.*; +import processing.app.syntax.im.CompositionTextPainter; import javax.swing.ToolTipManager; import javax.swing.text.*; @@ -33,6 +34,9 @@ implements TabExpander, Printable /** Current setting for editor.antialias preference */ boolean antialias; + /** A specific painter composed by the InputMethod.*/ + protected CompositionTextPainter compositionTextPainter; + /** * Creates a new repaint manager. This should be not be called * directly. @@ -73,6 +77,16 @@ implements TabExpander, Printable eolMarkers = defaults.eolMarkers; } + /** + * Get CompositionTextPainter. if CompositionTextPainter is not created, create it. + */ + public CompositionTextPainter getCompositionTextpainter(){ + if(compositionTextPainter == null){ + compositionTextPainter = new CompositionTextPainter(textArea); + } + return compositionTextPainter; + } + /** * Returns if this component can be traversed by pressing the * Tab key. This returns false. @@ -602,7 +616,12 @@ implements TabExpander, Printable y += fm.getHeight(); x = Utilities.drawTabbedText(currentLine,x,y,gfx,this,0); - + /* + * Draw characters via input method. + */ + if (compositionTextPainter != null && compositionTextPainter.hasComposedTextLayout()) { + compositionTextPainter.draw(gfx, lineHighlightColor); + } if (eolMarkers) { gfx.setColor(eolMarkerColor); gfx.drawString(".",x,y); @@ -625,7 +644,12 @@ implements TabExpander, Printable x = SyntaxUtilities.paintSyntaxLine(currentLine, currentLineTokens, styles, this, gfx, x, y); - + /* + * Draw characters via input method. + */ + if (compositionTextPainter != null && compositionTextPainter.hasComposedTextLayout()) { + compositionTextPainter.draw(gfx, lineHighlightColor); + } if (eolMarkers) { gfx.setColor(eolMarkerColor); gfx.drawString(".",x,y); diff --git a/app/src/processing/app/syntax/im/CompositionTextManager.java b/app/src/processing/app/syntax/im/CompositionTextManager.java new file mode 100644 index 000000000..3c2bec063 --- /dev/null +++ b/app/src/processing/app/syntax/im/CompositionTextManager.java @@ -0,0 +1,187 @@ +package processing.app.syntax.im; + +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.font.FontRenderContext; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; + +import javax.swing.text.BadLocationException; + +import processing.app.syntax.JEditTextArea; +import processing.app.syntax.TextAreaPainter; + +/** + * This class Manage texts from input method + * by begin-process-end steps. + * + * First, if a user start inputing via input method, + * beginCompositionText is called from InputMethodSupport. + * Second, the user continues from input method, processCompositionText is called + * and reflect user inputs to text area. + * Finally the user try to commit text, endCompositionText is called. + * + * @author Takashi Maekawa (takachin@generative.info) + */ + +public class CompositionTextManager { + private JEditTextArea textArea; + private String prevComposeString; + private int prevCommittedCount; + private boolean isInputProcess; + private int initialCaretPosition; + public static final int COMPOSING_UNDERBAR_HEIGHT = 5; + + /** + * Create text manager class with a textarea. + * @param textArea texarea component for PDE. + */ + public CompositionTextManager(JEditTextArea textArea) { + this.textArea = textArea; + prevComposeString = ""; + isInputProcess = false; + prevCommittedCount = 0; + } + + /** + * Get this text manager is whether in input process or not. + */ + public boolean getIsInputProcess() { + return isInputProcess; + } + + /** + * Called when a user begins input from input method. + * This method initializes text manager. + * + * @param text Text from InputMethodEvent. + * @param commited_count Numbers of committed characters in text. + */ + public void beginCompositionText(AttributedCharacterIterator text, int committed_count) { + isInputProcess = true; + prevComposeString = ""; + initialCaretPosition = textArea.getCaretPosition(); + processCompositionText(text, committed_count); + } + + /** + * Called when a user processing input characters and + * select candidates from input method. + * + * @param text Text from InputMethodEvent. + * @param commited_count Numbers of committed characters in text. + */ + public void processCompositionText(AttributedCharacterIterator text, int committed_count) { + int layoutCaretPosition = initialCaretPosition + committed_count; + CompositionTextPainter compositionPainter = textArea.getPainter().getCompositionTextpainter(); + compositionPainter.setComposedTextLayout(getTextLayout(text, committed_count), layoutCaretPosition); + int textLength = text.getEndIndex() - text.getBeginIndex() - committed_count; + StringBuffer unCommitedStringBuf = new StringBuffer(textLength); + char c; + for (c = text.setIndex(committed_count); c != AttributedCharacterIterator.DONE + && textLength > 0; c = text.next(), --textLength) { + unCommitedStringBuf.append(c); + } + String unCommittedString = unCommitedStringBuf.toString(); + try { + if(canRemovePreviousInput(committed_count)){ + textArea.getDocument().remove(layoutCaretPosition, prevComposeString.length()); + } + textArea.getDocument().insertString(layoutCaretPosition, unCommittedString, null); + if(committed_count > 0){ + initialCaretPosition = initialCaretPosition + committed_count; + } + prevComposeString = unCommittedString; + prevCommittedCount = committed_count; + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + private boolean canRemovePreviousInput(int committed_count){ + return (prevCommittedCount == committed_count || prevCommittedCount > committed_count); + } + + /** + * Called when a user fixed text from input method or delete all + * composition text. This method resets CompositionTextPainter. + * + * @param text Text from InputMethodEvent. + * @param commited_count Numbers of committed characters in text. + */ + public void endCompositionText(AttributedCharacterIterator text, int committed_count) { + isInputProcess = false; + /* + * If there are no committed characters, remove it all from textarea. + * This case will happen if a user delete all composing characters by backspace or delete key. + * If it does, these previous characters are needed to be deleted. + */ + if(committed_count == 0){ + removeNotCommittedText(text); + } + CompositionTextPainter compositionPainter = textArea.getPainter().getCompositionTextpainter(); + compositionPainter.invalidateComposedTextLayout(initialCaretPosition + committed_count); + prevComposeString = ""; + isInputProcess = false; + } + + private void removeNotCommittedText(AttributedCharacterIterator text){ + if (prevComposeString.length() == 0) { + return; + } + try { + textArea.getDocument().remove(initialCaretPosition, prevComposeString.length()); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + private TextLayout getTextLayout(AttributedCharacterIterator text, int committed_count) { + AttributedString composed = new AttributedString(text, committed_count, text.getEndIndex()); + Font font = textArea.getPainter().getFont(); + FontRenderContext context = ((Graphics2D) (textArea.getPainter().getGraphics())).getFontRenderContext(); + composed.addAttribute(TextAttribute.FONT, font); + TextLayout layout = new TextLayout(composed.getIterator(), context); + return layout; + } + + private Point getCaretLocation() { + Point loc = new Point(); + TextAreaPainter painter = textArea.getPainter(); + FontMetrics fm = painter.getFontMetrics(); + int offsetY = fm.getHeight() - COMPOSING_UNDERBAR_HEIGHT; + int lineIndex = textArea.getCaretLine(); + loc.y = lineIndex * fm.getHeight() + offsetY; + int offsetX = textArea.getCaretPosition() + - textArea.getLineStartOffset(lineIndex); + loc.x = textArea.offsetToX(lineIndex, offsetX); + return loc; + } + + public Rectangle getTextLocation() { + Point caret = getCaretLocation(); + return getCaretRectangle(caret.x, caret.y); + } + + private Rectangle getCaretRectangle(int x, int y) { + TextAreaPainter painter = textArea.getPainter(); + Point origin = painter.getLocationOnScreen(); + int height = painter.getFontMetrics().getHeight(); + return new Rectangle(origin.x + x, origin.y + y, 0, height); + } + + public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex) { + int length = endIndex - beginIndex; + String textAreaString = textArea.getText(beginIndex, length); + return new AttributedString(textAreaString).getIterator(); + } + + public int getInsertPositionOffset() { + return textArea.getCaretPosition() * -1; + } +} diff --git a/app/src/processing/app/syntax/im/CompositionTextPainter.java b/app/src/processing/app/syntax/im/CompositionTextPainter.java new file mode 100644 index 000000000..0084f491f --- /dev/null +++ b/app/src/processing/app/syntax/im/CompositionTextPainter.java @@ -0,0 +1,124 @@ +package processing.app.syntax.im; + +import java.awt.Color; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.font.TextLayout; + +import processing.app.syntax.JEditTextArea; +import processing.app.syntax.TextAreaPainter; + +/** + * Paint texts from input method. Text via input method are transmitted by + * AttributedCaharacterIterator. This class helps the PDE's TextAreaPainter + * to handle AttributedCaharacterIterator. + * + * For practical purposes, paint to textarea is done by TextLayout class. + * Because TextLayout class is easy to draw composing texts. (For example, + * draw underline composing texts, focus when select from candidates text.) + * + * @author Takashi Maekawa (takachin@generative.info) + */ +public class CompositionTextPainter { + private TextLayout composedTextLayout; + private int composedBeginCaretPosition = 0; + private JEditTextArea textArea; + + /** + * Constructor for painter. + * @param textarea textarea used by PDE. + */ + public CompositionTextPainter(JEditTextArea textArea) { + this.textArea = textArea; + composedTextLayout = null; + } + + /** + * Check the painter has TextLayout. + * If a user input via InputMethod, this result will return true. + * @param textarea textarea used by PDE. + */ + public boolean hasComposedTextLayout() { + return (composedTextLayout != null); + } + + /** + * Set TextLayout to the painter. + * TextLayout will be created and set by CompositionTextManager. + * + * @see CompositionTextManager + * @param textarea textarea used by PDE. + */ + public void setComposedTextLayout(TextLayout composedTextLayout, int composedStartCaretPosition) { + this.composedTextLayout = composedTextLayout; + this.composedBeginCaretPosition = composedStartCaretPosition; + } + + /** + * Invalidate this TextLayout to set null. + * If a user end input via InputMethod, this method will called from CompositionTextManager.endCompositionText + */ + public void invalidateComposedTextLayout(int composedEndCaretPosition) { + this.composedTextLayout = null; + this.composedBeginCaretPosition = composedEndCaretPosition; + //this.composedBeginCaretPosition = textArea.getCaretPosition(); + } + + /** + * Draw text via input method with composed text information. + * This method can draw texts with some underlines to illustrate converting characters. + * + * This method is workaround for TextAreaPainter. + * Because, TextAreaPainter can't treat AttributedCharacterIterator directly. + * AttributedCharacterIterator has very important information when composing text. + * It has a map where are converted characters and committed characters. + * Ideally, changing TextAreaPainter method can treat AttributedCharacterIterator is better. But it's very tough!! + * So I choose to write some code as a workaround. + * + * This draw method is proceeded with the following steps. + * 1. Original TextAreaPainter draws characters. + * 2. This refillComposedArea method erase previous paint characters by textarea's background color. + * The refill area is only square that width and height defined by characters with input method. + * 3. CompositionTextPainter.draw method paints composed text. It was actually drawn by TextLayout. + * + * @param gfx set TextAreaPainter's Graphics object. + * @param fillBackGroundColor set textarea's background. + */ + public void draw(Graphics gfx, Color fillBackGroundColor) { + assert(composedTextLayout != null); + Point composedLoc = getCaretLocation(); + refillComposedArea(fillBackGroundColor, composedLoc.x, composedLoc.y); + composedTextLayout.draw((Graphics2D) gfx, composedLoc.x, composedLoc.y); + } + + /** + * Fill color to erase characters drawn by original TextAreaPainter. + * + * @param fillColor fill color to erase characters drawn by original TextAreaPainter method. + * @param x x-coordinate where to fill. + * @param y y-coordinate where to fill. + */ + private void refillComposedArea(Color fillColor, int x, int y) { + Graphics gfx = textArea.getPainter().getGraphics(); + gfx.setColor(fillColor); + FontMetrics fm = textArea.getPainter().getFontMetrics(); + int newY = y - (fm.getHeight() - CompositionTextManager.COMPOSING_UNDERBAR_HEIGHT); + int paintHeight = fm.getHeight(); + int paintWidth = (int) composedTextLayout.getBounds().getWidth(); + gfx.fillRect(x, newY, paintWidth, paintHeight); + } + + private Point getCaretLocation() { + Point loc = new Point(); + TextAreaPainter painter = textArea.getPainter(); + FontMetrics fm = painter.getFontMetrics(); + int offsetY = fm.getHeight() - CompositionTextManager.COMPOSING_UNDERBAR_HEIGHT; + int lineIndex = textArea.getCaretLine(); + loc.y = lineIndex * fm.getHeight() + offsetY; + int offsetX = composedBeginCaretPosition - textArea.getLineStartOffset(lineIndex); + loc.x = textArea.offsetToX(lineIndex, offsetX); + return loc; + } +} diff --git a/app/src/processing/app/syntax/im/InputMethodSupport.java b/app/src/processing/app/syntax/im/InputMethodSupport.java new file mode 100644 index 000000000..33a86bb1a --- /dev/null +++ b/app/src/processing/app/syntax/im/InputMethodSupport.java @@ -0,0 +1,105 @@ +package processing.app.syntax.im; + +import java.awt.Rectangle; +import java.awt.event.InputMethodEvent; +import java.awt.event.InputMethodListener; +import java.awt.font.TextHitInfo; +import java.awt.im.InputMethodRequests; +import java.text.AttributedCharacterIterator; + +import processing.app.syntax.JEditTextArea; + +/** + * Support in-line Japanese input for PDE. (Maybe Chinese, Korean and more) + * This class is implemented by Java Input Method Framework and handles + * If you would like to know more about Java Input Method Framework, + * Please see http://java.sun.com/j2se/1.5.0/docs/guide/imf/ + * + * This class is implemented to fix Bug #854. + * http://dev.processing.org/bugs/show_bug.cgi?id=854 + * + * @author Takashi Maekawa (takachin@generative.info) + */ +public class InputMethodSupport implements InputMethodRequests, + InputMethodListener { + + private int committed_count = 0; + private CompositionTextManager textManager; + + public InputMethodSupport(JEditTextArea textArea) { + textManager = new CompositionTextManager(textArea); + textArea.enableInputMethods(true); + textArea.addInputMethodListener(this); + } + + public Rectangle getTextLocation(TextHitInfo offset) { + return textManager.getTextLocation(); + } + + public TextHitInfo getLocationOffset(int x, int y) { + return null; + } + + public int getInsertPositionOffset() { + return textManager.getInsertPositionOffset(); + } + + public AttributedCharacterIterator getCommittedText(int beginIndex, + int endIndex, AttributedCharacterIterator.Attribute[] attributes) { + return textManager.getCommittedText(beginIndex, endIndex); + } + + public int getCommittedTextLength() { + return committed_count; + } + + public AttributedCharacterIterator cancelLatestCommittedText( + AttributedCharacterIterator.Attribute[] attributes) { + return null; + } + + public AttributedCharacterIterator getSelectedText( + AttributedCharacterIterator.Attribute[] attributes) { + return null; + } + + /** + * Handles events from InputMethod. + * This method judges whether beginning of input or + * progress of input or end and call related method. + * + * @param event event from Input Method. + */ + public void inputMethodTextChanged(InputMethodEvent event) { + AttributedCharacterIterator text = event.getText(); + committed_count = event.getCommittedCharacterCount(); + if(isBeginInputProcess(text, textManager)){ + textManager.beginCompositionText(text, committed_count); + caretPositionChanged(event); + return; + } + if (isInputProcess(text)){ + textManager.processCompositionText(text, committed_count); + caretPositionChanged(event); + return; + } + textManager.endCompositionText(text, committed_count); + caretPositionChanged(event); + } + + private boolean isBeginInputProcess(AttributedCharacterIterator text, CompositionTextManager textManager){ + if(text == null) + return false; + return (isInputProcess(text) && !textManager.getIsInputProcess()); + } + + private boolean isInputProcess(AttributedCharacterIterator text){ + if(text == null) + return false; + return (text.getEndIndex() - (text.getBeginIndex() + committed_count) > 0); + } + + public void caretPositionChanged(InputMethodEvent event) { + event.consume(); + } +} diff --git a/app/src/processing/app/tools/ColorSelector.java b/app/src/processing/app/tools/ColorSelector.java index d4843d18a..de1402239 100644 --- a/app/src/processing/app/tools/ColorSelector.java +++ b/app/src/processing/app/tools/ColorSelector.java @@ -120,6 +120,7 @@ public class ColorSelector implements Tool, DocumentListener { frame.setVisible(false); } }); + Base.setIcon(frame); hueField.getDocument().addDocumentListener(this); @@ -444,19 +445,25 @@ public class ColorSelector implements Tool, DocumentListener { } public Dimension getPreferredSize() { - //System.out.println("getting pref " + WIDE + " " + HIGH); return new Dimension(WIDE, HIGH); } public Dimension getMinimumSize() { - //System.out.println("getting min " + WIDE + " " + HIGH); return new Dimension(WIDE, HIGH); } public Dimension getMaximumSize() { - //System.out.println("getting max " + WIDE + " " + HIGH); return new Dimension(WIDE, HIGH); } + + public void keyPressed() { + if (key == ESC) { + ColorSelector.this.frame.setVisible(false); + // don't quit out of processing + // http://dev.processing.org/bugs/show_bug.cgi?id=1006 + key = 0; + } + } } @@ -506,19 +513,25 @@ public class ColorSelector implements Tool, DocumentListener { } public Dimension getPreferredSize() { - //System.out.println("s getting pref " + WIDE + " " + HIGH); return new Dimension(WIDE, HIGH); } public Dimension getMinimumSize() { - //System.out.println("s getting min " + WIDE + " " + HIGH); return new Dimension(WIDE, HIGH); } public Dimension getMaximumSize() { - //System.out.println("s getting max " + WIDE + " " + HIGH); return new Dimension(WIDE, HIGH); } + + public void keyPressed() { + if (key == ESC) { + ColorSelector.this.frame.setVisible(false); + // don't quit out of processing + // http://dev.processing.org/bugs/show_bug.cgi?id=1006 + key = 0; + } + } } @@ -540,7 +553,7 @@ public class ColorSelector implements Tool, DocumentListener { public Dimension getPreferredSize() { if (!allowHex) { - return new Dimension(35, super.getPreferredSize().height); + return new Dimension(45, super.getPreferredSize().height); } return super.getPreferredSize(); } diff --git a/app/src/processing/app/tools/CreateFont.java b/app/src/processing/app/tools/CreateFont.java index 663798985..62d2ce4c0 100644 --- a/app/src/processing/app/tools/CreateFont.java +++ b/app/src/processing/app/tools/CreateFont.java @@ -3,7 +3,7 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2004-06 Ben Fry and Casey Reas + Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify @@ -37,7 +37,7 @@ import javax.swing.event.*; /** - * gui interface to font creation heaven/hell. + * GUI tool for font creation heaven/hell. */ public class CreateFont extends JFrame implements Tool { Editor editor; @@ -46,30 +46,22 @@ public class CreateFont extends JFrame implements Tool { Dimension windowSize; JList fontSelector; - //JComboBox styleSelector; JTextField sizeSelector; - JCheckBox allBox; + JButton charsetButton; JCheckBox smoothBox; - JTextArea sample; + JComponent sample; JButton okButton; JTextField filenameField; - Hashtable table; + HashMap table; boolean smooth = true; - boolean all = false; Font font; String[] list; int selection = -1; - - //static { - //System.out.println("yep yep yep"); - //} - //static final String styles[] = { - //"Plain", "Bold", "Italic", "Bold Italic" - //}; + CharacterSelector charSelector; public CreateFont() { @@ -117,7 +109,7 @@ public class CreateFont extends JFrame implements Tool { Font fonts[] = ge.getAllFonts(); String flist[] = new String[fonts.length]; - table = new Hashtable(); + table = new HashMap(); int index = 0; for (int i = 0; i < fonts.length; i++) { @@ -150,20 +142,8 @@ public class CreateFont extends JFrame implements Tool { Dimension d1 = new Dimension(13, 13); pain.add(new Box.Filler(d1, d1, d1)); - // see http://rinkworks.com/words/pangrams.shtml - sample = new JTextArea("The quick brown fox blah blah.") { - // Forsaking monastic tradition, twelve jovial friars gave up their - // vocation for a questionable existence on the flying trapeze. - public void paintComponent(Graphics g) { - //System.out.println("disabling aa"); - Graphics2D g2 = (Graphics2D) g; - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - smooth ? - RenderingHints.VALUE_TEXT_ANTIALIAS_ON : - RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); - super.paintComponent(g2); - } - }; + sample = new SampleComponent(this); + // Seems that in some instances, no default font is set // http://dev.processing.org/bugs/show_bug.cgi?id=777 sample.setFont(new Font("Dialog", Font.PLAIN, 12)); @@ -193,14 +173,22 @@ public class CreateFont extends JFrame implements Tool { smoothBox.setSelected(smooth); panel.add(smoothBox); - allBox = new JCheckBox("All Characters"); - allBox.addActionListener(new ActionListener() { +// allBox = new JCheckBox("All Characters"); +// allBox.addActionListener(new ActionListener() { +// public void actionPerformed(ActionEvent e) { +// all = allBox.isSelected(); +// } +// }); +// allBox.setSelected(all); +// panel.add(allBox); + charsetButton = new JButton("Characters..."); + charsetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - all = allBox.isSelected(); + //showCharacterList(); + charSelector.setVisible(true); } }); - allBox.setSelected(all); - panel.add(allBox); + panel.add(charsetButton); pain.add(panel); @@ -239,6 +227,7 @@ public class CreateFont extends JFrame implements Tool { Base.registerWindowCloseKeys(root, disposer); Base.setIcon(this); + setResizable(false); pack(); // do this after pack so it doesn't affect layout @@ -251,6 +240,9 @@ public class CreateFont extends JFrame implements Tool { setLocation((screen.width - windowSize.width) / 2, (screen.height - windowSize.height) / 2); + + // create this behind the scenes + charSelector = new CharacterSelector(); } @@ -259,26 +251,6 @@ public class CreateFont extends JFrame implements Tool { } - /** - * make the window vertically resizable - */ - public Dimension getMaximumSize() { - return new Dimension(windowSize.width, 2000); - } - - public Dimension getMinimumSize() { - return windowSize; - } - - - /* - public void show(File targetFolder) { - this.targetFolder = targetFolder; - show(); - } - */ - - public void update() { int fontsize = 0; try { @@ -313,7 +285,7 @@ public class CreateFont extends JFrame implements Tool { return; } - String filename = filenameField.getText(); + String filename = filenameField.getText().trim(); if (filename.length() == 0) { JOptionPane.showMessageDialog(this, "Enter a file name for the font.", "Lameness", JOptionPane.WARNING_MESSAGE); @@ -323,23 +295,519 @@ public class CreateFont extends JFrame implements Tool { filename += ".vlw"; } + // Please implement me properly. The schematic is below, but not debugged. + // http://dev.processing.org/bugs/show_bug.cgi?id=1464 + +// final String filename2 = filename; +// final int fontsize2 = fontsize; +// SwingUtilities.invokeLater(new Runnable() { +// public void run() { try { Font instance = (Font) table.get(list[selection]); font = instance.deriveFont(Font.PLAIN, fontsize); - PFont f = new PFont(font, smooth, all ? null : PFont.DEFAULT_CHARSET); + //PFont f = new PFont(font, smooth, all ? null : PFont.CHARSET); + PFont f = new PFont(font, smooth, charSelector.getCharacters()); + +// PFont f = new PFont(font, smooth, null); +// char[] charset = charSelector.getCharacters(); +// ProgressMonitor progressMonitor = new ProgressMonitor(CreateFont.this, +// "Creating font", "", 0, charset.length); +// progressMonitor.setProgress(0); +// for (int i = 0; i < charset.length; i++) { +// System.out.println(charset[i]); +// f.index(charset[i]); // load this char +// progressMonitor.setProgress(i+1); +// } // make sure the 'data' folder exists File folder = editor.getSketch().prepareDataFolder(); f.save(new FileOutputStream(new File(folder, filename))); } catch (IOException e) { - JOptionPane.showMessageDialog(this, + JOptionPane.showMessageDialog(CreateFont.this, "An error occurred while creating font.", "No font for you", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } +// } +// }); setVisible(false); } + + + /** + * make the window vertically resizable + */ + public Dimension getMaximumSize() { + return new Dimension(windowSize.width, 2000); } + + + public Dimension getMinimumSize() { + return windowSize; + } + + + /* + public void show(File targetFolder) { + this.targetFolder = targetFolder; + show(); + } + */ +} + + +/** + * Component that draws the sample text. This is its own subclassed component + * because Mac OS X controls seem to reset the RenderingHints for smoothing + * so that they cannot be overridden properly for JLabel or JTextArea. + * @author fry + */ +class SampleComponent extends JComponent { + // see http://rinkworks.com/words/pangrams.shtml + String text = + "Forsaking monastic tradition, twelve jovial friars gave up their " + + "vocation for a questionable existence on the flying trapeze."; + int high = 80; + + CreateFont parent; + + public SampleComponent(CreateFont p) { + this.parent = p; + + // and yet, we still need an inner class to handle the basics. + // or no, maybe i'll refactor this as a separate class! + // maybe a few getters and setters? mmm? + addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + String input = + (String) JOptionPane.showInputDialog(parent, + "Enter new sample text:", + "Sample Text", + JOptionPane.PLAIN_MESSAGE, + null, // icon + null, // choices + text); + if (input != null) { + text = input; + parent.repaint(); + } + } + }); + } + + public void paintComponent(Graphics g) { +// System.out.println("smoothing set to " + smooth); + Graphics2D g2 = (Graphics2D) g; + g2.setColor(Color.WHITE); + Dimension dim = getSize(); + g2.fillRect(0, 0, dim.width, dim.height); + g2.setColor(Color.BLACK); + + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + parent.smooth ? + RenderingHints.VALUE_TEXT_ANTIALIAS_ON : + RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); + // add this one as well (after 1.0.9) + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + parent.smooth ? + RenderingHints.VALUE_ANTIALIAS_ON : + RenderingHints.VALUE_ANTIALIAS_OFF); + //super.paintComponent(g2); + Font font = getFont(); + int ascent = g2.getFontMetrics().getAscent(); +// System.out.println(f.getName()); + g2.setFont(font); + g2.drawString(text, 5, dim.height - (dim.height - ascent) / 2); + } + + public Dimension getPreferredSize() { + return new Dimension(400, high); + } + + public Dimension getMaximumSize() { + return new Dimension(10000, high); + } + + public Dimension getMinimumSize() { + return new Dimension(100, high); + } +} + + +/** + * Frame for selecting which characters will be included with the font. + */ +class CharacterSelector extends JFrame { + JRadioButton defaultCharsButton; + JRadioButton allCharsButton; + JRadioButton unicodeCharsButton; + JScrollPane unicodeBlockScroller; + JList charsetList; + + + public CharacterSelector() { + super("Character Selector"); + + charsetList = new CheckBoxList(); + DefaultListModel model = new DefaultListModel(); + charsetList.setModel(model); + for (String item : blockNames) { + model.addElement(new JCheckBox(item)); + } + + unicodeBlockScroller = + new JScrollPane(charsetList, + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + Container outer = getContentPane(); + outer.setLayout(new BorderLayout()); + + JPanel pain = new JPanel(); + pain.setBorder(new EmptyBorder(13, 13, 13, 13)); + outer.add(pain, BorderLayout.CENTER); + + pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS)); + + String labelText = + "Default characters will include most bitmaps for Mac OS\n" + + "and Windows Latin scripts. Including all characters may\n" + + "require large amounts of memory for all of the bitmaps.\n" + + "For greater control, you can select specific Unicode blocks."; + JTextArea textarea = new JTextArea(labelText); + textarea.setBorder(new EmptyBorder(13, 8, 13, 8)); + textarea.setBackground(null); + textarea.setEditable(false); + textarea.setHighlighter(null); + textarea.setFont(new Font("Dialog", Font.PLAIN, 12)); + pain.add(textarea); + + ActionListener listener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + //System.out.println("action " + unicodeCharsButton.isSelected()); + //unicodeBlockScroller.setEnabled(unicodeCharsButton.isSelected()); + charsetList.setEnabled(unicodeCharsButton.isSelected()); + } + }; + defaultCharsButton = new JRadioButton("Default Characters"); + allCharsButton = new JRadioButton("All Characters"); + unicodeCharsButton = new JRadioButton("Specific Unicode Blocks"); + + defaultCharsButton.addActionListener(listener); + allCharsButton.addActionListener(listener); + unicodeCharsButton.addActionListener(listener); + + ButtonGroup group = new ButtonGroup(); + group.add(defaultCharsButton); + group.add(allCharsButton); + group.add(unicodeCharsButton); + + JPanel radioPanel = new JPanel(); + //radioPanel.setBackground(Color.red); + radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS)); + radioPanel.add(defaultCharsButton); + radioPanel.add(allCharsButton); + radioPanel.add(unicodeCharsButton); + + JPanel rightStuff = new JPanel(); + rightStuff.setLayout(new BoxLayout(rightStuff, BoxLayout.X_AXIS)); + rightStuff.add(radioPanel); + rightStuff.add(Box.createHorizontalGlue()); + pain.add(rightStuff); + pain.add(Box.createVerticalStrut(13)); + +// pain.add(radioPanel); + +// pain.add(defaultCharsButton); +// pain.add(allCharsButton); +// pain.add(unicodeCharsButton); + + defaultCharsButton.setSelected(true); + charsetList.setEnabled(false); + + //frame.getContentPane().add(scroller); + pain.add(unicodeBlockScroller); + pain.add(Box.createVerticalStrut(8)); + + JPanel buttons = new JPanel(); + JButton okButton = new JButton("OK"); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setVisible(false); + } + }); + okButton.setEnabled(true); + buttons.add(okButton); + pain.add(buttons); + + JRootPane root = getRootPane(); + root.setDefaultButton(okButton); + ActionListener disposer = new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { + setVisible(false); + } + }; + Base.registerWindowCloseKeys(root, disposer); + Base.setIcon(this); + + pack(); + + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension windowSize = getSize(); + + setLocation((screen.width - windowSize.width) / 2, + (screen.height - windowSize.height) / 2); + } + + + protected char[] getCharacters() { + if (defaultCharsButton.isSelected()) { + return PFont.CHARSET; + } + + char[] charset = new char[65536]; + if (allCharsButton.isSelected()) { + for (int i = 0; i < 0xFFFF; i++) { + charset[i] = (char) i; + } + } else { + DefaultListModel model = (DefaultListModel) charsetList.getModel(); + int index = 0; + for (int i = 0; i < BLOCKS.length; i++) { + if (((JCheckBox) model.get(i)).isSelected()) { + for (int j = blockStart[i]; j <= blockStop[i]; j++) { + charset[index++] = (char) j; + } + } + } + charset = PApplet.subset(charset, 0, index); + } + //System.out.println("Creating font with " + charset.length + " characters."); + return charset; + } + + + // http://www.unicode.org/Public/UNIDATA/Blocks.txt + static final String[] BLOCKS = { + "0000..007F; Basic Latin", + "0080..00FF; Latin-1 Supplement", + "0100..017F; Latin Extended-A", + "0180..024F; Latin Extended-B", + "0250..02AF; IPA Extensions", + "02B0..02FF; Spacing Modifier Letters", + "0300..036F; Combining Diacritical Marks", + "0370..03FF; Greek and Coptic", + "0400..04FF; Cyrillic", + "0500..052F; Cyrillic Supplement", + "0530..058F; Armenian", + "0590..05FF; Hebrew", + "0600..06FF; Arabic", + "0700..074F; Syriac", + "0750..077F; Arabic Supplement", + "0780..07BF; Thaana", + "07C0..07FF; NKo", + "0800..083F; Samaritan", + "0900..097F; Devanagari", + "0980..09FF; Bengali", + "0A00..0A7F; Gurmukhi", + "0A80..0AFF; Gujarati", + "0B00..0B7F; Oriya", + "0B80..0BFF; Tamil", + "0C00..0C7F; Telugu", + "0C80..0CFF; Kannada", + "0D00..0D7F; Malayalam", + "0D80..0DFF; Sinhala", + "0E00..0E7F; Thai", + "0E80..0EFF; Lao", + "0F00..0FFF; Tibetan", + "1000..109F; Myanmar", + "10A0..10FF; Georgian", + "1100..11FF; Hangul Jamo", + "1200..137F; Ethiopic", + "1380..139F; Ethiopic Supplement", + "13A0..13FF; Cherokee", + "1400..167F; Unified Canadian Aboriginal Syllabics", + "1680..169F; Ogham", + "16A0..16FF; Runic", + "1700..171F; Tagalog", + "1720..173F; Hanunoo", + "1740..175F; Buhid", + "1760..177F; Tagbanwa", + "1780..17FF; Khmer", + "1800..18AF; Mongolian", + "18B0..18FF; Unified Canadian Aboriginal Syllabics Extended", + "1900..194F; Limbu", + "1950..197F; Tai Le", + "1980..19DF; New Tai Lue", + "19E0..19FF; Khmer Symbols", + "1A00..1A1F; Buginese", + "1A20..1AAF; Tai Tham", + "1B00..1B7F; Balinese", + "1B80..1BBF; Sundanese", + "1C00..1C4F; Lepcha", + "1C50..1C7F; Ol Chiki", + "1CD0..1CFF; Vedic Extensions", + "1D00..1D7F; Phonetic Extensions", + "1D80..1DBF; Phonetic Extensions Supplement", + "1DC0..1DFF; Combining Diacritical Marks Supplement", + "1E00..1EFF; Latin Extended Additional", + "1F00..1FFF; Greek Extended", + "2000..206F; General Punctuation", + "2070..209F; Superscripts and Subscripts", + "20A0..20CF; Currency Symbols", + "20D0..20FF; Combining Diacritical Marks for Symbols", + "2100..214F; Letterlike Symbols", + "2150..218F; Number Forms", + "2190..21FF; Arrows", + "2200..22FF; Mathematical Operators", + "2300..23FF; Miscellaneous Technical", + "2400..243F; Control Pictures", + "2440..245F; Optical Character Recognition", + "2460..24FF; Enclosed Alphanumerics", + "2500..257F; Box Drawing", + "2580..259F; Block Elements", + "25A0..25FF; Geometric Shapes", + "2600..26FF; Miscellaneous Symbols", + "2700..27BF; Dingbats", + "27C0..27EF; Miscellaneous Mathematical Symbols-A", + "27F0..27FF; Supplemental Arrows-A", + "2800..28FF; Braille Patterns", + "2900..297F; Supplemental Arrows-B", + "2980..29FF; Miscellaneous Mathematical Symbols-B", + "2A00..2AFF; Supplemental Mathematical Operators", + "2B00..2BFF; Miscellaneous Symbols and Arrows", + "2C00..2C5F; Glagolitic", + "2C60..2C7F; Latin Extended-C", + "2C80..2CFF; Coptic", + "2D00..2D2F; Georgian Supplement", + "2D30..2D7F; Tifinagh", + "2D80..2DDF; Ethiopic Extended", + "2DE0..2DFF; Cyrillic Extended-A", + "2E00..2E7F; Supplemental Punctuation", + "2E80..2EFF; CJK Radicals Supplement", + "2F00..2FDF; Kangxi Radicals", + "2FF0..2FFF; Ideographic Description Characters", + "3000..303F; CJK Symbols and Punctuation", + "3040..309F; Hiragana", + "30A0..30FF; Katakana", + "3100..312F; Bopomofo", + "3130..318F; Hangul Compatibility Jamo", + "3190..319F; Kanbun", + "31A0..31BF; Bopomofo Extended", + "31C0..31EF; CJK Strokes", + "31F0..31FF; Katakana Phonetic Extensions", + "3200..32FF; Enclosed CJK Letters and Months", + "3300..33FF; CJK Compatibility", + "3400..4DBF; CJK Unified Ideographs Extension A", + "4DC0..4DFF; Yijing Hexagram Symbols", + "4E00..9FFF; CJK Unified Ideographs", + "A000..A48F; Yi Syllables", + "A490..A4CF; Yi Radicals", + "A4D0..A4FF; Lisu", + "A500..A63F; Vai", + "A640..A69F; Cyrillic Extended-B", + "A6A0..A6FF; Bamum", + "A700..A71F; Modifier Tone Letters", + "A720..A7FF; Latin Extended-D", + "A800..A82F; Syloti Nagri", + "A830..A83F; Common Indic Number Forms", + "A840..A87F; Phags-pa", + "A880..A8DF; Saurashtra", + "A8E0..A8FF; Devanagari Extended", + "A900..A92F; Kayah Li", + "A930..A95F; Rejang", + "A960..A97F; Hangul Jamo Extended-A", + "A980..A9DF; Javanese", + "AA00..AA5F; Cham", + "AA60..AA7F; Myanmar Extended-A", + "AA80..AADF; Tai Viet", + "ABC0..ABFF; Meetei Mayek", + "AC00..D7AF; Hangul Syllables", + "D7B0..D7FF; Hangul Jamo Extended-B", + "D800..DB7F; High Surrogates", + "DB80..DBFF; High Private Use Surrogates", + "DC00..DFFF; Low Surrogates", + "E000..F8FF; Private Use Area", + "F900..FAFF; CJK Compatibility Ideographs", + "FB00..FB4F; Alphabetic Presentation Forms", + "FB50..FDFF; Arabic Presentation Forms-A", + "FE00..FE0F; Variation Selectors", + "FE10..FE1F; Vertical Forms", + "FE20..FE2F; Combining Half Marks", + "FE30..FE4F; CJK Compatibility Forms", + "FE50..FE6F; Small Form Variants", + "FE70..FEFF; Arabic Presentation Forms-B", + "FF00..FFEF; Halfwidth and Fullwidth Forms", + "FFF0..FFFF; Specials" + }; + + static String[] blockNames; + static int[] blockStart; + static int[] blockStop; + static { + int count = BLOCKS.length; + blockNames = new String[count]; + blockStart = new int[count]; + blockStop = new int[count]; + for (int i = 0; i < count; i++) { + String line = BLOCKS[i]; + blockStart[i] = PApplet.unhex(line.substring(0, 4)); + blockStop[i] = PApplet.unhex(line.substring(6, 10)); + blockNames[i] = line.substring(12); + } +// PApplet.println(codePointStop); +// PApplet.println(codePoints); + } +} + + +// Code for this CheckBoxList class found on the net, though I've lost the +// link. If you run across the original version, please let me know so that +// the original author can be credited properly. It was from a snippet +// collection, but it seems to have been picked up so many places with others +// placing their copyright on it, that I haven't been able to determine the +// original author. [fry 20100216] +class CheckBoxList extends JList { + protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); + + public CheckBoxList() { + setCellRenderer(new CellRenderer()); + + addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + if (isEnabled()) { + int index = locationToIndex(e.getPoint()); + + if (index != -1) { + JCheckBox checkbox = (JCheckBox) + getModel().getElementAt(index); + checkbox.setSelected(!checkbox.isSelected()); + repaint(); + } + } + } + }); + setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + } + + + protected class CellRenderer implements ListCellRenderer { + public Component getListCellRendererComponent(JList list, Object value, + int index, boolean isSelected, + boolean cellHasFocus) { + JCheckBox checkbox = (JCheckBox) value; + checkbox.setBackground(isSelected ? getSelectionBackground() : getBackground()); + checkbox.setForeground(isSelected ? getSelectionForeground() : getForeground()); + //checkbox.setEnabled(isEnabled()); + checkbox.setEnabled(list.isEnabled()); + checkbox.setFont(getFont()); + checkbox.setFocusPainted(false); + checkbox.setBorderPainted(true); + checkbox.setBorder(isSelected ? UIManager.getBorder("List.focusCellHighlightBorder") : noFocusBorder); + return checkbox; + } + } +} \ No newline at end of file diff --git a/app/src/processing/app/windows/Platform.java b/app/src/processing/app/windows/Platform.java index cdc685ecf..63e76145a 100644 --- a/app/src/processing/app/windows/Platform.java +++ b/app/src/processing/app/windows/Platform.java @@ -3,7 +3,7 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2008 Ben Fry and Casey Reas + Copyright (c) 2008-2009 Ben Fry and Casey Reas 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 @@ -25,6 +25,9 @@ package processing.app.windows; import java.io.File; import java.io.UnsupportedEncodingException; +import com.sun.jna.Library; +import com.sun.jna.Native; + import processing.app.Base; import processing.app.Preferences; import processing.app.windows.Registry.REGISTRY_ROOT_KEY; @@ -265,4 +268,38 @@ public class Platform extends processing.app.Platform { // not tested //Runtime.getRuntime().exec("start explorer \"" + folder + "\""); } + + + // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + + + // Code partially thanks to Richard Quirk from: + // http://quirkygba.blogspot.com/2009/11/setting-environment-variables-in-java.html + + static WinLibC clib = (WinLibC) Native.loadLibrary("msvcrt", WinLibC.class); + + public interface WinLibC extends Library { + //WinLibC INSTANCE = (WinLibC) Native.loadLibrary("msvcrt", WinLibC.class); + //libc = Native.loadLibrary("msvcrt", WinLibC.class); + public int _putenv(String name); +} + + + public void setenv(String variable, String value) { + //WinLibC clib = WinLibC.INSTANCE; + clib._putenv(variable + "=" + value); + } + + + public String getenv(String variable) { + return System.getenv(variable); + } + + + public int unsetenv(String variable) { + //WinLibC clib = WinLibC.INSTANCE; + //clib._putenv(variable + "="); + //return 0; + return clib._putenv(variable + "="); + } } diff --git a/build/macosx/make.sh b/build/macosx/make.sh index 12601e0b5..0b1ac3eea 100755 --- a/build/macosx/make.sh +++ b/build/macosx/make.sh @@ -113,6 +113,7 @@ javac \ src/processing/app/macosx/*.java \ src/processing/app/preproc/*.java \ src/processing/app/syntax/*.java \ + src/processing/app/syntax/im/*.java \ src/processing/app/tools/*.java cd ../build/macosx/work/classes diff --git a/build/shared/lib/preferences.txt b/build/shared/lib/preferences.txt index 0dc7963f6..fc74866a3 100755 --- a/build/shared/lib/preferences.txt +++ b/build/shared/lib/preferences.txt @@ -72,8 +72,15 @@ platform.auto_file_type_associations = true # default size for the main window -default.window.width = 500 -default.window.height = 600 +editor.window.width.default = 500 +editor.window.height.default = 600 + +editor.window.width.min = 400 +editor.window.height.min = 500 +# tested as approx 440 on OS X +editor.window.height.min.macosx = 450 +# tested to be 515 on Windows XP, this leaves some room +editor.window.height.min.windows = 530 # font size for editor editor.font=Monospaced,plain,12 @@ -92,6 +99,21 @@ editor.caret.blink=true # area that's not in use by the text (replaced with tildes) editor.invalid=false +# enable ctrl-ins, shift-ins, shift-delete for cut/copy/paste +# on windows and linux, but disable on the mac +editor.keys.alternative_cut_copy_paste = true +editor.keys.alternative_cut_copy_paste.macosx = false + +# true if shift-backspace sends the delete character, +# false if shift-backspace just means backspace +editor.keys.shift_backspace_is_delete = true + +# home and end keys should only travel to the start/end of the current line +editor.keys.home_and_end_travel_far = false +# the OS X HI Guidelines say that home/end are relative to the document +# if you don't like it, this is the preference to change +editor.keys.home_and_end_travel_far.macosx = true + console = true console.output.file = stdout.txt console.error.file = stderr.txt @@ -197,14 +219,14 @@ preproc.substitute_unicode = true # viewed in (at least) Mozilla or IE. useful when debugging the preprocessor. preproc.output_parse_tree = false -# imports to use by default (changed for 0149, some imports removed) -preproc.imports = java.applet,java.awt,java.awt.image,java.awt.event,java.io,java.net,java.text,java.util,java.util.zip,java.util.regex +# Changed after 1.0.9 to a new name, and also includes the specific entries +preproc.imports.list = java.applet.*,java.awt.Dimension,java.awt.Frame,java.awt.event.MouseEvent,java.awt.event.KeyEvent,java.awt.event.FocusEvent,java.awt.Image,java.io.*,java.net.*,java.text.*,java.util.*,java.util.zip.*,java.util.regex.* # set the browser to be used on linux browser.linux = mozilla # set to the program to be used for launching apps on linux -#launcher.linux = gnome-open +#launcher.linux = xdg-open # FULL SCREEN (PRESENT MODE) run.present.bgcolor = #666666 diff --git a/core/.project b/core/.project index 9884df8b9..e791e6fcd 100644 --- a/core/.project +++ b/core/.project @@ -1,17 +1,17 @@ - - - core - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - + + + processing-core + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/core/.settings/org.eclipse.jdt.core.prefs b/core/.settings/org.eclipse.jdt.core.prefs index f80f9b559..c06b36105 100644 --- a/core/.settings/org.eclipse.jdt.core.prefs +++ b/core/.settings/org.eclipse.jdt.core.prefs @@ -1,261 +1,271 @@ -#Thu Aug 28 17:36:28 EDT 2008 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.5 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=18 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=18 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=82 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=18 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=18 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=1 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.jdt.core.formatter.indentation.size=2 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=80 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=space -org.eclipse.jdt.core.formatter.tabulation.size=2 -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +#Thu Mar 04 09:10:18 EST 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=18 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=18 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=20 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=36 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=18 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=18 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=0 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=false +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false +org.eclipse.jdt.core.formatter.comment.format_line_comments=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false +org.eclipse.jdt.core.formatter.indentation.size=2 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=2 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true diff --git a/core/.settings/org.eclipse.jdt.ui.prefs b/core/.settings/org.eclipse.jdt.ui.prefs index cfbda4c3e..f0ea5a6a6 100644 --- a/core/.settings/org.eclipse.jdt.ui.prefs +++ b/core/.settings/org.eclipse.jdt.ui.prefs @@ -1,5 +1,5 @@ -#Thu Jan 10 10:50:38 PST 2008 +#Fri Feb 19 16:20:47 EST 2010 eclipse.preferences.version=1 -formatter_profile=_two spaces no tabs +formatter_profile=_processing formatter_settings_version=11 org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/core/build.xml b/core/build.xml new file mode 100644 index 000000000..5a8836abe --- /dev/null +++ b/core/build.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/core/done.txt b/core/done.txt index 6147f40ca..e09233a15 100644 --- a/core/done.txt +++ b/core/done.txt @@ -1,3 +1,58 @@ +0178 core (private) +X filter(DILATE/ERODE) +X dilate(boolean) has bug in clamping of top kernel coordinate +X http://dev.processing.org/bugs/show_bug.cgi?id=1477 +X deprecated 'screen', adding screenW and screenH +X write implementation for get/set methods inside PImage (w/o pixels[]) + + +0177 core (private) +X no changes + + +0176 core (private) +X opengl sketches run at 30fps in present mode on OS X +o still having problems w/ full screen non-FSEM +X http://dev.processing.org/bugs/show_bug.cgi?id=1425 +X PFont not working well with lots of characters +X only create bitmap chars on the fly when needed (in createFont) +X Implement better caching mechanism when creating large fonts +X http://dev.processing.org/bugs/show_bug.cgi?id=1111 +X fix problem with "create font" still showing anti-aliased text +X don't make fonts power of 2 +X PGraphics3D: beginDraw does not release old textures +X http://dev.processing.org/bugs/show_bug.cgi?id=1423 +X fix from taifun_browser +X removing camera() and perspective() from setSize() trashes resize +X probably regression b/c camera/perspective can't be called then +X http://dev.processing.org/bugs/show_bug.cgi?id=1391 + + +0175 core (private) +X changed createInputRaw() to only bother checking URLs if : present + + +0174 core (private) +X svg paths that use 'e' (exponent) not handled properly +X http://dev.processing.org/bugs/show_bug.cgi?id=1408 + + +0173 core (private) +X Re-enabled hack for temporary clipping. +X Clipping still needs to be implemented properly, however. Please help! +X http://dev.processing.org/bugs/show_bug.cgi?id=1393 + + +0172 core (private) +X no changes to the core (or were there?) + + +0171 core (1.0.9) +X Blurred PImages in OPENGL sketches +X removed NPOT texture support (for further testing) +X http://dev.processing.org/bugs/show_bug.cgi?id=1352 + + 0170 core (1.0.8) X added some min/max functions that work with doubles X not sure if those are staying in or not diff --git a/core/methods/.classpath b/core/methods/.classpath new file mode 100644 index 000000000..d9132e9f4 --- /dev/null +++ b/core/methods/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/core/methods/.project b/core/methods/.project new file mode 100644 index 000000000..629f1c16a --- /dev/null +++ b/core/methods/.project @@ -0,0 +1,17 @@ + + + preproc + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/core/methods/build.xml b/core/methods/build.xml new file mode 100644 index 000000000..c37b243eb --- /dev/null +++ b/core/methods/build.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/methods/demo/PApplet.java b/core/methods/demo/PApplet.java new file mode 100644 index 000000000..b2a09c1bb --- /dev/null +++ b/core/methods/demo/PApplet.java @@ -0,0 +1,9483 @@ +/* -*- 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; + + +/** + * 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 + */ +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; + } + } + + /** + * 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 future releases need to be better + * at handling multiple displays. + */ + 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 boolean finished; + + /** + * 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("Calling init()"); + + // 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, getSketchRenderer(), 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 = getSketchWidth(); + int h = getSketchHeight(); + g = makeGraphics(w, h, getSketchRenderer(), null, true); + // Fire component resize event + 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 getSketchWidth() { + return DEFAULT_WIDTH; + } + + + public int getSketchHeight() { + return DEFAULT_HEIGHT; + } + + + public String getSketchRenderer() { + 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() { + // When running inside a browser, start() will be called when someone + // returns to a page containing this applet. + // http://dev.processing.org/bugs/show_bug.cgi?id=581 + finished = false; + + if (thread != null) return; + 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() { + // bringing this back for 0111, hoping it'll help opengl shutdown + finished = true; // why did i comment this out? + + // don't run stop and disposers twice + if (thread == null) return; + thread = null; + + // call to shut down renderer, in case it needs it (pdf does) + if (g != null) g.dispose(); + + // maybe this should be done earlier? might help ensure it gets called + // before the vm just craps out since 1.5 craps out so aggressively. + disposeMethods.handle(); + } + + + /** + * 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. + *

+ * This also attempts to call PApplet.stop(), in case there + * was an inadvertent override of the stop() function by a user. + *

+ * 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).stop(); + } + + + /** + * 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) { + 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) { + // 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 + //println("requesting focus"); + requestFocus(); + } + + // 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(); + } + + stop(); // 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) { + stop(); + 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, stop() has already been called, + // meaning that the main thread has long since exited + exit2(); + + } else if (looping) { + // stop() 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, need to call stop explicitly, + // because the main thread will be sleeping + stop(); + + // now get out + exit2(); + } + } + + + void exit2() { + try { + System.exit(0); + } catch (SecurityException e) { + // don't care about applet security exceptions + } + } + + + + ////////////////////////////////////////////////////////////// + + + 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); + } + 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; + } + + + public PFont createFont(String name, float size) { + return createFont(name, size, true, PFont.DEFAULT_CHARSET); + } + + + public PFont createFont(String name, float size, boolean smooth) { + return createFont(name, size, smooth, PFont.DEFAULT_CHARSET); + } + + + /** + * 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. + *

+ * Only works with Java 1.3 or later. 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 use any of the 65,536 + * unicode characters that exist in the font. Note that this can + * produce an enormous file or may cause an OutOfMemoryError. + */ + public PFont createFont(String name, float size, + boolean smooth, char charset[]) { + String lowerName = name.toLowerCase(); + Font baseFont = null; + + try { + if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { + InputStream 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 = new Font(name, Font.PLAIN, 1); + baseFont = PFont.findFont(name); + } + } catch (Exception e) { + System.err.println("Problem using createFont() with " + name); + e.printStackTrace(); + } + return new PFont(baseFont.deriveFont(size), smooth, charset); + } + + + + ////////////////////////////////////////////////////////////// + + // 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 { + OutputStreamWriter osw = new OutputStreamWriter(output, "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; + } + } + + 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 void saveStream(String targetFilename, String sourceLocation) { + 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 void saveStream(File targetFile, String sourceLocation) { + saveStream(targetFile, createInputRaw(sourceLocation)); + } + + + static public void saveStream(File targetFile, InputStream sourceStream) { + File tempFile = null; + try { + File parentDir = targetFile.getParentFile(); + 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()); + } + } catch (IOException e) { + if (tempFile != null) { + tempFile.delete(); + } + e.printStackTrace(); + } + } + + + /** + * 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++) { + 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; + } + + + /** + * 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 = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); + 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 = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); + 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 main(String args[]) { + // 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", "true"); + } + + // 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); + + // Set the trimmings around the image + Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); + frame.setIconImage(image); + frame.setTitle(name); + + final PApplet applet; + 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(); + + 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; + + 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.screen.width - 33) || + (locationY + windowH > applet.screen.height - 33)) { + // otherwise center on screen + locationX = (applet.screen.width - windowW) / 2; + locationY = (applet.screen.height - windowH) / 2; + } + frame.setLocation(locationX, locationY); + } + } else { // just center on screen + frame.setLocation((applet.screen.width - applet.width) / 2, + (applet.screen.height - applet.height) / 2); + } + + 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); + } + } + + applet.requestFocus(); // ask for keydowns + //System.out.println("exiting main()"); + } + + + ////////////////////////////////////////////////////////////// + + + /** + * 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. NO TOUCH! + // This includes all of the comments, which are automatically pulled + // from their respective functions in PGraphics or PImage. + + // public functions for processing.core + + + public void flush() { + if (recorder != null) recorder.flush(); + g.flush(); + } + + + /** + * Enable a hint option. + *

+ * For the most part, hints are temporary api quirks, + * for which a proper api hasn't been properly worked out. + * for instance SMOOTH_IMAGES existed because smooth() + * wasn't yet implemented, but it will soon go away. + *

+ * They also exist for obscure features in the graphics + * engine, like enabling/disabling single pixel lines + * that ignore the zbuffer, the way they do in alphabot. + *

+ * Current hint options: + *

    + *
  • DISABLE_DEPTH_TEST - + * turns off the z-buffer in the P3D or OPENGL renderers. + *
+ */ + 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); + } + + + 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); + } + + + 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); + } + + + 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); + } + + + 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); + } + + + 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 ellipseMode(int mode) { + if (recorder != null) recorder.ellipseMode(mode); + g.ellipseMode(mode); + } + + + 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); + } + + + /** + * Identical parameters and placement to ellipse, + * but draws only an arc of that ellipse. + *

+ * start and stop are always radians because angleMode() was goofy. + * ellipseMode() sets the placement. + *

+ * also tries to be smart about start < stop. + */ + 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); + } + + + public void box(float size) { + if (recorder != null) recorder.box(size); + g.box(size); + } + + + public void box(float w, float h, float d) { + if (recorder != null) recorder.box(w, h, d); + g.box(w, h, d); + } + + + public void sphereDetail(int res) { + if (recorder != null) recorder.sphereDetail(res); + g.sphereDetail(res); + } + + + /** + * Set the detail level for approximating a sphere. The ures and vres params + * control the horizontal and vertical resolution. + * + * Code for sphereDetail() submitted by toxi [031031]. + * Code for enhanced u/v version from davbol [080801]. + */ + 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. + *

+ * 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
+   * 
+ */ + 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. + * t varies between 0 and 1, and a and d are the on curve points, + * 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. + *

+ * 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();
+ */ + public float bezierPoint(float a, float b, float c, float d, float t) { + return g.bezierPoint(a, b, c, d, t); + } + + + /** + * Provide the tangent at the given point on the bezier curve. + * Fix from davbol for 0136. + */ + public float bezierTangent(float a, float b, float c, float d, float t) { + return g.bezierTangent(a, b, c, d, t); + } + + + public void bezierDetail(int detail) { + if (recorder != null) recorder.bezierDetail(detail); + g.bezierDetail(detail); + } + + + /** + * 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);
+ */ + 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); + } + + + /** + * Get a location along a catmull-rom curve segment. + * + * @param t Value between zero and one for how far along the segment + */ + public float curvePoint(float a, float b, float c, float d, float t) { + return g.curvePoint(a, b, c, d, t); + } + + + /** + * Calculate the tangent at a t value (0..1) on a Catmull-Rom curve. + * Code thanks to Dave Bollinger (Bug #715) + */ + public float curveTangent(float a, float b, float c, float d, float t) { + return g.curveTangent(a, b, c, d, t); + } + + + public void curveDetail(int detail) { + if (recorder != null) recorder.curveDetail(detail); + g.curveDetail(detail); + } + + + public void curveTightness(float tightness) { + if (recorder != null) recorder.curveTightness(tightness); + g.curveTightness(tightness); + } + + + /** + * Draws a segment of Catmull-Rom curve. + *

+ * As of 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();
+   * 
+ */ + 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(); + } + + + /** + * The mode can only be set to CORNERS, CORNER, and CENTER. + *

+ * Support for CENTER was added in release 0146. + */ + 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); + } + + + 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); + } + + + /** + * Set the orientation for the shape() command (like imageMode() or rectMode()). + * @param mode Either CORNER, CORNERS, or CENTER. + */ + 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); + } + + + 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); + } + + + /** + * 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); + } + + + 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. + */ + 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); + } + + + 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); + } + + + 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); + } + + + 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); + } + + + public void tint(int rgb, float alpha) { + if (recorder != null) recorder.tint(rgb, alpha); + g.tint(rgb, alpha); + } + + + 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); + } + + + 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); + } + + + public void noFill() { + if (recorder != null) recorder.noFill(); + g.noFill(); + } + + + /** + * Set the fill to either a grayscale value or an ARGB int. + */ + 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); + } + + + 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); + } + + + 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. + */ + 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). + */ + 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); + } + + + /** + * 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. + */ + 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); + } + + + 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); + } + + + 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); + } + + + public final float alpha(int what) { + return g.alpha(what); + } + + + public final float red(int what) { + return g.red(what); + } + + + public final float green(int what) { + return g.green(what); + } + + + public final float blue(int what) { + return g.blue(what); + } + + + public final float hue(int what) { + return g.hue(what); + } + + + public final float saturation(int what) { + return g.saturation(what); + } + + + public final float brightness(int what) { + return g.brightness(what); + } + + + /** + * Interpolate between two colors, using the current color mode. + */ + 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 image. The x and y parameter specify the pixel or the upper-left corner of the image. The color parameter specifies the color value.

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". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values and calling updatePixels() to update the window. + *

As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Writes a color to any pixel or writes an image into another + * @param x x-coordinate of the pixel or upper-left corner of the image + * @param y y-coordinate of the pixel or upper-left corner of the image + * @param c any value of the color datatype + * + * @see processing.core.PImage#get(int, int, int, int) + * @see processing.core.PImage#pixels + * @see processing.core.PImage#copy(PImage, int, int, int, int, int, int, int, int) + */ + 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.PApplet#alpha(int) + * @see processing.core.PApplet#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.PApplet#alpha(int) + * @see processing.core.PApplet#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/core/methods/demo/PGraphics.java b/core/methods/demo/PGraphics.java new file mode 100644 index 000000000..95834f24b --- /dev/null +++ b/core/methods/demo/PGraphics.java @@ -0,0 +1,5075 @@ +/* -*- 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); + // other stroke attributes are set in the initializers + // inside the class (see above, strokeWeight = 1 et al) + + // 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 + + /** + * Enable a hint option. + *

+ * For the most part, hints are temporary api quirks, + * for which a proper api hasn't been properly worked out. + * for instance SMOOTH_IMAGES existed because smooth() + * wasn't yet implemented, but it will soon go away. + *

+ * They also exist for obscure features in the graphics + * engine, like enabling/disabling single pixel lines + * that ignore the zbuffer, the way they do in alphabot. + *

+ * Current hint options: + *

    + *
  • DISABLE_DEPTH_TEST - + * turns off the z-buffer in the P3D or OPENGL renderers. + *
+ */ + 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(); + } + + + 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(); + } + + + 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(); + } + + + 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(); + } + + + 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; + } + + + 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); + } + + + + ////////////////////////////////////////////////////////////// + + // ELLIPSE AND ARC + + + public void ellipseMode(int mode) { + ellipseMode = mode; + } + + + 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) { + } + + + /** + * Identical parameters and placement to ellipse, + * but draws only an arc of that ellipse. + *

+ * start and stop are always radians because angleMode() was goofy. + * ellipseMode() sets the placement. + *

+ * also tries to be smart about start < stop. + */ + 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 + + + public void box(float size) { + box(size, size, size); + } + + + // TODO not the least bit efficient, it even redraws lines + // along the vertices. ugly ugly ugly! + 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; + + 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 + + + public void sphereDetail(int res) { + sphereDetail(res, res); + } + + + /** + * Set the detail level for approximating a sphere. The ures and vres params + * control the horizontal and vertical resolution. + * + * Code for sphereDetail() submitted by toxi [031031]. + * Code for enhanced u/v version from davbol [080801]. + */ + 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. + *

+ * 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
+   * 
+ */ + 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 + + + /** + * Evalutes quadratic bezier at point t for points a, b, c, d. + * t varies between 0 and 1, and a and d are the on curve points, + * 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. + *

+ * 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();
+ */ + 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; + } + + + /** + * Provide the tangent at the given point on the bezier curve. + * Fix from davbol for 0136. + */ + 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; + } + + + 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); + } + + + /** + * 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);
+ */ + 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 + + + /** + * Get a location along a catmull-rom curve segment. + * + * @param t Value between zero and one for how far along the segment + */ + 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)); + } + + + /** + * Calculate the tangent at a t value (0..1) on a Catmull-Rom curve. + * Code thanks to Dave Bollinger (Bug #715) + */ + 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) ); + } + + + public void curveDetail(int detail) { + curveDetail = detail; + curveInit(); + } + + + 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 segment of Catmull-Rom curve. + *

+ * As of 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();
+   * 
+ */ + 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 + + + /** + * The mode can only be set to CORNERS, CORNER, and CENTER. + *

+ * Support for CENTER was added in release 0146. + */ + 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); + } + } + + + 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 + + + /** + * Set the orientation for the shape() command (like imageMode() or rectMode()). + * @param mode Either CORNER, CORNERS, or CENTER. + */ + 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(); + } + } + + + 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) { + showTextFontException("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) { + showTextFontException("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) { +// if ((textMode == SCREEN) && (size != textFont.size)) { +// throw new RuntimeException("textSize() is ignored with " + +// "textMode(SCREEN)"); +// } + textSize = size; + textLeading = (textAscent() + textDescent()) * 1.275f; + + } else { + showTextFontException("textSize"); + } + } + + + // ........................................................ + + + 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) { + showTextFontException("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) { + showTextFontException("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) { + showTextFontException("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) { + showTextFontException("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 = textAscent() + 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) { + int index = textFont.index(ch); + if (index == -1) return; + + PImage glyph = textFont.images[index]; + + if (textMode == MODEL) { + float high = (float) textFont.height[index] / textFont.fheight; + float bwidth = (float) textFont.width[index] / textFont.fwidth; + float lextent = (float) textFont.leftExtent[index] / textFont.fwidth; + float textent = (float) textFont.topExtent[index] / textFont.fheight; + + float x1 = x + lextent * textSize; + float y1 = y - textent * textSize; + float x2 = x1 + bwidth * textSize; + float y2 = y1 + high * textSize; + + textCharModelImpl(glyph, + x1, y1, x2, y2, + //x1, y1, z, x2, y2, z, + textFont.width[index], textFont.height[index]); + + } else if (textMode == SCREEN) { + int xx = (int) x + textFont.leftExtent[index];; + int yy = (int) y - textFont.topExtent[index]; + + int w0 = textFont.width[index]; + int h0 = textFont.height[index]; + + textCharScreenImpl(glyph, 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 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"); + } + + + ////////////////////////////////////////////////////////////// + + // 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 + + + public void noStroke() { + stroke = false; + } + + + /** + * Set the tint to either a grayscale or ARGB value. + * See notes attached to the fill() function. + */ + public void stroke(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above +// stroke((float) rgb); +// +// } else { +// colorCalcARGB(rgb, colorModeA); +// strokeFromCalc(); +// } + colorCalc(rgb); + strokeFromCalc(); + } + + + public void stroke(int rgb, float alpha) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// stroke((float) rgb, alpha); +// +// } else { +// colorCalcARGB(rgb, alpha); +// strokeFromCalc(); +// } + colorCalc(rgb, alpha); + strokeFromCalc(); + } + + + 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(); + } + + + 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 + + + public void noTint() { + tint = false; + } + + + /** + * Set the tint to either a grayscale or ARGB value. + */ + public void tint(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// tint((float) rgb); +// +// } else { +// colorCalcARGB(rgb, colorModeA); +// tintFromCalc(); +// } + colorCalc(rgb); + tintFromCalc(); + } + + public void tint(int rgb, float alpha) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { +// tint((float) rgb, alpha); +// +// } else { +// colorCalcARGB(rgb, alpha); +// tintFromCalc(); +// } + colorCalc(rgb, alpha); + tintFromCalc(); + } + + 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(); + } + + + 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 + + + public void noFill() { + fill = false; + } + + + /** + * Set the fill to either a grayscale value or an ARGB int. + */ + public void fill(int rgb) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above +// fill((float) rgb); +// +// } else { +// colorCalcARGB(rgb, colorModeA); +// fillFromCalc(); +// } + colorCalc(rgb); + fillFromCalc(); + } + + + public void fill(int rgb, float alpha) { +// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above +// fill((float) rgb, alpha); +// +// } else { +// colorCalcARGB(rgb, alpha); +// fillFromCalc(); +// } + colorCalc(rgb, alpha); + fillFromCalc(); + } + + + 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(); + } + + + 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. + */ + 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). + */ + 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(); + } + + + /** + * 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. + */ + 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 + + + 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); + } + + + 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. + + + public final float alpha(int what) { + float c = (what >> 24) & 0xff; + if (colorModeA == 255) return c; + return (c / 255.0f) * colorModeA; + } + + + public final float red(int what) { + float c = (what >> 16) & 0xff; + if (colorModeDefault) return c; + return (c / 255.0f) * colorModeX; + } + + + public final float green(int what) { + float c = (what >> 8) & 0xff; + if (colorModeDefault) return c; + return (c / 255.0f) * colorModeY; + } + + + public final float blue(int what) { + float c = (what) & 0xff; + if (colorModeDefault) return c; + return (c / 255.0f) * colorModeZ; + } + + + 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; + } + + + 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; + } + + + 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. + + + /** + * Interpolate between two colors, using the current color mode. + */ + 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); + } + + + /** + * Throw an exeption that halts the program because textFont() has not been + * used prior to the specified method. + */ + static protected void showTextFontException(String method) { + 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/core/methods/demo/PImage.java b/core/methods/demo/PImage.java new file mode 100644 index 000000000..276617825 --- /dev/null +++ b/core/methods/demo/PImage.java @@ -0,0 +1,2862 @@ +/* -*- 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.PApplet#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 image. The x and y parameter specify the pixel or the upper-left corner of the image. The color parameter specifies the color value.

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". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values and calling updatePixels() to update the window. + *

As of release 0149, this function ignores imageMode(). + * + * @webref + * @brief Writes a color to any pixel or writes an image into another + * @param x x-coordinate of the pixel or upper-left corner of the image + * @param y y-coordinate of the pixel or upper-left corner of the image + * @param c any value of the color datatype + * + * @see processing.core.PImage#get(int, int, int, int) + * @see processing.core.PImage#pixels + * @see processing.core.PImage#copy(PImage, int, int, int, int, int, int, int, int) + */ + 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) { + 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=0; + 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=0; + 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.PApplet#alpha(int) + * @see processing.core.PApplet#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.PApplet#alpha(int) + * @see processing.core.PApplet#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 - 1; + if (srcY2 >= img.height) srcY2 = img.height - 1; + + 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/core/methods/methods.jar b/core/methods/methods.jar new file mode 100644 index 0000000000000000000000000000000000000000..ff4276ba306846472b1e999976c4dbf742ec18d7 GIT binary patch literal 3725 zcmZ{ncQhPox5g(y)QJ!!!XZbAI=bjYbYqktqDBd#k3Pc)VvI6IH|iiFQ6st;L>na- zUBU^8-b?h5%;DzTbMN<^b=P;_z4m(dyVmo(`}y~00;Zs(0|00MfHJhM3g91y7C;Gr zXq#(*^o?{RE(QSrlmC&@07`#J6SA5gIsTG+|7w9q+HDDG-OS&7hU$~6Uei0=JR~p32yBcGVJ_H(g6sZ_-&8Sw|IrsqXm-!kfBRbaQ~r}yL7F=tUIo|XeXV5>{BCRW$wyjE=4 zhpa{91}3}1Y>7ARRpLvZ!at)6mpFi<9%nhIby>3QjgGPXHWa&Tn~-eB)P7o7m=#g< z_H%)ScfF{2n&S%8yvG?1H7!fFCvM;VI#y#z{ zOb6WW?!{i8`W$Q;twuIe2_MBo5Dt7_gxxph7;<8JS?u|~U4yZgG^SsRA2))A^JC-w z;NdF+VmxV*Uau8tlAiop2vJ}uN$+F5*@VDhoCf-fhL z^VFZneUI9V_nym)RZI|25#y)I1Pq#eB*x^;uDw;1|HF-^uCebfUs{t@J9soffP|C% zi98-lapZ_D<@{0PDAmX}@`gF?ax0+(hZlC@-_6ds!906Q--x?D#iDA!H5{cjVW0TT z){3--whr}IVAIzxqxqUIMZgH&E7rwuRpo99-$dIE=aMbg`kRiZUW zyy86;*JHWCx04`~i+(dX82+37&`hVzqT4Lj1K}vCU7rACIxYzLsm}RDU63-HVYj}2di+&byZIc zwB3s@3-&;hmbPXY2<0`ISo$Ee+cnzhpliVE=IQchMt?oUl_p0j-3ei31qaIWL9rFi zmaP@U9}o{jq1+l~V2Q@1Qt9=@AT|?%=-07IEt5vFh%t+SNd~(@$(S8xM zoy!>=9=g4j^l8}bo#&qK&Z&Stay z+LsQ|E>O@xBaJxunPh5GKW8)*gPDk_{nUlI%=%uH0OU{7#*Q!P$IH{^8X)y}mzomN zyy>OHw)9a$joND|PfsX#k$YrM>LC^w6DCz@;TMoAh7m59%Yoh-oZtsJS-UwkrFpwG z7AVEy3dRM&$DpuD#xTZ#uj{^NxrV)yxyw%=b+NR^%x@IJG9&4T zOrN8a3h!*lC^FZZO{cieBdnxVQYgGcR2gZlRixL}ZsXyUT7QT4OtrHDCA|rw-~%+j@-e}*=ccp+ z)zUW;72Iv{DdX{l6`I2`y{Gfcd;>d(ACX9sYeu|s8fQC_FF`Tu`t~DvPG5dr9omcX zc-5gdt5k6Kfb`HSY!0^ck*3>#t@0=&FYQaTy1BtB(3N8VFV6Refgd7Cxa<4x0`Q|W zr6ux`>lG8gKZdLdMrMJCkow&Top&#TFu~ihgkU*{9rJzf;iYi1dD_Rbt)6 zEBDDiV)6@ACE?IdA?(j;JE%Ip2<7H$CmAuYcn z1Q@}FG10VMt!6mg2DXMQk45q=j5ydEcbcvaJ6sk-%5;RRefPN}GhD}qE)7VPnITSO zHv8_{r%zHru28%2ekgo&Q8NXy5{7R&moc>VtO2M`I%BUUF|gGt8ePzQUothHi;pH# zyFowPN@A;t>hhC4Z8{?u<`VZJZD?$?;FV%vtrBI?2@vnM1w%Ds)dn{DO}dsCA8ny0 zj3LD_)7nsHsfzJPDsmW}74pmtA*gA}g`$V@H!a?pLps-T_Ad(uF2Kczq6)NOe$rpN zgkg+0tuqDqSZ{Lis(JFH`|mB~OqH8@$78h$=}Ed0xI{JU_~%<)cWhpnsjC;EZoFn< zm~`#gaLU)Tyrc0-a?_fBQzswXd}o-=rXigt{JW!blaG7=RY&(|C#4~NKP(^3Km9gu z70%JL;6(dTugi6AL`-~G%^$cf8h*tN14LZnck9|Q48qS!>1*SE&s0UEyZElPL~y@b zLZI@!7X6d7@*BM!pHl}Y<;3z-5p0&oprhf%**fhC_n6OXMK$#%j@6&M;uS(Fx5=^o zE%_HjJR)Nk>K%0B+x5}it5IH`2+wT^gEL#%xAJD}*6}E?XW#ftkGDtOnNR5vakWuz5HyluckX9a5MT9xj#c~Wb!ri*Y9FkW`jl<9`a%b>slkW<27<_a;A46KB!pg3Uvw? znIyYk@Pe%@hoWqqX&o(`uL%lI7uz|Bz7&V7sS}Cx|nz97FAjM*Q#*jYU~8+uI_#Od>s%wuuU_9JH?3m?pjzdIOxwD#rCZQur*={Ap}P z3z7RmPJorAhHJw+n_XxqcldjgRnj^nQx|?PGH;fz1M`=YIlTz3j;2bFPRcWoAg&(? zypN2XX3IFRc-vbF+p$AZ_(?T4fuTZbqnJHuvEEe$)+e2G2-?y`gQ~7+m|+Btb66f$ z=d%oskZaD_J(I2OeT^>&kzY`ni)*c=_#R+`xGKNwKKH`SkFyz#gJEX3?B`;dbC$yA zG)00_IhW02soj~{jUh1Pbz*YaZ>{AN$rHk7Qu4j3PZy*Nmi#_P3U2tT=+AeW1p*7+ zOwWa4_zM@-1a^Rv=W%8S$a1X}2Q}t(VNR5&{eG7;F2OcGNoPC9pxckoq|fnZ!MC-Qv$2D(gS z(Hnv&sB(Fup6R{84b3f@x*n%%@@Px9UAVs=J?6pS;R5 zUg41Q<#Ibc)Y@Au9kYHOb$oJfC~|K;CaBpsBFa=z#oYAxYF@u%>U0tHbMbe+bqT^2 zNM9GiyK@N>@Rh496#qZD{S9(A0J|E0P5*+kzd7!It^b+i{= 0) { + break; + } + } + + // read the rest of the file and append it to the + while ((line = applet.readLine()) != null) { + content.append(line); + content.append('\n'); + } + + applet.close(); + process(out, graphicsFile); + process(out, imageFile); + + out.append('}'); + out.append('\n'); + + //} catch (IOException e) { + //e.printStackTrace(); + + } catch (Exception e) { + //ex.printStackTrace(); + throw new BuildException(e); + } + //out.flush(); + + String outString = out.toString(); + if (content.toString().equals(outString)) { + System.out.println("No changes to PApplet API."); + } else { + System.out.println("Updating PApplet with API changes " + + "from PImage or PGraphics."); + try { + PrintStream temp = new PrintStream(appletFile, "UTF-8"); + temp.print(outString); + temp.flush(); + temp.close(); + } catch (IOException e) { + //e.printStackTrace(); + throw new BuildException(e); + } + } + } + + + private void process(StringBuffer out, File input) throws IOException { + BufferedReader in = createReader(input); + int comments = 0; + String line = null; + StringBuffer commentBuffer = new StringBuffer(); + + while ((line = in.readLine()) != null) { + String decl = ""; + + // Keep track of comments + //if (line.matches(Pattern.quote("/*"))) { + if (line.indexOf("/*") != -1) { + comments++; + } + + //if (line.matches(Pattern.quote("*/"))) { + if (line.indexOf("*/") != -1) { + commentBuffer.append(line); + commentBuffer.append('\n'); + //System.out.println("comment is: " + commentBuffer.toString()); + comments--; + // otherwise gotSomething will be false, and nuke the comment + continue; + } + + // Ignore everything inside comments + if (comments > 0) { + commentBuffer.append(line); + commentBuffer.append('\n'); + continue; + } + + boolean gotSomething = false; + boolean gotStatic = false; + + Matcher result; + + if ((result = Pattern.compile("^\\s*public ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) { + gotSomething = true; + + } else if ((result = Pattern.compile("^\\s*abstract public ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) { + gotSomething = true; + + } else if ((result = Pattern.compile("^\\s*public final ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) { + gotSomething = true; + + } else if ((result = Pattern.compile("^\\s*static public ([\\w\\[\\]]+) [a-zA-z_]+\\(.*$").matcher(line)).matches()) { + gotSomething = true; + gotStatic = true; + } + + // if function is marked "// ignore" then, uh, ignore it. + if (gotSomething && line.indexOf("// ignore") >= 0) { + gotSomething = false; + } + + String returns = ""; + if (gotSomething) { + if (result.group(1).equals("void")) { + returns = ""; + } else { + returns = "return "; + } + + // remove the abstract modifier + line = line.replaceFirst(Pattern.quote("abstract"), " "); + + // replace semicolons with a start def + line = line.replaceAll(Pattern.quote(";"), " {\n"); + + //out.println("\n\n" + line); + out.append('\n'); + out.append('\n'); + // end has its own newline + //out.print(commentBuffer.toString()); // TODO disabled for now XXXX + out.append(commentBuffer.toString()); // duplicates all comments + commentBuffer.setLength(0); + out.append(line); + out.append('\n'); + + decl += line; + while(line.indexOf(')') == -1) { + line = in.readLine(); + decl += line; + line = line.replaceAll("\\;\\s*$", " {\n"); + out.append(line); + out.append('\n'); + } + + result = Pattern.compile(".*?\\s(\\S+)\\(.*?").matcher(decl); + // try to match. don't remove this or things will stop working! + result.matches(); + String declName = result.group(1); + String gline = ""; + String rline = ""; + if (gotStatic) { + gline = " " + returns + "PGraphics." + declName + "("; + } else { + rline = " if (recorder != null) recorder." + declName + "("; + gline = " " + returns + "g." + declName + "("; + } + + decl = decl.replaceAll("\\s+", " "); // smush onto a single line + decl = decl.replaceFirst("^.*\\(", ""); + decl = decl.replaceFirst("\\).*$", ""); + + int prev = 0; + String parts[] = decl.split("\\, "); + + for (String part : parts) { + if (!part.trim().equals("")) { + String blargh[] = part.split(" "); + String theArg = blargh[1].replaceAll("[\\[\\]]", ""); + + if (prev != 0) { + gline += ", "; + rline += ", "; + } + + gline += theArg; + rline += theArg; + prev = 1; + } + } + + gline += ");"; + rline += ");"; + + if (!gotStatic && returns.equals("")) { + out.append(rline); + out.append('\n'); + } + out.append(gline); + out.append('\n'); + out.append(" }"); + out.append('\n'); + + } else { + commentBuffer.setLength(0); + } + } + + in.close(); + } + + + static BufferedReader createReader(File file) throws IOException { + FileInputStream fis = new FileInputStream(file); + return new BufferedReader(new InputStreamReader(fis, "UTF-8")); + } +} diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java index 06541c547..60bbe3d75 100644 --- a/core/src/processing/core/PApplet.java +++ b/core/src/processing/core/PApplet.java @@ -3,7 +3,7 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2004-09 Ben Fry and Casey Reas + 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 @@ -39,6 +39,8 @@ import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; +import processing.core.PShape; + /** * Base class for all sketches that use processing.core. @@ -157,6 +159,7 @@ import javax.swing.SwingUtilities; * 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 */ public class PApplet extends Applet implements PConstants, Runnable, @@ -217,6 +220,25 @@ public class PApplet extends Applet } } + /** + * 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 String useQuartz = "true"; + /** * Modifier flags for the shortcut key used to trigger menus. * (Cmd on Mac OS X, Ctrl on Linux and Windows) @@ -247,8 +269,15 @@ public class PApplet extends Applet * 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 future releases need to be better - * at handling multiple displays. + * 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(); @@ -305,23 +334,54 @@ public class PApplet extends Applet 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 */ + /** width of this applet's associated PGraphics + * @webref environment + */ public int width; - /** height of this applet's associated PGraphics */ + /** height of this applet's associated PGraphics + * @webref environment + * */ public int height; - /** current x position of the mouse */ + /** + * 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; - /** current y position of the mouse */ + /** + * 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; /** @@ -332,8 +392,20 @@ public class PApplet extends Applet * 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, pmouseY; + 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 @@ -360,36 +432,84 @@ public class PApplet extends Applet public boolean firstMouse; /** - * Last mouse button pressed, one of LEFT, CENTER, or RIGHT. - *

+ * 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; /** - * true if the mouse is currently pressed. + * 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; @@ -400,6 +520,7 @@ public class PApplet extends Applet /** * Gets set to true/false as the applet gains/loses focus. + * @webref environment */ public boolean focused = false; @@ -408,6 +529,7 @@ public class PApplet extends Applet *

* 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; @@ -542,6 +664,10 @@ public class PApplet extends Applet public void init() { // println("Calling init()"); + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + screenWidth = screen.width; + screenHeight = screen.height; + // send tab keys through to the PApplet setFocusTraversalKeysEnabled(false); @@ -935,6 +1061,17 @@ public class PApplet extends Applet /** + * 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. *

@@ -948,12 +1085,19 @@ public class PApplet extends Applet *

* 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); } @@ -1015,6 +1159,11 @@ public class PApplet extends Applet /** + * 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. *

    @@ -1063,6 +1212,14 @@ public class PApplet extends Applet * 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) { @@ -1075,7 +1232,7 @@ public class PApplet extends Applet /** * 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 can be an absolute or relative path + * @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) { @@ -1219,9 +1376,21 @@ public class PApplet extends Applet /** + * 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); @@ -1678,35 +1847,75 @@ public class PApplet extends Applet /** - * Mouse has been pressed, and should be considered "down" - * until mouseReleased() is called. If you must, use + * 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() { } /** - * Mouse button has been released. + * 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() { } /** - * Mouse button is pressed and the mouse has been dragged. + * 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() { } /** - * Mouse button is not pressed but the mouse has changed locations. + * 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() { } @@ -1801,6 +2010,15 @@ public class PApplet extends Applet /** + * + * 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 @@ -1846,12 +2064,23 @@ public class PApplet extends Applet * 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() { } /** - * See 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() { } @@ -1892,48 +2121,108 @@ public class PApplet extends Applet /** - * Get the number of milliseconds since the applet started. + * 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. */ + /** 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); } - /** Minutes position of the current time. */ + /** + * 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); } /** - * Get the current month in range 1 through 12. + * 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 @@ -1941,7 +2230,16 @@ public class PApplet extends Applet } /** - * Get the current year. + * 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); @@ -1978,12 +2276,20 @@ public class PApplet extends Applet /** + * 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; @@ -1995,8 +2301,16 @@ public class PApplet extends Applet /** - * Get a param from the web page, or (eventually) - * from a properties file. + * 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) { @@ -2010,9 +2324,16 @@ public class PApplet extends Applet /** + * 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) { @@ -2030,6 +2351,8 @@ public class PApplet extends Applet /** + * 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, @@ -2039,6 +2362,11 @@ public class PApplet extends Applet *

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) { @@ -2076,9 +2404,12 @@ public class PApplet extends Applet } else if (platform == MACOSX) { //com.apple.mrj.MRJFileUtils.openURL(url); try { - Class mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); +// 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 = - mrjFileUtils.getMethod("openURL", new Class[] { String.class }); + eieio.getMethod("openURL", new Class[] { String.class }); openMethod.invoke(null, new Object[] { url }); } catch (Exception e) { e.printStackTrace(); @@ -2097,7 +2428,19 @@ public class PApplet extends Applet /** - * Attempt to open a file using the platform's shell. + * 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 }); @@ -2111,6 +2454,8 @@ public class PApplet extends Applet * 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; @@ -2397,6 +2742,7 @@ public class PApplet extends Applet /** * Set the cursor type + * @param cursorType either ARROW, CROSS, HAND, MOVE, TEXT, WAIT */ public void cursor(int cursorType) { setCursor(Cursor.getPredefinedCursor(cursorType)); @@ -2415,6 +2761,11 @@ public class PApplet extends Applet /** + * 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 @@ -2422,6 +2773,11 @@ public class PApplet extends Applet * 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 @@ -2455,8 +2811,13 @@ public class PApplet extends Applet /** + * 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. @@ -3229,12 +3590,27 @@ public class PApplet extends Applet /** + * 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) { @@ -3315,12 +3691,22 @@ public class PApplet extends Applet 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 = @@ -3638,7 +4024,21 @@ public class PApplet extends Applet /** - * Load a geometry from a file as a PShape. Currently only supports SVG data. + * 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")) { @@ -3668,13 +4068,25 @@ public class PApplet extends Applet } + /** + * 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, PFont.DEFAULT_CHARSET); + return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { - return createFont(name, size, smooth, PFont.DEFAULT_CHARSET); + return createFont(name, size, smooth, null); } @@ -3683,8 +4095,8 @@ public class PApplet extends Applet * installed on the system, or from a .ttf or .otf that's inside * the data folder of this sketch. *

- * Only works with Java 1.3 or later. Many .otf fonts don't seem - * to be supported by Java, perhaps because they're CFF based? + * 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, @@ -3693,9 +4105,9 @@ public class PApplet extends Applet * 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 use any of the 65,536 - * unicode characters that exist in the font. Note that this can - * produce an enormous file or may cause an OutOfMemoryError. + * 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[]) { @@ -3703,8 +4115,9 @@ public class PApplet extends Applet Font baseFont = null; try { + InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { - InputStream stream = createInput(name); + stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + @@ -3715,14 +4128,16 @@ public class PApplet extends Applet baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { - //baseFont = new Font(name, Font.PLAIN, 1); baseFont = PFont.findFont(name); } + return new PFont(baseFont.deriveFont(size), smooth, charset, + stream != null); + } catch (Exception e) { - System.err.println("Problem using createFont() with " + name); + System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); + return null; } - return new PFont(baseFont.deriveFont(size), smooth, charset); } @@ -3764,9 +4179,14 @@ public class PApplet extends Applet /** - * Open a platform-specific file chooser dialog to select a file for input. - * @param prompt Mesage to show the user when prompting for 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); @@ -3783,9 +4203,17 @@ public class PApplet extends Applet /** - * Open a platform-specific file save dialog to select a file for output. - * @param prompt Mesage to show the user when prompting for a file. + * 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); @@ -3816,19 +4244,21 @@ public class PApplet extends Applet } - /** - * Open a platform-specific folder chooser dialog. - * @return full path to the selected folder, or null if no selection. - */ public String selectFolder() { return selectFolder("Select a folder..."); } /** - * Open a platform-specific folder chooser dialog. - * @param prompt Mesage to show the user when prompting for a file. + * 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(); @@ -3997,6 +4427,18 @@ public class PApplet extends Applet /** + * 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 @@ -4026,6 +4468,14 @@ public class PApplet extends Applet *

  • 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); @@ -4057,24 +4507,26 @@ public class PApplet extends Applet // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah - try { - URL url = new URL(filename); - stream = url.openStream(); - return stream; + 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 (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 (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); + } 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 @@ -4181,6 +4633,9 @@ public class PApplet extends Applet 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")) { @@ -4189,18 +4644,25 @@ public class PApplet extends Applet return input; } catch (IOException e) { - if (file == null) { - throw new RuntimeException("File passed to openStream() was null"); - - } else { - e.printStackTrace(); - throw new RuntimeException("Couldn't openStream() for " + - file.getAbsolutePath()); - } + 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); @@ -4247,6 +4709,12 @@ public class PApplet extends Applet /** + * 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 @@ -4257,6 +4725,13 @@ public class PApplet extends Applet * 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); @@ -4491,10 +4966,10 @@ public class PApplet extends Applet 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(); + for (int i = 0; i < strings.length; i++) { + writer.println(strings[i]); + } + writer.flush(); writer.close(); } @@ -6320,6 +6795,8 @@ public class PApplet extends Applet /** * 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) { @@ -6384,7 +6861,18 @@ public class PApplet extends Applet 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; @@ -6544,7 +7032,7 @@ public class PApplet extends Applet 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", "true"); + System.setProperty("apple.awt.graphics.UseQuartz", useQuartz); } // This doesn't do anything. @@ -6709,6 +7197,7 @@ public class PApplet extends Applet frame.setBackground(backgroundColor); if (exclusive) { displayDevice.setFullScreenWindow(frame); + frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); fullScreenRect = frame.getBounds(); } else { DisplayMode mode = displayDevice.getDisplayMode(); @@ -6933,16 +7422,33 @@ public class PApplet extends Applet /** + * 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(); } @@ -6955,7 +7461,10 @@ public class PApplet extends Applet ////////////////////////////////////////////////////////////// - // everything below this line is automatically generated. no touch. + // 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 @@ -7428,7 +7937,7 @@ public class PApplet extends Applet } - public void text(char[] chars, int start, int stop, + 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); @@ -8177,15 +8686,15 @@ public class PApplet extends Applet } - public void mask(int alpha[]) { - if (recorder != null) recorder.mask(alpha); - g.mask(alpha); + public void mask(int maskArray[]) { + if (recorder != null) recorder.mask(maskArray); + g.mask(maskArray); } - public void mask(PImage alpha) { - if (recorder != null) recorder.mask(alpha); - g.mask(alpha); + public void mask(PImage maskImg) { + if (recorder != null) recorder.mask(maskImg); + g.mask(maskImg); } diff --git a/core/src/processing/core/PConstants.java b/core/src/processing/core/PConstants.java index 24f0b9fa8..f1eae5882 100644 --- a/core/src/processing/core/PConstants.java +++ b/core/src/processing/core/PConstants.java @@ -34,6 +34,8 @@ import java.awt.event.KeyEvent; * 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 { @@ -158,11 +160,52 @@ public interface PConstants { // 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; diff --git a/core/src/processing/core/PFont.java b/core/src/processing/core/PFont.java index 74da5cb18..421cfb09e 100644 --- a/core/src/processing/core/PFont.java +++ b/core/src/processing/core/PFont.java @@ -3,13 +3,12 @@ /* Part of the Processing project - http://processing.org - Copyright (c) 2004-07 Ben Fry & Casey Reas + 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 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. + 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 @@ -25,17 +24,16 @@ package processing.core; import java.awt.*; -import java.awt.image.BufferedImage; -import java.awt.image.Raster; +import java.awt.image.*; import java.io.*; -//import java.lang.reflect.*; 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: + * Awful (and by that, I mean awesome) ASCII (non-)art for how this works: *

      *   |
      *   |                   height is the full used height of the image
    @@ -56,8 +54,60 @@ import java.util.Arrays;
      */
     public class PFont implements PConstants {
     
    -  public int charCount;
    -  public PImage images[];
    +  /** 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
    @@ -65,70 +115,179 @@ public class PFont implements PConstants {
        * 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;
     
       /**
    -   * Name of the font as seen by Java when it was created.
    -   * If the font is available, the native version will be used.
    +   * 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. 
        */
    -  public String name;
    -
    -  /**
    -   * Postscript name of the font that this bitmap was created from.
    -   */
    -  public String psname;
    -
    -  /** "natural" size of the font (most often 48) */
    -  public int size;
    -
    -  /** true if smoothing was enabled for this font, used for native impl */
    -  public boolean smooth;
    -
    -  /** next power of 2 over the max image size (usually 64) */
    -  public int mbox2;
    -
    -  /** floating point width (convenience) */
    -  protected float fwidth;
    -
    -  /** floating point width (convenience) */
    -  protected float fheight;
    -
    -  /** texture width, same as mbox2, but reserved for future use */
    -  public int twidth;
    -
    -  /** texture height, same as mbox2, but reserved for future use */
    -  public int theight;
    -
    -  public int value[];  // char code
    -  public int height[]; // height of the bitmap data
    -  public int width[];  // width of bitmap data
    -  public int setWidth[];  // width displaced by the char
    -  public int topExtent[];  // offset for the top
    -  public int leftExtent[];  // offset for the left
    -
    -  public int ascent;
    -  public int descent;
    -
    -  protected int ascii[];  // quick lookup for the ascii chars
    -
    -  // shared by the text() functions to avoid incessant allocation of memory
    -  //protected char textBuffer[] = new char[8 * 1024];
    -  //protected char widthBuffer[] = new char[8 * 1024];
    -  
       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) {
    +      // 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)) {
    +          glyphs[glyphCount++] = new Glyph(c);
    +        }
    +      }
    +
    +      // 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
    -    charCount = is.readInt();
    +    glyphCount = is.readInt();
     
    -    // bit count is ignored since this is always 8
    -    //int numBits = 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.
    @@ -137,62 +296,28 @@ public class PFont implements PConstants {
         // 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
    -    //mbox2 = is.readInt();
    -    mbox2 = is.readInt();
    -
    -    fwidth = size; //mbox;
    -    fheight = size; //mbox;
    -
    -    // size for image ("texture") is next power of 2
    -    // over the font size. for most vlw fonts, the size is 48
    -    // so the next power of 2 is 64.
    -    // double-check to make sure that mbox2 is a power of 2
    -    // there was a bug in the old font generator that broke this
    -    //mbox2 = (int) Math.pow(2, Math.ceil(Math.log(mbox2) / Math.log(2)));
    -    mbox2 = (int) Math.pow(2, Math.ceil(Math.log(mbox2) / Math.log(2)));
    -    // size for the texture is stored in the font
    -    twidth = theight = mbox2; //mbox2;
    +    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
    -    value       = new int[charCount];
    -    height      = new int[charCount];
    -    width       = new int[charCount];
    -    setWidth    = new int[charCount];
    -    topExtent   = new int[charCount];
    -    leftExtent  = new int[charCount];
    +    glyphs = new Glyph[glyphCount];
     
         ascii = new int[128];
    -    for (int i = 0; i < 128; i++) ascii[i] = -1;
    +    Arrays.fill(ascii, -1);
     
         // read the information about the individual characters
    -    for (int i = 0; i < charCount; i++) {
    -      value[i]      = is.readInt();
    -      height[i]     = is.readInt();
    -      width[i]      = is.readInt();
    -      setWidth[i]   = is.readInt();
    -      topExtent[i]  = is.readInt();
    -      leftExtent[i] = is.readInt();
    -
    -      // pointer in the c version, ignored
    -      is.readInt();
    -
    +    for (int i = 0; i < glyphCount; i++) {
    +      Glyph glyph = new Glyph(is);
           // cache locations of the ascii charset
    -      if (value[i] < 128) ascii[value[i]] = i;
    -
    -      // 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[i] == 'd') {
    -        if (ascent == 0) ascent = topExtent[i];
    -      }
    -      if (value[i] == 'p') {
    -        if (descent == 0) descent = -topExtent[i] + height[i];
    +      if (glyph.value < 128) {
    +        ascii[glyph.value] = i;
           }
    +      glyphs[i] = glyph;
         }
     
         // not a roman font, so throw an error and ask to re-build.
    @@ -202,29 +327,8 @@ public class PFont implements PConstants {
                                      "re-create this font.");
         }
     
    -    images = new PImage[charCount];
    -    for (int i = 0; i < charCount; i++) {
    -      images[i] = new PImage(twidth, theight, ALPHA);
    -      int bitmapSize = height[i] * width[i];
    -
    -      byte temp[] = new byte[bitmapSize];
    -      is.readFully(temp);
    -
    -      // convert the bitmap to an alpha channel
    -      int w = width[i];
    -      int h = height[i];
    -      for (int y = 0; y < h; y++) {
    -        for (int x = 0; x < w; x++) {
    -          int valu = temp[y*w + x] & 0xff;
    -          images[i].pixels[y * twidth + x] = valu;
    -          //(valu << 24) | 0xFFFFFF;  // windows
    -          //0xFFFFFF00 | valu;  // macosx
    -
    -          //System.out.print((images[i].pixels[y*64+x] > 128) ? "*" : ".");
    -        }
    -        //System.out.println();
    -      }
    -      //System.out.println();
    +    for (Glyph glyph : glyphs) {
    +      glyph.readBitmap(is);
         }
     
         if (version >= 10) {  // includes the font name at the end of the file
    @@ -237,6 +341,100 @@ public class PFont implements PConstants {
       }
     
     
    +  /**
    +   * 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. */ @@ -254,6 +452,11 @@ public class PFont implements PConstants { // } return font; } + + + public boolean isStream() { + return stream; + } /** @@ -284,77 +487,50 @@ public class PFont implements PConstants { } - /** - * 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(charCount); - - if ((name == null) || (psname == null)) { - name = ""; - psname = ""; - } - // formerly numBits, now used for version number - //os.writeInt((name != null) ? 11 : 8); - os.writeInt(11); - - os.writeInt(size); // formerly mboxX (was 64, now 48) - os.writeInt(mbox2); // formerly mboxY (was 64, still 64) - os.writeInt(ascent); // formerly baseHt (was ignored) - os.writeInt(descent); // formerly struct padding for c version - - for (int i = 0; i < charCount; i++) { - os.writeInt(value[i]); - os.writeInt(height[i]); - os.writeInt(width[i]); - os.writeInt(setWidth[i]); - os.writeInt(topExtent[i]); - os.writeInt(leftExtent[i]); - os.writeInt(0); // padding - } - - for (int i = 0; i < charCount; i++) { - for (int y = 0; y < height[i]; y++) { - for (int x = 0; x < width[i]; x++) { - os.write(images[i].pixels[y * mbox2 + x] & 0xff); - } - } - } - - //if (name != null) { // version 11 - os.writeUTF(name); - os.writeUTF(psname); - os.writeBoolean(smooth); - //} - - os.flush(); + public Glyph getGlyph(char c) { + int index = index(c); + return (index == -1) ? null : glyphs[index]; } /** - * Get index for the char (convert from unicode to bagel charset). + * Get index for the character. * @return index into arrays or -1 if not found */ - public int index(char c) { + 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 (charCount == 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, charCount-1); + return indexHunt(c, 0, glyphCount-1); } @@ -362,14 +538,14 @@ public class PFont implements PConstants { int pivot = (start + stop) / 2; // if this is the char, then return it - if (c == value[pivot]) return pivot; + 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 < value[pivot]) return indexHunt(c, start, pivot-1); + 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); @@ -390,7 +566,7 @@ public class PFont implements PConstants { * The value is based on a font of size 1. */ public float ascent() { - return ((float)ascent / fheight); + return ((float) ascent / (float) size); } @@ -399,7 +575,7 @@ public class PFont implements PConstants { * The value is based on a font size of 1. */ public float descent() { - return ((float)descent / fheight); + return ((float) descent / (float) size); } @@ -412,7 +588,7 @@ public class PFont implements PConstants { int cc = index(c); if (cc == -1) return 0; - return ((float)setWidth[cc] / fwidth); + return ((float) glyphs[cc].setWidth / (float) size); } @@ -465,200 +641,19 @@ public class PFont implements PConstants { *

    * Not that I expect that to happen. */ - static public char[] DEFAULT_CHARSET; + static public char[] CHARSET; static { - DEFAULT_CHARSET = new char[126-33+1 + EXTRA_CHARS.length]; + CHARSET = new char[126-33+1 + EXTRA_CHARS.length]; int index = 0; for (int i = 33; i <= 126; i++) { - DEFAULT_CHARSET[index++] = (char)i; + CHARSET[index++] = (char)i; } for (int i = 0; i < EXTRA_CHARS.length; i++) { - DEFAULT_CHARSET[index++] = EXTRA_CHARS[i]; + CHARSET[index++] = EXTRA_CHARS[i]; } }; - /** - * Create a new image-based font on the fly. - * - * @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(); - - // fix regression from sorting (bug #564) - if (charset != null) { - // 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); - } - - // the count gets reset later based on how many of - // the chars are actually found inside the font. - this.charCount = (charset == null) ? 65536 : charset.length; - this.size = font.getSize(); - - fwidth = fheight = size; - - PImage bitmaps[] = new PImage[charCount]; - - // allocate enough space for the character info - value = new int[charCount]; - height = new int[charCount]; - width = new int[charCount]; - setWidth = new int[charCount]; - topExtent = new int[charCount]; - leftExtent = new int[charCount]; - - ascii = new int[128]; - for (int i = 0; i < 128; i++) ascii[i] = -1; - - int mbox3 = size * 3; - - BufferedImage playground = - new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB); - - Graphics2D g = (Graphics2D) playground.getGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - smooth ? - RenderingHints.VALUE_ANTIALIAS_ON : - RenderingHints.VALUE_ANTIALIAS_OFF); - - g.setFont(font); - FontMetrics metrics = g.getFontMetrics(); - - int samples[] = new int[mbox3 * mbox3]; - - int maxWidthHeight = 0; - int index = 0; - for (int i = 0; i < charCount; i++) { - char c = (charset == null) ? (char)i : charset[i]; - - if (!font.canDisplay(c)) { // skip chars not in the font - continue; - } - - g.setColor(Color.white); - g.fillRect(0, 0, mbox3, mbox3); - g.setColor(Color.black); - g.drawString(String.valueOf(c), size, size * 2); - - // grabs copy of the current data.. so no updates (do each time) - Raster raster = playground.getData(); - raster.getSamples(0, 0, mbox3, mbox3, 0, samples); - - 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 = raster.getSample(x, y, 0); // maybe? - int sample = samples[y * mbox3 + x] & 0xff; - // or int samples[] = raster.getPixel(x, y, null); - - //if (sample == 0) { // or just not white? hmm - 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[index] = c; - height[index] = (maxY - minY) + 1; - width[index] = (maxX - minX) + 1; - setWidth[index] = metrics.charWidth(c); - //System.out.println((char)c + " " + setWidth[index]); - - // cache locations of the ascii charset - //if (value[i] < 128) ascii[value[i]] = i; - if (c < 128) ascii[c] = index; - - // offset from vertical location of baseline - // of where the char was drawn (size*2) - topExtent[index] = size*2 - minY; - - // offset from left of where coord was drawn - leftExtent[index] = minX - size; - - if (c == 'd') { - ascent = topExtent[index]; - } - if (c == 'p') { - descent = -topExtent[index] + height[index]; - } - - if (width[index] > maxWidthHeight) maxWidthHeight = width[index]; - if (height[index] > maxWidthHeight) maxWidthHeight = height[index]; - - bitmaps[index] = new PImage(width[index], height[index], ALPHA); - - for (int y = minY; y <= maxY; y++) { - for (int x = minX; x <= maxX; x++) { - int val = 255 - (samples[y * mbox3 + x] & 0xff); - int pindex = (y - minY) * width[index] + (x - minX); - bitmaps[index].pixels[pindex] = val; - } - } - index++; - } - charCount = index; - - // foreign font, so just make ascent the max topExtent - if ((ascent == 0) && (descent == 0)) { - for (int i = 0; i < charCount; i++) { - char cc = (char) value[i]; - if (Character.isWhitespace(cc) || - (cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) { - continue; - } - if (topExtent[i] > ascent) { - ascent = topExtent[i]; - } - int d = -topExtent[i] + height[i]; - if (d > descent) { - descent = d; - } - } - } - // size for image/texture is next power of 2 over largest char - mbox2 = (int) - Math.pow(2, Math.ceil(Math.log(maxWidthHeight) / Math.log(2))); - twidth = theight = mbox2; - - // shove the smaller PImage data into textures of next-power-of-2 size, - // so that this font can be used immediately by p5. - images = new PImage[charCount]; - for (int i = 0; i < charCount; i++) { - images[i] = new PImage(mbox2, mbox2, ALPHA); - for (int y = 0; y < height[i]; y++) { - System.arraycopy(bitmaps[i].pixels, y*width[i], - images[i].pixels, y*mbox2, - width[i]); - } - bitmaps[i] = null; - } - } - - /** * 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 @@ -688,24 +683,195 @@ public class PFont implements PConstants { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); fonts = ge.getAllFonts(); - } - } - - - /** - * Starting with Java 1.5, Apple broke the ability to specify most fonts. - * This has been filed as bug #4769141 at bugreporter.apple.com. More info at - * Bug 407. - */ - static public Font findFont(String name) { - loadFonts(); - if (PApplet.platform == PConstants.MACOSX) { - for (int i = 0; i < fonts.length; i++) { - if (name.equals(fonts[i].getName())) { - return fonts[i]; + 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/core/src/processing/core/PGraphics.java b/core/src/processing/core/PGraphics.java index 346b11cd1..9d50cdedd 100644 --- a/core/src/processing/core/PGraphics.java +++ b/core/src/processing/core/PGraphics.java @@ -29,6 +29,13 @@ 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

    @@ -106,6 +113,14 @@ import java.util.HashMap; * 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 { @@ -540,6 +555,7 @@ public class PGraphics extends PImage implements PConstants { * 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() { } @@ -627,20 +643,28 @@ public class PGraphics extends PImage implements PConstants { /** - * Prepares the PGraphics for drawing. + * 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 } /** - * This will finalize rendering so that it can be shown on-screen. + * 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 } @@ -673,8 +697,12 @@ public class PGraphics extends PImage implements PConstants { colorMode(RGB, 255); fill(255); stroke(0); - // other stroke attributes are set in the initializers - // inside the class (see above, strokeWeight = 1 et al) + + // 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; @@ -781,22 +809,22 @@ public class PGraphics extends PImage implements PConstants { // HINTS /** - * Enable a hint option. - *

    - * For the most part, hints are temporary api quirks, - * for which a proper api hasn't been properly worked out. - * for instance SMOOTH_IMAGES existed because smooth() - * wasn't yet implemented, but it will soon go away. - *

    - * They also exist for obscure features in the graphics - * engine, like enabling/disabling single pixel lines - * that ignore the zbuffer, the way they do in alphabot. - *

    - * Current hint options: - *

      - *
    • DISABLE_DEPTH_TEST - - * turns off the z-buffer in the P3D or OPENGL renderers. - *
    + * 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) { @@ -1394,6 +1422,26 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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); @@ -1409,6 +1457,32 @@ public class PGraphics extends PImage implements PConstants { } + + /** + * 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); @@ -1418,6 +1492,21 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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); @@ -1428,6 +1517,24 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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); @@ -1450,6 +1557,21 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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) { @@ -1498,11 +1620,42 @@ public class PGraphics extends PImage implements PConstants { // 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; @@ -1543,13 +1696,24 @@ public class PGraphics extends PImage implements PConstants { /** - * Identical parameters and placement to ellipse, - * but draws only an arc of that ellipse. - *

    - * start and stop are always radians because angleMode() was goofy. - * ellipseMode() sets the placement. - *

    - * also tries to be smart about start < stop. + * 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) { @@ -1577,7 +1741,7 @@ public class PGraphics extends PImage implements PConstants { 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; @@ -1610,18 +1774,33 @@ public class PGraphics extends PImage implements PConstants { // BOX + /** + * @param size dimension of the box in all dimensions, creates a cube + */ public void box(float size) { box(size, size, size); } - // TODO not the least bit efficient, it even redraws lines - // along the vertices. ugly ugly ugly! + /** + * 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 @@ -1676,17 +1855,44 @@ public class PGraphics extends PImage implements PConstants { // 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. * - * Code for sphereDetail() submitted by toxi [031031]. - * Code for enhanced u/v version from davbol [080801]. */ public void sphereDetail(int ures, int vres) { if (ures < 3) ures = 3; // force a minimum res @@ -1732,6 +1938,8 @@ public class PGraphics extends PImage implements PConstants { /** * 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: *

    @@ -1751,6 +1959,9 @@ public class PGraphics extends PImage implements PConstants { * * [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)) { @@ -1825,14 +2036,18 @@ public class PGraphics extends PImage implements PConstants { // 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. - * t varies between 0 and 1, and a and d are the on curve points, - * 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. - *

    + * 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);
    @@ -1852,6 +2067,17 @@ public class PGraphics extends PImage implements PConstants {
        *   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; @@ -1860,8 +2086,22 @@ public class PGraphics extends PImage implements PConstants { /** - * Provide the tangent at the given point on the bezier curve. - * Fix from davbol for 0136. + * 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) + @@ -1884,6 +2124,16 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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; @@ -1903,6 +2153,15 @@ public class PGraphics extends PImage implements PConstants { /** + * 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. @@ -1924,6 +2183,23 @@ public class PGraphics extends PImage implements PConstants { * 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, @@ -1956,9 +2232,22 @@ public class PGraphics extends PImage implements PConstants { /** - * Get a location along a catmull-rom curve segment. + * 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. * - * @param t Value between zero and one for how far along the segment + * @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(); @@ -1976,8 +2265,22 @@ public class PGraphics extends PImage implements PConstants { /** - * Calculate the tangent at a t value (0..1) on a Catmull-Rom curve. + * 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(); @@ -1994,12 +2297,41 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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(); @@ -2060,10 +2392,20 @@ public class PGraphics extends PImage implements PConstants { /** - * Draws a segment of Catmull-Rom curve. - *

    - * As of 0070, this function no longer doubles the first and - * last points. The curves are a bit more boring, but it's more + * 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:

    @@ -2074,6 +2416,24 @@ public class PGraphics extends PImage implements PConstants {
        * 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, @@ -2158,9 +2518,25 @@ public class PGraphics extends PImage implements PConstants { /** - * The mode can only be set to CORNERS, CORNER, and CENTER. - *

    - * Support for CENTER was added in release 0146. + * 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)) { @@ -2193,6 +2569,39 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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); } @@ -2200,7 +2609,7 @@ public class PGraphics extends PImage implements PConstants { /** * Draw an image(), also specifying u/v coordinates. - * In this method, the u, v coordinates are always based on image space + * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). */ public void image(PImage image, @@ -2310,8 +2719,24 @@ public class PGraphics extends PImage implements PConstants { /** - * Set the orientation for the shape() command (like imageMode() or rectMode()). - * @param mode Either CORNER, CORNERS, or CENTER. + * 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; @@ -2354,6 +2779,35 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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(); @@ -2415,7 +2869,7 @@ public class PGraphics extends PImage implements PConstants { */ public float textAscent() { if (textFont == null) { - showTextFontException("textAscent"); + defaultFontOrDeath("textAscent"); } return textFont.ascent() * ((textMode == SCREEN) ? textFont.size : textSize); } @@ -2428,7 +2882,7 @@ public class PGraphics extends PImage implements PConstants { */ public float textDescent() { if (textFont == null) { - showTextFontException("textDescent"); + defaultFontOrDeath("textDescent"); } return textFont.descent() * ((textMode == SCREEN) ? textFont.size : textSize); } @@ -2548,17 +3002,11 @@ public class PGraphics extends PImage implements PConstants { * Sets the text size, also resets the value for the leading. */ public void textSize(float size) { - if (textFont != null) { -// if ((textMode == SCREEN) && (size != textFont.size)) { -// throw new RuntimeException("textSize() is ignored with " + -// "textMode(SCREEN)"); -// } - textSize = size; - textLeading = (textAscent() + textDescent()) * 1.275f; - - } else { - showTextFontException("textSize"); + if (textFont == null) { + defaultFontOrDeath("textSize", size); } + textSize = size; + textLeading = (textAscent() + textDescent()) * 1.275f; } @@ -2577,7 +3025,7 @@ public class PGraphics extends PImage implements PConstants { */ public float textWidth(String str) { if (textFont == null) { - showTextFontException("textWidth"); + defaultFontOrDeath("textWidth"); } int length = str.length(); @@ -2604,14 +3052,14 @@ public class PGraphics extends PImage implements PConstants { } - /** + /** * 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. @@ -2646,7 +3094,7 @@ public class PGraphics extends PImage implements PConstants { */ public void text(char c, float x, float y) { if (textFont == null) { - showTextFontException("text"); + defaultFontOrDeath("text"); } if (textMode == SCREEN) loadPixels(); @@ -2702,7 +3150,7 @@ public class PGraphics extends PImage implements PConstants { */ public void text(String str, float x, float y) { if (textFont == null) { - showTextFontException("text"); + defaultFontOrDeath("text"); } if (textMode == SCREEN) loadPixels(); @@ -2717,9 +3165,9 @@ public class PGraphics extends PImage implements PConstants { /** - * 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. + * 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 @@ -2776,7 +3224,7 @@ public class PGraphics extends PImage implements PConstants { } - public void text(char[] chars, int start, int stop, + public void text(char[] chars, int start, int stop, float x, float y, float z) { if (z != 0) translate(0, 0, z); // slow! @@ -2785,8 +3233,8 @@ public class PGraphics extends PImage implements PConstants { 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 @@ -2802,7 +3250,7 @@ public class PGraphics extends PImage implements PConstants { */ public void text(String str, float x1, float y1, float x2, float y2) { if (textFont == null) { - showTextFontException("text"); + defaultFontOrDeath("text"); } if (textMode == SCREEN) loadPixels(); @@ -3080,35 +3528,32 @@ public class PGraphics extends PImage implements PConstants { protected void textCharImpl(char ch, float x, float y) { //, float z) { - int index = textFont.index(ch); - if (index == -1) return; + 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; - PImage glyph = textFont.images[index]; + float x1 = x + lextent * textSize; + float y1 = y - textent * textSize; + float x2 = x1 + bwidth * textSize; + float y2 = y1 + high * textSize; - if (textMode == MODEL) { - float high = (float) textFont.height[index] / textFont.fheight; - float bwidth = (float) textFont.width[index] / textFont.fwidth; - float lextent = (float) textFont.leftExtent[index] / textFont.fwidth; - float textent = (float) textFont.topExtent[index] / textFont.fheight; + textCharModelImpl(glyph.image, + x1, y1, x2, y2, + glyph.width, glyph.height); - float x1 = x + lextent * textSize; - float y1 = y - textent * textSize; - float x2 = x1 + bwidth * textSize; - float y2 = y1 + high * textSize; + } else if (textMode == SCREEN) { + int xx = (int) x + glyph.leftExtent; + int yy = (int) y - glyph.topExtent; - textCharModelImpl(glyph, - x1, y1, x2, y2, - //x1, y1, z, x2, y2, z, - textFont.width[index], textFont.height[index]); + int w0 = glyph.width; + int h0 = glyph.height; - } else if (textMode == SCREEN) { - int xx = (int) x + textFont.leftExtent[index];; - int yy = (int) y - textFont.topExtent[index]; - - int w0 = textFont.width[index]; - int h0 = textFont.height[index]; - - textCharScreenImpl(glyph, xx, yy, w0, h0); + textCharScreenImpl(glyph.image, xx, yy, w0, h0); + } } } @@ -3181,7 +3626,8 @@ public class PGraphics extends PImage implements PConstants { // 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 * 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)]; @@ -3801,6 +4247,14 @@ public class PGraphics extends PImage implements PConstants { // 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; } @@ -3809,33 +4263,25 @@ public class PGraphics extends PImage implements PConstants { /** * 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 (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above -// stroke((float) rgb); -// -// } else { -// colorCalcARGB(rgb, colorModeA); -// strokeFromCalc(); -// } colorCalc(rgb); strokeFromCalc(); } public void stroke(int rgb, float alpha) { -// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { -// stroke((float) rgb, alpha); -// -// } else { -// colorCalcARGB(rgb, alpha); -// strokeFromCalc(); -// } colorCalc(rgb, alpha); strokeFromCalc(); } + /** + * + * @param gray specifies a value between white and black + */ public void stroke(float gray) { colorCalc(gray); strokeFromCalc(); @@ -3854,6 +4300,28 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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(); @@ -3881,6 +4349,13 @@ public class PGraphics extends PImage implements PConstants { // 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; } @@ -3890,29 +4365,25 @@ public class PGraphics extends PImage implements PConstants { * Set the tint to either a grayscale or ARGB value. */ public void tint(int rgb) { -// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { -// tint((float) rgb); -// -// } else { -// colorCalcARGB(rgb, colorModeA); -// tintFromCalc(); -// } 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) { -// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { -// tint((float) rgb, alpha); -// -// } else { -// colorCalcARGB(rgb, alpha); -// tintFromCalc(); -// } colorCalc(rgb, alpha); tintFromCalc(); } + + /** + * @param gray any valid number + */ public void tint(float gray) { colorCalc(gray); tintFromCalc(); @@ -3931,6 +4402,35 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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(); @@ -3958,6 +4458,15 @@ public class PGraphics extends PImage implements PConstants { // 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; } @@ -3965,33 +4474,23 @@ public class PGraphics extends PImage implements PConstants { /** * 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 (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above -// fill((float) rgb); -// -// } else { -// colorCalcARGB(rgb, colorModeA); -// fillFromCalc(); -// } colorCalc(rgb); fillFromCalc(); } public void fill(int rgb, float alpha) { -// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above -// fill((float) rgb, alpha); -// -// } else { -// colorCalcARGB(rgb, alpha); -// fillFromCalc(); -// } colorCalc(rgb, alpha); fillFromCalc(); } + /** + * @param gray number specifying value between white and black + */ public void fill(float gray) { colorCalc(gray); fillFromCalc(); @@ -4010,6 +4509,24 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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(); @@ -4196,6 +4713,7 @@ public class PGraphics extends PImage implements PConstants { // BACKGROUND + /** * Set the background to a gray or ARGB color. *

    @@ -4206,6 +4724,8 @@ public class PGraphics extends PImage implements PConstants { * 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)) { @@ -4259,6 +4779,8 @@ public class PGraphics extends PImage implements PConstants { /** * 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) { @@ -4284,15 +4806,30 @@ public class PGraphics extends PImage implements PConstants { /** - * Clear the background with a color that includes an alpha value. This can + * 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 + * 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. + * 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) { @@ -4406,6 +4943,10 @@ public class PGraphics extends PImage implements PConstants { // 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); } @@ -4430,6 +4971,19 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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; @@ -4744,6 +5298,12 @@ public class PGraphics extends PImage implements PConstants { // 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; @@ -4751,6 +5311,19 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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; @@ -4758,6 +5331,19 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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; @@ -4765,6 +5351,18 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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; @@ -4772,6 +5370,18 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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, @@ -4782,6 +5392,18 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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, @@ -4792,6 +5414,19 @@ public class PGraphics extends PImage implements PConstants { } + /** + * 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, @@ -4811,7 +5446,15 @@ public class PGraphics extends PImage implements PConstants { /** - * Interpolate between two colors, using the current color mode. + * 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); @@ -5007,11 +5650,24 @@ public class PGraphics extends PImage implements PConstants { /** - * Throw an exeption that halts the program because textFont() has not been - * used prior to the specified method. + * Same as below, but defaults to a 12 point font, just as MacWrite intended. */ - static protected void showTextFontException(String method) { - throw new RuntimeException("Use textFont() before " + method + "()"); + 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 + "()"); + } } diff --git a/core/src/processing/core/PGraphics3D.java b/core/src/processing/core/PGraphics3D.java index 57dde4343..2a47d9547 100644 --- a/core/src/processing/core/PGraphics3D.java +++ b/core/src/processing/core/PGraphics3D.java @@ -52,9 +52,13 @@ public class PGraphics3D extends PGraphics { /** Inverse modelview matrix, used for lighting. */ public PMatrix3D modelviewInv; - /** - * The camera matrix, the modelview will be set to this on beginDraw. + /** + * 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 */ @@ -306,6 +310,9 @@ public class PGraphics3D extends PGraphics { * 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; @@ -357,13 +364,8 @@ public class PGraphics3D extends PGraphics { camera = new PMatrix3D(); cameraInv = new PMatrix3D(); - // 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(); + // set this flag so that beginDraw() will do an update to the camera. + sizeChanged = true; } @@ -409,6 +411,19 @@ public class PGraphics3D extends PGraphics { // 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 @@ -437,6 +452,7 @@ public class PGraphics3D extends PGraphics { shapeFirst = 0; // reset textures + Arrays.fill(textures, null); textureIndex = 0; normal(0, 0, 1); @@ -1350,7 +1366,10 @@ public class PGraphics3D extends PGraphics { boolean bClipped = false; int clippedCount = 0; -// cameraNear = -8; + // 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++; @@ -1364,15 +1383,15 @@ public class PGraphics3D extends PGraphics { clippedCount++; } if (clippedCount == 0) { -// if (vertices[a][VZ] < cameraFar && -// vertices[b][VZ] < cameraFar && +// 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 <| | diff --git a/core/src/processing/core/PGraphicsJava2D.java b/core/src/processing/core/PGraphicsJava2D.java index c45ae77ca..f72a566bb 100644 --- a/core/src/processing/core/PGraphicsJava2D.java +++ b/core/src/processing/core/PGraphicsJava2D.java @@ -967,6 +967,9 @@ public class PGraphicsJava2D extends PGraphics /*PGraphics2D*/ { public float textAscent() { + if (textFont == null) { + defaultFontOrDeath("textAscent"); + } Font font = textFont.getFont(); if (font == null) { return super.textAscent(); @@ -977,6 +980,9 @@ public class PGraphicsJava2D extends PGraphics /*PGraphics2D*/ { public float textDescent() { + if (textFont == null) { + defaultFontOrDeath("textAscent"); + } Font font = textFont.getFont(); if (font == null) { return super.textDescent(); @@ -1010,6 +1016,10 @@ public class PGraphicsJava2D extends PGraphics /*PGraphics2D*/ { * 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); diff --git a/core/src/processing/core/PImage.java b/core/src/processing/core/PImage.java index c1b38f095..c9fa24780 100644 --- a/core/src/processing/core/PImage.java +++ b/core/src/processing/core/PImage.java @@ -31,13 +31,31 @@ 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 { @@ -48,8 +66,32 @@ public class PImage implements PConstants, Cloneable { */ 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; - public int width, height; + + /** + * 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(). @@ -125,7 +167,12 @@ public class PImage implements PConstants, Cloneable { // toxi: agreed and same reasons why i left it out ;) } - + /** + * + * @param width image width + * @param height image height + * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel) + */ public PImage(int width, int height, int format) { init(width, height, format); } @@ -171,6 +218,8 @@ public class PImage implements PConstants, Cloneable { * Construct a new PImage from a java.awt.Image. This constructor assumes * that you've done the work of making sure a MediaTracker has been used * to fully download the data and that the img is valid. + * + * @param img assumes a MediaTracker has been used to fully download the data and the img is valid */ public PImage(java.awt.Image img) { if (img instanceof BufferedImage) { @@ -275,31 +324,39 @@ public class PImage implements PConstants, Cloneable { /** + * 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 } - - /** - * Call this when finished messing with the pixels[] array. - *

    - * Mark all pixels as needing update. - */ 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 @@ -369,8 +426,14 @@ public class PImage implements PConstants, Cloneable { /** - * Resize this image to a new width and height. - * Use 0 for wide or high to make that dimension scale proportionally. + * 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 @@ -442,8 +505,20 @@ public class PImage implements PConstants, Cloneable { /** - * Grab a subsection of a PImage, and copy it into a fresh PImage. - * As of release 0149, no longer honors imageMode() for the coordinates. + * 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) { /* @@ -512,7 +587,17 @@ public class PImage implements PConstants, Cloneable { /** - * Set a single pixel to the specified color. + * 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; @@ -594,18 +679,20 @@ public class PImage implements PConstants, Cloneable { * 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" grayscake by + * 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 alpha[]) { + public void mask(int maskArray[]) { loadPixels(); // don't execute if mask image is different size - if (alpha.length != pixels.length) { + 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] = ((alpha[i] & 0xff) << 24) | (pixels[i] & 0xffffff); + pixels[i] = ((maskArray[i] & 0xff) << 24) | (pixels[i] & 0xffffff); } format = ARGB; updatePixels(); @@ -613,10 +700,19 @@ public class PImage implements PConstants, Cloneable { /** - * Set alpha channel for an image using another image as the source. + * 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 alpha) { - mask(alpha.pixels); + public void mask(PImage maskImg) { + maskImg.loadPixels(); + mask(maskImg.pixels); } @@ -624,26 +720,6 @@ public class PImage implements PConstants, Cloneable { ////////////////////////////////////////////////////////////// // IMAGE FILTERS - - - /** - * 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 - */ public void filter(int kind) { loadPixels(); @@ -716,20 +792,29 @@ public class PImage implements PConstants, Cloneable { /** + * 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. - * These filters all take a parameter. *

    *

      - *
    • filter(BLUR, int radius) performs a gaussian blur of the - * specified radius. - *
    • filter(POSTERIZE, int levels) will posterize the image to - * between 2 and 255 levels. - *
    • filter(THRESHOLD, float center) allows you to set the - * center point for the threshold. It takes a value from 0 to 1.0. + *
    • 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 - * and later updated by toxi for better speed. + * + * @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(); @@ -1093,7 +1178,7 @@ public class PImage implements PConstants, Cloneable { if (idxRight>=maxRowIdx) idxRight=currIdx; if (idxUp<0) - idxUp=0; + idxUp=currIdx; if (idxDown>=maxIdx) idxDown=currIdx; @@ -1150,7 +1235,7 @@ public class PImage implements PConstants, Cloneable { if (idxRight>=maxRowIdx) idxRight=currIdx; if (idxUp<0) - idxUp=0; + idxUp=currIdx; if (idxDown>=maxIdx) idxDown=currIdx; @@ -1212,7 +1297,23 @@ public class PImage implements PConstants, Cloneable { /** - * Copies area of one image into another PImage object. + * 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, @@ -1321,6 +1422,7 @@ public class PImage implements PConstants, Cloneable { /** * 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, @@ -1330,7 +1432,39 @@ public class PImage implements PConstants, Cloneable { /** - * Copies area of one image into another PImage object. + * 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, @@ -2628,6 +2762,16 @@ public class PImage implements PConstants, Cloneable { 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, @@ -2651,15 +2795,19 @@ public class PImage implements PConstants, Cloneable { * 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 path) { // ignore + public void save(String filename) { // ignore boolean success = false; - File file = new File(path); + File file = new File(filename); if (!file.isAbsolute()) { if (parent != null) { //file = new File(parent.savePath(filename)); - path = parent.savePath(path); + filename = parent.savePath(filename); } else { String msg = "PImage.save() requires an absolute path. " + "Use createImage(), or pass savePath() to save()."; @@ -2678,24 +2826,24 @@ public class PImage implements PConstants, Cloneable { } if (saveImageFormats != null) { for (int i = 0; i < saveImageFormats.length; i++) { - if (path.endsWith("." + saveImageFormats[i])) { - saveImageIO(path); + if (filename.endsWith("." + saveImageFormats[i])) { + saveImageIO(filename); return; } } } - if (path.toLowerCase().endsWith(".tga")) { - os = new BufferedOutputStream(new FileOutputStream(path), 32768); + if (filename.toLowerCase().endsWith(".tga")) { + os = new BufferedOutputStream(new FileOutputStream(filename), 32768); success = saveTGA(os); //, pixels, width, height, format); } else { - if (!path.toLowerCase().endsWith(".tif") && - !path.toLowerCase().endsWith(".tiff")) { + if (!filename.toLowerCase().endsWith(".tif") && + !filename.toLowerCase().endsWith(".tiff")) { // if no .tif extension, add it.. - path += ".tif"; + filename += ".tif"; } - os = new BufferedOutputStream(new FileOutputStream(path), 32768); + os = new BufferedOutputStream(new FileOutputStream(filename), 32768); success = saveTIFF(os); //, pixels, width, height); } os.flush(); diff --git a/core/src/processing/core/PPolygon.java b/core/src/processing/core/PPolygon.java index 2a20b7c78..0651fbe2d 100644 --- a/core/src/processing/core/PPolygon.java +++ b/core/src/processing/core/PPolygon.java @@ -419,7 +419,7 @@ public class PPolygon implements PConstants { int tr, tg, tb, ta; // System.out.println("P2D interp uv " + interpUV + " " + -// vertices[2][U] + " " + vertices[2][V]); +// 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) { diff --git a/core/src/processing/core/PShape.java b/core/src/processing/core/PShape.java index cf2274480..a1a5fb99e 100644 --- a/core/src/processing/core/PShape.java +++ b/core/src/processing/core/PShape.java @@ -25,8 +25,17 @@ 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: @@ -51,6 +60,13 @@ import java.util.HashMap; *

    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 { @@ -81,7 +97,17 @@ public class PShape implements PConstants { //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 @@ -178,21 +204,39 @@ public class PShape implements PConstants { 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; @@ -204,7 +248,9 @@ public class PShape implements PConstants { /** - * Re-enables style information (fill and stroke) set in the shape. + * 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; @@ -591,12 +637,21 @@ public class PShape implements PConstants { 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; @@ -675,34 +730,78 @@ public class PShape implements PConstants { // 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); @@ -716,20 +815,34 @@ public class PShape implements PConstants { // - - + + /** + * @param s percentage to scale the object + */ public void scale(float s) { checkMatrix(2); // at least 2... matrix.scale(s); } - public void scale(float sx, float sy) { + public void scale(float x, float y) { checkMatrix(2); - matrix.scale(sx, sy); + 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); diff --git a/core/src/processing/core/PShapeSVG.java b/core/src/processing/core/PShapeSVG.java index db1bd9e88..0bbf2c51a 100644 --- a/core/src/processing/core/PShapeSVG.java +++ b/core/src/processing/core/PShapeSVG.java @@ -457,7 +457,11 @@ public class PShapeSVG extends PShape { separate = false; } if (c == '-' && !lastSeparate) { - pathBuffer.append("|"); + // 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)); diff --git a/core/src/processing/core/PVector.java b/core/src/processing/core/PVector.java index 91be2f52b..1fb4f1f76 100644 --- a/core/src/processing/core/PVector.java +++ b/core/src/processing/core/PVector.java @@ -428,8 +428,8 @@ public class PVector { 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; } diff --git a/core/src/processing/xml/XMLElement.java b/core/src/processing/xml/XMLElement.java index 873828996..1f1b28d9c 100644 --- a/core/src/processing/xml/XMLElement.java +++ b/core/src/processing/xml/XMLElement.java @@ -31,6 +31,10 @@ 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. * @@ -38,6 +42,10 @@ import processing.core.PApplet; * * @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 { @@ -103,6 +111,7 @@ public class XMLElement implements Serializable { /** * Creates an empty element to be used for #PCDATA content. + * @nowebref */ public XMLElement() { this(null, null, null, NO_LINE); @@ -173,6 +182,7 @@ public class XMLElement implements Serializable { * @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, @@ -204,21 +214,25 @@ public class XMLElement implements Serializable { * wraps exception handling, for more advanced exception handling, * use the constructor that takes a Reader or InputStream. * @author processing.org - * @param filename - * @param parent + * @param filename name of the XML file to load + * @param parent typically use "this" */ public XMLElement(PApplet parent, String filename) { this(); parseFromReader(parent.createReader(filename)); } - + /** + * @nowebref + */ public XMLElement(Reader r) { this(); parseFromReader(r); } - + /** + * @nowebref + */ public XMLElement(String xml) { this(); parseFromReader(new StringReader(xml)); @@ -348,6 +362,8 @@ public class XMLElement implements Serializable { * 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() { @@ -507,9 +523,12 @@ public class XMLElement implements Serializable { /** - * Returns the number of children. + * 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(); @@ -554,27 +573,35 @@ public class XMLElement implements Serializable { /** * Quick accessor for an element at a particular index. * @author processing.org + * @param index the element */ - public XMLElement getChild(int which) { - return (XMLElement) children.elementAt(which); + public XMLElement getChild(int index) { + return (XMLElement) children.elementAt(index); } /** - * Get a child by its name or path. - * @param name element name or path/to/element + * 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 name) { - if (name.indexOf('/') != -1) { - return getChildRecursive(PApplet.split(name, '/'), 0); + 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(name)) { + if (kidName != null && kidName.equals(path)) { return kid; } } @@ -681,20 +708,27 @@ public class XMLElement implements Serializable { /** - * Get any children that match this name or path. Similar to getChild(), - * but will grab multiple matches rather than only the first. - * @param name element name or path/to/element + * 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 name) { - if (name.indexOf('/') != -1) { - return getChildrenRecursive(PApplet.split(name, '/'), 0); + 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(name.charAt(0))) { - return new XMLElement[] { getChild(Integer.parseInt(name)) }; + if (Character.isDigit(path.charAt(0))) { + return new XMLElement[] { getChild(Integer.parseInt(path)) }; } int childCount = getChildCount(); XMLElement[] matches = new XMLElement[childCount]; @@ -702,7 +736,7 @@ public class XMLElement implements Serializable { for (int i = 0; i < childCount; i++) { XMLElement kid = getChild(i); String kidName = kid.getName(); - if (kidName != null && kidName.equals(name)) { + if (kidName != null && kidName.equals(path)) { matches[matchCount++] = kid; } } @@ -882,12 +916,22 @@ public class XMLElement implements Serializable { } } - + public String getStringAttribute(String name) { return getAttribute(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. + */ public String getStringAttribute(String name, String defaultValue) { return getAttribute(name, defaultValue); } @@ -899,18 +943,24 @@ public class XMLElement implements Serializable { return getAttribute(name, namespace, defaultValue); } - + /** + * Returns an integer attribute of the element. + */ public int getIntAttribute(String name) { return getIntAttribute(name, 0); } /** - * Returns the value of an attribute. + * 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 non-null full name of the attribute. - * @param defaultValue the default value of the attribute. + * @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 getIntAttribute(String name, @@ -944,12 +994,17 @@ public class XMLElement implements Serializable { /** - * Returns the value of an attribute. + * 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 non-null full name of the attribute. - * @param defaultValue the default value of the attribute. + * @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 getFloatAttribute(String name, float defaultValue) { @@ -966,6 +1021,7 @@ public class XMLElement implements Serializable { * @param defaultValue the default value of the attribute. * * @return the value, or defaultValue if the attribute does not exist. + * @nowebref */ public float getFloatAttribute(String name, String namespace, @@ -1253,11 +1309,15 @@ public class XMLElement implements Serializable { /** + * 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() { diff --git a/core/todo.txt b/core/todo.txt index cf4488272..6b6ce087f 100644 --- a/core/todo.txt +++ b/core/todo.txt @@ -1,10 +1,85 @@ -0171 core -X Blurred PImages in OPENGL sketches -X removed NPOT texture support (for further testing) -X http://dev.processing.org/bugs/show_bug.cgi?id=1352 +0179 core +X screenWidth/Height instead of screenW/H +X open up the pdf library more (philho) +X http://dev.processing.org/bugs/show_bug.cgi?id=1343 +X cache font information for the PDF library to improve setup time +X when using createFont("xxxx.ttf"), should use textMode(SHAPE) with PDF +X because ttf files will not be installed on the system when opening pdf +X added error messages for users +X bring back old-style textAscent() +X needs to just quickly run characters d and p +X only takes a couple ms, so no problem +X pdf library +X throw an error with the black boxes +X throw an error if loading fonts from a file, and not using mode(SHAPE) +X implement default font +X this can be done to replace the exception handler in PGraphics +o however it needs to be a legit font, so that it works w/ pdf +o or maybe pdf just has its own default? +X create characters on the fly when createFont() is used +o memory leak problem with fonts in JAVA2D +X can't get this to crash anymore +o http://dev.processing.org/bugs/show_bug.cgi?id=1252 + +earlier +X if no draw() method, and renderer is not displayable, then exit +X static mode PDFs shouldn't just hang + + +big ones +_ ortho() behaving differently in P3D vs OPENGL +_ http://dev.processing.org/bugs/show_bug.cgi?id=100 +_ shows a blank canvas +_ (was only happening once b/c was drawing first in perspective) +_ seems to be mapping to 0, 0 - width/2, height/2 +_ fix 3D > OrthoVsPerspective example once ortho works properly +_ there's a depth problem in addition to the ortho weirdness +_ modelx/y/z broken when aiming a camera +_ http://dev.processing.org/bugs/show_bug.cgi?id=1074 +_ opengl + resize window => window content garbled +_ http://dev.processing.org/bugs/show_bug.cgi?id=1360 +_ modify PVector to include better methods for chaining operations +_ http://dev.processing.org/bugs/show_bug.cgi?id=1415 + +quickies +_ img.get() weirdness +_ http://dev.processing.org/bugs/show_bug.cgi?id=1198 +_ copy and blend scale when unnecessary +_ http://dev.processing.org/bugs/show_bug.cgi?id=1482 +_ add a limit to pushStyle() to catch unmatched sets? +_ http://dev.processing.org/bugs/show_bug.cgi?id=1368 +_ P2D transformation bug from ira +_ http://dev.processing.org/bugs/show_bug.cgi?id=1175 +_ resize not working in revision 5707 +_ camera() and perspective() were commented out in setSize() +_ http://dev.processing.org/bugs/show_bug.cgi?id=1391 +_ chopping out triangles in OpenGL (though it's only 2D drawing) +_ http://dev.processing.org/bugs/show_bug.cgi?id=1359 +_ make sure that get() and set() (for pixels and subsets) work w/ loaded images +_ make sure that get() and set() (for pixels and subsets) work w/ P2D +_ make sure that get() and set() (for pixels and subsets) work w/ P3D +_ consider adding skewX/Y +_ do them as shearX/Y +_ http://dev.processing.org/bugs/show_bug.cgi?id=1448 + +_ add setOutput() method across other renderers? + +_ opengl applet problems +_ http://dev.processing.org/bugs/show_bug.cgi?id=1364 + +_ method of threading but queue an event to be run when safe +_ e.g. queueing items like mouse/keybd, but generic fxns + +_ inconsistent anti-aliasing with OpenGL +_ http://dev.processing.org/bugs/show_bug.cgi?id=1413 +_ modify PVector to include better methods for chaining operations +_ http://dev.processing.org/bugs/show_bug.cgi?id=1415 + +_ selectInput() fails when called from within keyPressed() +_ http://dev.processing.org/bugs/show_bug.cgi?id=1220 + +_ add java.io.Reader (and Writer?) to imports -_ open up the pdf library more (philho) -_ http://dev.processing.org/bugs/show_bug.cgi?id=1343 _ changing vertex alpha in P3D in a QUAD_STRIP is ignored _ with smoothing, it works fine, but with PTriangle, it's not _ smooth() not working with applets an createGraphics(JAVA2D) @@ -12,6 +87,9 @@ _ but works fine with applications _ get() with OPENGL is grabbing the wrong coords _ http://dev.processing.org/bugs/show_bug.cgi?id=1349 +_ gl power of 2 with textures +_ P3D also seems to have trouble w/ textures edges.. bad math? + _ No textures render with hint(ENABLE_ACCURATE_TEXTURES) _ http://dev.processing.org/bugs/show_bug.cgi?id=985 _ need to remove the hint from the reference @@ -20,11 +98,14 @@ _ deal with issue of single pixel seam at the edge of textures _ http://dev.processing.org/bugs/show_bug.cgi?id=602 _ should vertexTexture() divide by width/height or width-1/height-1? +looping/events _ key and mouse events delivered out of order _ http://dev.processing.org/bugs/show_bug.cgi?id=638 _ key/mouse events have concurrency problems with noLoop() _ http://dev.processing.org/bugs/show_bug.cgi?id=1323 _ need to say "no drawing inside mouse/key events w/ noLoop" +_ redraw() doesn't work from within draw() +_ http://dev.processing.org/bugs/show_bug.cgi?id=1363 _ make the index lookup use numbers up to 256? @@ -34,8 +115,6 @@ _ public float textWidth(char[] chars, int start, int length) _ textAlign(JUSTIFY) (with implementation) _ http://dev.processing.org/bugs/show_bug.cgi?id=1309 -_ create characters on the fly when createFont() is used - _ Semitransparent rect drawn over image not rendered correctly _ http://dev.processing.org/bugs/show_bug.cgi?id=1280 @@ -49,8 +128,6 @@ _ http://dev.processing.org/bugs/show_bug.cgi?id=1176 _ what's the difference with ascent on loadFont vs. createFont? _ noCursor() doesn't work in present mode _ http://dev.processing.org/bugs/show_bug.cgi?id=1177 -_ modelx/y/z broken when aiming a camera -_ http://dev.processing.org/bugs/show_bug.cgi?id=1074 _ in P2D, two vertex() line calls with fill() causes duplicate output _ works fine in other renderers, has to do with tesselation _ http://dev.processing.org/bugs/show_bug.cgi?id=1191 @@ -67,14 +144,10 @@ _ what other methods should work with doubles? all math functions? _ seems like internal (mostly static) things, but not graphics api _ look into replacing nanoxml _ http://www.exampledepot.com/egs/javax.xml.parsers/pkg.html -_ if no draw() method, and renderer is not displayable, then exit -_ static mode PDFs shouldn't just hang [ known problems ] -_ memory leak problem with fonts in JAVA2D -_ http://dev.processing.org/bugs/show_bug.cgi?id=1252 _ OPENGL sketches flicker w/ Vista when background() not used inside draw() _ http://dev.processing.org/bugs/show_bug.cgi?id=930 _ Disabling Aero scheme sometimes prevents the problem @@ -142,16 +215,11 @@ _ make sure that filter, blend, copy, etc say that no loadPixels necessary rework some text/font code [1.0] -_ PFont not working well with lots of characters -_ only create bitmap chars on the fly when needed (in createFont) _ text placement is ugly, seems like fractional metrics problem _ http://dev.processing.org/bugs/show_bug.cgi?id=866 _ text(char c) with char 0 and undefined should print nothing _ perhaps also DEL or other nonprintables? _ book example 25-03 -_ when using createFont("xxxx.ttf"), should use textMode(SHAPE) with PDF -_ because ttf files will not be installed on the system when opening pdf -_ maybe just add this to the reference so that people know _ text position is quantized in JAVA2D _ http://dev.processing.org/bugs/show_bug.cgi?id=806 _ accessors inside PFont need a lot of work @@ -159,8 +227,6 @@ _ osx 10.5 (not 10.4) performing text width calculation differently _ http://dev.processing.org/bugs/show_bug.cgi?id=972 _ Automatically use textMode(SCREEN) with text() when possible _ http://dev.processing.org/bugs/show_bug.cgi?id=1020 -_ Implement better caching mechanism when creating large fonts -_ http://dev.processing.org/bugs/show_bug.cgi?id=1111 P2D, P3D, PPolygon [1.0] @@ -200,19 +266,12 @@ _ also needs fix for last edge and the seam threading and exiting -_ pdf sketches exiting before writing has finished _ writing image file (missing a flush() call?) on exit() fails _ lots of zero length files _ saveFrame() at the end of a draw mode program is problematic _ app might exit before the file has finished writing to disk _ need to block other activity inside screenGrab until finished _ http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1081706752 -_ what's up with stop() vs exit()? -_ need to get this straightened for p5 (i.e. bc has this problem) -_ make sure the main() doesn't exit until the applet has finished -_ i.e. problem with main calling itself multiple times in Alpheus -_ if exit() (or stop) is called, then System.exit() gets called, -_ even though the main() wants to keep going _ for begin/endRecord, use a piggyback mechanism _ that way won't have to pass a PApplet around @@ -220,24 +279,32 @@ _ this has a big impact on the SVG library _ in fact, this maybe should be a library that does it _ so that the file size can be much smaller -_ when closing a sketch via the close box, make sure stop() getting called -X found a problem for release 0133 -_ test to see if it's working - _ STROKE_WEIGHT field in PGraphics3 is a disaster, because it's an int _ use the SW from vertex instead.. why set stroke in triangle vars at all? _ currently truncating to an int inside add_line_no_clip _ need to clean all this crap up +stop() mess +_ double stop() called with noLoop() +_ http://dev.processing.org/bugs/show_bug.cgi?id=1270 _ stop() not getting called _ http://dev.processing.org/bugs/show_bug.cgi?id=183 _ major problem for libraries _ and start() is supposedly called by the applet viewer _ http://java.sun.com/j2se/1.4.2/docs/api/java/applet/Applet.html#start() _ need to track this stuff down a bit +_ when closing a sketch via the close box, make sure stop() getting called +X found a problem for release 0133 +_ test to see if it's working +_ what's up with stop() vs exit()? +_ need to get this straightened for p5 (i.e. bc has this problem) +_ make sure the main() doesn't exit until the applet has finished +_ i.e. problem with main calling itself multiple times in Alpheus +_ if exit() (or stop) is called, then System.exit() gets called, +_ even though the main() wants to keep going +_ more chatter with this +_ http://dev.processing.org/bugs/show_bug.cgi?id=131 -_ method of threading but queue an event to be run when safe -_ e.g. queueing items like mouse/keybd, but generic fxns //////////////////////////////////////////////////////////////////// @@ -280,6 +347,8 @@ _ don't bother using a buffering stream, just handle internally. gah! _ remove some of the bloat, how can we make things more compact? _ i.e. if not using 3D, can leave out PGraphics3, PTriangle, PLine _ http://dev.processing.org/bugs/show_bug.cgi?id=127 +E4 _ add shuffle methods for arrays +E4 _ http://dev.processing.org/bugs/show_bug.cgi?id=1462 CORE / PApplet - main() @@ -309,7 +378,8 @@ _ or if the sketch window is foremost _ maybe a hack where a new menubar is added? _ --display not working on osx _ http://dev.processing.org/bugs/show_bug.cgi?id=531 - +_ "Target VM failed to initialize" when using Present mode on Mac OS X +_ http://dev.processing.org/bugs/show_bug.cgi?id=1257 CORE / PFont and text() @@ -412,13 +482,6 @@ CORE / PGraphics3D _ make thick lines draw perpendicular to the screen with P3D _ http://dev.processing.org/bugs/show_bug.cgi?id=956 _ ewjordan suggests building the quad in screen coords after perspective -_ ortho() behaving differently in P3D vs OPENGL -_ http://dev.processing.org/bugs/show_bug.cgi?id=100 -_ shows a blank canvas -_ (was only happening once b/c was drawing first in perspective) -_ seems to be mapping to 0, 0 - width/2, height/2 -_ fix 3D > OrthoVsPerspective example once ortho works properly -_ there's a depth problem in addition to the ortho weirdness _ improve hint(ENABLE_DEPTH_SORT) to use proper painter's algo _ http://dev.processing.org/bugs/show_bug.cgi?id=176 _ polygon z-order depth sorting with alpha in opengl @@ -433,11 +496,9 @@ _ images are losing pixels at the edges _ http://dev.processing.org/bugs/show_bug.cgi?id=102 _ odd error with some pixels from images not drawing properly _ http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1115681453 -_ clipping not yet completely implemented +_ clipping not implemented +_ http://dev.processing.org/bugs/show_bug.cgi?id=1393 _ http://processing.org/discourse/yabb_beta/YaBB.cgi?board=SoftwareBugs;action=display;num=1114184516 -_ Stroking a rect() leaves off the upper right pixel -_ http://dev.processing.org/bugs/show_bug.cgi?id=501 -_ clipping planes _ http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1058491568;start=0 _ http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_software_bugs;action=display;num=1052313604;start=0 _ http://processing.org/discourse/yabb/YaBB.cgi?board=Proce55ing_Software;action=display;num=1095170607;start=0 @@ -449,6 +510,8 @@ _ or at least that things get ridiculously slow _ clipping issues here.. but also something in scan converter _ not clipping areas from offscreen _ huge geometry slows things way down +_ Stroking a rect() leaves off the upper right pixel +_ http://dev.processing.org/bugs/show_bug.cgi?id=501 _ box is not opaque _ problem is that lines are drawn second _ one pixel lines have no z value.. argh @@ -462,6 +525,8 @@ _ box(40); CORE / PImage +_ accuracy problems make alpha channel go to FE with image.copy() +_ http://dev.processing.org/bugs/show_bug.cgi?id=1420 _ improve blend() accuracy when using ADD _ http://dev.processing.org/bugs/show_bug.cgi?id=1008 _ includes code for a slow but more accurate mode @@ -603,6 +668,10 @@ LIBRARIES / PGraphicsPDF _ pdf not rendering unicode with beginRecord() _ http://dev.processing.org/bugs/show_bug.cgi?id=727 +_ pdf sketches exiting before writing has finished +_ people have to call exit() (so that dispose() is called in particular) +_ when using noLoop() and the PDF renderer, sketch should exit gracefully +_ because isDisplayable() returns false, there's no coming back from noLoop @@ -710,3 +779,4 @@ _ exactly how should pixel filling work with single pixel strokes? _ http://dev.processing.org/bugs/show_bug.cgi?id=1025 _ Writing XML files (clean up the API) _ http://dev.processing.org/bugs/show_bug.cgi?id=964 +_ consider bringing back text/image using cache/names