From 85fe852c25d1079504b4d0a997afb56e6bce7dc4 Mon Sep 17 00:00:00 2001
From: JD Hsu
Date: Thu, 30 Apr 2020 13:04:25 -0700
Subject: [PATCH 01/39] Migrated to androidx, Android R preview
---
core/build.gradle | 2 +-
core/src/processing/android/PFragment.java | 14 ++++++++------
.../processing/android/PermissionRequestor.java | 2 +-
core/src/processing/core/PApplet.java | 2 +-
core/src/processing/core/PSurfaceNone.java | 9 +++++----
gradle.properties | 2 ++
gradle/wrapper/gradle-wrapper.properties | 3 ++-
7 files changed, 20 insertions(+), 14 deletions(-)
create mode 100644 gradle.properties
diff --git a/core/build.gradle b/core/build.gradle
index 002621c9a..b45fede08 100644
--- a/core/build.gradle
+++ b/core/build.gradle
@@ -7,7 +7,7 @@ apply plugin: 'aar'
dependencies {
implementation name: "android"
- implementationAar "com.android.support:support-v4:${supportLibsVersion}"
+ implementationAar 'androidx.legacy:legacy-support-v4:1.0.0'
implementationAar "com.google.android.support:wearable:${wearVersion}"
}
diff --git a/core/src/processing/android/PFragment.java b/core/src/processing/android/PFragment.java
index 1a2132ed3..859580dfd 100644
--- a/core/src/processing/android/PFragment.java
+++ b/core/src/processing/android/PFragment.java
@@ -22,12 +22,14 @@
package processing.android;
-import android.support.annotation.IdRes;
-import android.support.annotation.LayoutRes;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentManager;
-import android.support.v4.app.FragmentTransaction;
+
+import androidx.annotation.IdRes;
+import androidx.annotation.LayoutRes;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentTransaction;
+
import android.util.DisplayMetrics;
import android.content.Intent;
import android.content.pm.ActivityInfo;
diff --git a/core/src/processing/android/PermissionRequestor.java b/core/src/processing/android/PermissionRequestor.java
index 93c939238..fb8d59443 100644
--- a/core/src/processing/android/PermissionRequestor.java
+++ b/core/src/processing/android/PermissionRequestor.java
@@ -24,7 +24,7 @@
import android.app.Activity;
import android.os.Bundle;
-import android.support.v4.app.ActivityCompat;
+import androidx.core.app.ActivityCompat;
import android.support.v4.os.ResultReceiver;
// A simple utility activity to request permissions in a service.
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java
index 24e5dd3a7..8c0651e2c 100644
--- a/core/src/processing/core/PApplet.java
+++ b/core/src/processing/core/PApplet.java
@@ -45,7 +45,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
-import android.support.annotation.LayoutRes;
+import androidx.annotation.LayoutRes;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
diff --git a/core/src/processing/core/PSurfaceNone.java b/core/src/processing/core/PSurfaceNone.java
index cd350b873..901848ca4 100644
--- a/core/src/processing/core/PSurfaceNone.java
+++ b/core/src/processing/core/PSurfaceNone.java
@@ -33,8 +33,8 @@
import android.os.Handler;
import android.os.Looper;
import android.service.wallpaper.WallpaperService;
-import android.support.v4.app.ActivityCompat;
-import android.support.v4.content.ContextCompat;
+import androidx.core.app.ActivityCompat;
+import androidx.core.content.ContextCompat;
import android.support.wearable.watchface.WatchFaceService;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
@@ -89,14 +89,15 @@ public AppComponent getComponent() {
@Override
public Context getContext() {
- if (component.getKind() == AppComponent.FRAGMENT) {
+ return activity;
+ /*if (component.getKind() == AppComponent.FRAGMENT) {
return activity;
} else if (component.getKind() == AppComponent.WALLPAPER) {
return wallpaper;
} else if (component.getKind() == AppComponent.WATCHFACE) {
return watchface;
}
- return null;
+ */
}
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 000000000..5465fec0e
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,2 @@
+android.enableJetifier=true
+android.useAndroidX=true
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 2c2bbe5f9..f68335fce 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,6 @@
+#Thu Apr 30 13:02:23 PDT 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.4.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-all.zip
From 8de9a4c9a319b4c9eff13040364ee5036a553be9 Mon Sep 17 00:00:00 2001
From: Rupesh Kumar <46577873+rupesh-kumar-lpu@users.noreply.github.com>
Date: Thu, 24 Dec 2020 05:57:33 +0530
Subject: [PATCH 02/39] Added core-androidx source assets
---
.../src/assets/shaders/ColorFrag.glsl | 32 ++++
.../src/assets/shaders/ColorVert.glsl | 34 ++++
.../src/assets/shaders/LightFrag.glsl | 33 ++++
.../src/assets/shaders/LightVert.glsl | 151 +++++++++++++++++
.../src/assets/shaders/LineFrag.glsl | 32 ++++
.../src/assets/shaders/LineVert.glsl | 99 +++++++++++
.../src/assets/shaders/MaskFrag.glsl | 40 +++++
core-androidx/src/assets/shaders/P2DFrag.glsl | 14 ++
core-androidx/src/assets/shaders/P2DVert.glsl | 23 +++
.../src/assets/shaders/PointFrag.glsl | 32 ++++
.../src/assets/shaders/PointVert.glsl | 56 +++++++
core-androidx/src/assets/shaders/TexFrag.glsl | 37 +++++
.../src/assets/shaders/TexLightFrag.glsl | 37 +++++
.../src/assets/shaders/TexLightVert.glsl | 157 ++++++++++++++++++
core-androidx/src/assets/shaders/TexVert.glsl | 38 +++++
15 files changed, 815 insertions(+)
create mode 100644 core-androidx/src/assets/shaders/ColorFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/ColorVert.glsl
create mode 100644 core-androidx/src/assets/shaders/LightFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/LightVert.glsl
create mode 100644 core-androidx/src/assets/shaders/LineFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/LineVert.glsl
create mode 100644 core-androidx/src/assets/shaders/MaskFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/P2DFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/P2DVert.glsl
create mode 100644 core-androidx/src/assets/shaders/PointFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/PointVert.glsl
create mode 100644 core-androidx/src/assets/shaders/TexFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/TexLightFrag.glsl
create mode 100644 core-androidx/src/assets/shaders/TexLightVert.glsl
create mode 100644 core-androidx/src/assets/shaders/TexVert.glsl
diff --git a/core-androidx/src/assets/shaders/ColorFrag.glsl b/core-androidx/src/assets/shaders/ColorFrag.glsl
new file mode 100644
index 000000000..5f86d92b4
--- /dev/null
+++ b/core-androidx/src/assets/shaders/ColorFrag.glsl
@@ -0,0 +1,32 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+varying vec4 vertColor;
+
+void main() {
+ gl_FragColor = vertColor;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/ColorVert.glsl b/core-androidx/src/assets/shaders/ColorVert.glsl
new file mode 100644
index 000000000..65fd55716
--- /dev/null
+++ b/core-androidx/src/assets/shaders/ColorVert.glsl
@@ -0,0 +1,34 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+uniform mat4 transformMatrix;
+
+attribute vec4 position;
+attribute vec4 color;
+
+varying vec4 vertColor;
+
+void main() {
+ gl_Position = transformMatrix * position;
+
+ vertColor = color;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/LightFrag.glsl b/core-androidx/src/assets/shaders/LightFrag.glsl
new file mode 100644
index 000000000..6b60d4039
--- /dev/null
+++ b/core-androidx/src/assets/shaders/LightFrag.glsl
@@ -0,0 +1,33 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+varying vec4 vertColor;
+varying vec4 backVertColor;
+
+void main() {
+ gl_FragColor = gl_FrontFacing ? vertColor : backVertColor;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/LightVert.glsl b/core-androidx/src/assets/shaders/LightVert.glsl
new file mode 100644
index 000000000..adc4bf9ad
--- /dev/null
+++ b/core-androidx/src/assets/shaders/LightVert.glsl
@@ -0,0 +1,151 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+uniform mat4 modelviewMatrix;
+uniform mat4 transformMatrix;
+uniform mat3 normalMatrix;
+
+uniform int lightCount;
+uniform vec4 lightPosition[8];
+uniform vec3 lightNormal[8];
+uniform vec3 lightAmbient[8];
+uniform vec3 lightDiffuse[8];
+uniform vec3 lightSpecular[8];
+uniform vec3 lightFalloff[8];
+uniform vec2 lightSpot[8];
+
+attribute vec4 position;
+attribute vec4 color;
+attribute vec3 normal;
+
+attribute vec4 ambient;
+attribute vec4 specular;
+attribute vec4 emissive;
+attribute float shininess;
+
+varying vec4 vertColor;
+varying vec4 backVertColor;
+
+const float zero_float = 0.0;
+const float one_float = 1.0;
+const vec3 zero_vec3 = vec3(0);
+
+float falloffFactor(vec3 lightPos, vec3 vertPos, vec3 coeff) {
+ vec3 lpv = lightPos - vertPos;
+ vec3 dist = vec3(one_float);
+ dist.z = dot(lpv, lpv);
+ dist.y = sqrt(dist.z);
+ return one_float / dot(dist, coeff);
+}
+
+float spotFactor(vec3 lightPos, vec3 vertPos, vec3 lightNorm, float minCos, float spotExp) {
+ vec3 lpv = normalize(lightPos - vertPos);
+ vec3 nln = -one_float * lightNorm;
+ float spotCos = dot(nln, lpv);
+ return spotCos <= minCos ? zero_float : pow(spotCos, spotExp);
+}
+
+float lambertFactor(vec3 lightDir, vec3 vecNormal) {
+ return max(zero_float, dot(lightDir, vecNormal));
+}
+
+float blinnPhongFactor(vec3 lightDir, vec3 vertPos, vec3 vecNormal, float shine) {
+ vec3 np = normalize(vertPos);
+ vec3 ldp = normalize(lightDir - np);
+ return pow(max(zero_float, dot(ldp, vecNormal)), shine);
+}
+
+void main() {
+ // Vertex in clip coordinates
+ gl_Position = transformMatrix * position;
+
+ // Vertex in eye coordinates
+ vec3 ecVertex = vec3(modelviewMatrix * position);
+
+ // Normal vector in eye coordinates
+ vec3 ecNormal = normalize(normalMatrix * normal);
+ vec3 ecNormalInv = ecNormal * -one_float;
+
+ // Light calculations
+ vec3 totalAmbient = vec3(0, 0, 0);
+
+ vec3 totalFrontDiffuse = vec3(0, 0, 0);
+ vec3 totalFrontSpecular = vec3(0, 0, 0);
+
+ vec3 totalBackDiffuse = vec3(0, 0, 0);
+ vec3 totalBackSpecular = vec3(0, 0, 0);
+
+ for (int i = 0; i < 8; i++) {
+ if (lightCount == i) break;
+
+ vec3 lightPos = lightPosition[i].xyz;
+ bool isDir = lightPosition[i].w < one_float;
+ float spotCos = lightSpot[i].x;
+ float spotExp = lightSpot[i].y;
+
+ vec3 lightDir;
+ float falloff;
+ float spotf;
+
+ if (isDir) {
+ falloff = one_float;
+ lightDir = -one_float * lightNormal[i];
+ } else {
+ falloff = falloffFactor(lightPos, ecVertex, lightFalloff[i]);
+ lightDir = normalize(lightPos - ecVertex);
+ }
+
+ spotf = spotExp > zero_float ? spotFactor(lightPos, ecVertex, lightNormal[i],
+ spotCos, spotExp)
+ : one_float;
+
+ if (any(greaterThan(lightAmbient[i], zero_vec3))) {
+ totalAmbient += lightAmbient[i] * falloff;
+ }
+
+ if (any(greaterThan(lightDiffuse[i], zero_vec3))) {
+ totalFrontDiffuse += lightDiffuse[i] * falloff * spotf *
+ lambertFactor(lightDir, ecNormal);
+ totalBackDiffuse += lightDiffuse[i] * falloff * spotf *
+ lambertFactor(lightDir, ecNormalInv);
+ }
+
+ if (any(greaterThan(lightSpecular[i], zero_vec3))) {
+ totalFrontSpecular += lightSpecular[i] * falloff * spotf *
+ blinnPhongFactor(lightDir, ecVertex, ecNormal, shininess);
+ totalBackSpecular += lightSpecular[i] * falloff * spotf *
+ blinnPhongFactor(lightDir, ecVertex, ecNormalInv, shininess);
+ }
+ }
+
+ // Calculating final color as result of all lights (plus emissive term).
+ // Transparency is determined exclusively by the diffuse component.
+ vertColor = vec4(totalAmbient, 0) * ambient +
+ vec4(totalFrontDiffuse, 1) * color +
+ vec4(totalFrontSpecular, 0) * specular +
+ vec4(emissive.rgb, 0);
+
+ backVertColor = vec4(totalAmbient, 0) * ambient +
+ vec4(totalBackDiffuse, 1) * color +
+ vec4(totalBackSpecular, 0) * specular +
+ vec4(emissive.rgb, 0);
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/LineFrag.glsl b/core-androidx/src/assets/shaders/LineFrag.glsl
new file mode 100644
index 000000000..9046e17e9
--- /dev/null
+++ b/core-androidx/src/assets/shaders/LineFrag.glsl
@@ -0,0 +1,32 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+varying vec4 vertColor;
+
+void main() {
+ gl_FragColor = vertColor;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/LineVert.glsl b/core-androidx/src/assets/shaders/LineVert.glsl
new file mode 100644
index 000000000..15e7bf951
--- /dev/null
+++ b/core-androidx/src/assets/shaders/LineVert.glsl
@@ -0,0 +1,99 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-17 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#define PROCESSING_LINE_SHADER
+
+uniform mat4 modelviewMatrix;
+uniform mat4 projectionMatrix;
+
+uniform vec4 viewport;
+uniform int perspective;
+uniform vec3 scale;
+
+attribute vec4 position;
+attribute vec4 color;
+attribute vec4 direction;
+
+varying vec4 vertColor;
+
+void main() {
+ vec4 posp = modelviewMatrix * position;
+ vec4 posq = modelviewMatrix * (position + vec4(direction.xyz, 0));
+
+ // Moving vertices slightly toward the camera
+ // to avoid depth-fighting with the fill triangles.
+ // Discussed here:
+ // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848
+ posp.xyz = posp.xyz * scale;
+ posq.xyz = posq.xyz * scale;
+
+ vec4 p = projectionMatrix * posp;
+ vec4 q = projectionMatrix * posq;
+
+ // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])
+ // screen_p = (p.xy/p.w + <1,1>) * 0.5 * viewport.zw
+
+ // prevent division by W by transforming the tangent formula (div by 0 causes
+ // the line to disappear, see https://github.com/processing/processing/issues/5183)
+ // t = screen_q - screen_p
+ //
+ // tangent is normalized and we don't care which direction it points to (+-)
+ // t = +- normalize( screen_q - screen_p )
+ // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*viewport.zw - (p.xy/p.w+<1,1>)*0.5*viewport.zw )
+ //
+ // extract common factor, <1,1> - <1,1> cancels out
+ // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * viewport.zw )
+ //
+ // convert to common divisor
+ // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * viewport.zw )
+ //
+ // remove the common scalar divisor/factor, not needed due to normalize and +-
+ // (keep viewport - can't remove because it has different components for x and y
+ // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)
+ // t = +- normalize( (q.xy*p.w - p.xy*q.w) * viewport.zw )
+
+ vec2 tangent = (q.xy*p.w - p.xy*q.w) * viewport.zw;
+ // don't normalize zero vector (line join triangles and lines perpendicular to the eye plane)
+ tangent = length(tangent) == 0.0 ? vec2(0.0, 0.0) : normalize(tangent);
+
+ // flip tangent to normal (it's already normalized)
+ vec2 normal = vec2(-tangent.y, tangent.x);
+
+ float thickness = direction.w;
+ vec2 offset = normal * thickness;
+
+ // Perspective ---
+ // convert from world to clip by multiplying with projection scaling factor
+ // to get the right thickness (see https://github.com/processing/processing/issues/5182)
+ // invert Y, projections in Processing invert Y
+ vec2 perspScale = (projectionMatrix * vec4(1, -1, 0, 0)).xy;
+
+ // No Perspective ---
+ // multiply by W (to cancel out division by W later in the pipeline) and
+ // convert from screen to clip (derived from clip to screen above)
+ vec2 noPerspScale = p.w / (0.5 * viewport.zw);
+
+ gl_Position.xy = p.xy + offset.xy * mix(noPerspScale, perspScale, float(perspective > 0));
+ gl_Position.zw = p.zw;
+
+ vertColor = color;
+}
diff --git a/core-androidx/src/assets/shaders/MaskFrag.glsl b/core-androidx/src/assets/shaders/MaskFrag.glsl
new file mode 100644
index 000000000..3d7e7dbf1
--- /dev/null
+++ b/core-androidx/src/assets/shaders/MaskFrag.glsl
@@ -0,0 +1,40 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+#define PROCESSING_TEXTURE_SHADER
+
+uniform sampler2D texture;
+uniform sampler2D mask;
+
+varying vec4 vertTexCoord;
+
+void main() {
+ vec3 texColor = texture2D(texture, vertTexCoord.st).rgb;
+ vec3 maskColor = texture2D(mask, vertTexCoord.st).rgb;
+ float luminance = dot(maskColor, vec3(0.2126, 0.7152, 0.0722));
+ gl_FragColor = vec4(texColor, luminance);
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/P2DFrag.glsl b/core-androidx/src/assets/shaders/P2DFrag.glsl
new file mode 100644
index 000000000..ce3a3fb27
--- /dev/null
+++ b/core-androidx/src/assets/shaders/P2DFrag.glsl
@@ -0,0 +1,14 @@
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+varying vec4 vertColor;
+varying vec2 vertTexCoord;
+varying float vertTexFactor;
+
+uniform sampler2D texture;
+
+void main() {
+ gl_FragColor = mix(vertColor, vertColor * texture2D(texture, vertTexCoord), vertTexFactor);
+}
diff --git a/core-androidx/src/assets/shaders/P2DVert.glsl b/core-androidx/src/assets/shaders/P2DVert.glsl
new file mode 100644
index 000000000..4e9a1f7e1
--- /dev/null
+++ b/core-androidx/src/assets/shaders/P2DVert.glsl
@@ -0,0 +1,23 @@
+attribute vec3 position;
+attribute vec4 color;
+attribute vec2 texCoord;
+attribute float texFactor;
+
+varying vec4 vertColor;
+varying vec2 vertTexCoord;
+varying float vertTexFactor;
+
+uniform mat4 transform;
+uniform vec2 texScale;
+
+void main() {
+ gl_Position = transform * vec4(position, 1);
+
+ //we avoid affecting the Z component by the transform
+ //because it would mess up our depth testing
+ gl_Position.z = position.z;
+
+ vertColor = color.zyxw;
+ vertTexCoord = texCoord * texScale;
+ vertTexFactor = texFactor;
+}
diff --git a/core-androidx/src/assets/shaders/PointFrag.glsl b/core-androidx/src/assets/shaders/PointFrag.glsl
new file mode 100644
index 000000000..5f86d92b4
--- /dev/null
+++ b/core-androidx/src/assets/shaders/PointFrag.glsl
@@ -0,0 +1,32 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+varying vec4 vertColor;
+
+void main() {
+ gl_FragColor = vertColor;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/PointVert.glsl b/core-androidx/src/assets/shaders/PointVert.glsl
new file mode 100644
index 000000000..292674615
--- /dev/null
+++ b/core-androidx/src/assets/shaders/PointVert.glsl
@@ -0,0 +1,56 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-17 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+uniform mat4 projectionMatrix;
+uniform mat4 modelviewMatrix;
+
+uniform vec4 viewport;
+uniform int perspective;
+
+attribute vec4 position;
+attribute vec4 color;
+attribute vec2 offset;
+
+varying vec4 vertColor;
+
+void main() {
+ vec4 pos = modelviewMatrix * position;
+ vec4 clip = projectionMatrix * pos;
+
+ // Perspective ---
+ // convert from world to clip by multiplying with projection scaling factor
+ // invert Y, projections in Processing invert Y
+ vec2 perspScale = (projectionMatrix * vec4(1, -1, 0, 0)).xy;
+
+ // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])
+ // screen_p = (p.xy/p.w + <1,1>) * 0.5 * viewport.zw
+
+ // No Perspective ---
+ // multiply by W (to cancel out division by W later in the pipeline) and
+ // convert from screen to clip (derived from clip to screen above)
+ vec2 noPerspScale = clip.w / (0.5 * viewport.zw);
+
+ gl_Position.xy = clip.xy + offset.xy * mix(noPerspScale, perspScale, float(perspective > 0));
+ gl_Position.zw = clip.zw;
+
+ vertColor = color;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/TexFrag.glsl b/core-androidx/src/assets/shaders/TexFrag.glsl
new file mode 100644
index 000000000..c8e183d49
--- /dev/null
+++ b/core-androidx/src/assets/shaders/TexFrag.glsl
@@ -0,0 +1,37 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+uniform sampler2D texture;
+
+uniform vec2 texOffset;
+
+varying vec4 vertColor;
+varying vec4 vertTexCoord;
+
+void main() {
+ gl_FragColor = texture2D(texture, vertTexCoord.st) * vertColor;
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/TexLightFrag.glsl b/core-androidx/src/assets/shaders/TexLightFrag.glsl
new file mode 100644
index 000000000..fd9b61576
--- /dev/null
+++ b/core-androidx/src/assets/shaders/TexLightFrag.glsl
@@ -0,0 +1,37 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+#ifdef GL_ES
+precision mediump float;
+precision mediump int;
+#endif
+
+uniform sampler2D texture;
+
+uniform vec2 texOffset;
+
+varying vec4 vertColor;
+varying vec4 backVertColor;
+varying vec4 vertTexCoord;
+
+void main() {
+ gl_FragColor = texture2D(texture, vertTexCoord.st) * (gl_FrontFacing ? vertColor : backVertColor);
+}
\ No newline at end of file
diff --git a/core-androidx/src/assets/shaders/TexLightVert.glsl b/core-androidx/src/assets/shaders/TexLightVert.glsl
new file mode 100644
index 000000000..57551edce
--- /dev/null
+++ b/core-androidx/src/assets/shaders/TexLightVert.glsl
@@ -0,0 +1,157 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+uniform mat4 modelviewMatrix;
+uniform mat4 transformMatrix;
+uniform mat3 normalMatrix;
+uniform mat4 texMatrix;
+
+uniform int lightCount;
+uniform vec4 lightPosition[8];
+uniform vec3 lightNormal[8];
+uniform vec3 lightAmbient[8];
+uniform vec3 lightDiffuse[8];
+uniform vec3 lightSpecular[8];
+uniform vec3 lightFalloff[8];
+uniform vec2 lightSpot[8];
+
+attribute vec4 position;
+attribute vec4 color;
+attribute vec3 normal;
+attribute vec2 texCoord;
+
+attribute vec4 ambient;
+attribute vec4 specular;
+attribute vec4 emissive;
+attribute float shininess;
+
+varying vec4 vertColor;
+varying vec4 backVertColor;
+varying vec4 vertTexCoord;
+
+const float zero_float = 0.0;
+const float one_float = 1.0;
+const vec3 zero_vec3 = vec3(0);
+
+float falloffFactor(vec3 lightPos, vec3 vertPos, vec3 coeff) {
+ vec3 lpv = lightPos - vertPos;
+ vec3 dist = vec3(one_float);
+ dist.z = dot(lpv, lpv);
+ dist.y = sqrt(dist.z);
+ return one_float / dot(dist, coeff);
+}
+
+float spotFactor(vec3 lightPos, vec3 vertPos, vec3 lightNorm, float minCos, float spotExp) {
+ vec3 lpv = normalize(lightPos - vertPos);
+ vec3 nln = -one_float * lightNorm;
+ float spotCos = dot(nln, lpv);
+ return spotCos <= minCos ? zero_float : pow(spotCos, spotExp);
+}
+
+float lambertFactor(vec3 lightDir, vec3 vecNormal) {
+ return max(zero_float, dot(lightDir, vecNormal));
+}
+
+float blinnPhongFactor(vec3 lightDir, vec3 vertPos, vec3 vecNormal, float shine) {
+ vec3 np = normalize(vertPos);
+ vec3 ldp = normalize(lightDir - np);
+ return pow(max(zero_float, dot(ldp, vecNormal)), shine);
+}
+
+void main() {
+ // Vertex in clip coordinates
+ gl_Position = transformMatrix * position;
+
+ // Vertex in eye coordinates
+ vec3 ecVertex = vec3(modelviewMatrix * position);
+
+ // Normal vector in eye coordinates
+ vec3 ecNormal = normalize(normalMatrix * normal);
+ vec3 ecNormalInv = ecNormal * -one_float;
+
+ // Light calculations
+ vec3 totalAmbient = vec3(0, 0, 0);
+
+ vec3 totalFrontDiffuse = vec3(0, 0, 0);
+ vec3 totalFrontSpecular = vec3(0, 0, 0);
+
+ vec3 totalBackDiffuse = vec3(0, 0, 0);
+ vec3 totalBackSpecular = vec3(0, 0, 0);
+
+ for (int i = 0; i < 8; i++) {
+ if (lightCount == i) break;
+
+ vec3 lightPos = lightPosition[i].xyz;
+ bool isDir = lightPosition[i].w < one_float;
+ float spotCos = lightSpot[i].x;
+ float spotExp = lightSpot[i].y;
+
+ vec3 lightDir;
+ float falloff;
+ float spotf;
+
+ if (isDir) {
+ falloff = one_float;
+ lightDir = -one_float * lightNormal[i];
+ } else {
+ falloff = falloffFactor(lightPos, ecVertex, lightFalloff[i]);
+ lightDir = normalize(lightPos - ecVertex);
+ }
+
+ spotf = spotExp > zero_float ? spotFactor(lightPos, ecVertex, lightNormal[i],
+ spotCos, spotExp)
+ : one_float;
+
+ if (any(greaterThan(lightAmbient[i], zero_vec3))) {
+ totalAmbient += lightAmbient[i] * falloff;
+ }
+
+ if (any(greaterThan(lightDiffuse[i], zero_vec3))) {
+ totalFrontDiffuse += lightDiffuse[i] * falloff * spotf *
+ lambertFactor(lightDir, ecNormal);
+ totalBackDiffuse += lightDiffuse[i] * falloff * spotf *
+ lambertFactor(lightDir, ecNormalInv);
+ }
+
+ if (any(greaterThan(lightSpecular[i], zero_vec3))) {
+ totalFrontSpecular += lightSpecular[i] * falloff * spotf *
+ blinnPhongFactor(lightDir, ecVertex, ecNormal, shininess);
+ totalBackSpecular += lightSpecular[i] * falloff * spotf *
+ blinnPhongFactor(lightDir, ecVertex, ecNormalInv, shininess);
+ }
+ }
+
+ // Calculating final color as result of all lights (plus emissive term).
+ // Transparency is determined exclusively by the diffuse component.
+ vertColor = vec4(totalAmbient, 0) * ambient +
+ vec4(totalFrontDiffuse, 1) * color +
+ vec4(totalFrontSpecular, 0) * specular +
+ vec4(emissive.rgb, 0);
+
+ backVertColor = vec4(totalAmbient, 0) * ambient +
+ vec4(totalBackDiffuse, 1) * color +
+ vec4(totalBackSpecular, 0) * specular +
+ vec4(emissive.rgb, 0);
+
+ // Calculating texture coordinates, with r and q set both to one
+ vertTexCoord = texMatrix * vec4(texCoord, 1.0, 1.0);
+}
diff --git a/core-androidx/src/assets/shaders/TexVert.glsl b/core-androidx/src/assets/shaders/TexVert.glsl
new file mode 100644
index 000000000..c07dc30d7
--- /dev/null
+++ b/core-androidx/src/assets/shaders/TexVert.glsl
@@ -0,0 +1,38 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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
+*/
+
+uniform mat4 transformMatrix;
+uniform mat4 texMatrix;
+
+attribute vec4 position;
+attribute vec4 color;
+attribute vec2 texCoord;
+
+varying vec4 vertColor;
+varying vec4 vertTexCoord;
+
+void main() {
+ gl_Position = transformMatrix * position;
+
+ vertColor = color;
+ vertTexCoord = texMatrix * vec4(texCoord, 1.0, 1.0);
+}
\ No newline at end of file
From b48a88faae0416df008eb135a6351a952e99a841 Mon Sep 17 00:00:00 2001
From: Rupesh Kumar <46577873+rupesh-kumar-lpu@users.noreply.github.com>
Date: Thu, 24 Dec 2020 06:02:10 +0530
Subject: [PATCH 03/39] Added source processing inside core-androidx
---
.../processing/a2d/PGraphicsAndroid2D.java | 2386 +++
.../src/processing/a2d/PShapeAndroid2D.java | 109 +
.../src/processing/a2d/PSurfaceAndroid2D.java | 159 +
.../src/processing/android/ActivityAPI.java | 65 +
.../src/processing/android/AppComponent.java | 51 +
.../src/processing/android/CompatUtils.java | 111 +
.../src/processing/android/PFragment.java | 259 +
.../src/processing/android/PWallpaper.java | 302 +
.../processing/android/PWatchFaceCanvas.java | 367 +
.../processing/android/PWatchFaceGLES.java | 392 +
.../android/PermissionRequestor.java | 59 +
.../src/processing/android/ServiceEngine.java | 49 +
.../src/processing/core/PApplet.java | 12622 ++++++++++++++
.../src/processing/core/PConstants.java | 465 +
core-androidx/src/processing/core/PFont.java | 907 +
.../src/processing/core/PGraphics.java | 6134 +++++++
core-androidx/src/processing/core/PImage.java | 2881 ++++
.../src/processing/core/PMatrix.java | 170 +
.../src/processing/core/PMatrix2D.java | 467 +
.../src/processing/core/PMatrix3D.java | 806 +
core-androidx/src/processing/core/PShape.java | 3571 ++++
.../src/processing/core/PShapeOBJ.java | 467 +
.../src/processing/core/PShapeSVG.java | 2031 +++
core-androidx/src/processing/core/PStyle.java | 62 +
.../src/processing/core/PSurface.java | 107 +
.../src/processing/core/PSurfaceNone.java | 593 +
.../src/processing/core/PVector.java | 1062 ++
.../src/processing/data/DoubleDict.java | 850 +
.../src/processing/data/DoubleList.java | 928 +
.../src/processing/data/FloatDict.java | 847 +
.../src/processing/data/FloatList.java | 936 +
.../src/processing/data/IntDict.java | 807 +
.../src/processing/data/IntList.java | 936 +
.../src/processing/data/JSONArray.java | 1260 ++
.../src/processing/data/JSONObject.java | 2282 +++
.../src/processing/data/JSONTokener.java | 435 +
.../src/processing/data/LongDict.java | 802 +
.../src/processing/data/LongList.java | 937 +
core-androidx/src/processing/data/Sort.java | 46 +
.../src/processing/data/StringDict.java | 613 +
.../src/processing/data/StringList.java | 798 +
core-androidx/src/processing/data/Table.java | 4934 ++++++
.../src/processing/data/TableRow.java | 198 +
core-androidx/src/processing/data/XML.java | 1156 ++
core-androidx/src/processing/event/Event.java | 125 +
.../src/processing/event/KeyEvent.java | 69 +
.../src/processing/event/MouseEvent.java | 105 +
.../src/processing/event/TouchEvent.java | 142 +
.../src/processing/opengl/FontTexture.java | 379 +
.../src/processing/opengl/FrameBuffer.java | 503 +
.../src/processing/opengl/LinePath.java | 623 +
.../src/processing/opengl/LineStroker.java | 685 +
core-androidx/src/processing/opengl/PGL.java | 3363 ++++
.../src/processing/opengl/PGLES.java | 1608 ++
.../src/processing/opengl/PGraphics2D.java | 629 +
.../src/processing/opengl/PGraphics2DX.java | 2056 +++
.../src/processing/opengl/PGraphics3D.java | 281 +
.../processing/opengl/PGraphicsOpenGL.java | 14280 ++++++++++++++++
.../src/processing/opengl/PShader.java | 1478 ++
.../src/processing/opengl/PShapeOpenGL.java | 5250 ++++++
.../src/processing/opengl/PSurfaceGLES.java | 604 +
.../src/processing/opengl/Texture.java | 1670 ++
.../src/processing/opengl/VertexBuffer.java | 88 +
.../processing/opengl/tess/ActiveRegion.java | 70 +
.../processing/opengl/tess/CachedVertex.java | 60 +
.../src/processing/opengl/tess/Dict.java | 142 +
.../src/processing/opengl/tess/DictNode.java | 61 +
.../src/processing/opengl/tess/GLUface.java | 66 +
.../processing/opengl/tess/GLUhalfEdge.java | 72 +
.../src/processing/opengl/tess/GLUmesh.java | 63 +
.../opengl/tess/GLUtessellatorImpl.java | 645 +
.../src/processing/opengl/tess/GLUvertex.java | 67 +
.../src/processing/opengl/tess/Geom.java | 340 +
.../src/processing/opengl/tess/Mesh.java | 736 +
.../src/processing/opengl/tess/Normal.java | 288 +
.../src/processing/opengl/tess/PGLU.java | 158 +
.../opengl/tess/PGLUtessellator.java | 70 +
.../opengl/tess/PGLUtessellatorCallback.java | 359 +
.../tess/PGLUtessellatorCallbackAdapter.java | 87 +
.../src/processing/opengl/tess/PriorityQ.java | 102 +
.../processing/opengl/tess/PriorityQHeap.java | 271 +
.../processing/opengl/tess/PriorityQSort.java | 288 +
.../src/processing/opengl/tess/Render.java | 558 +
.../src/processing/opengl/tess/Sweep.java | 1354 ++
.../src/processing/opengl/tess/TessMono.java | 243 +
.../src/processing/opengl/tess/TessState.java | 61 +
86 files changed, 95518 insertions(+)
create mode 100644 core-androidx/src/processing/a2d/PGraphicsAndroid2D.java
create mode 100644 core-androidx/src/processing/a2d/PShapeAndroid2D.java
create mode 100644 core-androidx/src/processing/a2d/PSurfaceAndroid2D.java
create mode 100644 core-androidx/src/processing/android/ActivityAPI.java
create mode 100644 core-androidx/src/processing/android/AppComponent.java
create mode 100644 core-androidx/src/processing/android/CompatUtils.java
create mode 100644 core-androidx/src/processing/android/PFragment.java
create mode 100644 core-androidx/src/processing/android/PWallpaper.java
create mode 100644 core-androidx/src/processing/android/PWatchFaceCanvas.java
create mode 100644 core-androidx/src/processing/android/PWatchFaceGLES.java
create mode 100644 core-androidx/src/processing/android/PermissionRequestor.java
create mode 100644 core-androidx/src/processing/android/ServiceEngine.java
create mode 100644 core-androidx/src/processing/core/PApplet.java
create mode 100644 core-androidx/src/processing/core/PConstants.java
create mode 100644 core-androidx/src/processing/core/PFont.java
create mode 100644 core-androidx/src/processing/core/PGraphics.java
create mode 100644 core-androidx/src/processing/core/PImage.java
create mode 100644 core-androidx/src/processing/core/PMatrix.java
create mode 100644 core-androidx/src/processing/core/PMatrix2D.java
create mode 100644 core-androidx/src/processing/core/PMatrix3D.java
create mode 100644 core-androidx/src/processing/core/PShape.java
create mode 100644 core-androidx/src/processing/core/PShapeOBJ.java
create mode 100644 core-androidx/src/processing/core/PShapeSVG.java
create mode 100644 core-androidx/src/processing/core/PStyle.java
create mode 100644 core-androidx/src/processing/core/PSurface.java
create mode 100644 core-androidx/src/processing/core/PSurfaceNone.java
create mode 100644 core-androidx/src/processing/core/PVector.java
create mode 100644 core-androidx/src/processing/data/DoubleDict.java
create mode 100644 core-androidx/src/processing/data/DoubleList.java
create mode 100644 core-androidx/src/processing/data/FloatDict.java
create mode 100644 core-androidx/src/processing/data/FloatList.java
create mode 100644 core-androidx/src/processing/data/IntDict.java
create mode 100644 core-androidx/src/processing/data/IntList.java
create mode 100644 core-androidx/src/processing/data/JSONArray.java
create mode 100644 core-androidx/src/processing/data/JSONObject.java
create mode 100644 core-androidx/src/processing/data/JSONTokener.java
create mode 100644 core-androidx/src/processing/data/LongDict.java
create mode 100644 core-androidx/src/processing/data/LongList.java
create mode 100644 core-androidx/src/processing/data/Sort.java
create mode 100644 core-androidx/src/processing/data/StringDict.java
create mode 100644 core-androidx/src/processing/data/StringList.java
create mode 100644 core-androidx/src/processing/data/Table.java
create mode 100644 core-androidx/src/processing/data/TableRow.java
create mode 100644 core-androidx/src/processing/data/XML.java
create mode 100644 core-androidx/src/processing/event/Event.java
create mode 100644 core-androidx/src/processing/event/KeyEvent.java
create mode 100644 core-androidx/src/processing/event/MouseEvent.java
create mode 100644 core-androidx/src/processing/event/TouchEvent.java
create mode 100644 core-androidx/src/processing/opengl/FontTexture.java
create mode 100644 core-androidx/src/processing/opengl/FrameBuffer.java
create mode 100644 core-androidx/src/processing/opengl/LinePath.java
create mode 100644 core-androidx/src/processing/opengl/LineStroker.java
create mode 100644 core-androidx/src/processing/opengl/PGL.java
create mode 100644 core-androidx/src/processing/opengl/PGLES.java
create mode 100644 core-androidx/src/processing/opengl/PGraphics2D.java
create mode 100644 core-androidx/src/processing/opengl/PGraphics2DX.java
create mode 100644 core-androidx/src/processing/opengl/PGraphics3D.java
create mode 100644 core-androidx/src/processing/opengl/PGraphicsOpenGL.java
create mode 100644 core-androidx/src/processing/opengl/PShader.java
create mode 100644 core-androidx/src/processing/opengl/PShapeOpenGL.java
create mode 100644 core-androidx/src/processing/opengl/PSurfaceGLES.java
create mode 100644 core-androidx/src/processing/opengl/Texture.java
create mode 100644 core-androidx/src/processing/opengl/VertexBuffer.java
create mode 100644 core-androidx/src/processing/opengl/tess/ActiveRegion.java
create mode 100644 core-androidx/src/processing/opengl/tess/CachedVertex.java
create mode 100644 core-androidx/src/processing/opengl/tess/Dict.java
create mode 100644 core-androidx/src/processing/opengl/tess/DictNode.java
create mode 100644 core-androidx/src/processing/opengl/tess/GLUface.java
create mode 100644 core-androidx/src/processing/opengl/tess/GLUhalfEdge.java
create mode 100644 core-androidx/src/processing/opengl/tess/GLUmesh.java
create mode 100644 core-androidx/src/processing/opengl/tess/GLUtessellatorImpl.java
create mode 100644 core-androidx/src/processing/opengl/tess/GLUvertex.java
create mode 100644 core-androidx/src/processing/opengl/tess/Geom.java
create mode 100644 core-androidx/src/processing/opengl/tess/Mesh.java
create mode 100644 core-androidx/src/processing/opengl/tess/Normal.java
create mode 100644 core-androidx/src/processing/opengl/tess/PGLU.java
create mode 100644 core-androidx/src/processing/opengl/tess/PGLUtessellator.java
create mode 100644 core-androidx/src/processing/opengl/tess/PGLUtessellatorCallback.java
create mode 100644 core-androidx/src/processing/opengl/tess/PGLUtessellatorCallbackAdapter.java
create mode 100644 core-androidx/src/processing/opengl/tess/PriorityQ.java
create mode 100644 core-androidx/src/processing/opengl/tess/PriorityQHeap.java
create mode 100644 core-androidx/src/processing/opengl/tess/PriorityQSort.java
create mode 100644 core-androidx/src/processing/opengl/tess/Render.java
create mode 100644 core-androidx/src/processing/opengl/tess/Sweep.java
create mode 100644 core-androidx/src/processing/opengl/tess/TessMono.java
create mode 100644 core-androidx/src/processing/opengl/tess/TessState.java
diff --git a/core-androidx/src/processing/a2d/PGraphicsAndroid2D.java b/core-androidx/src/processing/a2d/PGraphicsAndroid2D.java
new file mode 100644
index 000000000..53df26eb2
--- /dev/null
+++ b/core-androidx/src/processing/a2d/PGraphicsAndroid2D.java
@@ -0,0 +1,2386 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2005-12 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.a2d;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.nio.ByteBuffer;
+import java.io.InputStream;
+import java.util.zip.GZIPInputStream;
+
+import processing.android.AppComponent;
+import processing.core.PApplet;
+import processing.core.PFont;
+import processing.core.PGraphics;
+import processing.core.PImage;
+import processing.core.PMatrix;
+import processing.core.PMatrix2D;
+import processing.core.PMatrix3D;
+import processing.core.PShape;
+import processing.core.PShapeSVG;
+import processing.core.PSurface;
+import processing.data.XML;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.app.ActivityManager.MemoryInfo;
+import android.content.Context;
+import android.graphics.*;
+import android.graphics.Bitmap.Config;
+import android.graphics.Paint.Style;
+import android.os.Build;
+import android.os.Environment;
+import android.view.SurfaceHolder;
+
+import static android.os.Environment.isExternalStorageRemovable;
+
+
+/**
+ * Subclass for PGraphics that implements the graphics API using
+ * the Android 2D graphics model. Similar tradeoffs to JAVA2D mode
+ * with the original (desktop) version of Processing.
+ */
+public class PGraphicsAndroid2D extends PGraphics {
+ static public boolean useBitmap = true;
+
+ public Canvas canvas; // like g2 for PGraphicsJava2D
+
+ /// break the shape at the next vertex (next vertex() call is a moveto())
+ boolean breakShape;
+
+ /// coordinates for internal curve calculation
+ float[] curveCoordX;
+ float[] curveCoordY;
+ float[] curveDrawX;
+ float[] curveDrawY;
+
+ static protected final int MATRIX_STACK_DEPTH = 32;
+ protected float[][] transformStack;
+ public PMatrix2D transform;
+ protected Matrix transformMatrix;
+ protected float[] transformArray;
+ int transformCount;
+
+// Line2D.Float line = new Line2D.Float();
+// Ellipse2D.Float ellipse = new Ellipse2D.Float();
+// Rectangle2D.Float rect = new Rectangle2D.Float();
+// Arc2D.Float arc = new Arc2D.Float();
+ /**
+ * The temporary path object that does most of the drawing work. If there are
+ * any points in the path (meaning that moveto has been called), then
+ * vertexCount will be 1 (or more). In the POLYGON case, vertexCount is only
+ * set to 1 after the first point is drawn (to indicate a moveto) and not
+ * incremented after, since the variable isn't used for POLYGON paths.
+ */
+ Path path;
+
+ /** Temporary rectangle object. */
+ RectF rect;
+
+// protected Color tintColorObject;
+
+// protected Color fillColorObject;
+// public boolean fillGradient;
+// public Paint fillGradientObject;
+
+// protected Color strokeColorObject;
+// public boolean strokeGradient;
+// public Paint strokeGradientObject;
+
+ Paint fillPaint;
+ Paint strokePaint;
+ Paint tintPaint;
+
+
+ /**
+ * Marks when changes to the size have occurred, so that the backing bitmap
+ * can be recreated.
+ */
+ protected boolean sized;
+
+ /**
+ * Marks when some changes have occurred, to the surface view.
+ */
+ protected boolean changed;
+
+ //////////////////////////////////////////////////////////////
+
+ // INTERNAL
+
+
+ public PGraphicsAndroid2D() {
+ transformStack = new float[MATRIX_STACK_DEPTH][6];
+ transform = new PMatrix2D();
+ transformMatrix = new Matrix();
+ transformArray = new float[9];
+
+ path = new Path();
+ rect = new RectF();
+
+ fillPaint = new Paint();
+ fillPaint.setStyle(Style.FILL);
+ strokePaint = new Paint();
+ strokePaint.setStyle(Style.STROKE);
+ tintPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
+ }
+
+
+ //public void setParent(PApplet parent)
+
+
+ //public void setPrimary(boolean primary)
+
+
+ //public void setPath(String path)
+
+ @Override
+ public void surfaceChanged() {
+ changed = true;
+ }
+
+
+ @Override
+ public void setSize(int iwidth, int iheight) {
+ sized = iwidth != width || iheight != height;
+ super.setSize(iwidth, iheight);
+ }
+
+
+ @Override
+ public void dispose() {
+ if (bitmap != null) bitmap.recycle();
+ }
+
+
+ @Override
+ public PSurface createSurface(AppComponent component, SurfaceHolder holder, boolean reset) { // ignore
+ return new PSurfaceAndroid2D(this, component, holder);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FRAME
+
+ @SuppressLint("NewApi")
+ protected Canvas checkCanvas() {
+ if ((canvas == null || sized) && (useBitmap || !primaryGraphics)) {
+ if (bitmap == null || bitmap.getWidth() * bitmap.getHeight() < width * height ||
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
+ if (bitmap != null) bitmap.recycle();
+ bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
+ } else {
+ // reconfigure is only available in API level 19 or higher.
+ bitmap.reconfigure(width, height, bitmap.getConfig());
+ }
+ canvas = new Canvas(bitmap);
+ sized = false;
+ }
+ restoreSurface();
+ return canvas;
+ }
+
+
+ @Override
+ public void beginDraw() {
+ canvas = checkCanvas();
+
+ checkSettings();
+
+ resetMatrix(); // reset model matrix
+
+ // reset vertices
+ vertexCount = 0;
+ }
+
+
+ @Override
+ public void endDraw() {
+ if (bitmap == null) return;
+
+ if (primaryGraphics) {
+ SurfaceHolder holder = parent.getSurface().getSurfaceHolder();
+ if (holder != null) {
+ Canvas screen = null;
+ try {
+ screen = holder.lockCanvas(null);
+ if (screen != null) {
+ screen.drawBitmap(bitmap, new Matrix(), null);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (screen != null) {
+ try {
+ holder.unlockCanvasAndPost(screen);
+ } catch (IllegalStateException ex) {
+ } catch (IllegalArgumentException ex) {
+ }
+ }
+ }
+ }
+ } else {
+ // TODO this is probably overkill for most tasks...
+ loadPixels();
+ }
+
+ // Marking as modified, and then calling updatePixels() in
+ // the super class, which just sets the mx1, my1, mx2, my2
+ // coordinates of the modified area. This avoids doing the
+ // full copy of the pixels to the surface in this.updatePixels().
+ setModified();
+ super.updatePixels();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SETTINGS
+
+
+ //protected void checkSettings()
+
+
+ //protected void defaultSettings()
+
+
+ //protected void reapplySettings()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // HINT
+
+
+ //public void hint(int which)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPES
+
+
+ //public void beginShape(int kind)
+
+
+ @Override
+ public void beginShape(int kind) {
+ //super.beginShape(kind);
+ shape = kind;
+ vertexCount = 0;
+ curveVertexCount = 0;
+
+ // reset the path, because when mixing curves and straight
+ // lines, vertexCount will be set back to zero, so vertexCount == 1
+ // is no longer a good indicator of whether the shape is new.
+ // this way, just check to see if gpath is null, and if it isn't
+ // then just use it to continue the shape.
+ //path = null;
+// path.reset();
+// pathReset = true;
+ }
+
+
+ //public boolean edge(boolean e)
+
+
+ //public void normal(float nx, float ny, float nz) {
+
+
+ //public void textureMode(int mode)
+
+
+ @Override
+ public void texture(PImage image) {
+ showMethodWarning("texture");
+ }
+
+
+ @Override
+ public void vertex(float x, float y) {
+ // POLYGON and POINTS are broken out for efficiency
+ if (shape == POLYGON) {
+// if (path == null) {
+// path = new Path();
+// path.moveTo(x, y);
+ //if (pathReset) {
+ if (vertexCount == 0) {
+ path.reset();
+ path.moveTo(x, y);
+ vertexCount = 1;
+// pathReset = false;
+ } else if (breakShape) {
+ path.moveTo(x, y);
+ breakShape = false;
+ } else {
+ path.lineTo(x, y);
+ }
+
+ // this is way too slow, otherwise what's the point of using beginShape()
+// } else if (shape == POINTS) {
+// point(x, y);
+
+ } else {
+ curveVertexCount = 0;
+
+ if (vertexCount == vertices.length) {
+ float temp[][] = new float[vertexCount<<1][VERTEX_FIELD_COUNT];
+ System.arraycopy(vertices, 0, temp, 0, vertexCount);
+ vertices = temp;
+ }
+ // not everyone needs this, but just easier to store rather
+ // than adding another moving part to the code...
+ vertices[vertexCount][X] = x;
+ vertices[vertexCount][Y] = y;
+ vertexCount++;
+
+ switch (shape) {
+
+ case POINTS:
+ // store them for later
+ break;
+
+ case LINES:
+ if ((vertexCount % 2) == 0) {
+ line(vertices[vertexCount-2][X],
+ vertices[vertexCount-2][Y], x, y);
+ vertexCount = 0;
+ }
+ break;
+
+ case LINE_STRIP:
+ case LINE_LOOP:
+ if (vertexCount >= 2) {
+ line(vertices[vertexCount-2][X],
+ vertices[vertexCount-2][Y], x, y);
+ }
+ break;
+
+ case TRIANGLES:
+ if ((vertexCount % 3) == 0) {
+ triangle(vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y],
+ vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, y);
+ vertexCount = 0;
+ }
+ break;
+
+ case TRIANGLE_STRIP:
+ if (vertexCount >= 3) {
+ triangle(vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, //vertices[vertexCount - 1][X],
+ y, //vertices[vertexCount - 1][Y],
+ vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y]);
+ }
+ break;
+
+ case TRIANGLE_FAN:
+ if (vertexCount >= 3) {
+ triangle(vertices[0][X],
+ vertices[0][Y],
+ vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, y);
+ }
+ break;
+
+ case QUAD:
+ case QUADS:
+ if ((vertexCount % 4) == 0) {
+ quad(vertices[vertexCount - 4][X],
+ vertices[vertexCount - 4][Y],
+ vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y],
+ vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, y);
+ vertexCount = 0;
+ }
+ break;
+
+ case QUAD_STRIP:
+ // 0---2---4
+ // | | |
+ // 1---3---5
+ if ((vertexCount >= 4) && ((vertexCount % 2) == 0)) {
+ quad(vertices[vertexCount - 4][X],
+ vertices[vertexCount - 4][Y],
+ vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, y,
+ vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y]);
+ }
+ break;
+ }
+ }
+ }
+
+
+ @Override
+ public void vertex(float x, float y, float z) {
+ showDepthWarningXYZ("vertex");
+ }
+
+
+ @Override
+ public void vertex(float x, float y, float u, float v) {
+ showVariationWarning("vertex(x, y, u, v)");
+ }
+
+
+ @Override
+ public void vertex(float x, float y, float z, float u, float v) {
+ showDepthWarningXYZ("vertex");
+ }
+
+
+ @Override
+ public void breakShape() {
+ breakShape = true;
+ }
+
+
+ @Override
+ public void endShape(int mode) {
+ if (shape == POINTS && stroke && vertexCount > 0) {
+ Matrix m = getMatrixImp();
+ if (strokeWeight == 1 && m.isIdentity()) {
+ if (screenPoint == null) {
+ screenPoint = new float[2];
+ }
+ for (int i = 0; i < vertexCount; i++) {
+ screenPoint[0] = vertices[i][X];
+ screenPoint[1] = vertices[i][Y];
+ m.mapPoints(screenPoint);
+ set(PApplet.round(screenPoint[0]), PApplet.round(screenPoint[1]), strokeColor);
+ float x = vertices[i][X];
+ float y = vertices[i][Y];
+ set(PApplet.round(screenX(x, y)), PApplet.round(screenY(x, y)), strokeColor);
+ }
+ } else {
+ float sw = strokeWeight / 2;
+ // temporarily use the stroke Paint as a fill
+ strokePaint.setStyle(Style.FILL);
+ for (int i = 0; i < vertexCount; i++) {
+ float x = vertices[i][X];
+ float y = vertices[i][Y];
+ rect.set(x - sw, y - sw, x + sw, y + sw);
+ canvas.drawOval(rect, strokePaint);
+ }
+ strokePaint.setStyle(Style.STROKE);
+ }
+ } else if (shape == POLYGON) {
+ if (!path.isEmpty()) {
+ if (mode == CLOSE) {
+ path.close();
+ }
+ drawPath();
+ }
+ } else if (shape == LINE_LOOP && vertexCount >= 2) {
+ line(vertices[vertexCount-1][X],
+ vertices[vertexCount-1][Y],
+ vertices[0][X],
+ vertices[0][Y]);
+ }
+ shape = 0;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CLIPPING
+
+
+ @Override
+ protected void clipImpl(float x1, float y1, float x2, float y2) {
+ canvas.clipRect(x1, y1, x2, y2);
+ }
+
+
+ @Override
+ public void noClip() {
+ canvas.clipRect(0, 0, width, height, Region.Op.REPLACE);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BEZIER VERTICES
+
+
+ @Override
+ public void bezierVertex(float x1, float y1,
+ float x2, float y2,
+ float x3, float y3) {
+ // will check to make sure that vertexCount > 0
+ bezierVertexCheck();
+ path.cubicTo(x1, y1, x2, y2, x3, y3);
+ }
+
+
+ @Override
+ public void bezierVertex(float x2, float y2, float z2,
+ float x3, float y3, float z3,
+ float x4, float y4, float z4) {
+ showDepthWarningXYZ("bezierVertex");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // QUADRATIC BEZIER VERTICES
+
+
+ @Override
+ public void quadraticVertex(float ctrlX, float ctrlY,
+ float endX, float endY) {
+ bezierVertexCheck();
+ path.quadTo(ctrlX, ctrlY, endX, endY);
+ }
+
+
+ @Override
+ public void quadraticVertex(float x2, float y2, float z2,
+ float x4, float y4, float z4) {
+ showDepthWarningXYZ("quadVertex");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CURVE VERTICES
+
+
+ @Override
+ protected void curveVertexCheck() {
+ super.curveVertexCheck();
+
+ if (curveCoordX == null) {
+ curveCoordX = new float[4];
+ curveCoordY = new float[4];
+ curveDrawX = new float[4];
+ curveDrawY = new float[4];
+ }
+ }
+
+
+ @Override
+ protected void curveVertexSegment(float x1, float y1,
+ float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ curveCoordX[0] = x1;
+ curveCoordY[0] = y1;
+
+ curveCoordX[1] = x2;
+ curveCoordY[1] = y2;
+
+ curveCoordX[2] = x3;
+ curveCoordY[2] = y3;
+
+ curveCoordX[3] = x4;
+ curveCoordY[3] = y4;
+
+ curveToBezierMatrix.mult(curveCoordX, curveDrawX);
+ curveToBezierMatrix.mult(curveCoordY, curveDrawY);
+
+ // since the paths are continuous,
+ // only the first point needs the actual moveto
+ if (vertexCount == 0) {
+// if (path == null) {
+// path = new Path();
+ path.moveTo(curveDrawX[0], curveDrawY[0]);
+ vertexCount = 1;
+ }
+
+ path.cubicTo(curveDrawX[1], curveDrawY[1],
+ curveDrawX[2], curveDrawY[2],
+ curveDrawX[3], curveDrawY[3]);
+ }
+
+
+ @Override
+ public void curveVertex(float x, float y, float z) {
+ showDepthWarningXYZ("curveVertex");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RENDERER
+
+
+ //public void flush()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // POINT, LINE, TRIANGLE, QUAD
+
+
+ @Override
+ public void point(float x, float y) {
+ // this is a slow function to call on its own anyway.
+ // most people will use set().
+ beginShape(POINTS);
+ vertex(x, y);
+ endShape();
+// if (strokeWeight > 1) {
+// //line(x, y, x + EPSILON, y + EPSILON);
+// float sw = strokeWeight / 2;
+// rect.set(x - sw, y - sw, x + sw, y + sw);
+// strokePaint.setStyle(Style.FILL);
+// canvas.drawOval(rect, strokePaint);
+// strokePaint.setStyle(Style.STROKE);
+// } else {
+// // TODO this isn't accurate, really we need to
+// set(PApplet.round(screenX(x, y)), PApplet.round(screenY(x, y)), strokeColor);
+// }
+ }
+
+
+ @Override
+ public void line(float x1, float y1, float x2, float y2) {
+// line.setLine(x1, y1, x2, y2);
+// strokeShape(line);
+ if (stroke) {
+ canvas.drawLine(x1, y1, x2, y2, strokePaint);
+ }
+ }
+
+
+ @Override
+ public void triangle(float x1, float y1, float x2, float y2,
+ float x3, float y3) {
+ path.reset();
+ path.moveTo(x1, y1);
+ path.lineTo(x2, y2);
+ path.lineTo(x3, y3);
+ path.close();
+ drawPath();
+ }
+
+
+ @Override
+ public void quad(float x1, float y1, float x2, float y2,
+ float x3, float y3, float x4, float y4) {
+ path.reset();
+ path.moveTo(x1, y1);
+ path.lineTo(x2, y2);
+ path.lineTo(x3, y3);
+ path.lineTo(x4, y4);
+ path.close();
+ drawPath();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RECT
+
+
+ //public void rectMode(int mode)
+
+
+ //public void rect(float a, float b, float c, float d)
+
+
+ @Override
+ protected void rectImpl(float x1, float y1, float x2, float y2) {
+// rect.setFrame(x1, y1, x2-x1, y2-y1);
+// drawShape(rect);
+ //rect.set(x1, y1, x2, y2);
+ if (fill) {
+ canvas.drawRect(x1, y1, x2, y2, fillPaint);
+ }
+ if (stroke) {
+ canvas.drawRect(x1, y1, x2, y2, strokePaint);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ELLIPSE
+
+
+ //public void ellipseMode(int mode)
+
+
+ //public void ellipse(float a, float b, float c, float d)
+
+
+ @Override
+ protected void ellipseImpl(float x, float y, float w, float h) {
+// ellipse.setFrame(x, y, w, h);
+// drawShape(ellipse);
+ rect.set(x, y, x+w, y+h);
+ if (fill) {
+ canvas.drawOval(rect, fillPaint);
+ }
+ if (stroke) {
+ canvas.drawOval(rect, strokePaint);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ARC
+
+
+ //public void arc(float a, float b, float c, float d,
+ // float start, float stop)
+
+
+ @Override
+ protected void arcImpl(float x, float y, float w, float h,
+ float start, float stop, int mode) {
+ // 0 to 90 in java would be 0 to -90 for p5 renderer
+ // but that won't work, so -90 to 0?
+
+ if (stop - start >= TWO_PI) {
+ ellipseImpl(x, y, w, h);
+
+ } else {
+ // Android agrees with us, so don't set start/stop negative like Java 2D
+ start = start * RAD_TO_DEG;
+ stop = stop * RAD_TO_DEG;
+
+ // ok to do this because already checked for NaN
+ while (start < 0) {
+ start += 360;
+ stop += 360;
+ }
+ if (start > stop) {
+ float temp = start;
+ start = stop;
+ stop = temp;
+ }
+
+ float sweep = stop - start;
+ rect.set(x, y, x+w, y+h);
+
+ if (mode == 0) {
+ if (fill) {
+ canvas.drawArc(rect, start, sweep, true, fillPaint);
+ }
+ if (stroke) {
+ canvas.drawArc(rect, start, sweep, false, strokePaint);
+ }
+ } else if (mode == OPEN) {
+ if (fill) {
+ // Android does not support stroke and fill with different color
+ // after drawing the arc,draw the arc with Paint.Style.Stroke style
+ // again
+ canvas.drawArc(rect, start, sweep, false, fillPaint);
+ canvas.drawArc(rect, start, sweep, false, strokePaint);
+ }
+ if (stroke) {
+ canvas.drawArc(rect, start, sweep, false, strokePaint);
+ }
+ } else if (mode == CHORD) {
+ // Draw an extra line between start angle point and end point to
+ // achieve the chord
+ float endAngle = start + sweep;
+ float halfRectWidth = rect.width()/2;
+ float halfRectHeight = rect.height()/2;
+ float centerX = rect.centerX();
+ float centerY = rect.centerY();
+
+ float startX = (float) (halfRectWidth* Math.cos(Math.toRadians(start))) + centerX;
+ float startY = (float) (halfRectHeight * Math.sin(Math.toRadians(start))) + centerY;
+ float endX = (float) (halfRectWidth * Math.cos(Math.toRadians(endAngle))) + centerX;
+ float endY = (float) (halfRectHeight * Math.sin(Math.toRadians(endAngle))) + centerY;
+
+ if (fill) {
+ // draw the fill arc
+ canvas.drawArc(rect,start,sweep,false,fillPaint);
+ // draw the arc round border
+ canvas.drawArc(rect,start,sweep,false,strokePaint);
+ // draw the straight border
+ canvas.drawLine(startX,startY,endX,endY,strokePaint);
+ }
+ if (stroke) {
+ // draw the arc
+ canvas.drawArc(rect,start,sweep,false,strokePaint);
+ // draw the straight border
+ canvas.drawLine(startX,startY,endX,endY,strokePaint);
+ }
+ } else if (mode == PIE) {
+ if (fill) {
+ canvas.drawArc(rect, start, sweep, true, fillPaint);
+ }
+ if (stroke) {
+ canvas.drawArc(rect, start, sweep, true, strokePaint);
+ }
+ }
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // JAVA2D SHAPE/PATH HANDLING
+
+
+// protected void fillShape(Shape s) {
+// if (fillGradient) {
+// canvas.setPaint(fillGradientObject);
+// canvas.fill(s);
+// } else if (fill) {
+// canvas.setColor(fillColorObject);
+// canvas.fill(s);
+// }
+// }
+
+
+// protected void strokeShape(Shape s) {
+// if (strokeGradient) {
+// canvas.setPaint(strokeGradientObject);
+// canvas.draw(s);
+// } else if (stroke) {
+// canvas.setColor(strokeColorObject);
+// canvas.draw(s);
+// }
+// }
+
+
+// protected void drawShape(Shape s) {
+// if (fillGradient) {
+// canvas.setPaint(fillGradientObject);
+// canvas.fill(s);
+// } else if (fill) {
+// canvas.setColor(fillColorObject);
+// canvas.fill(s);
+// }
+// if (strokeGradient) {
+// canvas.setPaint(strokeGradientObject);
+// canvas.draw(s);
+// } else if (stroke) {
+// canvas.setColor(strokeColorObject);
+// canvas.draw(s);
+// }
+// }
+
+
+ protected void drawPath() {
+ if (fill) {
+ canvas.drawPath(path, fillPaint);
+ }
+ if (stroke) {
+ canvas.drawPath(path, strokePaint);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BOX
+
+
+ //public void box(float size)
+
+
+ @Override
+ public void box(float w, float h, float d) {
+ showMethodWarning("box");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SPHERE
+
+
+ //public void sphereDetail(int res)
+
+
+ //public void sphereDetail(int ures, int vres)
+
+
+ @Override
+ public void sphere(float r) {
+ showMethodWarning("sphere");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BEZIER
+
+
+ //public float bezierPoint(float a, float b, float c, float d, float t)
+
+
+ //public float bezierTangent(float a, float b, float c, float d, float t)
+
+
+ //protected void bezierInitCheck()
+
+
+ //protected void bezierInit()
+
+
+ /** Ignored (not needed) in Java 2D. */
+ @Override
+ public void bezierDetail(int detail) {
+ }
+
+
+ //public void bezier(float x1, float y1,
+ // float x2, float y2,
+ // float x3, float y3,
+ // float x4, float y4)
+
+
+ //public void bezier(float x1, float y1, float z1,
+ // float x2, float y2, float z2,
+ // float x3, float y3, float z3,
+ // float x4, float y4, float z4)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CURVE
+
+
+ //public float curvePoint(float a, float b, float c, float d, float t)
+
+
+ //public float curveTangent(float a, float b, float c, float d, float t)
+
+
+ /** Ignored (not needed) in Java 2D. */
+ @Override
+ public void curveDetail(int detail) {
+ }
+
+ //public void curveTightness(float tightness)
+
+
+ //protected void curveInitCheck()
+
+
+ //protected void curveInit()
+
+
+ //public void curve(float x1, float y1,
+ // float x2, float y2,
+ // float x3, float y3,
+ // float x4, float y4)
+
+
+ //public void curve(float x1, float y1, float z1,
+ // float x2, float y2, float z2,
+ // float x3, float y3, float z3,
+ // float x4, float y4, float z4)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SMOOTH
+
+
+ @Override
+ public void smooth(int quality) { // ignore
+ super.smooth(quality);
+// smooth = true;
+// canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+// RenderingHints.VALUE_ANTIALIAS_ON);
+// canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+// RenderingHints.VALUE_INTERPOLATION_BICUBIC);
+ strokePaint.setAntiAlias(true);
+ fillPaint.setAntiAlias(true);
+ }
+
+
+ @Override
+ public void noSmooth() {
+ super.noSmooth();
+// smooth = false;
+// canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+// RenderingHints.VALUE_ANTIALIAS_OFF);
+// canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+// RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
+ strokePaint.setAntiAlias(false);
+ fillPaint.setAntiAlias(false);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // IMAGE
+
+
+ //public void imageMode(int mode)
+
+
+ //public void image(PImage image, float x, float y)
+
+
+ //public void image(PImage image, float x, float y, float c, float d)
+
+
+ //public void image(PImage image,
+ // float a, float b, float c, float d,
+ // int u1, int v1, int u2, int v2)
+
+
+ Rect imageImplSrcRect;
+ RectF imageImplDstRect;
+ //android.widget.ImageView imv;
+
+ /**
+ * Handle renderer-specific image drawing.
+ */
+ @Override
+ protected void imageImpl(PImage src,
+ float x1, float y1, float x2, float y2,
+ int u1, int v1, int u2, int v2) {
+ Bitmap bitmap = (Bitmap)src.getNative();
+
+ if (bitmap != null && bitmap.isRecycled()) {
+ // Let's make sure it is recreated
+ bitmap = null;
+ }
+
+ if (bitmap == null && src.format == ALPHA) {
+ // create an alpha bitmap for this feller
+ bitmap = Bitmap.createBitmap(src.width, src.height, Config.ARGB_8888);
+ int[] px = new int[src.pixels.length];
+ for (int i = 0; i < px.length; i++) {
+ px[i] = src.pixels[i] << 24 | 0xFFFFFF;
+ }
+ bitmap.setPixels(px, 0, src.width, 0, 0, src.width, src.height);
+ modified = false;
+ src.setNative(bitmap);
+ }
+
+ // this version's not usable because it doesn't allow you to set output w/h
+// if (src.bitmap == null) { // format is ARGB or RGB
+// int offset = v1*src.width + u1;
+// canvas.drawBitmap(src.pixels, offset, src.width,
+// x1, y1, u2-u1, v2-v1,
+// src.format == ARGB, tint ? tintPaint : null);
+// } else {
+
+ if (bitmap == null ||
+ src.width != bitmap.getWidth() ||
+ src.height != bitmap.getHeight()) {
+ if (bitmap != null) bitmap.recycle();
+ bitmap = Bitmap.createBitmap(src.width, src.height, Config.ARGB_8888);
+ modified = true;
+ src.setNative(bitmap);
+ }
+
+ if (src.isModified()) {
+ //System.out.println("mutable, recycled = " + who.bitmap.isMutable() + ", " + who.bitmap.isRecycled());
+ if (!bitmap.isMutable()) {
+ bitmap.recycle();
+ bitmap = Bitmap.createBitmap(src.width, src.height, Config.ARGB_8888);
+ src.setNative(bitmap);
+ }
+ if (src.pixels != null) {
+ bitmap.setPixels(src.pixels, 0, src.width, 0, 0, src.width, src.height);
+ }
+ src.setModified(false);
+ }
+
+ if (imageImplSrcRect == null) {
+ imageImplSrcRect = new Rect(u1, v1, u2, v2);
+ imageImplDstRect = new RectF(x1, y1, x2, y2);
+ } else {
+ imageImplSrcRect.set(u1, v1, u2, v2);
+ imageImplDstRect.set(x1, y1, x2, y2);
+ }
+ //canvas.drawBitmap(who.bitmap, imageImplSrcRect, imageImplDstRect, tint ? tintPaint : null);
+ //System.out.println(PApplet.hex(fillPaint.getColor()));
+ //canvas.drawBitmap(who.bitmap, imageImplSrcRect, imageImplDstRect, fillPaint);
+ // System.out.println("drawing lower, tint = " + tint + " " + PApplet.hex(tintPaint.getColor()));
+ canvas.drawBitmap(bitmap, imageImplSrcRect, imageImplDstRect, tint ? tintPaint : null);
+
+ // If the OS things the memory is low, then recycles bitmaps automatically...
+ // but I don't think it is particularly efficient, as the bitmaps are stored
+ // in native heap for Android 10 and older.
+ MemoryInfo mi = new MemoryInfo();
+ Activity activity = parent.getSurface().getActivity();
+ if (activity == null) return;
+ ActivityManager activityManager = (ActivityManager) activity.getSystemService(android.content.Context.ACTIVITY_SERVICE);
+ activityManager.getMemoryInfo(mi);
+ if (mi.lowMemory) {
+ bitmap.recycle();
+ src.setNative(null);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPE
+
+
+ //public void shapeMode(int mode)
+
+
+ //public void shape(PShape shape)
+
+
+ //public void shape(PShape shape, float x, float y)
+
+
+ //public void shape(PShape shape, float x, float y, float c, float d)
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPE I/O
+
+
+ @Override
+ public PShape loadShape(String filename) {
+ String extension = PApplet.getExtension(filename);
+
+ PShapeSVG svg = null;
+
+ if (extension.equals("svg")) {
+ svg = new PShapeSVG(parent.loadXML(filename));
+
+ } else if (extension.equals("svgz")) {
+ try {
+ InputStream input = new GZIPInputStream(parent.createInput(filename));
+ XML xml = new XML(input);
+ svg = new PShapeSVG(xml);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ } else {
+ PGraphics.showWarning("Unsupported format");
+ }
+
+ return svg;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TEXT ATTRIBTUES
+
+
+ //public void textAlign(int align)
+
+
+ //public void textAlign(int alignX, int alignY)
+
+
+// public float textAscent() {
+// if (textFont == null) {
+// defaultFontOrDeath("textAscent");
+// }
+//// Font font = textFont.getFont();
+// Typeface font = textFont.getTypeface();
+// if (font == null) {
+// return super.textAscent();
+// }
+// return fillPaint.ascent();
+// }
+
+
+// public float textDescent() {
+// if (textFont == null) {
+// defaultFontOrDeath("textDescent");
+// }
+//// Font font = textFont.getFont();
+// Typeface font = textFont.getTypeface();
+// if (font == null) {
+// return super.textDescent();
+// }
+// return fillPaint.descent();
+// }
+
+
+ @Override
+ public void textFont(PFont which) {
+ super.textFont(which);
+ fillPaint.setTypeface((Typeface) which.getNative());
+ fillPaint.setTextSize(which.getDefaultSize());
+ }
+
+
+ @Override
+ public void textFont(PFont which, float size) {
+ super.textFont(which, size);
+ fillPaint.setTypeface((Typeface) which.getNative());
+ fillPaint.setTextSize(size);
+ }
+
+
+ //public void textLeading(float leading)
+
+
+ //public void textMode(int mode)
+
+
+ @Override
+ protected boolean textModeCheck(int mode) {
+ return mode == MODEL;
+ }
+
+
+ /**
+ * Same as parent, but override for native version of the font.
+ *
+ * Also gets called by textFont, so the metrics
+ * will get recorded properly.
+ */
+ @Override
+ public void textSize(float size) {
+ if (textFont == null) {
+ defaultFontOrDeath("textSize", size);
+ }
+
+ Typeface font = (Typeface) textFont.getNative();
+ if (font != null) {
+ fillPaint.setTextSize(size);
+ }
+
+ handleTextSize(size);
+ }
+
+
+ protected void beginTextScreenMode() {
+ loadPixels();
+ }
+
+ protected void endTextScreenMode() {
+ updatePixels();
+ }
+
+ //public float textWidth(char c)
+
+
+ //public float textWidth(String str)
+
+
+ @Override
+ protected float textWidthImpl(char buffer[], int start, int stop) {
+// Font font = textFont.getFont();
+ Typeface font = (Typeface) textFont.getNative();
+ if (font == null) {
+ return super.textWidthImpl(buffer, start, stop);
+ }
+ // maybe should use one of the newer/fancier functions for this?
+ int length = stop - start;
+// FontMetrics metrics = canvas.getFontMetrics(font);
+// return metrics.charsWidth(buffer, start, length);
+ return fillPaint.measureText(buffer, start, length);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TEXT
+
+ // None of the variations of text() are overridden from PGraphics.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TEXT IMPL
+
+
+ //protected void textLineAlignImpl(char buffer[], int start, int stop,
+ // float x, float y)
+
+
+ @Override
+ protected void textLineImpl(char buffer[], int start, int stop,
+ float x, float y) {
+ Typeface font = (Typeface) textFont.getNative();
+ if (font == null) {
+ showWarning("Inefficient font rendering: use createFont() with a TTF/OTF instead of loadFont().");
+ //new Exception().printStackTrace(System.out);
+ super.textLineImpl(buffer, start, stop, x, y);
+ return;
+ }
+
+ /*
+ // save the current setting for text smoothing. note that this is
+ // different from the smooth() function, because the font smoothing
+ // is controlled when the font is created, not now as it's drawn.
+ // fixed a bug in 0116 that handled this incorrectly.
+ Object textAntialias =
+ g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
+
+ // override the current text smoothing setting based on the font
+ // (don't change the global smoothing settings)
+ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+ textFont.smooth ?
+ RenderingHints.VALUE_ANTIALIAS_ON :
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ */
+
+// Object antialias =
+// canvas.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
+// if (antialias == null) {
+// // if smooth() and noSmooth() not called, this will be null (0120)
+// antialias = RenderingHints.VALUE_ANTIALIAS_DEFAULT;
+// }
+
+ // override the current smoothing setting based on the font
+ // also changes global setting for antialiasing, but this is because it's
+ // not possible to enable/disable them independently in some situations.
+// canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+// textFont.smooth ?
+// RenderingHints.VALUE_ANTIALIAS_ON :
+// RenderingHints.VALUE_ANTIALIAS_OFF);
+ fillPaint.setAntiAlias(textFont.isSmooth());
+
+ //System.out.println("setting frac metrics");
+ //g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
+ // RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+
+// canvas.setColor(fillColorObject);
+ int length = stop - start;
+// canvas.drawChars(buffer, start, length, (int) (x + 0.5f), (int) (y + 0.5f));
+ canvas.drawText(buffer, start, length, x, y, fillPaint);
+
+ // return to previous smoothing state if it was changed
+// canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias);
+ fillPaint.setAntiAlias(0 < smooth);
+
+// textX = x + textWidthImpl(buffer, start, stop);
+// textY = y;
+// textZ = 0; // this will get set by the caller if non-zero
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX STACK
+
+
+ @Override
+ public void pushMatrix() {
+ if (transformCount == transformStack.length) {
+ throw new RuntimeException("pushMatrix() cannot use push more than " +
+ transformStack.length + " times");
+ }
+ transform.get(transformStack[transformCount]);
+ transformCount++;
+
+// canvas.save();
+ }
+
+
+ @Override
+ public void popMatrix() {
+ if (transformCount == 0) {
+ throw new RuntimeException("missing a popMatrix() " +
+ "to go with that pushMatrix()");
+ }
+ transformCount--;
+ transform.set(transformStack[transformCount]);
+ updateTransformMatrix();
+
+ // Using canvas.restore() here and canvas.save() in popMatrix() and should achieve
+ // the same effect as setting copying transform into transformMatrix with updateTransformMatrix()
+ // and setting it below, although it has been reported that with the later approach, a push/pop
+ // would not result in the initial matrix state:
+ // https://github.com/processing/processing-android/issues/445
+ // However, cannot find
+ canvas.setMatrix(transformMatrix);
+// canvas.restore();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX TRANSFORMS
+
+
+ @Override
+ public void translate(float tx, float ty) {
+ transform.translate(tx, ty);
+ canvas.translate(tx, ty);
+ }
+
+
+ @Override
+ public void rotate(float angle) {
+ transform.rotate(angle);
+ canvas.rotate(angle * RAD_TO_DEG);
+ }
+
+
+ @Override
+ public void rotateX(float angle) {
+ showDepthWarning("rotateX");
+ }
+
+
+ @Override
+ public void rotateY(float angle) {
+ showDepthWarning("rotateY");
+ }
+
+
+ @Override
+ public void rotateZ(float angle) {
+ showDepthWarning("rotateZ");
+ }
+
+
+ @Override
+ public void rotate(float angle, float vx, float vy, float vz) {
+ showVariationWarning("rotate");
+ }
+
+
+ @Override
+ public void scale(float s) {
+ transform.scale(s, s);
+ canvas.scale(s, s);
+ }
+
+
+ @Override
+ public void scale(float sx, float sy) {
+ transform.scale(sx, sy);
+ canvas.scale(sx, sy);
+ }
+
+
+ @Override
+ public void scale(float sx, float sy, float sz) {
+ showDepthWarningXYZ("scale");
+ }
+
+
+ @Override
+ public void shearX(float angle) {
+ float t = (float) Math.tan(angle);
+ transform.apply(1, t, 0, 0, 1, 0);
+ canvas.skew(t, 0);
+ }
+
+
+ @Override
+ public void shearY(float angle) {
+ float t = (float) Math.tan(angle);
+ transform.apply(1, 0, 0, t, 1, 0);
+ canvas.skew(0, t);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX MORE
+
+
+ @Override
+ public void resetMatrix() {
+ transform.reset();
+ canvas.setMatrix(null);
+ }
+
+
+ //public void applyMatrix(PMatrix2D source)
+
+
+ @Override
+ public void applyMatrix(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ transform.apply(n00, n01, n02, n10, n11, n12);
+ updateTransformMatrix();
+ canvas.concat(transformMatrix);
+ }
+
+
+ //public void applyMatrix(PMatrix3D source)
+
+
+ @Override
+ public void applyMatrix(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+ showVariationWarning("applyMatrix");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX GET/SET
+
+
+ @Override
+ public PMatrix getMatrix() {
+ return getMatrix((PMatrix2D) null);
+ }
+
+
+ @Override
+ public PMatrix2D getMatrix(PMatrix2D target) {
+ if (target == null) {
+ target = new PMatrix2D();
+ }
+ target.set(transform);
+ return target;
+ }
+
+
+ @Override
+ public PMatrix3D getMatrix(PMatrix3D target) {
+ showVariationWarning("getMatrix");
+ return target;
+ }
+
+
+ //public void setMatrix(PMatrix source)
+
+
+ @Override
+ public void setMatrix(PMatrix2D source) {
+ transform.set(source);
+ updateTransformMatrix();
+ canvas.setMatrix(transformMatrix);
+ }
+
+
+ @Override
+ public void setMatrix(PMatrix3D source) {
+ showVariationWarning("setMatrix");
+ }
+
+
+ @Override
+ public void printMatrix() {
+ getMatrix((PMatrix2D) null).print();
+ }
+
+
+ protected Matrix getMatrixImp() {
+ Matrix m = new Matrix();
+ updateTransformMatrix();
+ m.set(transformMatrix);
+ return m;
+// return canvas.getMatrix();
+ }
+
+
+ public void updateTransformMatrix() {
+ transformArray[0] = transform.m00;
+ transformArray[1] = transform.m01;
+ transformArray[2] = transform.m02;
+ transformArray[3] = transform.m10;
+ transformArray[4] = transform.m11;
+ transformArray[5] = transform.m12;
+ transformArray[6] = 0;
+ transformArray[7] = 0;
+ transformArray[8] = 1;
+ transformMatrix.setValues(transformArray);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CAMERA and PROJECTION
+
+ // Inherit the plaintive warnings from PGraphics
+
+
+ //public void beginCamera()
+ //public void endCamera()
+ //public void camera()
+ //public void camera(float eyeX, float eyeY, float eyeZ,
+ // float centerX, float centerY, float centerZ,
+ // float upX, float upY, float upZ)
+ //public void printCamera()
+
+ //public void ortho()
+ //public void ortho(float left, float right,
+ // float bottom, float top,
+ // float near, float far)
+ //public void perspective()
+ //public void perspective(float fov, float aspect, float near, float far)
+ //public void frustum(float left, float right,
+ // float bottom, float top,
+ // float near, float far)
+ //public void printProjection()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SCREEN and MODEL transforms
+
+ float[] screenPoint;
+
+ @Override
+ public float screenX(float x, float y) {
+ if (screenPoint == null) {
+ screenPoint = new float[2];
+ }
+ screenPoint[0] = x;
+ screenPoint[1] = y;
+ getMatrixImp().mapPoints(screenPoint);
+ return screenPoint[0];
+ }
+
+
+ @Override
+ public float screenY(float x, float y) {
+ if (screenPoint == null) {
+ screenPoint = new float[2];
+ }
+ screenPoint[0] = x;
+ screenPoint[1] = y;
+ getMatrixImp().mapPoints(screenPoint);
+ return screenPoint[1];
+ }
+
+
+ @Override
+ public float screenX(float x, float y, float z) {
+ showDepthWarningXYZ("screenX");
+ return 0;
+ }
+
+
+ @Override
+ public float screenY(float x, float y, float z) {
+ showDepthWarningXYZ("screenY");
+ return 0;
+ }
+
+
+ @Override
+ public float screenZ(float x, float y, float z) {
+ showDepthWarningXYZ("screenZ");
+ return 0;
+ }
+
+
+ //public float modelX(float x, float y, float z)
+
+
+ //public float modelY(float x, float y, float z)
+
+
+ //public float modelZ(float x, float y, float z)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STYLE
+
+ // pushStyle(), popStyle(), style() and getStyle() inherited.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STROKE CAP/JOIN/WEIGHT
+
+
+ @Override
+ public void strokeCap(int cap) {
+ super.strokeCap(cap);
+
+ if (strokeCap == ROUND) {
+ strokePaint.setStrokeCap(Paint.Cap.ROUND);
+ } else if (strokeCap == PROJECT) {
+ strokePaint.setStrokeCap(Paint.Cap.SQUARE);
+ } else {
+ strokePaint.setStrokeCap(Paint.Cap.BUTT);
+ }
+ }
+
+
+ @Override
+ public void strokeJoin(int join) {
+ super.strokeJoin(join);
+
+ if (strokeJoin == MITER) {
+ strokePaint.setStrokeJoin(Paint.Join.MITER);
+ } else if (strokeJoin == ROUND) {
+ strokePaint.setStrokeJoin(Paint.Join.ROUND);
+ } else {
+ strokePaint.setStrokeJoin(Paint.Join.BEVEL);
+ }
+ }
+
+
+ @Override
+ public void strokeWeight(float weight) {
+ super.strokeWeight(weight);
+ strokePaint.setStrokeWidth(weight);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STROKE
+
+ // noStroke() and stroke() inherited from PGraphics.
+
+
+ @Override
+ protected void strokeFromCalc() {
+ super.strokeFromCalc();
+// strokeColorObject = new Color(strokeColor, true);
+ strokePaint.setColor(strokeColor);
+// strokeGradient = false;
+ strokePaint.setShader(null);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TINT
+
+ // noTint() and tint() inherited from PGraphics.
+
+
+ @Override
+ protected void tintFromCalc() {
+ super.tintFromCalc();
+ tintPaint.setColorFilter(new PorterDuffColorFilter(tintColor, PorterDuff.Mode.MULTIPLY));
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILL
+
+ // noFill() and fill() inherited from PGraphics.
+
+
+ @Override
+ protected void fillFromCalc() {
+ super.fillFromCalc();
+// fillColorObject = new Color(fillColor, true);
+ fillPaint.setColor(fillColor);
+// fillGradient = false;
+ fillPaint.setShader(null);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATERIAL PROPERTIES
+
+
+ //public void ambient(int rgb)
+ //public void ambient(float gray)
+ //public void ambient(float x, float y, float z)
+ //protected void ambientFromCalc()
+ //public void specular(int rgb)
+ //public void specular(float gray)
+ //public void specular(float x, float y, float z)
+ //protected void specularFromCalc()
+ //public void shininess(float shine)
+ //public void emissive(int rgb)
+ //public void emissive(float gray)
+ //public void emissive(float x, float y, float z )
+ //protected void emissiveFromCalc()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // LIGHTS
+
+
+ //public void lights()
+ //public void noLights()
+ //public void ambientLight(float red, float green, float blue)
+ //public void ambientLight(float red, float green, float blue,
+ // float x, float y, float z)
+ //public void directionalLight(float red, float green, float blue,
+ // float nx, float ny, float nz)
+ //public void pointLight(float red, float green, float blue,
+ // float x, float y, float z)
+ //public void spotLight(float red, float green, float blue,
+ // float x, float y, float z,
+ // float nx, float ny, float nz,
+ // float angle, float concentration)
+ //public void lightFalloff(float constant, float linear, float quadratic)
+ //public void lightSpecular(float x, float y, float z)
+ //protected void lightPosition(int num, float x, float y, float z)
+ //protected void lightDirection(int num, float x, float y, float z)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BACKGROUND
+
+ // background() methods inherited from PGraphics, along with the
+ // PImage version of backgroundImpl(), since it just calls set().
+
+
+ //public void backgroundImpl(PImage image)
+
+
+// int[] clearPixels;
+
+ @Override
+ public void backgroundImpl() {
+ canvas.drawColor(backgroundColor);
+
+// if (backgroundAlpha) {
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// if ((clearPixels == null) || (clearPixels.length < width)) {
+// clearPixels = new int[width];
+// }
+// java.util.Arrays.fill(clearPixels, backgroundColor);
+// for (int i = 0; i < height; i++) {
+// raster.setDataElements(0, i, width, 1, clearPixels);
+// }
+// } else {
+// //new Exception().printStackTrace(System.out);
+// // in case people do transformations before background(),
+// // need to handle this with a push/reset/pop
+// pushMatrix();
+// resetMatrix();
+// canvas.setColor(new Color(backgroundColor)); //, backgroundAlpha));
+// canvas.fillRect(0, 0, width, height);
+// popMatrix();
+// }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR MODE
+
+ // All colorMode() variations are inherited from PGraphics.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR CALC
+
+ // colorCalc() and colorCalcARGB() inherited from PGraphics.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR DATATYPE STUFFING
+
+ // final color() variations inherited.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR DATATYPE EXTRACTION
+
+ // final methods alpha, red, green, blue,
+ // hue, saturation, and brightness all inherited.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR DATATYPE INTERPOLATION
+
+ // both lerpColor variants inherited.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BEGIN/END RAW
+
+
+ @Override
+ public void beginRaw(PGraphics recorderRaw) {
+ showMethodWarning("beginRaw");
+ }
+
+
+ @Override
+ public void endRaw() {
+ showMethodWarning("endRaw");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // WARNINGS and EXCEPTIONS
+
+ // showWarning and showException inherited.
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RENDERER SUPPORT QUERIES
+
+
+ //public boolean displayable() // true
+
+
+ //public boolean is2D() // true
+
+
+ //public boolean is3D() // false
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // PIMAGE METHODS
+
+
+ // getImage, setCache, getCache, removeCache, isModified, setModified
+
+
+ @Override
+ public void loadPixels() {
+ if (bitmap == null) {
+ throw new RuntimeException("The pixels array is not available in this " +
+ "renderer withouth a backing bitmap");
+ }
+
+ if ((pixels == null) || (pixels.length != width * height)) {
+ pixels = new int[width * height];
+ }
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// raster.getDataElements(0, 0, width, height, pixels);
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
+ }
+
+
+ /**
+ * Update the pixels[] buffer to the PGraphics image.
+ *
+ * Unlike in PImage, where updatePixels() only requests that the
+ * update happens, in PGraphicsJava2D, this will happen immediately.
+ */
+ @Override
+ public void updatePixels() {
+ if (bitmap == null) {
+ throw new RuntimeException("The pixels array is not available in this " +
+ "renderer withouth a backing bitmap");
+ }
+
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// raster.setDataElements(0, 0, width, height, pixels);
+ bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
+ }
+
+
+ /**
+ * Update the pixels[] buffer to the PGraphics image.
+ *
+ * Unlike in PImage, where updatePixels() only requests that the
+ * update happens, in PGraphicsJava2D, this will happen immediately.
+ */
+ @Override
+ public void updatePixels(int x, int y, int c, int d) {
+ //if ((x == 0) && (y == 0) && (c == width) && (d == height)) {
+ if ((x != 0) || (y != 0) || (c != width) || (d != height)) {
+ // Show a warning message, but continue anyway.
+ showVariationWarning("updatePixels(x, y, w, h)");
+ }
+ updatePixels();
+ }
+
+
+ @Override
+ public void resize(int wide, int high) {
+ showMethodWarning("resize");
+ }
+
+
+ @Override
+ protected void clearState() {
+ super.clearState();
+ if (restoreFilename != null) {
+ File cacheFile = new File(restoreFilename);
+ cacheFile.delete();
+ }
+ }
+
+
+ @Override
+ protected void saveState() {
+ super.saveState();
+
+ Context context = parent.getContext();
+ if (context == null || bitmap == null || parent.getSurface().getComponent().isService()) return;
+ try {
+ // Saving current width and height to avoid restoring the screen after a screen rotation
+ restoreWidth = pixelWidth;
+ restoreHeight = pixelHeight;
+
+ int size = bitmap.getHeight() * bitmap.getRowBytes();
+ ByteBuffer restoreBitmap = ByteBuffer.allocate(size);
+ bitmap.copyPixelsToBuffer(restoreBitmap);
+
+ // Tries to use external but if not mounted, falls back on internal storage, as shown in
+ // https://developer.android.com/topic/performance/graphics/cache-bitmap#java
+ File cacheDir = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !isExternalStorageRemovable() ?
+ context.getExternalCacheDir() : context.getCacheDir();
+ File cacheFile = new File(cacheDir + File.separator + "restore_pixels");
+ restoreFilename = cacheFile.getAbsolutePath();
+
+ FileOutputStream stream = new FileOutputStream(cacheFile);
+ ObjectOutputStream dout = new ObjectOutputStream(stream);
+ byte[] array = new byte[size];
+ restoreBitmap.rewind();
+ restoreBitmap.get(array);
+ dout.writeObject(array);
+ dout.flush();
+ stream.getFD().sync();
+ stream.close();
+ } catch (Exception ex) {
+ PGraphics.showWarning("Could not save screen contents to cache");
+ ex.printStackTrace();
+ }
+ }
+
+
+ @Override
+ protected void restoreSurface() {
+ if (changed) {
+ changed = false;
+ if (restoreFilename != null && restoreWidth == pixelWidth && restoreHeight == pixelHeight) {
+ // Set the counter to 1 so the restore bitmap is drawn in the next frame.
+ restoreCount = 1;
+ }
+ } else if (restoreCount > 0) {
+ restoreCount--;
+ if (restoreCount == 0) {
+ Context context = parent.getContext();
+ if (context == null) return;
+ try {
+ // Load cached bitmap and draw
+ File cacheFile = new File(restoreFilename);
+ FileInputStream inStream = new FileInputStream(cacheFile);
+ ObjectInputStream din = new ObjectInputStream(inStream);
+ byte[] array = (byte[]) din.readObject();
+ ByteBuffer restoreBitmap = ByteBuffer.wrap(array);
+ if (restoreBitmap.capacity() == bitmap.getHeight() * bitmap.getRowBytes()) {
+ restoreBitmap.rewind();
+ bitmap.copyPixelsFromBuffer(restoreBitmap);
+ }
+ inStream.close();
+ cacheFile.delete();
+ } catch (Exception ex) {
+ PGraphics.showWarning("Could not restore screen contents from cache");
+ ex.printStackTrace();
+ } finally {
+ restoreFilename = null;
+ restoreWidth = -1;
+ restoreHeight = -1;
+ restoredSurface = true;
+ }
+ }
+ }
+ super.restoreSurface();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // GET/SET
+
+
+ static int getset[] = new int[1];
+
+
+ @Override
+ public int get(int x, int y) {
+ if ((bitmap == null) || (x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0;
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// raster.getDataElements(x, y, getset);
+// return getset[0];
+ return bitmap.getPixel(x, y);
+ }
+
+
+ //public PImage get(int x, int y, int w, int h)
+
+
+// @Override
+// public PImage getImpl(int x, int y, int w, int h) {
+// PImage output = new PImage();
+// output.width = w;
+// output.height = h;
+// output.parent = parent;
+//
+// Bitmap bitsy = Bitmap.createBitmap(bitmap, x, y, w, h);
+// // guessing it's more efficient to use Bitmap instead of pixels[]
+// //bitsy.getPixels(output.pixels, 0, w, 0, 0, w, h);
+// output.bitmap = bitsy;
+//
+// return output;
+// }
+
+
+ @Override
+ public PImage get() {
+ return get(0, 0, width, height);
+ }
+
+
+ @Override
+ public void set(int x, int y, int argb) {
+ if ((bitmap == null) || (x < 0) || (y < 0) || (x >= width) || (y >= height)) return;
+// getset[0] = argb;
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// raster.setDataElements(x, y, getset);
+ bitmap.setPixel(x, y, argb);
+ }
+
+
+ @Override
+ public void set(int x, int y, PImage src) {
+ if (src.format == ALPHA) {
+ // set() doesn't really make sense for an ALPHA image, since it
+ // directly replaces pixels and does no blending.
+ throw new RuntimeException("set() not available for ALPHA images");
+ }
+
+ Bitmap bitmap = (Bitmap)src.getNative();
+ if (bitmap == null) {
+ bitmap = Bitmap.createBitmap(src.width, src.height, Config.ARGB_8888);
+ src.setNative(bitmap);
+ src.setModified();
+ }
+ if (src.width != bitmap.getWidth() ||
+ src.height != bitmap.getHeight()) {
+ bitmap.recycle();
+ bitmap = Bitmap.createBitmap(src.width, src.height, Config.ARGB_8888);
+ src.setNative(bitmap);
+ src.setModified();
+ }
+ if (src.isModified()) {
+ if (!bitmap.isMutable()) {
+ bitmap.recycle();
+ bitmap = Bitmap.createBitmap(src.width, src.height, Config.ARGB_8888);
+ setNative(bitmap);
+ }
+ bitmap.setPixels(src.pixels, 0, src.width, 0, 0, src.width, src.height);
+ src.setModified(false);
+ }
+ // set() happens in screen coordinates, so need to clear the ctm
+ pushMatrix();
+ canvas.setMatrix(null); // set to identity
+ canvas.drawBitmap(bitmap, x, y, null);
+ popMatrix();
+ }
+
+
+ // elaborate but silly version, since android will happily do this work
+// private Rect setImplSrcRect;
+// private Rect setImplDstRect;
+//
+// protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh,
+// PImage src) {
+// if (setImplSrcRect == null) {
+// setImplSrcRect = new Rect(sx, sy, sx+sw, sy+sh);
+// setImplDstRect = new Rect(dx, dy, dx+sw, dy+sh);
+// } else {
+// setImplSrcRect.set(sx, sy, sx+sw, sy+sh);
+// setImplDstRect.set(dx, dy, dx+sw, dy+sh);
+// }
+// // set() happens in screen coordinates, so need to nuke the ctm
+// canvas.save(Canvas.MATRIX_SAVE_FLAG);
+// canvas.setMatrix(null); // set to identity
+// canvas.drawBitmap(src.image, setImplSrcRect, setImplDstRect, null);
+// canvas.restore();
+// }
+
+ // PImage version
+// 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);
+
+ // PGraphicsJava2D version
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// if ((sx == 0) && (sy == 0) && (sw == src.width) && (sh == src.height)) {
+// raster.setDataElements(dx, dy, src.width, src.height, src.pixels);
+// } else {
+// // TODO Optimize, incredibly inefficient to reallocate this much memory
+// PImage temp = src.get(sx, sy, sw, sh);
+// raster.setDataElements(dx, dy, temp.width, temp.height, temp.pixels);
+// }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MASK
+
+
+ @Override
+ public void mask(int alpha[]) {
+ showMethodWarning("mask");
+ }
+
+
+ @Override
+ public void mask(PImage alpha) {
+ showMethodWarning("mask");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILTER
+
+ // Because the PImage versions call loadPixels() and
+ // updatePixels(), no need to override anything here.
+
+
+ //public void filter(int kind)
+
+
+ //public void filter(int kind, float param)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COPY
+
+
+ @Override
+ public void copy(int sx, int sy, int sw, int sh,
+ int dx, int dy, int dw, int dh) {
+ if (bitmap == null) {
+ throw new RuntimeException("The pixels array is not available in this " +
+ "renderer withouth a backing bitmap");
+ }
+
+// Bitmap bitsy = Bitmap.createBitmap(image, sx, sy, sw, sh);
+// rect.set(dx, dy, dx + dw, dy + dh);
+// canvas.drawBitmap(bitsy,
+ rect.set(dx, dy, dx+dw, dy+dh);
+ Rect src = new Rect(sx, sy, sx+sw, sy+sh);
+ canvas.drawBitmap(bitmap, src, rect, null);
+
+// if ((sw != dw) || (sh != dh)) {
+// // use slow version if changing size
+// copy(this, sx, sy, sw, sh, dx, dy, dw, dh);
+//
+// } else {
+// dx = dx - sx; // java2d's "dx" is the delta, not dest
+// dy = dy - sy;
+// canvas.copyArea(sx, sy, sw, sh, dx, dy);
+// }
+ }
+
+
+// public void copy(PImage src,
+// int sx1, int sy1, int sx2, int sy2,
+// int dx1, int dy1, int dx2, int dy2) {
+// loadPixels();
+// super.copy(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2);
+// updatePixels();
+// }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BLEND
+
+
+// static public int blendColor(int c1, int c2, int mode)
+
+
+// public void blend(int sx, int sy, int sw, int sh,
+// int dx, int dy, int dw, int dh, int mode)
+
+
+// public void blend(PImage src,
+// int sx, int sy, int sw, int sh,
+// int dx, int dy, int dw, int dh, int mode)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SAVE
+
+
+// public void save(String filename) {
+// loadPixels();
+// super.save(filename);
+// }
+}
\ No newline at end of file
diff --git a/core-androidx/src/processing/a2d/PShapeAndroid2D.java b/core-androidx/src/processing/a2d/PShapeAndroid2D.java
new file mode 100644
index 000000000..e5ace2266
--- /dev/null
+++ b/core-androidx/src/processing/a2d/PShapeAndroid2D.java
@@ -0,0 +1,109 @@
+package processing.a2d;
+
+import android.graphics.Shader;
+import processing.core.PGraphics;
+import processing.core.PShapeSVG;
+import processing.data.XML;
+
+public class PShapeAndroid2D extends PShapeSVG {
+ protected Shader strokeGradientPaint;
+ protected Shader fillGradientPaint;
+
+
+ public PShapeAndroid2D(XML svg) {
+ super(svg);
+ }
+
+
+ public PShapeAndroid2D(PShapeSVG parent, XML properties, boolean parseKids) {
+ super(parent, properties, parseKids);
+ }
+
+
+ @Override
+ protected void setParent(PShapeSVG parent) {
+ super.setParent(parent);
+
+ if (parent instanceof PShapeAndroid2D) {
+ PShapeAndroid2D pj = (PShapeAndroid2D) parent;
+ fillGradientPaint = pj.fillGradientPaint;
+ strokeGradientPaint = pj.strokeGradientPaint;
+
+ } else { // parent is null or not Android2D
+ fillGradientPaint = null;
+ strokeGradientPaint = null;
+ }
+ }
+
+
+ /** Factory method for subclasses. */
+ @Override
+ protected PShapeSVG createShape(PShapeSVG parent, XML properties, boolean parseKids) {
+ return new PShapeAndroid2D(parent, properties, parseKids);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ protected Shader calcGradientPaint(Gradient gradient) {
+ // TODO just do this with the other parsing
+ int[] colors = new int[gradient.count];
+ int opacityMask = ((int) (opacity * 255)) << 24;
+ for (int i = 0; i < gradient.count; i++) {
+ colors[i] = opacityMask | (gradient.color[i] & 0xFFFFFF);
+ }
+
+ if (gradient instanceof LinearGradient) {
+ LinearGradient grad = (LinearGradient) gradient;
+// return new LinearGradientPaint(grad.x1, grad.y1, grad.x2, grad.y2,
+// grad.offset, grad.color, grad.count,
+// opacity);
+ return new android.graphics.LinearGradient(grad.x1, grad.y1,
+ grad.x2, grad.y2,
+ colors, grad.offset,
+ Shader.TileMode.CLAMP );
+
+ } else if (gradient instanceof RadialGradient) {
+ RadialGradient grad = (RadialGradient) gradient;
+// return new RadialGradientPaint(grad.cx, grad.cy, grad.r,
+// grad.offset, grad.color, grad.count,
+// opacity);
+ return new android.graphics.RadialGradient(grad.cx, grad.cy, grad.r,
+ colors, grad.offset,
+ Shader.TileMode.CLAMP);
+ }
+ return null;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ @Override
+ protected void styles(PGraphics g) {
+ super.styles(g);
+
+ if (g instanceof PGraphicsAndroid2D) {
+ PGraphicsAndroid2D gg = (PGraphicsAndroid2D) g;
+
+ if (strokeGradient != null) {
+// gg.strokeGradient = true;
+ if (strokeGradientPaint == null) {
+ strokeGradientPaint = calcGradientPaint(strokeGradient);
+ }
+ gg.strokePaint.setShader(strokeGradientPaint);
+ }
+ if (fillGradient != null) {
+// gg.fillGradient = true;
+ if (fillGradientPaint == null) {
+ fillGradientPaint = calcGradientPaint(fillGradient);
+ }
+ gg.fillPaint.setShader(fillGradientPaint);
+ } else {
+ // need to shut off, in case parent object has a gradient applied
+ //gg.fillGradient = false;
+ }
+ }
+ }
+}
diff --git a/core-androidx/src/processing/a2d/PSurfaceAndroid2D.java b/core-androidx/src/processing/a2d/PSurfaceAndroid2D.java
new file mode 100644
index 000000000..47297ea25
--- /dev/null
+++ b/core-androidx/src/processing/a2d/PSurfaceAndroid2D.java
@@ -0,0 +1,159 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.a2d;
+
+import android.content.Context;
+
+import android.graphics.Color;
+import android.graphics.PixelFormat;
+import android.service.wallpaper.WallpaperService;
+import android.support.wearable.watchface.CanvasWatchFaceService;
+import android.view.MotionEvent;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import processing.android.AppComponent;
+import processing.android.PFragment;
+import processing.core.PApplet;
+import processing.core.PGraphics;
+import processing.core.PSurfaceNone;
+
+public class PSurfaceAndroid2D extends PSurfaceNone {
+
+ public PSurfaceAndroid2D() { }
+
+ public PSurfaceAndroid2D(PGraphics graphics, AppComponent component, SurfaceHolder holder) {
+ this.sketch = graphics.parent;
+ this.graphics = graphics;
+ this.component = component;
+ if (component.getKind() == AppComponent.FRAGMENT) {
+ PFragment frag = (PFragment)component;
+ activity = frag.getActivity();
+ surfaceView = new SurfaceViewAndroid2D(activity, null);
+ } else if (component.getKind() == AppComponent.WALLPAPER) {
+ wallpaper = (WallpaperService)component;
+ surfaceView = new SurfaceViewAndroid2D(wallpaper, holder);
+ } else if (component.getKind() == AppComponent.WATCHFACE) {
+ watchface = (CanvasWatchFaceService)component;
+ surfaceView = null;
+ // Set as ready here, as watch faces don't have a surface view with a
+ // surfaceCreate() event to do it.
+ surfaceReady = true;
+ }
+ }
+
+ ///////////////////////////////////////////////////////////
+
+ // SurfaceView
+
+ public class SurfaceViewAndroid2D extends SurfaceView implements SurfaceHolder.Callback {
+ SurfaceHolder holder;
+
+ public SurfaceViewAndroid2D(Context context, SurfaceHolder holder) {
+ super(context);
+ this.holder = holder;
+
+// println("surface holder");
+ // Install a SurfaceHolder.Callback so we get notified when the
+ // underlying surface is created and destroyed
+ SurfaceHolder h = getHolder();
+ h.addCallback(this);
+// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); // no longer needed.
+
+// println("setting focusable, requesting focus");
+ setFocusable(true);
+ setFocusableInTouchMode(true);
+ requestFocus();
+// println("done making surface view");
+
+ surfaceReady = false; // Will be ready when the surfaceCreated() event is called
+
+ // Solves screen flickering:
+ // https://github.com/processing/processing-android/issues/570
+ setBackgroundColor(Color.argb(0, 0, 0, 0));
+ getHolder().setFormat(PixelFormat.TRANSPARENT);
+ }
+
+ @Override
+ public SurfaceHolder getHolder() {
+ if (holder == null) {
+ return super.getHolder();
+ } else {
+ return holder;
+ }
+ }
+
+ // part of SurfaceHolder.Callback
+ public void surfaceCreated(SurfaceHolder holder) {
+ surfaceReady = true;
+ if (requestedThreadStart) {
+ // Only start the thread once the surface has been created, otherwise it will not be able to draw
+ startThread();
+ }
+ if (PApplet.DEBUG) {
+ System.out.println("surfaceCreated()");
+ }
+ }
+
+
+ // part of SurfaceHolder.Callback
+ public void surfaceDestroyed(SurfaceHolder holder) {
+ if (PApplet.DEBUG) {
+ System.out.println("surfaceDestroyed()");
+ }
+ }
+
+
+ // part of SurfaceHolder.Callback
+ public void surfaceChanged(SurfaceHolder holder, int format, int iwidth, int iheight) {
+ if (PApplet.DEBUG) {
+ System.out.println("SketchSurfaceView.surfaceChanged() " + iwidth + " " + iheight);
+ }
+
+ sketch.surfaceChanged();
+ sketch.setSize(iwidth, iheight);
+ }
+
+ @Override
+ public void onWindowFocusChanged(boolean hasFocus) {
+ super.onWindowFocusChanged(hasFocus);
+ sketch.surfaceWindowFocusChanged(hasFocus);
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent event) {
+ return sketch.surfaceTouchEvent(event);
+ }
+
+ @Override
+ public boolean onKeyDown(int code, android.view.KeyEvent event) {
+ sketch.surfaceKeyDown(code, event);
+ return super.onKeyDown(code, event);
+ }
+
+ @Override
+ public boolean onKeyUp(int code, android.view.KeyEvent event) {
+ sketch.surfaceKeyUp(code, event);
+ return super.onKeyUp(code, event);
+ }
+ }
+}
diff --git a/core-androidx/src/processing/android/ActivityAPI.java b/core-androidx/src/processing/android/ActivityAPI.java
new file mode 100644
index 000000000..e668ea63d
--- /dev/null
+++ b/core-androidx/src/processing/android/ActivityAPI.java
@@ -0,0 +1,65 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016-17 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.ContextMenu;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.Window;
+import android.app.FragmentManager;
+
+
+// Methods that should be implemented in PApplet to maintain backward
+// compatibility with (some) functionality available from Activity/Fragment
+public interface ActivityAPI {
+ // Lifecycle events
+ public void onCreate(Bundle savedInstanceState);
+ public void onDestroy();
+ public void onStart();
+ public void onStop();
+ public void onPause();
+ public void onResume();
+
+ // Activity and intent events
+ public void onActivityResult(int requestCode, int resultCode, Intent data);
+ public void onNewIntent(Intent intent);
+
+ // Menu API
+ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater);
+ public boolean onOptionsItemSelected(MenuItem item);
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
+ public boolean onContextItemSelected(MenuItem item);
+ public void setHasOptionsMenu(boolean hasMenu);
+
+ // IO events
+ public void onBackPressed();
+
+ // Activity management
+ public FragmentManager getFragmentManager();
+ public Window getWindow();
+}
diff --git a/core-androidx/src/processing/android/AppComponent.java b/core-androidx/src/processing/android/AppComponent.java
new file mode 100644
index 000000000..1574061ee
--- /dev/null
+++ b/core-androidx/src/processing/android/AppComponent.java
@@ -0,0 +1,51 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016-17 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import android.content.Intent;
+import processing.core.PApplet;
+import processing.core.PConstants;
+
+abstract public interface AppComponent extends PConstants {
+ static public final int FRAGMENT = 0;
+ static public final int WALLPAPER = 1;
+ static public final int WATCHFACE = 2;
+
+ public void initDimensions();
+ public int getDisplayWidth();
+ public int getDisplayHeight();
+ public float getDisplayDensity();
+ public int getKind();
+ public void setSketch(PApplet sketch);
+ public PApplet getSketch();
+
+ public boolean isService();
+ public ServiceEngine getEngine();
+
+ public void startActivity(Intent intent);
+
+ public void requestDraw();
+ public boolean canDraw();
+
+ public void dispose();
+}
diff --git a/core-androidx/src/processing/android/CompatUtils.java b/core-androidx/src/processing/android/CompatUtils.java
new file mode 100644
index 000000000..b4f8f55bd
--- /dev/null
+++ b/core-androidx/src/processing/android/CompatUtils.java
@@ -0,0 +1,111 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2017 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicInteger;
+import android.annotation.SuppressLint;
+import android.os.Build;
+import android.util.DisplayMetrics;
+import android.view.Display;
+import android.view.View;
+import android.graphics.Point;
+
+/**
+ * Compatibility utilities that work across versions of Android. Even though
+ * the mode sets API level 17 (Android 4.2) as the minimum target, because the
+ * core library could be used from another IDE and lower targets, then this
+ * compatibility methods are still needed.
+ */
+public class CompatUtils {
+ // Start at 15,000,000, taking into account the comment from Singed
+ // http://stackoverflow.com/a/39307421
+ private static final AtomicInteger nextId = new AtomicInteger(15000000);
+
+
+ /**
+ * This method retrieves the "real" display metrics and size, without
+ * subtracting any window decor or applying any compatibility scale factors.
+ * @param display the Display object
+ * @param metrics the metrics to retrieve
+ * @param size the size to retrieve
+ */
+ static public void getDisplayParams(Display display,
+ DisplayMetrics metrics, Point size) {
+ if (Build.VERSION_CODES.JELLY_BEAN_MR1 <= Build.VERSION.SDK_INT) {
+ display.getRealMetrics(metrics);
+ display.getRealSize(size);
+ } if (Build.VERSION_CODES.ICE_CREAM_SANDWICH <= Build.VERSION.SDK_INT) {
+ display.getMetrics(metrics);
+ // Use undocumented methods getRawWidth, getRawHeight
+ try {
+ size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
+ size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
+ } catch (Exception e) {
+ display.getSize(size);
+ }
+ } else {
+ display.getMetrics(metrics);
+ display.getSize(size);
+ }
+ }
+
+
+ /**
+ * This method generates a unique View ID's. Handles the lack of
+ * View.generateViewId() in Android versions lower than 17, using a technique
+ * based on fantouch's code at http://stackoverflow.com/a/21000252
+ * @return view ID
+ */
+ @SuppressLint("NewApi")
+ static public int getUniqueViewId() {
+ if (Build.VERSION_CODES.JELLY_BEAN_MR1 <= Build.VERSION.SDK_INT) {
+ return View.generateViewId();
+ } else {
+ for (;;) {
+ final int result = nextId.get();
+ // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
+ int newValue = result + 1;
+ if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
+ if (nextId.compareAndSet(result, newValue)) {
+ return result;
+ }
+ }
+ }
+ }
+
+
+ /**
+ * This method returns the UTF-8 charset
+ * @return UTF-8 charset
+ */
+ @SuppressLint("NewApi")
+ static public Charset getCharsetUTF8() {
+ if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
+ return StandardCharsets.UTF_8;
+ } else {
+ return Charset.forName("UTF-8");
+ }
+ }
+}
diff --git a/core-androidx/src/processing/android/PFragment.java b/core-androidx/src/processing/android/PFragment.java
new file mode 100644
index 000000000..08e245bca
--- /dev/null
+++ b/core-androidx/src/processing/android/PFragment.java
@@ -0,0 +1,259 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016-17 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import androidx.annotation.IdRes;
+import androidx.annotation.LayoutRes;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
+import androidx.fragment.app.FragmentManager;
+import androidx.fragment.app.FragmentTransaction;
+import android.util.DisplayMetrics;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.res.Configuration;
+import android.graphics.Point;
+import android.os.Bundle;
+import android.view.ContextMenu;
+import android.view.Display;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.view.ContextMenu.ContextMenuInfo;
+import processing.core.PApplet;
+
+public class PFragment extends Fragment implements AppComponent {
+ private DisplayMetrics metrics;
+ private Point size;
+ private PApplet sketch;
+ private @LayoutRes int layout = -1;
+
+
+ public PFragment() {
+ super();
+ }
+
+
+ public PFragment(PApplet sketch) {
+ super();
+ setSketch(sketch);
+ }
+
+
+ public void initDimensions() {
+ metrics = new DisplayMetrics();
+ size = new Point();
+ WindowManager wm = getActivity().getWindowManager();
+ Display display = wm.getDefaultDisplay();
+ CompatUtils.getDisplayParams(display, metrics, size);
+ }
+
+
+ public int getDisplayWidth() {
+ return size.x;
+ }
+
+
+ public int getDisplayHeight() {
+ return size.y;
+ }
+
+
+ public float getDisplayDensity() {
+ return metrics.density;
+ }
+
+
+ public int getKind() {
+ return FRAGMENT;
+ }
+
+
+ public void setSketch(PApplet sketch) {
+ this.sketch = sketch;
+ if (layout != -1) {
+ sketch.parentLayout = layout;
+ }
+ }
+
+
+ public PApplet getSketch() {
+ return sketch;
+ }
+
+
+ public void setLayout(@LayoutRes int layout, @IdRes int id, FragmentActivity activity) {
+ this.layout = layout;
+ if (sketch != null) {
+ sketch.parentLayout = layout;
+ }
+ FragmentManager manager = activity.getSupportFragmentManager();
+ FragmentTransaction transaction = manager.beginTransaction();
+ transaction.add(id, this);
+ transaction.commit();
+ }
+
+
+ public void setView(View view, FragmentActivity activity) {
+ FragmentManager manager = activity.getSupportFragmentManager();
+ FragmentTransaction transaction = manager.beginTransaction();
+ transaction.add(view.getId(), this);
+ transaction.commit();
+ }
+
+
+ public boolean isService() {
+ return false;
+ }
+
+
+ public ServiceEngine getEngine() {
+ return null;
+ }
+
+
+ public void dispose() {
+ }
+
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ if (sketch != null) {
+ sketch.initSurface(inflater, container, savedInstanceState, this, null);
+
+ // For compatibility with older sketches that run some hardware initialization
+ // inside onCreate(), don't call from Fragment.onCreate() because the surface
+ // will not be yet ready, and so the reference to the activity and other
+ // system variables will be null. In any case, onCreateView() is called
+ // immediately after onCreate():
+ // https://developer.android.com/reference/android/app/Fragment.html#Lifecycle
+ sketch.onCreate(savedInstanceState);
+
+ return sketch.getSurface().getRootView();
+ } else {
+ return null;
+ }
+ }
+
+
+ @Override
+ public void onStart() {
+ super.onStart();
+ if (sketch != null) {
+ sketch.onStart();
+ }
+ }
+
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (sketch != null) {
+ sketch.onResume();
+ }
+ }
+
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ if (sketch != null) {
+ sketch.onPause();
+ }
+ }
+
+
+ @Override
+ public void onStop() {
+ super.onStop();
+ if (sketch != null) {
+ sketch.onStop();
+ }
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (sketch != null) {
+ sketch.onDestroy();
+ }
+ }
+
+
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (sketch != null) sketch.onActivityResult(requestCode, resultCode, data);
+ }
+
+ @Override
+ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+ if (sketch != null) sketch.onCreateOptionsMenu(menu, inflater);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item){
+ if (sketch != null) return sketch.onOptionsItemSelected(item);
+ return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
+ if (sketch != null) sketch.onCreateContextMenu(menu, v, menuInfo);
+ }
+
+ @Override
+ public boolean onContextItemSelected(MenuItem item) {
+ if (sketch != null) return sketch.onContextItemSelected(item);
+ return super.onContextItemSelected(item);
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration newConfig) {
+ if (PApplet.DEBUG) System.out.println("configuration changed: " + newConfig);
+ super.onConfigurationChanged(newConfig);
+ }
+
+
+ public void setOrientation(int which) {
+ if (which == PORTRAIT) {
+ getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ } else if (which == LANDSCAPE) {
+ getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+ }
+ }
+
+
+ public void requestDraw() {
+ }
+
+
+ public boolean canDraw() {
+ return sketch != null && sketch.isLooping();
+ }
+}
diff --git a/core-androidx/src/processing/android/PWallpaper.java b/core-androidx/src/processing/android/PWallpaper.java
new file mode 100644
index 000000000..a285fc90d
--- /dev/null
+++ b/core-androidx/src/processing/android/PWallpaper.java
@@ -0,0 +1,302 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016-17 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import android.service.wallpaper.WallpaperService;
+import android.view.MotionEvent;
+import android.view.SurfaceHolder;
+import android.view.WindowManager;
+import processing.core.PApplet;
+import android.util.DisplayMetrics;
+import android.view.Display;
+import android.graphics.Point;
+import android.graphics.Rect;
+
+
+public class PWallpaper extends WallpaperService implements AppComponent {
+ private Point size;
+ private DisplayMetrics metrics;
+ private WallpaperEngine engine;
+
+
+ public void initDimensions() {
+ metrics = new DisplayMetrics();
+ size = new Point();
+ WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
+ Display display = wm.getDefaultDisplay();
+ CompatUtils.getDisplayParams(display, metrics, size);
+ }
+
+
+ public int getDisplayWidth() {
+ return size.x;
+ }
+
+
+ public int getDisplayHeight() {
+ return size.y;
+ }
+
+
+ public float getDisplayDensity() {
+ return metrics.density;
+ }
+
+
+ public int getKind() {
+ return WALLPAPER;
+ }
+
+
+ public PApplet createSketch() {
+ return new PApplet();
+ }
+
+
+ public void setSketch(PApplet sketch) {
+ engine.sketch = sketch;
+ }
+
+
+ public PApplet getSketch() {
+ return engine.sketch;
+ }
+
+
+ public boolean isService() {
+ return true;
+ }
+
+
+ public ServiceEngine getEngine() {
+ return engine;
+ }
+
+
+ public void requestDraw() {
+ }
+
+
+ public boolean canDraw() {
+ return true;
+ }
+
+
+ public void dispose() {
+ }
+
+
+ public void requestPermissions() {
+ }
+
+
+ @Override
+ public Engine onCreateEngine() {
+ engine = new WallpaperEngine();
+ return engine;
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ if (engine != null){
+ //engine.sketch = null;
+ engine.onDestroy();
+ }
+ }
+
+
+ public class WallpaperEngine extends Engine implements ServiceEngine {
+ PApplet sketch;
+ private float xOffset, xOffsetStep;
+ private float yOffset, yOffsetStep;
+ private int xPixelOffset, yPixelOffset;
+
+
+ @Override
+ public void onCreate(SurfaceHolder surfaceHolder) {
+ super.onCreate(surfaceHolder);
+ sketch = createSketch();
+ sketch.initSurface(PWallpaper.this, getSurfaceHolder());
+ if (isPreview()) requestPermissions();
+ setTouchEventsEnabled(true);
+ }
+
+
+ @Override
+ public void onSurfaceCreated(SurfaceHolder surfaceHolder) {
+ super.onSurfaceCreated(surfaceHolder);
+ }
+
+
+ @Override
+ public void onSurfaceChanged(final SurfaceHolder holder, final int format,
+ final int width, final int height) {
+ // When the surface of a live wallpaper changes (eg: after a screen rotation) the same sketch
+ // continues to run (unlike the case of regular apps, where its re-created) so we need to
+ // force a reset of the renderer so the backing FBOs (in the case of the OpenGL renderers)
+ // get reinitalized with the correct size.
+ sketch.g.reset();
+ super.onSurfaceChanged(holder, format, width, height);
+ }
+
+
+ @Override
+ public void onVisibilityChanged(boolean visible) {
+ if (sketch != null) {
+ if (visible) {
+ sketch.onResume();
+ } else {
+ sketch.onPause();
+ }
+ }
+ super.onVisibilityChanged(visible);
+ }
+
+
+ /*
+ * Store the position of the touch event so we can use it for drawing
+ * later
+ */
+ @Override
+ public void onTouchEvent(MotionEvent event) {
+ super.onTouchEvent(event);
+ if (sketch != null) {
+ sketch.surfaceTouchEvent(event);
+ }
+ }
+
+
+ @Override
+ public void onOffsetsChanged(float xOffset, float yOffset,
+ float xOffsetStep, float yOffsetStep,
+ int xPixelOffset, int yPixelOffset) {
+
+ if (sketch != null) {
+ this.xOffset = xOffset;
+ this.yOffset = yOffset;
+ this.xOffsetStep = xOffsetStep;
+ this.yOffsetStep = yOffsetStep;
+ this.xPixelOffset = xPixelOffset;
+ this.yPixelOffset = yPixelOffset;
+ }
+ }
+
+
+ @Override
+ public void onSurfaceDestroyed(SurfaceHolder holder) {
+ // This is called immediately before a surface is being destroyed.
+ // After returning from this call, you should no longer try to access this
+ // surface. If you have a rendering thread that directly accesses the
+ // surface, you must ensure that thread is no longer touching the Surface
+ // before returning from this function.
+ super.onSurfaceDestroyed(holder);
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (sketch != null) {
+ sketch.onDestroy();
+ }
+ }
+
+
+ @Override
+ public float getXOffset() {
+ return xOffset;
+ }
+
+
+ @Override
+ public float getYOffset() {
+ return yOffset;
+ }
+
+
+ @Override
+ public float getXOffsetStep() {
+ return xOffsetStep;
+ }
+
+
+ @Override
+ public float getYOffsetStep() {
+ return yOffsetStep;
+ }
+
+
+ @Override
+ public int getXPixelOffset() {
+ return xPixelOffset;
+ }
+
+
+ @Override
+ public int getYPixelOffset() {
+ return yPixelOffset;
+ }
+
+
+ @Override
+ public boolean isInAmbientMode() {
+ return false;
+ }
+
+
+ @Override
+ public boolean isRound() {
+ return false;
+ }
+
+
+ @Override
+ public Rect getInsets() {
+ return null;
+ }
+
+
+ @Override
+ public boolean useLowBitAmbient() {
+ return false;
+ }
+
+
+ @Override
+ public boolean requireBurnInProtection() {
+ return false;
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode,
+ String permissions[],
+ int[] grantResults) {
+ if (sketch != null) {
+ sketch.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ }
+ }
+ }
+}
diff --git a/core-androidx/src/processing/android/PWatchFaceCanvas.java b/core-androidx/src/processing/android/PWatchFaceCanvas.java
new file mode 100644
index 000000000..227022cfe
--- /dev/null
+++ b/core-androidx/src/processing/android/PWatchFaceCanvas.java
@@ -0,0 +1,367 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016-17 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import java.lang.reflect.Method;
+
+import android.annotation.TargetApi;
+import android.graphics.Canvas;
+import android.graphics.Point;
+import android.os.Bundle;
+import android.graphics.Rect;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.watchface.CanvasWatchFaceService;
+import android.support.wearable.watchface.WatchFaceStyle;
+import android.util.DisplayMetrics;
+import android.view.Display;
+import android.view.MotionEvent;
+import android.view.SurfaceHolder;
+import android.view.WindowInsets;
+import android.view.WindowManager;
+import processing.a2d.PGraphicsAndroid2D;
+import processing.core.PApplet;
+
+@TargetApi(21)
+public class PWatchFaceCanvas extends CanvasWatchFaceService implements AppComponent {
+ private Point size;
+ private DisplayMetrics metrics;
+ private CanvasEngine engine;
+
+ public void initDimensions() {
+ metrics = new DisplayMetrics();
+ size = new Point();
+ WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
+ Display display = wm.getDefaultDisplay();
+ CompatUtils.getDisplayParams(display, metrics, size);
+ }
+
+
+ public int getDisplayWidth() {
+ return size.x;
+ }
+
+
+ public int getDisplayHeight() {
+ return size.y;
+ }
+
+
+ public float getDisplayDensity() {
+ return metrics.density;
+ }
+
+
+ public int getKind() {
+ return WATCHFACE;
+ }
+
+
+ public PApplet createSketch() {
+ return new PApplet();
+ }
+
+
+ public void setSketch(PApplet sketch) {
+ engine.sketch = sketch;
+ }
+
+
+ public PApplet getSketch() {
+ return engine.sketch;
+ }
+
+
+ public boolean isService() {
+ return true;
+ }
+
+
+ public ServiceEngine getEngine() {
+ return engine;
+ }
+
+
+ public void requestDraw() {
+ if (engine != null) engine.invalidateIfNecessary();
+ }
+
+
+ public boolean canDraw() {
+ // The rendering loop should never call handleDraw() directly,
+ // it only needs to invalidate the screen
+ return false;
+ }
+
+
+ public void dispose() {
+ }
+
+
+ public void requestPermissions() {
+ }
+
+
+ @Override
+ public Engine onCreateEngine() {
+ engine = new CanvasEngine();
+ return engine;
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (engine != null) engine.onDestroy();
+ }
+
+
+ private class CanvasEngine extends CanvasWatchFaceService.Engine implements ServiceEngine {
+ private PApplet sketch;
+ private Method compUpdatedMethod;
+ private Method tapCommandMethod;
+ private boolean isRound = false;
+ private Rect insets = new Rect();
+ private boolean lowBitAmbient = false;
+ private boolean burnInProtection = false;
+
+ @Override
+ public void onCreate(SurfaceHolder surfaceHolder) {
+ super.onCreate(surfaceHolder);
+ setWatchFaceStyle(new WatchFaceStyle.Builder(PWatchFaceCanvas.this)
+ .setAcceptsTapEvents(true)
+ .build());
+ sketch = createSketch();
+ PGraphicsAndroid2D.useBitmap = false;
+ sketch.initSurface(PWatchFaceCanvas.this, null);
+ initTapEvents();
+ initComplications();
+ requestPermissions();
+ }
+
+
+ private void initTapEvents() {
+ try {
+ tapCommandMethod = sketch.getClass().getMethod("onTapCommand",
+ new Class[] {int.class, int.class, int.class, long.class});
+ } catch (Exception e) {
+ tapCommandMethod = null;
+ }
+ }
+
+
+ private void initComplications() {
+ try {
+ compUpdatedMethod = sketch.getClass().getMethod("onComplicationDataUpdate",
+ new Class[] {int.class, ComplicationData.class});
+ } catch (Exception e) {
+ compUpdatedMethod = null;
+ }
+ }
+
+
+ private void invalidateIfNecessary() {
+ if (isVisible() && !isInAmbientMode()) {
+ invalidate();
+ }
+ }
+
+
+ @Override
+ public void onAmbientModeChanged(boolean inAmbientMode) {
+ super.onAmbientModeChanged(inAmbientMode);
+ invalidateIfNecessary();
+ // call new event handlers in sketch (?)
+ }
+
+
+ @Override
+ public void onPropertiesChanged(Bundle properties) {
+ super.onPropertiesChanged(properties);
+ lowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
+ burnInProtection = properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false);
+ }
+
+
+ @Override
+ public void onApplyWindowInsets(WindowInsets insets) {
+ super.onApplyWindowInsets(insets);
+ isRound = insets.isRound();
+ this.insets.set(insets.getSystemWindowInsetLeft(),
+ insets.getSystemWindowInsetTop(),
+ insets.getSystemWindowInsetRight(),
+ insets.getSystemWindowInsetBottom());
+ }
+
+
+ @Override
+ public void onVisibilityChanged(boolean visible) {
+ super.onVisibilityChanged(visible);
+ if (sketch != null) {
+ if (visible) {
+ sketch.onResume();
+ } else {
+ sketch.onPause();
+ }
+ }
+ }
+
+
+ @Override
+ public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
+ super.onSurfaceChanged(holder, format, width, height);
+ if (sketch != null) {
+ sketch.surfaceChanged();
+ sketch.setSize(width, height);
+ }
+ }
+
+
+ @Override
+ public void onPeekCardPositionUpdate(Rect rect) { }
+
+
+ @Override
+ public void onTimeTick() {
+ invalidate();
+ }
+
+
+ @Override
+ public void onDraw(Canvas canvas, Rect bounds) {
+ super.onDraw(canvas, bounds);
+ if (sketch != null) {
+ PGraphicsAndroid2D g2 = (PGraphicsAndroid2D)sketch.g;
+ g2.canvas = canvas;
+ sketch.handleDraw();
+ }
+ }
+
+
+ @Override
+ public void onTouchEvent(MotionEvent event) {
+ super.onTouchEvent(event);
+ if (sketch != null) sketch.surfaceTouchEvent(event);
+ }
+
+
+ @Override
+ public void onTapCommand(@TapType int tapType, int x, int y, long eventTime) {
+ if (tapCommandMethod != null) {
+ try {
+ tapCommandMethod.invoke(tapType, x, y, eventTime);
+ } catch (Exception e) { }
+ invalidate();
+ }
+ }
+
+
+ @Override
+ public void onComplicationDataUpdate(int complicationId,
+ ComplicationData complicationData) {
+ if (compUpdatedMethod != null) {
+ try {
+ compUpdatedMethod.invoke(complicationId, complicationData);
+ } catch (Exception e) { }
+ invalidate();
+ }
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (sketch != null) {
+ sketch.onDestroy();
+ }
+ }
+
+
+ @Override
+ public float getXOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public float getYOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public float getXOffsetStep() {
+ return 0;
+ }
+
+
+ @Override
+ public float getYOffsetStep() {
+ return 0;
+ }
+
+
+ @Override
+ public int getXPixelOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public int getYPixelOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public boolean isRound() {
+ return isRound;
+ }
+
+
+ @Override
+ public Rect getInsets() {
+ return insets;
+ }
+
+
+ @Override
+ public boolean useLowBitAmbient() {
+ return lowBitAmbient;
+ }
+
+
+ @Override
+ public boolean requireBurnInProtection() {
+ return burnInProtection;
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode,
+ String permissions[],
+ int[] grantResults) {
+ if (sketch != null) {
+ sketch.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ }
+ }
+ }
+}
diff --git a/core-androidx/src/processing/android/PWatchFaceGLES.java b/core-androidx/src/processing/android/PWatchFaceGLES.java
new file mode 100644
index 000000000..8d385d286
--- /dev/null
+++ b/core-androidx/src/processing/android/PWatchFaceGLES.java
@@ -0,0 +1,392 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2016-17 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import android.annotation.TargetApi;
+import android.graphics.Point;
+import android.opengl.EGL14;
+import android.opengl.EGLConfig;
+import android.opengl.EGLDisplay;
+import android.os.Bundle;
+import android.view.Display;
+import android.view.WindowInsets;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.watchface.Gles2WatchFaceService;
+import android.support.wearable.watchface.WatchFaceStyle;
+import android.util.DisplayMetrics;
+import android.view.MotionEvent;
+import android.view.SurfaceHolder;
+import android.view.WindowManager;
+import processing.core.PApplet;
+import java.lang.reflect.Method;
+
+import android.graphics.Rect;
+
+@TargetApi(21)
+public class PWatchFaceGLES extends Gles2WatchFaceService implements AppComponent {
+ private static final int[] CONFIG_ATTRIB_LIST = new int[]{
+ EGL14.EGL_RENDERABLE_TYPE, 4,
+ EGL14.EGL_RED_SIZE, 8,
+ EGL14.EGL_GREEN_SIZE, 8,
+ EGL14.EGL_BLUE_SIZE, 8,
+ EGL14.EGL_ALPHA_SIZE, 8,
+ EGL14.EGL_DEPTH_SIZE, 16, // this was missing
+ EGL14.EGL_NONE};
+
+ private Point size;
+ private DisplayMetrics metrics;
+ private GLES2Engine engine;
+
+
+ public void initDimensions() {
+ metrics = new DisplayMetrics();
+ size = new Point();
+ WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
+ Display display = wm.getDefaultDisplay();
+ CompatUtils.getDisplayParams(display, metrics, size);
+ }
+
+
+ public int getDisplayWidth() {
+ return size.x;
+ }
+
+
+ public int getDisplayHeight() {
+ return size.y;
+ }
+
+
+ public float getDisplayDensity() {
+ return metrics.density;
+ }
+
+
+ public int getKind() {
+ return WATCHFACE;
+ }
+
+
+ public PApplet createSketch() {
+ return new PApplet();
+ }
+
+
+ public void setSketch(PApplet sketch) {
+ engine.sketch = sketch;
+ }
+
+
+ public PApplet getSketch() {
+ return engine.sketch;
+ }
+
+
+ public boolean isService() {
+ return true;
+ }
+
+
+ public ServiceEngine getEngine() {
+ return engine;
+ }
+
+
+ public void requestDraw() {
+ if (engine != null) engine.invalidateIfNecessary();
+ }
+
+
+ public boolean canDraw() {
+ // The rendering loop should never call handleDraw() directly, it only needs to invalidate the
+ // screen
+ return false;
+ }
+
+
+ public void dispose() {
+ }
+
+
+ public void requestPermissions() {
+ }
+
+
+ @Override
+ public Engine onCreateEngine() {
+ engine = new GLES2Engine();
+ return engine;
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (engine != null) engine.onDestroy();
+ }
+
+
+ private class GLES2Engine extends Gles2WatchFaceService.Engine implements ServiceEngine {
+ private PApplet sketch;
+ private Method compUpdatedMethod;
+ private Method tapCommandMethod;
+ private boolean isRound = false;
+ private Rect insets = new Rect();
+ private boolean lowBitAmbient = false;
+ private boolean burnInProtection = false;
+
+ @Override
+ public void onCreate(SurfaceHolder surfaceHolder) {
+ super.onCreate(surfaceHolder);
+ setWatchFaceStyle(new WatchFaceStyle.Builder(PWatchFaceGLES.this)
+ .setAcceptsTapEvents(true)
+ .build());
+ sketch = createSketch();
+ sketch.initSurface(PWatchFaceGLES.this, null);
+ initTapEvents();
+ initComplications();
+ requestPermissions();
+ }
+
+
+ public EGLConfig chooseEglConfig(EGLDisplay eglDisplay) {
+ int[] numEglConfigs = new int[1];
+ EGLConfig[] eglConfigs = new EGLConfig[1];
+ if(!EGL14.eglChooseConfig(eglDisplay, CONFIG_ATTRIB_LIST, 0, eglConfigs, 0, eglConfigs.length, numEglConfigs, 0)) {
+ throw new RuntimeException("eglChooseConfig failed");
+ } else if(numEglConfigs[0] == 0) {
+ throw new RuntimeException("no matching EGL configs");
+ } else {
+ return eglConfigs[0];
+ }
+ }
+
+ @Override
+ public void onGlContextCreated() {
+ super.onGlContextCreated();
+ }
+
+
+ @Override
+ public void onGlSurfaceCreated(int width, int height) {
+ super.onGlSurfaceCreated(width, height);
+ if (sketch != null) {
+ sketch.surfaceChanged();
+ sketch.setSize(width, height);
+ }
+ }
+
+
+ private void initTapEvents() {
+ try {
+ tapCommandMethod = sketch.getClass().getMethod("onTapCommand",
+ new Class[] {int.class, int.class, int.class, long.class});
+ } catch (Exception e) {
+ tapCommandMethod = null;
+ }
+ }
+
+
+ private void initComplications() {
+ try {
+ compUpdatedMethod = sketch.getClass().getMethod("onComplicationDataUpdate",
+ new Class[] {int.class, ComplicationData.class});
+ } catch (Exception e) {
+ compUpdatedMethod = null;
+ }
+ }
+
+
+ private void invalidateIfNecessary() {
+ if (isVisible() && !isInAmbientMode()) {
+ invalidate();
+ }
+ }
+
+
+ @Override
+ public void onAmbientModeChanged(boolean inAmbientMode) {
+ super.onAmbientModeChanged(inAmbientMode);
+ invalidateIfNecessary();
+ // call new event handlers in sketch (?)
+ }
+
+
+ @Override
+ public void onPropertiesChanged(Bundle properties) {
+ super.onPropertiesChanged(properties);
+ lowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
+ burnInProtection = properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false);
+ }
+
+
+ @Override
+ public void onApplyWindowInsets(WindowInsets insets) {
+ super.onApplyWindowInsets(insets);
+ this.insets.set(insets.getSystemWindowInsetLeft(),
+ insets.getSystemWindowInsetTop(),
+ insets.getSystemWindowInsetRight(),
+ insets.getSystemWindowInsetBottom());
+ }
+
+
+ @Override
+ public void onVisibilityChanged(boolean visible) {
+ super.onVisibilityChanged(visible);
+ if (sketch != null) {
+ if (visible) {
+ sketch.onResume();
+ } else {
+ sketch.onPause();
+ }
+ }
+ }
+
+
+ @Override
+ public void onPeekCardPositionUpdate(Rect rect) { }
+
+
+ @Override
+ public void onTimeTick() {
+ invalidate();
+ }
+
+
+ @Override
+ public void onDraw() {
+ super.onDraw();
+ if (sketch != null) sketch.handleDraw();
+ }
+
+
+ @Override
+ public void onTouchEvent(MotionEvent event) {
+ super.onTouchEvent(event);
+ if (sketch != null) sketch.surfaceTouchEvent(event);
+ }
+
+
+ @Override
+ public void onTapCommand(@TapType int tapType, int x, int y, long eventTime) {
+ if (tapCommandMethod != null) {
+ try {
+ tapCommandMethod.invoke(tapType, x, y, eventTime);
+ } catch (Exception e) { }
+ invalidate();
+ }
+ }
+
+
+ @Override
+ public void onComplicationDataUpdate(int complicationId,
+ ComplicationData complicationData) {
+ if (compUpdatedMethod != null) {
+ try {
+ compUpdatedMethod.invoke(complicationId, complicationData);
+ } catch (Exception e) {
+ }
+ invalidate();
+ }
+ }
+
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (sketch != null) {
+ sketch.onDestroy();
+ }
+ }
+
+
+ @Override
+ public float getXOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public float getYOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public float getXOffsetStep() {
+ return 0;
+ }
+
+
+ @Override
+ public float getYOffsetStep() {
+ return 0;
+ }
+
+
+ @Override
+ public int getXPixelOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public int getYPixelOffset() {
+ return 0;
+ }
+
+
+ @Override
+ public boolean isRound() {
+ return isRound;
+ }
+
+
+ @Override
+ public Rect getInsets() {
+ return insets;
+ }
+
+
+ @Override
+ public boolean useLowBitAmbient() {
+ return lowBitAmbient;
+ }
+
+
+ @Override
+ public boolean requireBurnInProtection() {
+ return burnInProtection;
+ }
+
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode,
+ String permissions[],
+ int[] grantResults) {
+ if (sketch != null) {
+ sketch.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ }
+ }
+ }
+}
diff --git a/core-androidx/src/processing/android/PermissionRequestor.java b/core-androidx/src/processing/android/PermissionRequestor.java
new file mode 100644
index 000000000..3c524da4b
--- /dev/null
+++ b/core-androidx/src/processing/android/PermissionRequestor.java
@@ -0,0 +1,59 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2017 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+
+import androidx.core.app.ActivityCompat;
+
+// A simple utility activity to request permissions in a service.
+public class PermissionRequestor extends Activity {
+ public static final String KEY_RESULT_RECEIVER = "resultReceiver";
+ public static final String KEY_PERMISSIONS = "permissions";
+ public static final String KEY_GRANT_RESULTS = "grantResults";
+ public static final String KEY_REQUEST_CODE = "requestCode";
+
+ ResultReceiver resultReceiver;
+ String[] permissions;
+ int requestCode;
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ resultReceiver = this.getIntent().getParcelableExtra(KEY_RESULT_RECEIVER);
+ permissions = this.getIntent().getStringArrayExtra(KEY_PERMISSIONS);
+ requestCode = this.getIntent().getIntExtra(KEY_REQUEST_CODE, 0);
+ ActivityCompat.requestPermissions(this, permissions, requestCode);
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
+ Bundle resultData = new Bundle();
+ resultData.putStringArray(KEY_PERMISSIONS, permissions);
+ resultData.putIntArray(KEY_GRANT_RESULTS, grantResults);
+ resultReceiver.send(requestCode, resultData);
+ finish();
+ }
+}
\ No newline at end of file
diff --git a/core-androidx/src/processing/android/ServiceEngine.java b/core-androidx/src/processing/android/ServiceEngine.java
new file mode 100644
index 000000000..4ca043075
--- /dev/null
+++ b/core-androidx/src/processing/android/ServiceEngine.java
@@ -0,0 +1,49 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2017 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.android;
+
+import android.graphics.Rect;
+import processing.core.PConstants;
+
+public interface ServiceEngine extends PConstants {
+ // wallpapers
+ public boolean isPreview();
+ public float getXOffset();
+ public float getYOffset();
+ public float getXOffsetStep();
+ public float getYOffsetStep();
+ public int getXPixelOffset();
+ public int getYPixelOffset();
+
+ // wear
+ public boolean isInAmbientMode();
+ public boolean isRound();
+ public Rect getInsets();
+ public boolean useLowBitAmbient();
+ public boolean requireBurnInProtection();
+
+ // Service permissions
+ public void onRequestPermissionsResult(int requestCode,
+ String permissions[],
+ int[] grantResults);
+}
diff --git a/core-androidx/src/processing/core/PApplet.java b/core-androidx/src/processing/core/PApplet.java
new file mode 100644
index 000000000..3c1406698
--- /dev/null
+++ b/core-androidx/src/processing/core/PApplet.java
@@ -0,0 +1,12622 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-17 The Processing Foundation
+ Copyright (c) 2004-12 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 version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.net.*;
+import java.text.NumberFormat;
+import java.util.*;
+import java.util.regex.*;
+import java.util.zip.*;
+
+import android.app.FragmentManager;
+import android.view.Window;
+import android.view.inputmethod.InputMethodManager;
+import android.app.Activity;
+import android.content.*;
+import android.content.pm.PackageManager;
+import android.content.res.AssetManager;
+import android.graphics.*;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.view.ContextMenu;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.MotionEvent;
+import android.view.SurfaceHolder;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ContextMenu.ContextMenuInfo;
+
+import androidx.annotation.LayoutRes;
+
+import processing.a2d.PGraphicsAndroid2D;
+import processing.android.ActivityAPI;
+import processing.android.AppComponent;
+import processing.android.CompatUtils;
+import processing.data.*;
+import processing.event.*;
+import processing.opengl.*;
+
+public class PApplet extends Object implements ActivityAPI, PConstants {
+
+ static final public boolean DEBUG = false;
+// static final public boolean DEBUG = true;
+
+ // Convenience public constant holding the SDK version, akin to platform in Java mode
+ static final public int SDK = Build.VERSION.SDK_INT;
+
+ //static final public int SDK = Build.VERSION_CODES.ICE_CREAM_SANDWICH; // Forcing older SDK for testing
+
+ /**
+ * The surface this sketch draws to.
+ */
+ protected PSurface surface;
+
+ /**
+ * The view group containing the surface view of the PApplet.
+ */
+ public @LayoutRes int parentLayout = -1;
+
+ /** The PGraphics renderer associated with this PApplet */
+ public PGraphics g;
+
+ /**
+ * The screen size when the sketch was started. This is initialized inside
+ * onCreate().
+ *
+ * Note that this won't update if you change the resolution
+ * of your screen once the the applet is running.
+ *
+ * This variable is not static because in the desktop version of Processing,
+ * not all instances of PApplet will necessarily be started on a screen of
+ * the same size.
+ */
+ public int displayWidth, displayHeight;
+
+ /**
+ * Command line options passed in from main().
+ *
+ * This does not include the arguments passed in to PApplet itself.
+ */
+// public String[] args;
+
+ /**
+ * Path to where sketch can read/write files (read-only).
+ * Android: This is the writable area for the Activity, which is correct
+ * for purposes of how sketchPath is used in practice from a sketch,
+ * even though it's technically different than the desktop version.
+ */
+ 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 = -1;
+ static public final int DEFAULT_HEIGHT = -1;
+
+ /**
+ * Set true when the surface dimensions have changed, so that the PGraphics
+ * object can be resized on the next trip through handleDraw().
+ */
+ protected boolean surfaceChanged;
+
+ /**
+ * Pixel buffer from this applet's PGraphics.
+ *
+ * When used with OpenGL or Java2D, this value will
+ * be null until loadPixels() has been called.
+ */
+ public int[] pixels;
+
+ /** width of this applet's associated PGraphics */
+ public int width = DEFAULT_WIDTH;
+
+ /** height of this applet's associated PGraphics */
+ public int height = DEFAULT_HEIGHT;
+
+ /** The logical density of the display from getDisplayMetrics().density
+ * According to Android's documentation:
+ * This is a scaling factor for the Density Independent Pixel unit,
+ * where one DIP is one pixel on an approximately 160 dpi screen
+ * (for example a 240x320, 1.5"x2" screen), providing the baseline of the
+ * system's display. Thus on a 160dpi screen this density value will be 1;
+ * on a 120 dpi screen it would be .75; etc.
+ */
+ public float displayDensity = 1;
+
+ // For future use
+ public int pixelDensity = 1;
+ public int pixelWidth;
+ public int pixelHeight;
+
+ ///////////////////////////////////////////////////////////////
+ // Mouse events
+
+ /** absolute x position of input on screen */
+ public int mouseX;
+
+ /** absolute x position of input on screen */
+ 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.
+ */
+ public int pmouseX, pmouseY;
+
+ public int mouseButton;
+
+ public boolean mousePressed;
+
+
+ public boolean touchIsStarted;
+
+
+ public TouchEvent.Pointer[] touches = new TouchEvent.Pointer[0];
+
+
+ /**
+ * 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;
+
+
+ /**
+ * pmotionX/Y for the event handlers (motionPressed(), motionDragged() etc)
+ * these are different because motion events are queued to the end of
+ * draw, so the previous position has to be updated on each event,
+ * as opposed to the pmotionX/Y that's used inside draw, which is expected
+ * to be updated once per trip through draw().
+ */
+ protected int emouseX, emouseY;
+
+
+ /**
+ * ID of the pointer tracked for mouse events.
+ */
+ protected int mousePointerId;
+
+
+ /**
+ * ID of the most recently touch pointer gone up or down.
+ */
+ protected int touchPointerId;
+
+ ///////////////////////////////////////////////////////////////
+ // Key events
+
+ /**
+ * 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).
+ */
+ public char key;
+
+ /**
+ * 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.
+ */
+ public int keyCode;
+
+ /**
+ * true if the mouse is currently pressed.
+ */
+ 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.
+ */
+ public boolean focused = false;
+
+ /**
+ * Keeps track of ENABLE_KEY_REPEAT hint
+ */
+ protected boolean keyRepeatEnabled = false;
+
+ /**
+ * Set to open when openKeyboard() is called, and used to close the keyboard when the sketch is
+ * paused, otherwise it remains visible.
+ */
+ boolean keyboardIsOpen = false;
+
+ /**
+ * Flag to determine if the back key was pressed.
+ */
+ private boolean requestedBackPress = false;
+
+ /**
+ * Flag to determine if the user handled the back press.
+ */
+ public boolean handledBackPressed = true;
+
+ ///////////////////////////////////////////////////////////////
+ // Permission handling
+
+ /**
+ * Callback methods to handle permission requests
+ */
+ protected HashMap permissionMethods = new HashMap();
+
+
+ /**
+ * Permissions requested during one frame
+ */
+ protected ArrayList reqPermissions = new ArrayList();
+
+
+ ///////////////////////////////////////////////////////////////
+ // Rendering/timing
+
+ /**
+ * Time in milliseconds when the applet was started.
+ *
+ * Used by the millis() function.
+ */
+ long millisOffset = System.currentTimeMillis();
+
+ protected boolean insideDraw;
+
+ /** Last time in nanoseconds that frameRate was checked */
+ protected long frameRateLastNanos = 0;
+
+ /**
+ * 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;
+
+ 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;
+
+ boolean insideSettings;
+
+ String renderer = JAVA2D;
+
+ int smooth = 1; // default smoothing (whatever that means for the renderer)
+
+ boolean fullScreen = false;
+
+ int display = -1; // use default
+
+ // Background default needs to be different from the default value in
+ // PGraphics.backgroundColor, otherwise size(100, 100) bg spills over.
+ // https://github.com/processing/processing/issues/2297
+ int windowColor = 0xffDDDDDD;
+
+ ///////////////////////////////////////////////////////////////
+ // Error messages
+
+ static final String ERROR_MIN_MAX =
+ "Cannot use min() or max() on an empty array.";
+
+ ///////////////////////////////////////////////////////////////
+ // Command line options
+
+ /**
+ * 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;
+
+
+ //////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * Required empty constructor.
+ */
+ public PApplet() {
+
+ }
+
+
+ public PSurface getSurface() {
+ return surface;
+ }
+
+
+ public Context getContext() {
+ return surface.getContext();
+ }
+
+
+ public Activity getActivity() {
+ return surface.getActivity();
+ }
+
+
+ public void initSurface(AppComponent component, SurfaceHolder holder) {
+ parentLayout = -1;
+ initSurface(null, null, null, component, holder);
+ }
+
+
+ public void initSurface(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState,
+ AppComponent component, SurfaceHolder holder) {
+ if (DEBUG) println("initSurface() happening here: " + Thread.currentThread().getName());
+
+ component.initDimensions();
+ displayWidth = component.getDisplayWidth();
+ displayHeight = component.getDisplayHeight();
+ displayDensity = component.getDisplayDensity();
+
+ handleSettings();
+
+ boolean parentSize = false;
+ if (parentLayout == -1) {
+ if (fullScreen || width == -1 || height == -1) {
+ // Either sketch explicitly set to full-screen mode, or not
+ // size/fullScreen provided, so sketch uses the entire display
+ width = displayWidth;
+ height = displayHeight;
+ }
+ } else {
+ if (fullScreen || width == -1 || height == -1) {
+ // Dummy weight and height to initialize the PGraphics, will be resized
+ // when the view associated to the parent layout is created
+ width = 100;
+ height = 100;
+ parentSize = true;
+ }
+ }
+
+ pixelWidth = width * pixelDensity;
+ pixelHeight = height * pixelDensity;
+
+ String rendererName = sketchRenderer();
+ if (DEBUG) println("Renderer " + rendererName);
+ g = makeGraphics(width, height, rendererName, true);
+ if (DEBUG) println("Created renderer");
+ surface = g.createSurface(component, holder, false);
+ if (DEBUG) println("Created surface");
+
+ if (parentLayout == -1) {
+ setFullScreenVisibility();
+ surface.initView(width, height);
+ } else {
+ surface.initView(width, height, parentSize,
+ inflater, container, savedInstanceState);
+ }
+
+ finished = false; // just for clarity
+ // this will be cleared by draw() if it is not overridden
+ looping = true;
+ redraw = true; // draw this guy once
+
+ sketchPath = surface.getFilesDir().getAbsolutePath();
+
+ surface.startThread();
+
+ if (DEBUG) println("Done with init surface");
+ }
+
+
+ private void setFullScreenVisibility() {
+ if (fullScreen) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ int visibility;
+ if (SDK < 19) {
+ // Pre-4.4
+ visibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
+ } else {
+ // 4.4 and higher. Integer instead of constants defined in View so it can
+ // build with SDK < 4.4
+ visibility = 256 | // View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ 512 | // View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ 1024 | // View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
+ 4 | // View.SYSTEM_UI_FLAG_FULLSCREEN
+ 4096; // View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ // However, this visibility does not fix a bug where the navigation area
+ // turns black after resuming the app:
+ // https://code.google.com/p/android/issues/detail?id=170752
+ }
+ surface.setSystemUiVisibility(visibility);
+ }
+ });
+ }
+ }
+
+
+ public void onResume() {
+ if (DEBUG) System.out.println("PApplet.onResume() called");
+ if (parentLayout == -1) {
+ setFullScreenVisibility();
+ }
+
+ handleMethods("resume");
+
+ // Don't call resume() when the app is starting and setup() has not been called yet:
+ // https://github.com/processing/processing-android/issues/274
+ // Also, there is no need to call resume() from anywhere else (for example, from
+ // onStart) since onResume() is always called in the activity lifecyle:
+ // https://developer.android.com/guide/components/activities/activity-lifecycle.html
+ if (0 < frameCount) {
+ resume();
+ }
+
+ // Set the handledBackPressed to true to handle the situation where a fragment is popping
+ // right back after pressing the back button (the sketch does not exit).
+ handledBackPressed = true;
+
+ if (g != null) {
+ g.restoreState();
+ }
+
+ surface.resumeThread();
+ }
+
+
+ public void onPause() {
+ surface.pauseThread();
+
+ // Make sure that the keyboard is not left open after leaving the app
+ closeKeyboard();
+
+ if (g != null) {
+ g.saveState();
+ }
+
+ handleMethods("pause");
+
+ pause(); // handler for others to write
+ }
+
+
+ public void onStart() {
+ start();
+ }
+
+
+ public void onStop() {
+ stop();
+ }
+
+
+ public void onCreate(Bundle savedInstanceState) {
+ create();
+ }
+
+
+ public void onDestroy() {
+ handleMethods("onDestroy");
+
+ surface.stopThread();
+
+ dispose();
+ }
+
+
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ handleMethods("onActivityResult", new Object[] { requestCode, resultCode, data });
+ }
+
+
+ public void onNewIntent(Intent intent) {
+ handleMethods("onNewIntent", new Object[] { intent });
+ }
+
+
+ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
+
+ }
+
+
+ public boolean onOptionsItemSelected(MenuItem item) {
+ return false;
+ }
+
+
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
+
+ }
+
+
+ public boolean onContextItemSelected(MenuItem item) {
+ return false;
+ }
+
+
+ public void setHasOptionsMenu(boolean hasMenu) {
+ surface.setHasOptionsMenu(hasMenu);
+ }
+
+
+ synchronized public void onBackPressed() {
+ requestedBackPress = true;
+ }
+
+
+ public FragmentManager getFragmentManager() {
+ if (getActivity() != null) {
+ return getActivity().getFragmentManager();
+ }
+ return null;
+ }
+
+
+ public Window getWindow(){
+ if (getActivity() != null) {
+ return getActivity().getWindow();
+ }
+ return null;
+ }
+
+
+ public void startActivity(Intent intent) {
+ surface.startActivity(intent);
+ }
+
+
+ public void runOnUiThread(Runnable action) {
+ surface.runOnUiThread(action);
+ }
+
+
+ public boolean hasPermission(String permission) {
+ return surface.hasPermission(permission);
+ }
+
+
+ public void requestPermission(String permission) {
+ if (!hasPermission(permission)) {
+ reqPermissions.add(permission);
+ }
+ }
+
+
+ public void requestPermission(String permission, String callback) {
+ requestPermission(permission, callback, this);
+ }
+
+
+ public void requestPermission(String permission, String callback, Object target) {
+ registerWithArgs(callback, target, new Class[] { boolean.class });
+ if (hasPermission(permission)) {
+ // If the app already has permission, still call the handle method as it
+ // may be doing some initialization
+ handleMethods(callback, new Object[] { true });
+ } else {
+ permissionMethods.put(permission, callback);
+ // Accumulating permissions so they requested all at once at the end
+ // of draw.
+ reqPermissions.add(permission);
+ }
+ }
+
+
+ public void onRequestPermissionsResult(int requestCode,
+ String permissions[],
+ int[] grantResults) {
+ if (requestCode == PSurface.REQUEST_PERMISSIONS) {
+ for (int i = 0; i < grantResults.length; i++) {
+ boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
+ handlePermissionsResult(permissions[i], granted);
+ }
+ }
+ }
+
+
+ private void handlePermissionsResult(String permission, final boolean granted) {
+ String methodName = permissionMethods.get(permission);
+ final RegisteredMethods meth = registerMap.get(methodName);
+ if (meth != null) {
+ Handler handler = new Handler(Looper.getMainLooper());
+ handler.post(new Runnable() {
+ @Override
+ public void run() {
+ meth.handle(new Object[] { granted });
+ }
+ });
+ }
+ }
+
+
+ private void handlePermissions() {
+ if (0 < reqPermissions.size()) {
+ String[] req = reqPermissions.toArray(new String[reqPermissions.size()]);
+ surface.requestPermissions(req);
+ reqPermissions.clear();
+ }
+ }
+
+ synchronized private void handleBackPressed() {
+ if (requestedBackPress) {
+ requestedBackPress = false;
+ backPressed();
+ if (!handledBackPressed) {
+ if (getActivity() != null) {
+ // Services don't have an activity associated to them, but back press could not be triggered for those anyways
+ getActivity().finish();
+ }
+ handledBackPressed = false;
+ }
+ }
+ }
+
+ /**
+ * @param method "size" or "fullScreen"
+ * @param args parameters passed to the function so we can show the user
+ * @return true if safely inside the settings() method
+ */
+ boolean insideSettings(String method, Object... args) {
+ if (insideSettings) {
+ return true;
+ }
+ final String url = "https://processing.org/reference/" + method + "_.html";
+ if (!external) { // post a warning for users of Eclipse and other IDEs
+ StringList argList = new StringList(args);
+ System.err.println("When not using the PDE, " + method + "() can only be used inside settings().");
+ System.err.println("Remove the " + method + "() method from setup(), and add the following:");
+ System.err.println("public void settings() {");
+ System.err.println(" " + method + "(" + argList.join(", ") + ");");
+ System.err.println("}");
+ }
+ throw new IllegalStateException(method + "() cannot be used here, see " + url);
+ }
+
+
+ void handleSettings() {
+ insideSettings = true;
+ //Do stuff
+ settings();
+ insideSettings = false;
+ }
+
+
+ public void settings() {
+ //It'll be empty. Will be overridden by user's sketch class.
+ }
+
+
+ final public int sketchWidth() {
+ return width;
+ }
+
+
+ final public int sketchHeight() {
+ return height;
+ }
+
+
+ final public String sketchRenderer() {
+ return renderer;
+ }
+
+
+ public int sketchSmooth() {
+ return smooth;
+ }
+
+
+ final public boolean sketchFullScreen() {
+ return fullScreen;
+ }
+
+
+ final public int sketchDisplay() {
+ return display;
+ }
+
+
+ final public String sketchOutputPath() {
+ return null;
+ }
+
+
+ final public OutputStream sketchOutputStream() {
+ return null;
+ }
+
+
+ final public int sketchWindowColor() {
+ return windowColor;
+ }
+
+
+ final public int sketchPixelDensity() {
+ return pixelDensity;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public void surfaceChanged() {
+ surfaceChanged = true;
+ g.surfaceChanged();
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /**
+ * Called by the sketch surface view, thought it could conceivably be called
+ * by Android as well.
+ */
+ public void surfaceWindowFocusChanged(boolean hasFocus) {
+ focused = hasFocus;
+ if (focused) {
+ focusGained();
+ } else {
+ focusLost();
+ }
+ }
+
+
+ /**
+ * If you override this function without calling super.onTouchEvent(),
+ * then motionX, motionY, motionPressed, and motionEvent will not be set.
+ */
+ public boolean surfaceTouchEvent(MotionEvent event) {
+ nativeMotionEvent(event);
+ return true;
+ }
+
+
+ public void surfaceKeyDown(int code, android.view.KeyEvent event) {
+ nativeKeyEvent(event);
+ }
+
+
+ public void surfaceKeyUp(int code, android.view.KeyEvent event) {
+ nativeKeyEvent(event);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /**
+ * 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() {
+ }
+
+
+ /**
+ * 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() {
+ }
+
+
+ /**
+ * Developers can override here to save state. The 'paused' variable will be
+ * set before this function is called.
+ */
+ public void pause() {
+ }
+
+
+ /**
+ * Developers can override here to restore state. The 'paused' variable
+ * will be cleared before this function is called.
+ */
+ public void resume() {
+ }
+
+
+ public void backPressed() {
+ handledBackPressed = false;
+ }
+
+ //////////////////////////////////////////////////////////////
+
+
+ /** Map of registered methods, stored by name. */
+ HashMap registerMap =
+ new HashMap();
+
+
+ class RegisteredMethods {
+ int count;
+ Object[] objects;
+ // Because the Method comes from the class being called,
+ // it will be unique for most, if not all, objects.
+ Method[] methods;
+ Object[] emptyArgs = new Object[] { };
+
+
+ void handle() {
+ handle(emptyArgs);
+ }
+
+
+ void handle(Object[] args) {
+ for (int i = 0; i < count; i++) {
+ try {
+ methods[i].invoke(objects[i], args);
+ } catch (Exception e) {
+ // check for wrapped exception, get root exception
+ Throwable t;
+ if (e instanceof InvocationTargetException) {
+ InvocationTargetException ite = (InvocationTargetException) e;
+ t = ite.getCause();
+ } else {
+ t = e;
+ }
+ // check for RuntimeException, and allow to bubble up
+ if (t instanceof RuntimeException) {
+ // re-throw exception
+ throw (RuntimeException) t;
+ } else {
+ // trap and print as usual
+ t.printStackTrace();
+ }
+ }
+ }
+ }
+
+
+ void add(Object object, Method method) {
+ if (findIndex(object) == -1) {
+ if (objects == null) {
+ objects = new Object[5];
+ methods = new Method[5];
+
+ } else if (count == objects.length) {
+ objects = (Object[]) PApplet.expand(objects);
+ methods = (Method[]) PApplet.expand(methods);
+ }
+ objects[count] = object;
+ methods[count] = method;
+ count++;
+ } else {
+ die(method.getName() + "() already added for this instance of " +
+ object.getClass().getName());
+ }
+ }
+
+
+ /**
+ * 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);
+ public void remove(Object object) {
+ int index = findIndex(object);
+ 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) {
+ protected int findIndex(Object object) {
+ for (int i = 0; i < count; i++) {
+ if (objects[i] == object) {
+// 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;
+ }
+ }
+
+
+ /**
+ * Register a built-in event so that it can be fired for libraries, etc.
+ * Supported events include:
+ *
+ *
pre – at the very top of the draw() method (safe to draw)
+ *
draw – at the end of the draw() method (safe to draw)
+ *
post – after draw() has exited (not safe to draw)
+ *
pause – called when the sketch is paused
+ *
resume – called when the sketch is resumed
+ *
dispose – when the sketch is shutting down (definitely not safe to draw)
+ *
+ * In addition, the new (for 2.0) processing.event classes are passed to
+ * the following event types:
+ *
+ *
mouseEvent
+ *
keyEvent
+ *
touchEvent
+ *
+ * The older java.awt events are no longer supported.
+ * See the Library Wiki page for more details.
+ * @param methodName name of the method to be called
+ * @param target the target object that should receive the event
+ */
+ public void registerMethod(String methodName, Object target) {
+ if (methodName.equals("mouseEvent")) {
+ registerWithArgs("mouseEvent", target, new Class[] { processing.event.MouseEvent.class });
+
+ } else if (methodName.equals("keyEvent")) {
+ registerWithArgs("keyEvent", target, new Class[] { processing.event.KeyEvent.class });
+
+ } else if (methodName.equals("touchEvent")) {
+ registerWithArgs("touchEvent", target, new Class[] { processing.event.TouchEvent.class });
+
+ // Android-lifecycle event handlers
+ } else if (methodName.equals("onDestroy")) {
+ registerNoArgs(methodName, target);
+ } else if (methodName.equals("onActivityResult")) {
+ registerWithArgs("onActivityResult", target, new Class[] { int.class, int.class, Intent.class });
+ } else if (methodName.equals("onNewIntent")) {
+ registerWithArgs("onNewIntent", target, new Class[] { Intent.class });
+
+ } else {
+ registerNoArgs(methodName, target);
+ }
+ }
+
+
+ private void registerNoArgs(String name, Object o) {
+ RegisteredMethods meth = registerMap.get(name);
+ if (meth == null) {
+ meth = new RegisteredMethods();
+ registerMap.put(name, meth);
+ }
+ 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);
+ }
+ }
+
+
+ private void registerWithArgs(String name, Object o, Class> cargs[]) {
+ RegisteredMethods meth = registerMap.get(name);
+ if (meth == null) {
+ meth = new RegisteredMethods();
+ registerMap.put(name, meth);
+ }
+ 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 registerMethod(String methodName, Object target, Object... args) {
+// registerWithArgs(methodName, target, args);
+// }
+
+
+ public void unregisterMethod(String name, Object target) {
+ RegisteredMethods meth = registerMap.get(name);
+ if (meth == null) {
+ die("No registered methods with the name " + name + "() were found.");
+ }
+ try {
+// Method method = o.getClass().getMethod(name, new Class[] {});
+// meth.remove(o, method);
+ meth.remove(target);
+ } catch (Exception e) {
+ die("Could not unregister " + name + "() for " + target, e);
+ }
+ }
+
+
+ protected void handleMethods(String methodName) {
+ RegisteredMethods meth = registerMap.get(methodName);
+ if (meth != null) {
+ meth.handle();
+ }
+ }
+
+
+ protected void handleMethods(String methodName, final Object[] args) {
+ final RegisteredMethods meth = registerMap.get(methodName);
+ if (meth != null) {
+ Handler handler = new Handler(Looper.getMainLooper());
+ handler.post(new Runnable() {
+ @Override
+ public void run() {
+ meth.handle(args);
+ }
+ });
+ }
+ }
+
+
+ @Deprecated
+ public void registerSize(Object o) {
+ System.err.println("The registerSize() command is no longer supported.");
+// Class> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
+// registerWithArgs(sizeMethods, "size", o, methodArgs);
+ }
+
+
+ @Deprecated
+ public void registerPre(Object o) {
+ registerNoArgs("pre", o);
+ }
+
+
+ @Deprecated
+ public void registerDraw(Object o) {
+ registerNoArgs("draw", o);
+ }
+
+
+ @Deprecated
+ public void registerPost(Object o) {
+ registerNoArgs("post", o);
+ }
+
+
+ @Deprecated
+ public void registerDispose(Object o) {
+ registerNoArgs("dispose", o);
+ }
+
+
+ @Deprecated
+ public void unregisterSize(Object o) {
+ System.err.println("The unregisterSize() command is no longer supported.");
+// Class> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
+// unregisterWithArgs(sizeMethods, "size", o, methodArgs);
+ }
+
+
+ @Deprecated
+ public void unregisterPre(Object o) {
+ unregisterMethod("pre", o);
+ }
+
+
+ @Deprecated
+ public void unregisterDraw(Object o) {
+ unregisterMethod("draw", o);
+ }
+
+
+ @Deprecated
+ public void unregisterPost(Object o) {
+ unregisterMethod("post", o);
+ }
+
+
+ @Deprecated
+ public void unregisterDispose(Object o) {
+ unregisterMethod("dispose", o);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ 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) {
+//// int left = (screenWidth - iwidth) / 2;
+//// int right = screenWidth - (left + iwidth);
+//// int top = (screenHeight - iheight) / 2;
+//// int bottom = screenHeight - (top + iheight);
+//// surfaceView.setPadding(left, top, right, bottom);
+//
+// g.setSize(iwidth, iheight);
+// width = iwidth;
+// height = iheight;
+// overallLayout.invalidate();
+// layout.invalidate();
+// }
+// }
+
+
+ /**
+ * Create a full-screen sketch using the default renderer.
+ */
+ public void fullScreen() {
+ if (!fullScreen) {
+ if (insideSettings("fullScreen")) {
+ this.fullScreen = true;
+ }
+ }
+ }
+
+
+ public void fullScreen(int display) {
+ //Display index doesn't make sense in Android.
+ //Should we throw some error in log ?
+ if (!fullScreen /*|| display != this.display*/) {
+ if (insideSettings("fullScreen", display)) {
+ this.fullScreen = true;
+// this.display = display;
+ }
+ }
+ }
+
+
+ public void fullScreen(String renderer) {
+ if (!fullScreen ||
+ !renderer.equals(this.renderer)) {
+ if (insideSettings("fullScreen", renderer)) {
+ this.fullScreen = true;
+ this.renderer = renderer;
+ }
+ }
+ }
+
+
+ public void fullScreen(String renderer, int display) {
+ if (!fullScreen ||
+ !renderer.equals(this.renderer) /*||
+ display != this.display*/) {
+ if (insideSettings("fullScreen", renderer, display)) {
+ this.fullScreen = true;
+ this.renderer = renderer;
+// this.display = display;
+ }
+ }
+ }
+
+
+ /**
+ * 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 called once a renderer has already been set, this will use the
+ * previous renderer and simply resize it.
+ */
+ public void size(int iwidth, int iheight) {
+ if (iwidth != this.width || iheight != this.height) {
+ if (insideSettings("size", iwidth, iheight)) {
+ this.width = iwidth;
+ this.height = iheight;
+ }
+ }
+ }
+
+
+ public void size(int iwidth, int iheight, String irenderer) {
+ if (iwidth != this.width || iheight != this.height ||
+ !this.renderer.equals(irenderer)) {
+ if (insideSettings("size", iwidth, iheight, irenderer)) {
+ this.width = iwidth;
+ this.height = iheight;
+ this.renderer = irenderer;
+ }
+ }
+ }
+
+
+ public void setSize(int width, int height) {
+ if (fullScreen) {
+ this.displayWidth = width;
+ this.displayHeight = height;
+ }
+ this.width = width;
+ this.height = height;
+ pixelWidth = width * pixelDensity;
+ pixelHeight = height * pixelDensity;
+ g.setSize(sketchWidth(), sketchHeight());
+ }
+
+
+ public void setExternal(boolean external) {
+ this.external = external;
+ }
+
+
+//. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public void smooth() {
+ smooth(1);
+ }
+
+
+ public void smooth(int level) {
+ if (insideSettings) {
+ this.smooth = level;
+ } else if (this.smooth != level) {
+ smoothWarning("smooth");
+ }
+ }
+
+
+ public void noSmooth() {
+ if (insideSettings) {
+ this.smooth = 0;
+ } else if (this.smooth != 0) {
+ smoothWarning("noSmooth");
+ }
+ }
+
+ private void smoothWarning(String method) {
+ // When running from the PDE, say setup(), otherwise say settings()
+ final String where = external ? "setup" : "settings";
+ PGraphics.showWarning("%s() can only be used inside %s()", method, where);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public PGraphics getGraphics() {
+ return g;
+ }
+
+ public void orientation(int which) {
+ surface.setOrientation(which);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ // not finished yet--will swap the renderer at a bad time
+ /*
+ public void renderer(String name) {
+ if (name.equals(A2D)) {
+ if (!(surfaceView instanceof SketchSurfaceView2D)) {
+ surfaceView = new SketchSurfaceView2D(this);
+ getWindow().setContentView(surfaceView); // set full screen
+ }
+ } else if (name.equals(A3D)) {
+ if (!(surfaceView instanceof SketchSurfaceView3D)) {
+ surfaceView = new SketchSurfaceView3D(this);
+ getWindow().setContentView(surfaceView); // set full screen
+ }
+ }
+ }
+ */
+
+
+ /**
+ * 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,
+ final String irenderer, final String ipath) {
+ if (iwidth != this.width || iheight != this.height ||
+ !this.renderer.equals(irenderer)) {
+ if (insideSettings("size", iwidth, iheight, irenderer,
+ ipath)) {
+ this.width = iwidth;
+ this.height = iheight;
+ this.renderer = irenderer;
+ }
+ }
+ }
+
+
+ public PGraphics createGraphics(int iwidth, int iheight) {
+ return createGraphics(iwidth, iheight, JAVA2D);
+ }
+
+
+ /**
+ * 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().
+ *
+ */
+ public PGraphics createGraphics(int iwidth, int iheight, String irenderer) {
+ return makeGraphics(iwidth, iheight, irenderer, false);
+ }
+
+
+ protected PGraphics makeGraphics(int w, int h,
+ String renderer, boolean primary) {
+ PGraphics pg = null;
+ if (renderer.equals(JAVA2D)) {
+ pg = new PGraphicsAndroid2D();
+ } else if (renderer.equals(P2D)) {
+ if (!primary && !g.isGL()) {
+ throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D");
+ }
+ pg = new PGraphics2D();
+
+ } else if (renderer.equals(P3D)) {
+ if (!primary && !g.isGL()) {
+ throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D");
+ }
+ pg = new PGraphics3D();
+ } else {
+ Class> rendererClass = null;
+ Constructor> constructor = null;
+ try {
+ // http://code.google.com/p/android/issues/detail?id=11101
+ rendererClass = Thread.currentThread().getContextClassLoader().loadClass(renderer);
+ } catch (ClassNotFoundException cnfe) {
+ throw new RuntimeException("Missing renderer class");
+ }
+
+ if (rendererClass != null) {
+ try {
+ constructor = rendererClass.getConstructor(new Class[] { });
+ } catch (NoSuchMethodException nsme) {
+ throw new RuntimeException("Missing renderer constructor");
+ }
+
+ if (constructor != null) {
+ try {
+ pg = (PGraphics) constructor.newInstance();
+ } catch (InvocationTargetException e) {
+ printStackTrace(e);
+ throw new RuntimeException(e.getMessage());
+ } catch (IllegalAccessException e) {
+ printStackTrace(e);
+ throw new RuntimeException(e.getMessage());
+ } catch (InstantiationException e) {
+ printStackTrace(e);
+ throw new RuntimeException(e.getMessage());
+ } catch (IllegalArgumentException e) {
+ // TODO Auto-generated catch block
+ printStackTrace(e);
+ }
+ }
+ }
+ }
+
+ pg.setParent(this);
+ pg.setPrimary(primary);
+ pg.setSize(w, h);
+ 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 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) {
+ try {
+ Class> rendererClass =
+ Thread.currentThread().getContextClassLoader().loadClass(irenderer);
+
+ 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) {
+ ite.getTargetException().printStackTrace();
+ Throwable target = ite.getTargetException();
+ throw new RuntimeException(target.getMessage());
+
+ } catch (ClassNotFoundException cnfe) {
+ throw new RuntimeException("You need to use \"Import Library\" " +
+ "to add " + irenderer + " to your sketch.");
+ } catch (Exception e) {
+ 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.
+ */
+ public PImage createImage(int wide, int high, int format) {
+// return createImage(wide, high, format, null);
+// }
+//
+//
+// /**
+// * 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.
+// */
+// public PImage createImage(int wide, int high, int format, Object params) {
+ PImage image = new PImage(wide, high, format);
+// if (params != null) {
+// image.setParams(g, params);
+// }
+ image.parent = this; // make save() work
+ return image;
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ // not necessary, ja?
+// 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();
+ }
+ }
+ }
+ */
+
+
+ //////////////////////////////////////////////////////////////
+
+
+/*
+ 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;
+
+ while (!finished) {
+
+ while (paused) {
+ try{
+ Thread.sleep(100L);
+ } catch (InterruptedException e) {
+ //ignore?
+ }
+ }
+
+ // render a single frame
+ if (g != null) g.requestDraw();
+
+ // 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();
+ }
+
+ // if this isn't just a pause, shut it all down
+ if (!paused) {
+ stop(); // call to shutdown libs?
+
+ // If the user called the exit() function, the window should close,
+ // rather than the sketch just halting.
+ if (exitCalled) {
+ exitActual();
+ }
+ }
+ }
+*/
+
+ public void handleDraw() {
+ //debug("handleDraw() " + g + " " + looping + " " + redraw + " valid:" + this.isValid() + " visible:" + this.isVisible());
+
+ if (g == null) return;
+
+ if (!surfaceChanged && parentLayout != -1) {
+ // When using a parent layout, don't start drawing until the sketch
+ // has been properly sized.
+ return;
+ }
+
+ if (!looping && !redraw) return;
+
+ if (insideDraw) {
+ System.err.println("handleDraw() called before finishing");
+ System.exit(1);
+ }
+
+ insideDraw = true;
+
+// if (recorder != null) {
+// recorder.beginDraw();
+// }
+
+ if (handleSpecialDraw()) return;
+
+ g.beginDraw();
+
+ long now = System.nanoTime();
+
+ if (frameCount == 0) {
+ setup();
+
+ } else { // frameCount > 0, meaning an actual draw()
+ // update the current frameRate
+ double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0);
+ float instantaneousRate = (float) (rate / 1000.0);
+ frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f);
+
+ if (frameCount != 0) {
+ handleMethods("pre");
+ }
+
+ // 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;
+
+ 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.
+ dequeueEvents();
+
+ handleMethods("draw");
+ handlePermissions();
+ handleBackPressed();
+
+ 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();
+// }
+ insideDraw = false;
+
+ if (frameCount != 0) {
+ handleMethods("post");
+ }
+
+ frameRateLastNanos = now;
+ frameCount++;
+ }
+
+
+ // This method handles some special situations on Android where beginDraw/endDraw are needed,
+ // but not to render the actual contents of draw(). In general, these situations arise from
+ // having to refresh/restore the screen after requesting no loop, or resuming the sketch in
+ // no-loop state.
+ protected boolean handleSpecialDraw() {
+ boolean handled = false;
+
+ if (g.restoringState()) {
+ // The sketch is restoring, so begin/end the frame properly and quit drawing.
+ g.beginDraw();
+ g.endDraw();
+
+ handled = true;
+ } else if (g.requestedNoLoop) {
+ // noLoop() was called sometime in the previous frame with a GL renderer, but only now
+ // we are sure that the frame is properly displayed.
+ looping = false;
+
+ // Perform a full frame draw, to ensure that the previous frame is properly displayed (see
+ // comment in the declaration of requestedNoLoop).
+ g.beginDraw();
+ g.endDraw();
+
+ g.requestedNoLoop = false;
+ handled = true;
+ }
+
+ if (handled) {
+ insideDraw = false;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ 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) {
+ if (g.requestNoLoop()) {
+ g.requestedNoLoop = true;
+ } else {
+ looping = false;
+ }
+ }
+ }
+
+
+ public boolean isLooping() {
+ return looping;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ // all these are handled in SurfaceView, which is a listener for all of em
+// 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;
+// }
+// });
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ InternalEventQueue eventQueue = new InternalEventQueue();
+
+
+ class InternalEventQueue {
+ protected Event queue[] = new Event[10];
+ protected int offset;
+ protected int count;
+
+ synchronized void add(Event e) {
+ if (count == queue.length) {
+ queue = (Event[]) expand(queue);
+ }
+ queue[count++] = e;
+ }
+
+ synchronized Event remove() {
+ if (offset == count) {
+ throw new RuntimeException("Nothing left on the event queue.");
+ }
+ Event outgoing = queue[offset++];
+ if (offset == count) {
+ // All done, time to reset
+ offset = 0;
+ count = 0;
+ }
+ return outgoing;
+ }
+
+ synchronized boolean available() {
+ return count != 0;
+ }
+ }
+
+ /**
+ * Add an event to the internal event queue, or process it immediately if
+ * the sketch is not currently looping.
+ */
+ public void postEvent(processing.event.Event pe) {
+ eventQueue.add(pe);
+
+ if (!looping) {
+ dequeueEvents();
+ }
+ }
+
+
+ protected void dequeueEvents() {
+ while (eventQueue.available()) {
+ Event e = eventQueue.remove();
+
+ switch (e.getFlavor()) {
+ case Event.TOUCH:
+ handleTouchEvent((TouchEvent) e);
+ break;
+ case Event.MOUSE:
+ handleMouseEvent((MouseEvent) e);
+ break;
+ case Event.KEY:
+ handleKeyEvent((KeyEvent) e);
+ break;
+ }
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ protected void handleMouseEvent(MouseEvent event) {
+// mouseEvent = event;
+
+ // 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 == java.awt.event.MouseEvent.MOUSE_DRAGGED) ||
+// (id == java.awt.event.MouseEvent.MOUSE_MOVED)) {
+ if (event.getAction() == MouseEvent.DRAG ||
+ event.getAction() == MouseEvent.MOVE) {
+ pmouseX = emouseX;
+ pmouseY = emouseY;
+ mouseX = event.getX();
+ mouseY = event.getY();
+ }
+
+ // Because we only get DRAGGED (and no MOVED) events, pmouseX/Y will make
+ // things jump because they aren't updated while a finger isn't on the
+ // screen. This makes for weirdness with the continuous lines example,
+ // causing it to jump. Since we're emulating the mouse here, do the right
+ // thing for mouse events. It breaks the situation where random taps/clicks
+ // to the screen won't show up as 'previous' values, but that's probably
+ // less common.
+// if (event.getAction() == MouseEvent.PRESS) {
+// System.out.println("resetting");
+//// pmouseX = event.getX();
+//// pmouseY = event.getY();
+// firstMotion = true;
+// }
+
+ // Get the (already processed) button code
+ mouseButton = event.getButton();
+
+ // Added in 0215 (2.0b7) so that pmouseX/Y behave more like one would
+ // expect from the desktop. This makes the ContinousLines example behave.
+ if (event.getAction() == MouseEvent.PRESS) {
+ mouseX = event.getX();
+ mouseY = event.getY();
+ pmouseX = mouseX;
+ pmouseY = mouseY;
+ dmouseX = mouseX;
+ dmouseY = mouseY;
+ }
+
+// if (event.getAction() == MouseEvent.RELEASE) {
+// mouseX = event.getX();
+// mouseY = event.getY();
+// }
+
+// mouseEvent = event;
+
+ // Do this up here in case a registered method relies on the
+ // boolean for mousePressed.
+
+ switch (event.getAction()) {
+ case MouseEvent.PRESS:
+ mousePressed = true;
+ break;
+ case MouseEvent.RELEASE:
+ mousePressed = false;
+ break;
+ }
+
+ handleMethods("mouseEvent", new Object[] { event });
+
+ switch (event.getAction()) {
+ case MouseEvent.PRESS:
+ mousePressed(event);
+ break;
+ case MouseEvent.RELEASE:
+ mouseReleased(event);
+ break;
+ case MouseEvent.CLICK:
+ mouseClicked(event);
+ break;
+ case MouseEvent.DRAG:
+ mouseDragged(event);
+ break;
+ case MouseEvent.MOVE:
+ mouseMoved(event);
+ break;
+ case MouseEvent.ENTER:
+ mouseEntered(event);
+ break;
+ case MouseEvent.EXIT:
+ mouseExited(event);
+ break;
+ }
+
+ if ((event.getAction() == MouseEvent.DRAG) ||
+ (event.getAction() == MouseEvent.MOVE)) {
+ emouseX = mouseX;
+ emouseY = mouseY;
+ }
+ if (event.getAction() == MouseEvent.PRESS) { // Android-only
+ emouseX = mouseX;
+ emouseY = mouseY;
+ }
+// if (event.getAction() == MouseEvent.RELEASE) { // Android-only
+// emouseX = mouseX;
+// emouseY = mouseY;
+// }
+ }
+
+
+ protected void handleTouchEvent(TouchEvent event) {
+ touches = event.getTouches(touches);
+
+ switch (event.getAction()) {
+ case TouchEvent.START:
+ touchIsStarted = true;
+ break;
+ case TouchEvent.END:
+ touchIsStarted = false;
+ break;
+ }
+
+ handleMethods("touchEvent", new Object[] { event });
+
+ switch (event.getAction()) {
+ case TouchEvent.START:
+ touchStarted(event);
+ break;
+ case TouchEvent.END:
+ touchEnded(event);
+ break;
+ case TouchEvent.MOVE:
+ touchMoved(event);
+ break;
+ case TouchEvent.CANCEL:
+ touchCancelled(event);
+ break;
+ }
+ }
+
+
+ /**
+ * 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 nativeMotionEvent(MotionEvent motionEvent) {
+ int metaState = motionEvent.getMetaState();
+ int modifiers = 0;
+ if ((metaState & android.view.KeyEvent.META_SHIFT_ON) != 0) {
+ modifiers |= Event.SHIFT;
+ }
+ if ((metaState & android.view.KeyEvent.META_CTRL_ON) != 0) {
+ modifiers |= Event.CTRL;
+ }
+ if ((metaState & android.view.KeyEvent.META_META_ON) != 0) {
+ modifiers |= Event.META;
+ }
+ if ((metaState & android.view.KeyEvent.META_ALT_ON) != 0) {
+ modifiers |= Event.ALT;
+ }
+
+ int button;
+ int state = motionEvent.getButtonState();
+ switch (state) {
+ case MotionEvent.BUTTON_PRIMARY:
+ button = LEFT;
+ break;
+ case MotionEvent.BUTTON_SECONDARY:
+ button = RIGHT;
+ break;
+ case MotionEvent.BUTTON_TERTIARY:
+ button = CENTER;
+ break;
+ default:
+ // Covers the BUTTON_FORWARD, BUTTON_BACK,
+ // BUTTON_STYLUS_PRIMARY, and BUTTON_STYLUS_SECONDARY
+ button = state;
+ }
+
+ enqueueMouseEvents(motionEvent, button, modifiers);
+ enqueueTouchEvents(motionEvent, button, modifiers);
+ }
+
+
+ protected void enqueueTouchEvents(MotionEvent event, int button, int modifiers) {
+ int action = event.getAction();
+ int actionMasked = action & MotionEvent.ACTION_MASK;
+ int paction = 0;
+ switch (actionMasked) {
+ case MotionEvent.ACTION_DOWN:
+ paction = TouchEvent.START;
+ break;
+ case MotionEvent.ACTION_POINTER_DOWN:
+ paction = TouchEvent.START;
+ break;
+ case MotionEvent.ACTION_MOVE:
+ paction = TouchEvent.MOVE;
+ break;
+ case MotionEvent.ACTION_UP:
+ paction = TouchEvent.END;
+ break;
+ case MotionEvent.ACTION_POINTER_UP:
+ paction = TouchEvent.END;
+ break;
+ default:
+ // Covers any other action value, including ACTION_CANCEL
+ paction = TouchEvent.CANCEL;
+ break;
+ }
+
+ if (paction == TouchEvent.START || paction == TouchEvent.END) {
+ touchPointerId = event.getPointerId(0);
+ }
+
+ int pointerCount = event.getPointerCount();
+
+ if (actionMasked == MotionEvent.ACTION_MOVE) {
+ // Post historical movement events, if any.
+ int historySize = event.getHistorySize();
+ for (int h = 0; h < historySize; h++) {
+ TouchEvent touchEvent = new TouchEvent(event, event.getHistoricalEventTime(h),
+ paction, modifiers, button);
+ touchEvent.setNumPointers(pointerCount);
+ for (int p = 0; p < pointerCount; p++) {
+ touchEvent.setPointer(p, event.getPointerId(p), event.getHistoricalX(p, h), event.getHistoricalY(p, h),
+ event.getHistoricalSize(p, h), event.getHistoricalPressure(p, h));
+ }
+ postEvent(touchEvent);
+ }
+ }
+
+ // Current event
+ TouchEvent touchEvent = new TouchEvent(event, event.getEventTime(),
+ paction, modifiers, button);
+ if (actionMasked == MotionEvent.ACTION_UP) {
+ // Last pointer up
+ touchEvent.setNumPointers(0);
+ } else {
+ // We still have some pointers left
+ touchEvent.setNumPointers(pointerCount);
+ for (int p = 0; p < event.getPointerCount(); p++) {
+ touchEvent.setPointer(p, event.getPointerId(p), event.getX(p), event.getY(p),
+ event.getSize(p), event.getPressure(p));
+ }
+ }
+ postEvent(touchEvent);
+ }
+
+
+ protected void enqueueMouseEvents(MotionEvent event, int button, int modifiers) {
+ int action = event.getAction();
+
+ int clickCount = 1; // not really set... (i.e. not catching double taps)
+ int index;
+
+ switch (action & MotionEvent.ACTION_MASK) {
+ case MotionEvent.ACTION_DOWN:
+ mousePointerId = event.getPointerId(0);
+ postEvent(new MouseEvent(event, event.getEventTime(),
+ MouseEvent.PRESS, modifiers,
+ (int) event.getX(), (int) event.getY(),
+ button, clickCount));
+ break;
+ case MotionEvent.ACTION_MOVE:
+ index = event.findPointerIndex(mousePointerId);
+ if (index != -1) {
+ postEvent(new MouseEvent(event, event.getEventTime(),
+ MouseEvent.DRAG, modifiers,
+ (int) event.getX(index), (int) event.getY(index),
+ button, clickCount));
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ index = event.findPointerIndex(mousePointerId);
+ if (index != -1) {
+ postEvent(new MouseEvent(event, event.getEventTime(),
+ MouseEvent.RELEASE, modifiers,
+ (int) event.getX(index), (int) event.getY(index),
+ button, clickCount));
+ }
+ break;
+ }
+ }
+
+ public void mousePressed() { }
+
+
+ public void mousePressed(MouseEvent event) {
+ mousePressed();
+ }
+
+
+ public void mouseReleased() { }
+
+
+ public void mouseReleased(MouseEvent event) {
+ mouseReleased();
+ }
+
+
+ /**
+ * mouseClicked is currently not fired at all (no direct match on Android).
+ * http://code.google.com/p/processing/issues/detail?id=215
+ */
+ public void mouseClicked() { }
+
+
+ public void mouseClicked(MouseEvent event) {
+ mouseClicked();
+ }
+
+
+ public void mouseDragged() { }
+
+
+ public void mouseDragged(MouseEvent event) {
+ mouseDragged();
+ }
+
+
+ public void mouseMoved() { }
+
+
+ public void mouseMoved(MouseEvent event) {
+ mouseMoved();
+ }
+
+
+ public void mouseEntered() { }
+
+
+ public void mouseEntered(MouseEvent event) {
+ mouseEntered();
+ }
+
+
+ public void mouseExited() { }
+
+
+ public void mouseExited(MouseEvent event) {
+ mouseExited();
+ }
+
+
+ public void touchStarted() { }
+
+
+ public void touchStarted(TouchEvent event) {
+ touchStarted();
+ }
+
+
+ public void touchMoved() { }
+
+
+ public void touchMoved(TouchEvent event) {
+ touchMoved();
+ }
+
+
+ public void touchEnded() { }
+
+
+ public void touchEnded(TouchEvent event) {
+ touchEnded();
+ }
+
+
+ public void touchCancelled() { }
+
+
+ public void touchCancelled(TouchEvent event) {
+ touchCancelled();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+// KeyEvent[] keyEventQueue = new KeyEvent[10];
+// int keyEventCount;
+//
+// protected void enqueueKeyEvent(KeyEvent e) {
+// synchronized (keyEventQueue) {
+// if (keyEventCount == keyEventQueue.length) {
+// keyEventQueue = (KeyEvent[]) expand(keyEventQueue);
+// }
+// keyEventQueue[keyEventCount++] = e;
+// }
+// }
+//
+// protected void dequeueKeyEvents() {
+// synchronized (keyEventQueue) {
+// for (int i = 0; i < keyEventCount; i++) {
+// handleKeyEvent(keyEventQueue[i]);
+// }
+// keyEventCount = 0;
+// }
+// }
+
+
+ protected void handleKeyEvent(KeyEvent event) {
+
+ // Get rid of auto-repeating keys if desired and supported
+ if (!keyRepeatEnabled && event.isAutoRepeat()) return;
+
+// keyEvent = event;
+ key = event.getKey();
+ keyCode = event.getKeyCode();
+
+ switch (event.getAction()) {
+ case KeyEvent.PRESS:
+ keyPressed = true;
+ keyPressed(event);
+ break;
+ case KeyEvent.RELEASE:
+ keyPressed = false;
+ keyReleased(event);
+ break;
+ }
+
+ handleMethods("keyEvent", new Object[] { event });
+ }
+
+
+ protected void nativeKeyEvent(android.view.KeyEvent event) {
+ // event.isPrintingKey() returns false for whitespace and others,
+ // which is a problem if the space bar or tab key are used.
+ char key = (char) event.getUnicodeChar();
+ // if not mappable to a unicode character, instead mark as coded key
+ if (key == 0 || key == 0xFFFF) {
+ key = CODED;
+ }
+
+ int keyCode = event.getKeyCode();
+
+ int keAction = 0;
+ int action = event.getAction();
+ if (action == android.view.KeyEvent.ACTION_DOWN) {
+ keAction = KeyEvent.PRESS;
+ } else if (action == android.view.KeyEvent.ACTION_UP) {
+ keAction = KeyEvent.RELEASE;
+ }
+
+ // TODO set up proper key modifier handling
+ int keModifiers = 0;
+
+ KeyEvent ke = new KeyEvent(event, event.getEventTime(),
+ keAction, keModifiers, key, keyCode, 0 < event.getRepeatCount());
+
+ postEvent(ke);
+ }
+
+
+ public void openKeyboard() {
+ Context context = surface.getContext();
+ InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
+ keyboardIsOpen = true;
+ }
+
+
+ public void closeKeyboard() {
+ if (keyboardIsOpen) {
+ Context context = surface.getContext();
+ InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
+ keyboardIsOpen = false;
+ if (parentLayout == -1) {
+ setFullScreenVisibility();
+ }
+ }
+ }
+
+
+ public void keyPressed() { }
+
+
+ public void keyPressed(KeyEvent event) {
+ keyPressed();
+ }
+
+
+ /**
+ * See keyPressed().
+ */
+ public void keyReleased() { }
+
+
+ public void keyReleased(KeyEvent event) {
+ keyReleased();
+ }
+
+
+ public void keyTyped() { }
+
+
+ public void keyTyped(KeyEvent event) {
+ keyTyped();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ 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
+
+
+ /**
+ * Get the number of milliseconds since the applet started.
+ *
+ * This is a function, rather than a variable, because it may
+ * change multiple times per frame.
+ */
+ public int millis() {
+ return (int) (System.currentTimeMillis() - millisOffset);
+ }
+
+ /** Seconds position of the current time. */
+ static public int second() {
+ return Calendar.getInstance().get(Calendar.SECOND);
+ }
+
+ /** Minutes position of the current time. */
+ static public int minute() {
+ return Calendar.getInstance().get(Calendar.MINUTE);
+ }
+
+ /**
+ * 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;
+ */
+ static public int hour() {
+ return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
+ }
+
+ /**
+ * 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()
+ */
+ static public int day() {
+ return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
+ }
+
+ /**
+ * Get the current month in range 1 through 12.
+ */
+ static public int month() {
+ // months are number 0..11 so change to colloquial 1..12
+ return Calendar.getInstance().get(Calendar.MONTH) + 1;
+ }
+
+ /**
+ * Get the current year.
+ */
+ 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.
+ *
+ * The screen only updates when the end of draw() is reached, so delay()
+ * cannot be used to slow down drawing. For instance, you cannot use delay()
+ * to control the timing of an animation.
+ *
+ * The delay() function should only be used for pausing scripts (i.e.
+ * a script that needs to pause a few seconds before attempting a download,
+ * or a sketch that needs to wait a few milliseconds before reading from
+ * the serial port).
+ */
+ public void delay(int napTime) {
+ //if (frameCount != 0) {
+ //if (napTime > 0) {
+ try {
+ Thread.sleep(napTime);
+ } catch (InterruptedException e) { }
+ //}
+ //}
+ }
+
+
+ /**
+ * ( begin auto-generated from frameRate.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ */
+ public void frameRate(float fps) {
+//
+// frameRateTarget = newRateTarget;
+// frameRatePeriod = (long) (1000000000.0 / frameRateTarget);
+// g.setFrameRate(newRateTarget);
+ surface.setFrameRate(fps);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Get a param from the web page, or (eventually)
+ * from a properties file.
+ */
+// public String param(String what) {
+// if (online) {
+// return getParameter(what);
+//
+// } else {
+// System.err.println("param() only works inside a web browser");
+// }
+// return null;
+// }
+
+
+ /**
+ * 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.
+ */
+// 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);
+ }
+
+
+ /**
+ * 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.
+ */
+ public void link(String url, String frameTitle) {
+ Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(url));
+ surface.startActivity(viewIntent);
+ }
+
+
+ /**
+ * Attempt to open a file using the platform's shell.
+ */
+ static public void open(String filename) {
+ open(new String[] { filename });
+ }
+
+
+ /**
+ * 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).
+ */
+ static public Process open(String argv[]) {
+ return exec(argv);
+ }
+
+
+ static public Process exec(String[] argv) {
+ try {
+ return Runtime.getRuntime().exec(argv);
+ } catch (Exception e) {
+ throw new RuntimeException("Could not open " + join(argv, ' '));
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Better way of handling e.printStackTrace() calls so that they can be
+ * handled by subclasses as necessary.
+ */
+ protected void printStackTrace(Throwable t) {
+ t.printStackTrace();
+ }
+
+
+ /**
+ * 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);
+ }
+
+
+ /**
+ * Conveniency method so perform initialization tasks when the activity is
+ * created, while avoiding the ackward call to onCreate() with the bundle
+ * and super.onCreate().
+ */
+ public void create() {
+
+ }
+
+ /**
+ * Should trigger a graceful activity/service shutdown (calling onPause/onStop, etc).
+ */
+ public void exit() {
+ surface.finish();
+ }
+
+
+ /**
+ * Called to dispose of resources and shut down the sketch.
+ * Destroys the thread, dispose the renderer, and notify listeners.
+ *
+ * Not to be called or overriden by users. If called multiple times,
+ * will only notify listeners once. Register a dispose listener instead.
+ */
+ final public void dispose() {
+ // moved here from stop()
+ finished = true; // let the sketch know it is shut down time
+
+ // call to shut down renderer, in case it needs it (pdf does)
+ if (surface != null) {
+ surface.stopThread();
+ surface.dispose();
+ }
+ if (g != null) {
+ g.clearState(); // This should probably go in dispose, but for the time being...
+ g.dispose();
+ }
+
+ handleMethods("dispose");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Call a method in the current class based on its name.
+ *
+ * Note that the function being called must be public. Inside the PDE,
+ * 'public' is automatically added, but when used without the preprocessor,
+ * (like from Eclipse) you'll have to do it yourself.
+ */
+ public void method(String name) {
+ try {
+ Method method = getClass().getMethod(name, new Class[] {});
+ method.invoke(this, new Object[] { });
+
+ } catch (IllegalArgumentException e) {
+ printStackTrace(e);
+ } catch (IllegalAccessException e) {
+ printStackTrace(e);
+ } 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) {
+ printStackTrace(e);
+ }
+ }
+
+
+ /**
+ * Launch a new thread and call the specified function from that new thread.
+ * This is a very simple way to do a thread without needing to get into
+ * classes, runnables, etc.
+ *
+ * Note that the function being called must be public. Inside the PDE,
+ * 'public' is automatically added, but when used without the preprocessor,
+ * (like from Eclipse) you'll have to do it yourself.
+ */
+ public void thread(final String name) {
+ Thread later = new Thread() {
+ @Override
+ public void run() {
+ method(name);
+ }
+ };
+ later.start();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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
+
+ // Removed, this doesn't make sense in a touch interface.
+
+
+// int cursorType = ARROW; // cursor type
+// boolean cursorVisible = true; // cursor visibility flag
+// PImage invisibleCursor;
+
+
+ /**
+ * Set the cursor type
+ */
+// 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);
+// }
+
+
+ /**
+ * 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.
+ */
+// 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));
+// }
+// }
+
+
+ /**
+ * Hide the cursor by creating a transparent image
+ * and using it as a custom cursor.
+ */
+// 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();
+ }
+
+ /**
+ * @param variables list of data, separated by commas
+ */
+ static public void print(Object... variables) {
+ StringBuilder sb = new StringBuilder();
+ for (Object o : variables) {
+ if (sb.length() != 0) {
+ sb.append(" ");
+ }
+ if (o == null) {
+ sb.append("null");
+ } else {
+ sb.append(o.toString());
+ }
+ }
+ System.out.print(sb.toString());
+ }
+
+ /*
+ 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();
+ }
+
+ /**
+ * @param variables list of data, separated by commas
+ */
+ static public void println(Object... variables) {
+// System.out.println("got " + variables.length + " variables");
+ print(variables);
+ 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);
+ }
+ }
+ }
+
+
+/**
+ * @webref output:text_area
+ * @param what one-dimensional array
+ * @usage IDE
+ * @see PApplet#print(byte)
+ * @see PApplet#println()
+ */
+ static public void printArray(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 'J': // int
+ long jj[] = (long[]) what;
+ for (int i = 0; i < jj.length; i++) {
+ System.out.println("[" + i + "] " + jj[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);
+ }
+ }
+ System.out.flush();
+ }
+
+ //
+
+ /*
+ // 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 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;
+ }
+
+
+ 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 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);
+ }
+
+
+ /**
+ * 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;
+ }
+
+
+ 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));
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RANDOM NUMBERS
+
+
+ Random internalRandom;
+
+ /**
+ *
+ */
+ public final float random(float high) {
+ // avoid an infinite loop when 0 or NaN are passed in
+ if (high == 0 || high != high) {
+ return 0;
+ }
+
+ if (internalRandom == null) {
+ internalRandom = new Random();
+ }
+
+ // 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'
+ float value = 0;
+ do {
+ value = internalRandom.nextFloat() * high;
+ } while (value == high);
+ return value;
+ }
+
+ /**
+ * ( begin auto-generated from randomGaussian.xml )
+ *
+ * Returns a float from a random series of numbers having a mean of 0
+ * and standard deviation of 1. Each time the randomGaussian()
+ * function is called, it returns a number fitting a Gaussian, or
+ * normal, distribution. There is theoretically no minimum or maximum
+ * value that randomGaussian() might return. Rather, there is
+ * just a very low probability that values far from the mean will be
+ * returned; and a higher probability that numbers near the mean will
+ * be returned.
+ *
+ * ( end auto-generated )
+ * @webref math:random
+ * @see PApplet#random(float,float)
+ * @see PApplet#noise(float, float, float)
+ */
+ public final float randomGaussian() {
+ if (internalRandom == null) {
+ internalRandom = new Random();
+ }
+ return (float) internalRandom.nextGaussian();
+ }
+
+
+ /**
+ * ( begin auto-generated from random.xml )
+ *
+ * Generates random numbers. Each time the random() function is
+ * called, it returns an unexpected value within the specified range. If
+ * one parameter is passed to the function it will return a float
+ * between zero and the value of the high parameter. The function
+ * call random(5) returns values between 0 and 5 (starting at zero,
+ * up to but not including 5). If two parameters are passed, it will return
+ * a float with a value between the the parameters. The function
+ * call random(-5, 10.2) returns values starting at -5 up to (but
+ * not including) 10.2. To convert a floating-point random number to an
+ * integer, use the int() function.
+ *
+ * ( end auto-generated )
+ * @webref math:random
+ * @param low lower limit
+ * @param high upper limit
+ * @see PApplet#randomSeed(long)
+ * @see PApplet#noise(float, float, float)
+ */
+ public final float random(float low, float high) {
+ if (low >= high) return low;
+ float diff = high - low;
+ float value = 0;
+ // because of rounding error, can't just add low, otherwise it may hit high
+ // https://github.com/processing/processing/issues/4551
+ do {
+ value = random(diff) + low;
+ } while (value == high);
+ return value;
+ }
+
+
+ /**
+ * ( begin auto-generated from randomSeed.xml )
+ *
+ * Sets the seed value for random(). By default, random()
+ * produces different results each time the program is run. Set the
+ * value parameter to a constant to return the same pseudo-random
+ * numbers each time the software is run.
+ *
+ * ( end auto-generated )
+ * @webref math:random
+ * @param seed seed value
+ * @see PApplet#random(float,float)
+ * @see PApplet#noise(float, float, float)
+ * @see PApplet#noiseSeed(long)
+ */
+ public final void randomSeed(long seed) {
+ if (internalRandom == null) {
+ internalRandom = new Random();
+ }
+ internalRandom.setSeed(seed);
+ }
+
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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<random() function.
+ * It was invented by Ken Perlin in the 1980s and been used since in
+ * graphical applications to produce procedural textures, natural motion,
+ * shapes, terrains etc.
The main difference to the
+ * random() function is that Perlin noise is defined in an infinite
+ * n-dimensional space where each pair of coordinates corresponds to a
+ * fixed semi-random value (fixed only for the lifespan of the program).
+ * The resulting value will always be between 0.0 and 1.0. Processing can
+ * compute 1D, 2D and 3D noise, depending on the number of coordinates
+ * given. The noise value can be animated by moving through the noise space
+ * as demonstrated in the example above. The 2nd and 3rd dimension can also
+ * be interpreted as time.
The actual noise is structured
+ * similar to an audio signal, in respect to the function's use of
+ * frequencies. Similar to the concept of harmonics in physics, perlin
+ * noise is computed over several octaves which are added together for the
+ * final result.
Another way to adjust the character of the
+ * resulting sequence is the scale of the input coordinates. As the
+ * function works within an infinite space the value of the coordinates
+ * doesn't matter as such, only the distance between successive coordinates
+ * does (eg. when using noise() within a loop). As a general rule
+ * the smaller the difference between coordinates, the smoother the
+ * resulting noise sequence will be. Steps of 0.005-0.03 work best for most
+ * applications, but this will differ depending on use.
+ *
+ * ( end auto-generated )
+ *
+ * @webref math:random
+ * @param x x-coordinate in noise space
+ * @param y y-coordinate in noise space
+ * @param z z-coordinate in noise space
+ * @see PApplet#noiseSeed(long)
+ * @see PApplet#noiseDetail(int, float)
+ * @see PApplet#random(float,float)
+ */
+ public float noise(float x, float y, float z) {
+ if (perlin == null) {
+ if (perlinRandom == null) {
+ perlinRandom = new Random();
+ }
+ perlin = new float[PERLIN_SIZE + 1];
+ for (int i = 0; i < PERLIN_SIZE + 1; i++) {
+ perlin[i] = perlinRandom.nextFloat(); //(float)Math.random();
+ }
+ // [toxi 031112]
+ // noise broke due to recent change of cos table in PGraphics
+ // this will take care of it
+ perlin_cosTable = PGraphics.cosLUT;
+ perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH;
+ perlin_PI >>= 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 = x - xi;
+ float yf = y - yi;
+ float zf = 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
+
+ /**
+ * ( begin auto-generated from noiseDetail.xml )
+ *
+ * Adjusts the character and level of detail produced by the Perlin noise
+ * function. Similar to harmonics in physics, noise is computed over
+ * several octaves. Lower octaves contribute more to the output signal and
+ * as such define the overal intensity of the noise, whereas higher octaves
+ * create finer grained details in the noise sequence. By default, noise is
+ * computed over 4 octaves with each octave contributing exactly half than
+ * its predecessor, starting at 50% strength for the 1st octave. This
+ * falloff amount can be changed by adding an additional function
+ * parameter. Eg. a falloff factor of 0.75 means each octave will now have
+ * 75% impact (25% less) of the previous lower octave. Any value between
+ * 0.0 and 1.0 is valid, however note that values greater than 0.5 might
+ * result in greater than 1.0 values returned by noise().
By changing these parameters, the signal created by the noise()
+ * function can be adapted to fit very specific needs and characteristics.
+ *
+ * ( end auto-generated )
+ * @webref math:random
+ * @param lod number of octaves to be used by the noise
+ * @see PApplet#noise(float, float, float)
+ */
+ public void noiseDetail(int lod) {
+ if (lod>0) perlin_octaves=lod;
+ }
+
+ /**
+ * @see #noiseDetail(int)
+ * @param falloff falloff factor for each octave
+ */
+ public void noiseDetail(int lod, float falloff) {
+ if (lod>0) perlin_octaves=lod;
+ if (falloff>0) perlin_amp_falloff=falloff;
+ }
+
+ /**
+ * ( begin auto-generated from noiseSeed.xml )
+ *
+ * Sets the seed value for noise(). By default, noise()
+ * produces different results each time the program is run. Set the
+ * value parameter to a constant to return the same pseudo-random
+ * numbers each time the software is run.
+ *
+ * ( end auto-generated )
+ * @webref math:random
+ * @param seed seed value
+ * @see PApplet#noise(float, float, float)
+ * @see PApplet#noiseDetail(int, float)
+ * @see PApplet#random(float,float)
+ * @see PApplet#randomSeed(long)
+ */
+ public void noiseSeed(long seed) {
+ if (perlinRandom == null) perlinRandom = new Random();
+ perlinRandom.setSeed(seed);
+ // force table reset after changing the random number seed [0122]
+ perlin = null;
+ }
+
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+
+ public PImage loadImage(String filename) { //, Object params) {
+// return loadImage(filename, null);
+ InputStream stream = createInput(filename);
+ if (stream == null) {
+ System.err.println("Could not find the image " + filename + ".");
+ return null;
+ }
+// long t = System.currentTimeMillis();
+ Bitmap bitmap = null;
+ try {
+ bitmap = BitmapFactory.decodeStream(stream);
+ } finally {
+ try {
+ stream.close();
+ stream = null;
+ } catch (IOException e) { }
+ }
+// int much = (int) (System.currentTimeMillis() - t);
+// println("loadImage(" + filename + ") was " + nfc(much));
+ if (bitmap == null) {
+ System.err.println("Could not load the image because the bitmap was empty.");
+ return null;
+ } else {
+ PImage image = new PImage(bitmap);
+ image.parent = this;
+ return image;
+ }
+ }
+
+
+ public PImage loadImage(String filename, String extension) {
+ return loadImage(filename);
+ }
+
+
+ public PImage requestImage(String filename) {
+ PImage vessel = createImage(0, 0, ARGB);
+ AsyncImageLoader ail = new AsyncImageLoader(filename, 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;
+
+ // Removed 'extension' from the android version. If the extension is needed
+ // later, re-copy this from the original PApplet code.
+ class AsyncImageLoader extends Thread {
+ String filename;
+ PImage vessel;
+
+ public AsyncImageLoader(String filename, PImage vessel) {
+ this.filename = filename;
+ this.vessel = vessel;
+ }
+
+ @Override
+ public void run() {
+ while (requestImageCount == requestImageMax) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) { }
+ }
+ requestImageCount++;
+
+ PImage actual = loadImage(filename);
+
+ // 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;
+ // an android, pixels[] will probably be null, we want this one
+ vessel.bitmap = actual.bitmap;
+
+ vessel.pixelWidth = actual.width;
+ vessel.pixelHeight = actual.height;
+ vessel.pixelDensity = 1;
+ }
+ requestImageCount--;
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // DATA I/O
+
+
+ public XML createXML(String name) {
+ try {
+ return new XML(name);
+ } catch (Exception e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+
+ /**
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL.
+ * @see XML#parse(String)
+ * @see PApplet#loadBytes(String)
+ * @see PApplet#loadStrings(String)
+ * @see PApplet#loadTable(String)
+ */
+ public XML loadXML(String filename) {
+ return loadXML(filename, null);
+ }
+
+
+ // version that uses 'options' though there are currently no supported options
+ public XML loadXML(String filename, String options) {
+ try {
+ return new XML(createInput(filename), options);
+ } catch (Exception e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+
+ public XML parseXML(String xmlString) {
+ return parseXML(xmlString, null);
+ }
+
+
+ public XML parseXML(String xmlString, String options) {
+ try {
+ return XML.parse(xmlString, options);
+ } catch (Exception e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+
+ public boolean saveXML(XML xml, String filename) {
+ return saveXML(xml, filename, null);
+ }
+
+
+ public boolean saveXML(XML xml, String filename, String options) {
+ return xml.save(saveFile(filename), options);
+ }
+
+
+ /**
+ * @webref input:files
+ * @param input String to parse as a JSONObject
+ * @see PApplet#loadJSONObject(String)
+ * @see PApplet#saveJSONObject(JSONObject, String)
+ */
+ public JSONObject parseJSONObject(String input) {
+ return new JSONObject(new StringReader(input));
+ }
+
+
+ /**
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL
+ * @see JSONObject
+ * @see JSONArray
+ * @see PApplet#loadJSONArray(String)
+ * @see PApplet#saveJSONObject(JSONObject, String)
+ * @see PApplet#saveJSONArray(JSONArray, String)
+ */
+ public JSONObject loadJSONObject(String filename) {
+ // can't pass of createReader() to the constructor b/c of resource leak
+ BufferedReader reader = createReader(filename);
+ JSONObject outgoing = new JSONObject(reader);
+ try {
+ reader.close();
+ } catch (IOException e) { // not sure what would cause this
+ e.printStackTrace();
+ }
+ return outgoing;
+ }
+
+
+ static public JSONObject loadJSONObject(File file) {
+ // can't pass of createReader() to the constructor b/c of resource leak
+ BufferedReader reader = createReader(file);
+ JSONObject outgoing = new JSONObject(reader);
+ try {
+ reader.close();
+ } catch (IOException e) { // not sure what would cause this
+ e.printStackTrace();
+ }
+ return outgoing;
+ }
+
+
+ /**
+ * @webref output:files
+ * @see JSONObject
+ * @see JSONArray
+ * @see PApplet#loadJSONObject(String)
+ * @see PApplet#loadJSONArray(String)
+ * @see PApplet#saveJSONArray(JSONArray, String)
+ */
+ public boolean saveJSONObject(JSONObject json, String filename) {
+ return saveJSONObject(json, filename, null);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public boolean saveJSONObject(JSONObject json, String filename, String options) {
+ return json.save(saveFile(filename), options);
+ }
+
+
+ /**
+ * @webref input:files
+ * @param input String to parse as a JSONArray
+ * @see JSONObject
+ * @see PApplet#loadJSONObject(String)
+ * @see PApplet#saveJSONObject(JSONObject, String)
+ */
+ public JSONArray parseJSONArray(String input) {
+ return new JSONArray(new StringReader(input));
+ }
+
+
+ /**
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL
+ * @see JSONArray
+ * @see PApplet#loadJSONObject(String)
+ * @see PApplet#saveJSONObject(JSONObject, String)
+ * @see PApplet#saveJSONArray(JSONArray, String)
+ */
+ public JSONArray loadJSONArray(String filename) {
+ // can't pass of createReader() to the constructor b/c of resource leak
+ BufferedReader reader = createReader(filename);
+ JSONArray outgoing = new JSONArray(reader);
+ try {
+ reader.close();
+ } catch (IOException e) { // not sure what would cause this
+ e.printStackTrace();
+ }
+ return outgoing;
+ }
+
+
+ static public JSONArray loadJSONArray(File file) {
+ // can't pass of createReader() to the constructor b/c of resource leak
+ BufferedReader reader = createReader(file);
+ JSONArray outgoing = new JSONArray(reader);
+ try {
+ reader.close();
+ } catch (IOException e) { // not sure what would cause this
+ e.printStackTrace();
+ }
+ return outgoing;
+ }
+
+
+ /**
+ * @webref output:files
+ * @see JSONObject
+ * @see JSONArray
+ * @see PApplet#loadJSONObject(String)
+ * @see PApplet#loadJSONArray(String)
+ * @see PApplet#saveJSONObject(JSONObject, String)
+ */
+ public boolean saveJSONArray(JSONArray json, String filename) {
+ return saveJSONArray(json, filename, null);
+ }
+
+
+ public boolean saveJSONArray(JSONArray json, String filename, String options) {
+ return json.save(saveFile(filename), options);
+ }
+
+
+ public Table createTable() {
+ return new Table();
+ }
+
+
+ /**
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL.
+ * @see PApplet#loadBytes(String)
+ * @see PApplet#loadStrings(String)
+ * @see PApplet#loadXML(String)
+ */
+ public Table loadTable(String filename) {
+ return loadTable(filename, null);
+ }
+
+
+ public Table loadTable(String filename, String options) {
+ try {
+ String ext = checkExtension(filename);
+ if (ext != null) {
+ if (ext.equals("csv") || ext.equals("tsv")) {
+ if (options == null) {
+ options = ext;
+ } else {
+ options = ext + "," + options;
+ }
+ }
+ }
+ return new Table(createInput(filename), options);
+
+ } catch (IOException e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+
+ public boolean saveTable(Table table, String filename) {
+ return saveTable(table, filename, null);
+ }
+
+
+ public boolean saveTable(Table table, String filename, String options) {
+ try {
+ table.save(saveFile(filename), options);
+ return true;
+ } catch (IOException e) {
+ printStackTrace(e);
+ }
+ return false;
+ }
+
+
+
+ // FONT I/O
+
+
+ public PFont loadFont(String filename) {
+ try {
+ InputStream input = createInput(filename);
+ return new PFont(input);
+
+ } catch (Exception e) {
+ die("Could not load font " + filename + ". " +
+ "Make sure that the font has been copied " +
+ "to the data folder of your sketch.", e);
+ }
+ return null;
+ }
+
+
+ /**
+ * Used by PGraphics to remove the requirement for loading a font!
+ */
+ protected PFont createDefaultFont(float size) {
+ return createFont("SansSerif", size, true, null);
+ }
+
+
+ public PFont createFont(String name, float size) {
+ return createFont(name, size, true, null);
+ }
+
+
+ public PFont createFont(String name, float size, boolean smooth) {
+ return createFont(name, size, smooth, null);
+ }
+
+
+ /**
+ * Create a bitmap 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.
+ *
+ * Use 'null' for the charset if you want to dynamically create
+ * character bitmaps only as they're needed.
+ */
+ public PFont createFont(String name, float size,
+ boolean smooth, char[] charset) {
+ String lowerName = name.toLowerCase();
+ Typeface baseFont = null;
+
+ if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
+ AssetManager assets = surface.getAssets();
+ baseFont = Typeface.createFromAsset(assets, name);
+ } else {
+ baseFont = (Typeface) PFont.findNative(name);
+ }
+ return new PFont(baseFont, round(size), smooth, charset);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILE/FOLDER SELECTION
+
+ // Doesn't appear to be implemented by Android, but this article might help:
+ // http://linuxdevices.com/articles/AT6247038002.html
+
+// 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...");
+// }
+//
+//
+// /**
+// * 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.
+// * @return full path to the selected file, or null if canceled.
+// */
+// 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 select a file for output.
+// * @param prompt Mesage to show the user when prompting for a file.
+// * @return full path to the file entered, or null if canceled.
+// */
+// 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;
+// }
+// }
+//
+//
+// /**
+// * 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.
+// * @return full path to the selected folder, or null if no selection.
+// */
+// 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;
+// }
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // LISTING DIRECTORIES
+
+
+ public String[] listPaths(String path, String... options) {
+ File[] list = listFiles(path, options);
+
+ int offset = 0;
+ for (String opt : options) {
+ if (opt.equals("relative")) {
+ if (!path.endsWith(File.pathSeparator)) {
+ path += File.pathSeparator;
+ }
+ offset = path.length();
+ break;
+ }
+ }
+ String[] outgoing = new String[list.length];
+ for (int i = 0; i < list.length; i++) {
+ // as of Java 1.8, substring(0) returns the original object
+ outgoing[i] = list[i].getAbsolutePath().substring(offset);
+ }
+ return outgoing;
+ }
+
+
+ public File[] listFiles(String path, String... options) {
+ File file = new File(path);
+ // if not an absolute path, make it relative to the sketch folder
+ if (!file.isAbsolute()) {
+ file = sketchFile(path);
+ }
+ return listFiles(file, options);
+ }
+
+
+ // "relative" -> no effect with the Files version, but important for listPaths
+ // "recursive"
+ // "extension=js" or "extensions=js|csv|txt" (no dot)
+ // "directories" -> only directories
+ // "files" -> only files
+ // "hidden" -> include hidden files (prefixed with .) disabled by default
+ static public File[] listFiles(File base, String... options) {
+ boolean recursive = false;
+ String[] extensions = null;
+ boolean directories = true;
+ boolean files = true;
+ boolean hidden = false;
+
+ for (String opt : options) {
+ if (opt.equals("recursive")) {
+ recursive = true;
+ } else if (opt.startsWith("extension=")) {
+ extensions = new String[] { opt.substring(10) };
+ } else if (opt.startsWith("extensions=")) {
+ extensions = split(opt.substring(10), ',');
+ } else if (opt.equals("files")) {
+ directories = false;
+ } else if (opt.equals("directories")) {
+ files = false;
+ } else if (opt.equals("hidden")) {
+ hidden = true;
+ } else if (opt.equals("relative")) {
+ // ignored
+ } else {
+ throw new RuntimeException(opt + " is not a listFiles() option");
+ }
+ }
+
+ if (extensions != null) {
+ for (int i = 0; i < extensions.length; i++) {
+ extensions[i] = "." + extensions[i];
+ }
+ }
+
+ if (!files && !directories) {
+ // just make "only files" and "only directories" mean... both
+ files = true;
+ directories = true;
+ }
+
+ if (!base.canRead()) {
+ return null;
+ }
+
+ List outgoing = new ArrayList<>();
+ listFilesImpl(base, recursive, extensions, hidden, directories, files, outgoing);
+ return outgoing.toArray(new File[0]);
+ }
+
+
+ static void listFilesImpl(File folder, boolean recursive,
+ String[] extensions, boolean hidden,
+ boolean directories, boolean files,
+ List list) {
+ File[] items = folder.listFiles();
+ if (items != null) {
+ for (File item : items) {
+ String name = item.getName();
+ if (!hidden && name.charAt(0) == '.') {
+ continue;
+ }
+ if (item.isDirectory()) {
+ if (recursive) {
+ listFilesImpl(item, recursive, extensions, hidden, directories, files, list);
+ }
+ if (directories) {
+ list.add(item);
+ }
+ } else if (files) {
+ if (extensions == null) {
+ list.add(item);
+ } else {
+ for (String ext : extensions) {
+ if (item.getName().toLowerCase().endsWith(ext)) {
+ list.add(item);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // EXTENSIONS
+
+
+ /**
+ * Get the compression-free extension for this filename.
+ * @param filename The filename to check
+ * @return an extension, skipping past .gz if it's present
+ */
+ static public String checkExtension(String filename) {
+ // Don't consider the .gz as part of the name, createInput()
+ // and createOuput() will take care of fixing that up.
+ if (filename.toLowerCase().endsWith(".gz")) {
+ filename = filename.substring(0, filename.length() - 3);
+ }
+ int dotIndex = filename.lastIndexOf('.');
+ if (dotIndex != -1) {
+ return filename.substring(dotIndex + 1).toLowerCase();
+ }
+ 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 =
+ new InputStreamReader(input, CompatUtils.getCharsetUTF8());
+
+ BufferedReader reader = new BufferedReader(isr);
+ // consume the Unicode BOM (byte order marker) if present
+ try {
+ reader.mark(1);
+ int c = reader.read();
+ // if not the BOM, back up to the beginning again
+ if (c != '\uFEFF') {
+ reader.reset();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return reader;
+ }
+
+
+ /**
+ * 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 {
+ 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) {
+ BufferedOutputStream bos = new BufferedOutputStream(output, 8192);
+ OutputStreamWriter osw =
+ new OutputStreamWriter(bos, CompatUtils.getCharsetUTF8());
+ return new PrintWriter(osw);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILE INPUT
+
+
+ /**
+ * 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)
+ *
+ */
+ public InputStream createInput(String filename) {
+ InputStream input = createInputRaw(filename);
+ final String lower = filename.toLowerCase();
+ if ((input != null) &&
+ (lower.endsWith(".gz") || lower.endsWith(".svgz"))) {
+ try {
+ // buffered has to go *around* the GZ, otherwise 25x slower
+ return new BufferedInputStream(new GZIPInputStream(input));
+ } catch (IOException e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+ return new BufferedInputStream(input);
+ }
+
+
+ /**
+ * Call createInput() without automatic gzip decompression.
+ */
+ public InputStream createInputRaw(String filename) {
+ // Additional considerations for Android version:
+ // http://developer.android.com/guide/topics/resources/resources-i18n.html
+ 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 {
+ // Workaround for Android bug 6066
+ // http://code.google.com/p/android/issues/detail?id=6066
+ // http://code.google.com/p/processing/issues/detail?id=629
+// URL url = new URL(filename);
+// stream = url.openStream();
+// return stream;
+ URL url = new URL(filename);
+ HttpURLConnection con = (HttpURLConnection) url.openConnection();
+ con.setRequestMethod("GET");
+ con.setDoInput(true);
+ con.connect();
+ return con.getInputStream();
+ //The following code is deprecaded by Android
+// HttpGet httpRequest = null;
+// httpRequest = new HttpGet(URI.create(filename));
+// HttpClient httpclient = new DefaultHttpClient();
+// HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
+// HttpEntity entity = response.getEntity();
+// return entity.getContent();
+ // can't use BufferedHttpEntity because it may try to allocate a byte
+ // buffer of the size of the download, bad when DL is 25 MB... [0200]
+// BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
+// return bufHttpEntity.getContent();
+
+ } 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
+ printStackTrace(e);
+ //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)
+
+ /*
+ // this works, but requires files to be stored in the src folder
+ ClassLoader cl = getClass().getClassLoader();
+ stream = cl.getResourceAsStream(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;
+ }
+ }
+ */
+
+ // Try the assets folder
+ AssetManager assets = surface.getAssets();
+ try {
+ stream = assets.open(filename);
+ if (stream != null) {
+ return stream;
+ }
+ } catch (IOException e) {
+ // ignore this and move on
+ //e.printStackTrace();
+ }
+
+ // Maybe this is an absolute path, didja ever think of that?
+ File absFile = new File(filename);
+ if (absFile.exists()) {
+ try {
+ stream = new FileInputStream(absFile);
+ if (stream != null) {
+ return stream;
+ }
+ } catch (FileNotFoundException fnfe) {
+ //fnfe.printStackTrace();
+ }
+ }
+
+ // Maybe this is a file that was written by the sketch on another occasion.
+ File sketchFile = new File(sketchPath(filename));
+ if (sketchFile.exists()) {
+ try {
+ stream = new FileInputStream(sketchFile);
+ if (stream != null) {
+ return stream;
+ }
+ } catch (FileNotFoundException fnfe) {
+ //fnfe.printStackTrace();
+ }
+ }
+
+ // Attempt to load the file more directly. Doesn't like paths.
+// try {
+// // MODE_PRIVATE is default, should we use something else?
+// stream = surface.openFileInput(filename);
+// if (stream != null) {
+// return stream;
+// }
+// } catch (FileNotFoundException e) {
+// // ignore this and move on
+// //e.printStackTrace();
+// }
+
+ return surface.openFileInput(filename);
+ }
+
+
+ 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 BufferedInputStream(new GZIPInputStream(input));
+ }
+ return new BufferedInputStream(input);
+
+ } catch (IOException e) {
+ System.err.println("Could not createInput() for " + file);
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+
+ 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;
+ }
+
+
+ static public String[] loadStrings(BufferedReader reader) {
+ try {
+ 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;
+ }
+
+
+ /**
+ * 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.
+ */
+ 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) {
+ try {
+ // in spite of appearing to be the 'correct' option, this doesn't allow
+ // for paths, so no subfolders, none of that savePath() goodness.
+// Context context = getApplicationContext();
+// // MODE_PRIVATE is default, should we use that instead?
+// return context.openFileOutput(filename, MODE_WORLD_READABLE);
+
+ File file = new File(filename);
+ if (!file.isAbsolute()) {
+ file = new File(sketchPath(filename));
+ }
+ FileOutputStream fos = new FileOutputStream(file);
+ if (file.getName().toLowerCase().endsWith(".gz")) {
+ return new GZIPOutputStream(fos);
+ }
+ return fos;
+
+ } catch (IOException e) {
+ printStackTrace(e);
+ }
+ return null;
+ }
+
+
+ static public OutputStream createOutput(File file) {
+ try {
+ createPath(file); // make sure the path exists
+ OutputStream output = new FileOutputStream(file);
+ if (file.getName().toLowerCase().endsWith(".gz")) {
+ return new BufferedOutputStream(new GZIPOutputStream(output));
+ }
+ return new BufferedOutputStream(output);
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+
+ /**
+ * Save the contents of a stream to a file in the sketch folder.
+ * This is basically saveBytes(blah, loadBytes()), but done
+ * more efficiently (and with less confusing syntax).
+ */
+ public boolean saveStream(String targetFilename, String sourceLocation) {
+ return saveStream(saveFile(targetFilename), sourceLocation);
+ }
+
+
+ /**
+ * Identical to the other saveStream(), but writes to a File
+ * object, for greater control over the file location.
+ * Note that unlike other api methods, this will not automatically
+ * compress or uncompress gzip files.
+ */
+ public boolean saveStream(File targetFile, String sourceLocation) {
+ return saveStream(targetFile, createInputRaw(sourceLocation));
+ }
+
+
+ public boolean saveStream(String targetFilename, InputStream sourceStream) {
+ return saveStream(saveFile(targetFilename), sourceStream);
+ }
+
+
+ static public boolean saveStream(File target, InputStream source) {
+ File tempFile = null;
+ try {
+ // make sure that this path actually exists before writing
+ createPath(target);
+ tempFile = createTempFile(target);
+ FileOutputStream targetStream = new FileOutputStream(tempFile);
+
+ saveStream(targetStream, source);
+ targetStream.close();
+ targetStream = null;
+
+ if (target.exists()) {
+ if (!target.delete()) {
+ System.err.println("Could not replace " +
+ target.getAbsolutePath() + ".");
+ }
+ }
+ if (!tempFile.renameTo(target)) {
+ System.err.println("Could not rename temporary file " +
+ tempFile.getAbsolutePath());
+ return false;
+ }
+ return true;
+
+ } catch (IOException e) {
+ if (tempFile != null) {
+ tempFile.delete();
+ }
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+
+ static public void saveStream(OutputStream target,
+ InputStream source) throws IOException {
+ BufferedInputStream bis = new BufferedInputStream(source, 16384);
+ BufferedOutputStream bos = new BufferedOutputStream(target);
+
+ byte[] buffer = new byte[8192];
+ int bytesRead;
+ while ((bytesRead = bis.read(buffer)) != -1) {
+ bos.write(buffer, 0, bytesRead);
+ }
+
+ bos.flush();
+ }
+
+
+ /**
+ * 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[] data) {
+ saveBytes(saveFile(filename), data);
+ }
+
+
+ /**
+ * Creates a temporary file based on the name/extension of another file
+ * and in the same parent directory. Ensures that the same extension is used
+ * (i.e. so that .gz files are gzip compressed on output) and that it's done
+ * from the same directory so that renaming the file later won't cross file
+ * system boundaries.
+ */
+ static private File createTempFile(File file) throws IOException {
+ File parentDir = file.getParentFile();
+ String name = file.getName();
+ String prefix;
+ String suffix = null;
+ int dot = name.lastIndexOf('.');
+ if (dot == -1) {
+ prefix = name;
+ } else {
+ // preserve the extension so that .gz works properly
+ prefix = name.substring(0, dot);
+ suffix = name.substring(dot);
+ }
+ // Prefix must be three characters
+ if (prefix.length() < 3) {
+ prefix += "processing";
+ }
+ return File.createTempFile(prefix, suffix, parentDir);
+ }
+
+
+ /**
+ * Saves bytes to a specific File location specified by the user.
+ */
+ static public void saveBytes(File file, byte[] data) {
+ File tempFile = null;
+ try {
+ tempFile = createTempFile(file);
+
+ OutputStream output = createOutput(tempFile);
+ saveBytes(output, data);
+ output.close();
+ output = null;
+
+ if (file.exists()) {
+ if (!file.delete()) {
+ System.err.println("Could not replace " + file.getAbsolutePath());
+ }
+ }
+
+ 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[] data) {
+ try {
+ output.write(data);
+ 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[]) {
+ 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[]) {
+ try {
+ OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
+ PrintWriter writer = new PrintWriter(osw);
+ for (int i = 0; i < strings.length; i++) {
+ writer.println(strings[i]);
+ }
+ writer.flush();
+ } catch (UnsupportedEncodingException e) { } // will not happen
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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 surface.getFileStreamPath(where).getAbsolutePath();
+ }
+
+
+ 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;
+// System.out.println("filename before sketchpath is " + where);
+ String filename = sketchPath(where);
+// System.out.println("filename after sketchpath is " + filename);
+ 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.
+ *
+ * The behavior of this function differs from the equivalent on the Java mode: files stored in
+ * the data folder of the sketch get packed as assets in the apk, and the path to the data folder
+ * is no longer valid. Only the name is needed to open them. However, if the file is not an asset,
+ * we can assume it has been created by the sketch, so it should have the sketch path.
+ * Discussed here:
+ * https://github.com/processing/processing-android/issues/450
+ */
+ public String dataPath(String where) {
+ // First, we check if it is asset:
+ boolean isAsset = false;
+ AssetManager assets = surface.getAssets();
+ InputStream is = null;
+ try {
+ is = assets.open(where);
+ isAsset = true;
+ } catch (IOException ex) {
+ //file does not exist
+ } finally {
+ try {
+ is.close();
+ } catch (Exception ex) { }
+ }
+ if (isAsset) return where;
+ // Not an asset, let's just use sketch path:
+ return sketchPath(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());
+ }
+ }
+
+
+ static public String getExtension(String filename) {
+ String extension;
+
+ 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);
+ }
+
+ return extension;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // URL ENCODING
+
+ static public String urlEncode(String what) {
+ try {
+ return URLEncoder.encode(what, "UTF-8");
+ } catch (UnsupportedEncodingException e) { // oh c'mon
+ return null;
+ }
+ }
+
+
+ static public String urlDecode(String what) {
+ try {
+ return URLDecoder.decode(what, "UTF-8");
+ } catch (UnsupportedEncodingException e) { // safe per the JDK source
+ return null;
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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));
+ }
+
+ //
+
+ 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 long[] expand(long list[]) {
+ return expand(list, list.length > 0 ? list.length << 1 : 1);
+ }
+
+ static public long[] expand(long list[], int newSize) {
+ long temp[] = new long[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 double[] expand(double list[]) {
+ return expand(list, list.length > 0 ? list.length << 1 : 1);
+ }
+
+ static public double[] expand(double list[], int newSize) {
+ double temp[] = new double[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 long[] subset(long[] list, int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public long[] subset(long[] list, int start, int count) {
+ long[] output = new long[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 double[] subset(double[] list, int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public double[] subset(double[] list, int start, int count) {
+ double[] output = new double[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+ static public String[] subset(String list[], int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public String[] subset(String list[], int start, int count) {
+ String output[] = new String[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+
+ static public Object subset(Object list, int start) {
+ int length = Array.getLength(list);
+ return subset(list, start, length - start);
+ }
+
+ static public Object subset(Object list, int start, int count) {
+ Class> type = list.getClass().getComponentType();
+ Object outgoing = Array.newInstance(type, count);
+ System.arraycopy(list, start, outgoing, 0, count);
+ return outgoing;
+ }
+
+ //
+
+ static public boolean[] concat(boolean a[], boolean b[]) {
+ boolean c[] = new boolean[a.length + b.length];
+ System.arraycopy(a, 0, c, 0, a.length);
+ System.arraycopy(b, 0, c, a.length, b.length);
+ return c;
+ }
+
+ static public byte[] concat(byte a[], byte b[]) {
+ byte c[] = new byte[a.length + b.length];
+ System.arraycopy(a, 0, c, 0, a.length);
+ System.arraycopy(b, 0, c, a.length, b.length);
+ return c;
+ }
+
+ static public char[] concat(char a[], char b[]) {
+ char c[] = new char[a.length + b.length];
+ System.arraycopy(a, 0, c, 0, a.length);
+ System.arraycopy(b, 0, c, a.length, b.length);
+ return c;
+ }
+
+ static public int[] concat(int a[], int b[]) {
+ int c[] = new int[a.length + b.length];
+ System.arraycopy(a, 0, c, 0, a.length);
+ System.arraycopy(b, 0, c, a.length, b.length);
+ return c;
+ }
+
+ static public float[] concat(float a[], float b[]) {
+ float c[] = new float[a.length + b.length];
+ System.arraycopy(a, 0, c, 0, a.length);
+ System.arraycopy(b, 0, c, a.length, b.length);
+ return c;
+ }
+
+ static public String[] concat(String a[], String b[]) {
+ String c[] = new String[a.length + b.length];
+ System.arraycopy(a, 0, c, 0, a.length);
+ System.arraycopy(b, 0, c, a.length, b.length);
+ return c;
+ }
+
+ static public Object concat(Object a, Object b) {
+ Class> type = a.getClass().getComponentType();
+ int alength = Array.getLength(a);
+ int blength = Array.getLength(b);
+ Object outgoing = Array.newInstance(type, alength + blength);
+ System.arraycopy(a, 0, outgoing, 0, alength);
+ System.arraycopy(b, 0, outgoing, alength, blength);
+ return outgoing;
+ }
+
+ //
+
+ static public boolean[] reverse(boolean list[]) {
+ boolean outgoing[] = new boolean[list.length];
+ int length1 = list.length - 1;
+ for (int i = 0; i < list.length; i++) {
+ outgoing[i] = list[length1 - i];
+ }
+ return outgoing;
+ }
+
+ static public byte[] reverse(byte list[]) {
+ byte outgoing[] = new byte[list.length];
+ int length1 = list.length - 1;
+ for (int i = 0; i < list.length; i++) {
+ outgoing[i] = list[length1 - i];
+ }
+ return outgoing;
+ }
+
+ static public char[] reverse(char list[]) {
+ char outgoing[] = new char[list.length];
+ int length1 = list.length - 1;
+ for (int i = 0; i < list.length; i++) {
+ outgoing[i] = list[length1 - i];
+ }
+ return outgoing;
+ }
+
+ static public int[] reverse(int list[]) {
+ int outgoing[] = new int[list.length];
+ int length1 = list.length - 1;
+ for (int i = 0; i < list.length; i++) {
+ outgoing[i] = list[length1 - i];
+ }
+ return outgoing;
+ }
+
+ static public float[] reverse(float list[]) {
+ float outgoing[] = new float[list.length];
+ int length1 = list.length - 1;
+ for (int i = 0; i < list.length; i++) {
+ outgoing[i] = list[length1 - i];
+ }
+ return outgoing;
+ }
+
+ static public String[] reverse(String list[]) {
+ String outgoing[] = new String[list.length];
+ int length1 = list.length - 1;
+ for (int i = 0; i < list.length; i++) {
+ outgoing[i] = list[length1 - i];
+ }
+ return outgoing;
+ }
+
+ static public Object reverse(Object list) {
+ Class> type = list.getClass().getComponentType();
+ int length = Array.getLength(list);
+ Object outgoing = Array.newInstance(type, length);
+ for (int i = 0; i < length; i++) {
+ Array.set(outgoing, i, Array.get(list, (length - 1) - i));
+ }
+ return outgoing;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STRINGS
+
+
+ /**
+ * Remove whitespace characters from the beginning and ending
+ * of a String. Works like String.trim() but includes the
+ * unicode nbsp character as well.
+ */
+ static public String trim(String str) {
+ return str.replace('\u00A0', ' ').trim();
+ }
+
+
+ /**
+ * Trim the whitespace from a String array. This returns a new
+ * array and does not affect the passed-in array.
+ */
+ static public String[] trim(String[] array) {
+ String[] outgoing = new String[array.length];
+ for (int i = 0; i < array.length; i++) {
+ if (array[i] != null) {
+ outgoing[i] = array[i].replace('\u00A0', ' ').trim();
+ }
+ }
+ return outgoing;
+ }
+
+
+ /**
+ * Join an array of Strings together as a single String,
+ * separated by the whatever's passed in for the separator.
+ */
+ static public String join(String str[], char separator) {
+ return join(str, String.valueOf(separator));
+ }
+
+
+ /**
+ * Join an array of Strings together as a single String,
+ * separated by the whatever's passed in for the separator.
+ *
+ * To use this on numbers, first pass the array to nf() or nfs()
+ * to get a list of String objects, then use join on that.
+ *
+ * e.g. String stuff[] = { "apple", "bear", "cat" };
+ * String list = join(stuff, ", ");
+ * // list is now "apple, bear, cat"
+ */
+ static public String join(String str[], String separator) {
+ StringBuffer buffer = new StringBuffer();
+ for (int i = 0; i < str.length; i++) {
+ if (i != 0) buffer.append(separator);
+ buffer.append(str[i]);
+ }
+ return buffer.toString();
+ }
+
+
+ /**
+ * Split the provided String at wherever whitespace occurs.
+ * Multiple whitespace (extra spaces or tabs or whatever)
+ * between items will count as a single break.
+ *
+ * The whitespace characters are "\t\n\r\f", which are the defaults
+ * for java.util.StringTokenizer, plus the unicode non-breaking space
+ * character, which is found commonly on files created by or used
+ * in conjunction with Mac OS X (character 160, or 0x00A0 in hex).
+ *
+ */
+ 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.
+ *
+ */
+ static public String[] splitTokens(String what, String delim) {
+ StringTokenizer toker = new StringTokenizer(what, delim);
+ String pieces[] = new String[toker.countTokens()];
+
+ int index = 0;
+ while (toker.hasMoreTokens()) {
+ pieces[index++] = toker.nextToken();
+ }
+ return pieces;
+ }
+
+
+ /**
+ * Split a string into pieces along a specific character.
+ * Most commonly used to break up a String along a space or a tab
+ * character.
+ *
+ * This operates differently than the others, where the
+ * single delimeter is the only breaking point, and consecutive
+ * delimeters will produce an empty string (""). This way,
+ * one can split on tab characters, but maintain the column
+ * alignments (of say an excel file) where there are empty columns.
+ */
+ static public String[] split(String what, char delim) {
+ // do this so that the exception occurs inside the user's
+ // program, rather than appearing to be a bug inside split()
+ if (what == null) return null;
+ //return split(what, String.valueOf(delim)); // huh
+
+ char chars[] = what.toCharArray();
+ int splitCount = 0; //1;
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == delim) splitCount++;
+ }
+ // make sure that there is something in the input string
+ //if (chars.length > 0) {
+ // if the last char is a delimeter, get rid of it..
+ //if (chars[chars.length-1] == delim) splitCount--;
+ // on second thought, i don't agree with this, will disable
+ //}
+ if (splitCount == 0) {
+ String splits[] = new String[1];
+ splits[0] = new String(what);
+ return splits;
+ }
+ //int pieceCount = splitCount + 1;
+ String splits[] = new String[splitCount + 1];
+ int splitIndex = 0;
+ int startIndex = 0;
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == delim) {
+ splits[splitIndex++] =
+ new String(chars, startIndex, i-startIndex);
+ startIndex = i + 1;
+ }
+ }
+ //if (startIndex != chars.length) {
+ splits[splitIndex] =
+ new String(chars, startIndex, chars.length-startIndex);
+ //}
+ return splits;
+ }
+
+
+ /**
+ * Split a String on a specific delimiter. Unlike Java's String.split()
+ * method, this does not parse the delimiter as a regexp because it's more
+ * confusing than necessary, and String.split() is always available for
+ * those who want regexp.
+ */
+ static public String[] split(String what, String delim) {
+ ArrayList items = new ArrayList();
+ int index;
+ int offset = 0;
+ while ((index = what.indexOf(delim, offset)) != -1) {
+ items.add(what.substring(offset, index));
+ offset = index + delim.length();
+ }
+ items.add(what.substring(offset));
+ String[] outgoing = new String[items.size()];
+ items.toArray(outgoing);
+ return outgoing;
+ }
+
+
+ static protected HashMap matchPatterns;
+
+ static Pattern matchPattern(String regexp) {
+ Pattern p = null;
+ if (matchPatterns == null) {
+ matchPatterns = new HashMap();
+ } else {
+ p = matchPatterns.get(regexp);
+ }
+ if (p == null) {
+ if (matchPatterns.size() == 10) {
+ // Just clear out the match patterns here if more than 10 are being
+ // used. It's not terribly efficient, but changes that you have >10
+ // different match patterns are very slim, unless you're doing
+ // something really tricky (like custom match() methods), in which
+ // case match() won't be efficient anyway. (And you should just be
+ // using your own Java code.) The alternative is using a queue here,
+ // but that's a silly amount of work for negligible benefit.
+ matchPatterns.clear();
+ }
+ p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
+ matchPatterns.put(regexp, p);
+ }
+ return p;
+ }
+
+
+ /**
+ * Match a string with a regular expression, and returns the match as an
+ * array. The first index is the matching expression, and array elements
+ * [1] and higher represent each of the groups (sequences found in parens).
+ *
+ * This uses multiline matching (Pattern.MULTILINE) and dotall mode
+ * (Pattern.DOTALL) by default, so that ^ and $ match the beginning and
+ * end of any lines found in the source, and the . operator will also
+ * pick up newline characters.
+ */
+ static public String[] match(String what, String regexp) {
+ Pattern p = matchPattern(regexp);
+ Matcher m = p.matcher(what);
+ if (m.find()) {
+ int count = m.groupCount() + 1;
+ String[] groups = new String[count];
+ for (int i = 0; i < count; i++) {
+ groups[i] = m.group(i);
+ }
+ return groups;
+ }
+ return null;
+ }
+
+
+ /**
+ * Identical to match(), except that it returns an array of all matches in
+ * the specified String, rather than just the first.
+ */
+ static public String[][] matchAll(String what, String regexp) {
+ Pattern p = matchPattern(regexp);
+ Matcher m = p.matcher(what);
+ ArrayList results = new ArrayList();
+ int count = m.groupCount() + 1;
+ while (m.find()) {
+ String[] groups = new String[count];
+ for (int i = 0; i < count; i++) {
+ groups[i] = m.group(i);
+ }
+ results.add(groups);
+ }
+ if (results.isEmpty()) {
+ return null;
+ }
+ String[][] matches = new String[results.size()][count];
+ for (int i = 0; i < matches.length; i++) {
+ matches[i] = (String[]) results.get(i);
+ }
+ return matches;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CASTING FUNCTIONS, INSERTED BY PREPROC
+
+
+ /**
+ * Convert a char to a boolean. 'T', 't', and '1' will become the
+ * boolean value true, while 'F', 'f', or '0' will become false.
+ */
+ /*
+ static final public boolean parseBoolean(char what) {
+ return ((what == 't') || (what == 'T') || (what == '1'));
+ }
+ */
+
+ /**
+ *
Convert an integer to a boolean. Because of how Java handles upgrading
+ * numbers, this will also cover byte and char (as they will upgrade to
+ * an int without any sort of explicit cast).
+ *
The preprocessor will convert boolean(what) to parseBoolean(what).
+ * @return false if 0, true if any other number
+ */
+ static final public boolean parseBoolean(int what) {
+ return (what != 0);
+ }
+
+ /*
+ // removed because this makes no useful sense
+ static final public boolean parseBoolean(float what) {
+ return (what != 0);
+ }
+ */
+
+ /**
+ * Convert the string "true" or "false" to a boolean.
+ * @return true if 'what' is "true" or "TRUE", false otherwise
+ */
+ static final public boolean parseBoolean(String what) {
+ return new Boolean(what).booleanValue();
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /*
+ // removed, no need to introduce strange syntax from other languages
+ static final public boolean[] parseBoolean(char what[]) {
+ boolean outgoing[] = new boolean[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] =
+ ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
+ }
+ return outgoing;
+ }
+ */
+
+ /**
+ * Convert a byte array to a boolean array. Each element will be
+ * evaluated identical to the integer case, where a byte equal
+ * to zero will return false, and any other value will return true.
+ * @return array of boolean elements
+ */
+ static final public boolean[] parseBoolean(byte what[]) {
+ boolean outgoing[] = new boolean[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (what[i] != 0);
+ }
+ return outgoing;
+ }
+
+ /**
+ * Convert an int array to a boolean array. An int equal
+ * to zero will return false, and any other value will return true.
+ * @return array of boolean elements
+ */
+ static final public boolean[] parseBoolean(int what[]) {
+ boolean outgoing[] = new boolean[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (what[i] != 0);
+ }
+ return outgoing;
+ }
+
+ /*
+ // removed, not necessary... if necessary, convert to int array first
+ static final public boolean[] parseBoolean(float what[]) {
+ boolean outgoing[] = new boolean[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (what[i] != 0);
+ }
+ return outgoing;
+ }
+ */
+
+ static final public boolean[] parseBoolean(String what[]) {
+ boolean outgoing[] = new boolean[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = new Boolean(what[i]).booleanValue();
+ }
+ return outgoing;
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ static final public byte parseByte(boolean what) {
+ return what ? (byte)1 : 0;
+ }
+
+ static final public byte parseByte(char what) {
+ return (byte) what;
+ }
+
+ static final public byte parseByte(int what) {
+ return (byte) what;
+ }
+
+ static final public byte parseByte(float what) {
+ return (byte) what;
+ }
+
+ /*
+ // nixed, no precedent
+ static final public byte[] parseByte(String what) { // note: array[]
+ return what.getBytes();
+ }
+ */
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ static final public byte[] parseByte(boolean what[]) {
+ byte outgoing[] = new byte[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = what[i] ? (byte)1 : 0;
+ }
+ return outgoing;
+ }
+
+ static final public byte[] parseByte(char what[]) {
+ byte outgoing[] = new byte[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (byte) what[i];
+ }
+ return outgoing;
+ }
+
+ static final public byte[] parseByte(int what[]) {
+ byte outgoing[] = new byte[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (byte) what[i];
+ }
+ return outgoing;
+ }
+
+ static final public byte[] parseByte(float what[]) {
+ byte outgoing[] = new byte[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (byte) what[i];
+ }
+ return outgoing;
+ }
+
+ /*
+ static final public byte[][] parseByte(String what[]) { // note: array[][]
+ byte outgoing[][] = new byte[what.length][];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = what[i].getBytes();
+ }
+ return outgoing;
+ }
+ */
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /*
+ static final public char parseChar(boolean what) { // 0/1 or T/F ?
+ return what ? 't' : 'f';
+ }
+ */
+
+ static final public char parseChar(byte what) {
+ return (char) (what & 0xff);
+ }
+
+ static final public char parseChar(int what) {
+ return (char) what;
+ }
+
+ /*
+ static final public char parseChar(float what) { // nonsensical
+ return (char) what;
+ }
+
+ static final public char[] parseChar(String what) { // note: array[]
+ return what.toCharArray();
+ }
+ */
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /*
+ static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
+ char outgoing[] = new char[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = what[i] ? 't' : 'f';
+ }
+ return outgoing;
+ }
+ */
+
+ static final public char[] parseChar(byte what[]) {
+ char outgoing[] = new char[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (char) (what[i] & 0xff);
+ }
+ return outgoing;
+ }
+
+ static final public char[] parseChar(int what[]) {
+ char outgoing[] = new char[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (char) what[i];
+ }
+ return outgoing;
+ }
+
+ /*
+ static final public char[] parseChar(float what[]) { // nonsensical
+ char outgoing[] = new char[what.length];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = (char) what[i];
+ }
+ return outgoing;
+ }
+
+ static final public char[][] parseChar(String what[]) { // note: array[][]
+ char outgoing[][] = new char[what.length][];
+ for (int i = 0; i < what.length; i++) {
+ outgoing[i] = what[i].toCharArray();
+ }
+ return outgoing;
+ }
+ */
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ static final public int parseInt(boolean what) {
+ return what ? 1 : 0;
+ }
+
+ /**
+ * Note that parseInt() will un-sign a signed byte value.
+ */
+ static final public int parseInt(byte what) {
+ return what & 0xff;
+ }
+
+ /**
+ * Note that parseInt('5') is unlike String in the sense that it
+ * won't return 5, but the ascii value. This is because ((int) someChar)
+ * returns the ascii value, and parseInt() is just longhand for the cast.
+ */
+ static final public int parseInt(char what) {
+ return what;
+ }
+
+ /**
+ * Same as floor(), or an (int) cast.
+ */
+ static final public int parseInt(float what) {
+ return (int) what;
+ }
+
+ /**
+ * Parse a String into an int value. Returns 0 if the value is bad.
+ */
+ static final public int parseInt(String what) {
+ return parseInt(what, 0);
+ }
+
+ /**
+ * Parse a String to an int, and provide an alternate value that
+ * should be used when the number is invalid.
+ */
+ static final public int parseInt(String what, int otherwise) {
+ try {
+ int offset = what.indexOf('.');
+ if (offset == -1) {
+ return Integer.parseInt(what);
+ } else {
+ return Integer.parseInt(what.substring(0, offset));
+ }
+ } catch (NumberFormatException e) { }
+ return otherwise;
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ static final public int[] parseInt(boolean what[]) {
+ int list[] = new int[what.length];
+ for (int i = 0; i < what.length; i++) {
+ list[i] = what[i] ? 1 : 0;
+ }
+ return list;
+ }
+
+ static final public int[] parseInt(byte what[]) { // note this unsigns
+ int list[] = new int[what.length];
+ for (int i = 0; i < what.length; i++) {
+ list[i] = (what[i] & 0xff);
+ }
+ return list;
+ }
+
+ static final public int[] parseInt(char what[]) {
+ int list[] = new int[what.length];
+ for (int i = 0; i < what.length; i++) {
+ list[i] = what[i];
+ }
+ return list;
+ }
+
+ static public int[] parseInt(float what[]) {
+ int inties[] = new int[what.length];
+ for (int i = 0; i < what.length; i++) {
+ inties[i] = (int)what[i];
+ }
+ return inties;
+ }
+
+ /**
+ * Make an array of int elements from an array of String objects.
+ * If the String can't be parsed as a number, it will be set to zero.
+ *
+ * String s[] = { "1", "300", "44" };
+ * int numbers[] = parseInt(s);
+ *
+ * numbers will contain { 1, 300, 44 }
+ */
+ static public int[] parseInt(String what[]) {
+ return parseInt(what, 0);
+ }
+
+ /**
+ * Make an array of int elements from an array of String objects.
+ * If the String can't be parsed as a number, its entry in the
+ * array will be set to the value of the "missing" parameter.
+ *
+ * String s[] = { "1", "300", "apple", "44" };
+ * int numbers[] = parseInt(s, 9999);
+ *
+ * numbers will contain { 1, 300, 9999, 44 }
+ */
+ static public int[] parseInt(String what[], int missing) {
+ int output[] = new int[what.length];
+ for (int i = 0; i < what.length; i++) {
+ try {
+ output[i] = Integer.parseInt(what[i]);
+ } catch (NumberFormatException e) {
+ output[i] = missing;
+ }
+ }
+ return output;
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /*
+ static final public float parseFloat(boolean what) {
+ return what ? 1 : 0;
+ }
+ */
+
+ /**
+ * Convert an int to a float value. Also handles bytes because of
+ * Java's rules for upgrading values.
+ */
+ static final public float parseFloat(int what) { // also handles byte
+ return (float)what;
+ }
+
+ static final public float parseFloat(String what) {
+ return parseFloat(what, Float.NaN);
+ }
+
+ static final public float parseFloat(String what, float otherwise) {
+ try {
+ return new Float(what).floatValue();
+ } catch (NumberFormatException e) { }
+
+ return otherwise;
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /*
+ static final public float[] parseFloat(boolean what[]) {
+ float floaties[] = new float[what.length];
+ for (int i = 0; i < what.length; i++) {
+ floaties[i] = what[i] ? 1 : 0;
+ }
+ return floaties;
+ }
+
+ static final public float[] parseFloat(char what[]) {
+ float floaties[] = new float[what.length];
+ for (int i = 0; i < what.length; i++) {
+ floaties[i] = (char) what[i];
+ }
+ return floaties;
+ }
+ */
+
+ static final public float[] parseByte(byte what[]) {
+ float floaties[] = new float[what.length];
+ for (int i = 0; i < what.length; i++) {
+ floaties[i] = what[i];
+ }
+ return floaties;
+ }
+
+ static final public float[] parseFloat(int what[]) {
+ float floaties[] = new float[what.length];
+ for (int i = 0; i < what.length; i++) {
+ floaties[i] = what[i];
+ }
+ return floaties;
+ }
+
+ static final public float[] parseFloat(String what[]) {
+ return parseFloat(what, Float.NaN);
+ }
+
+ static final public float[] parseFloat(String what[], float missing) {
+ float output[] = new float[what.length];
+ for (int i = 0; i < what.length; i++) {
+ try {
+ output[i] = new Float(what[i]).floatValue();
+ } catch (NumberFormatException e) {
+ output[i] = missing;
+ }
+ }
+ return output;
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ static final public String str(boolean x) {
+ return String.valueOf(x);
+ }
+
+ static final public String str(byte x) {
+ return String.valueOf(x);
+ }
+
+ static final public String str(char x) {
+ return String.valueOf(x);
+ }
+
+ static final public String str(int x) {
+ return String.valueOf(x);
+ }
+
+ static final public String str(float x) {
+ return String.valueOf(x);
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ static final public String[] str(boolean x[]) {
+ String s[] = new String[x.length];
+ for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
+ return s;
+ }
+
+ static final public String[] str(byte x[]) {
+ String s[] = new String[x.length];
+ for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
+ return s;
+ }
+
+ static final public String[] str(char x[]) {
+ String s[] = new String[x.length];
+ for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
+ return s;
+ }
+
+ static final public String[] str(int x[]) {
+ String s[] = new String[x.length];
+ for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
+ return s;
+ }
+
+ static final public String[] str(float x[]) {
+ String s[] = new String[x.length];
+ for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
+ return s;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // INT NUMBER FORMATTING
+
+
+ /**
+ * Integer number formatter.
+ */
+ static private NumberFormat int_nf;
+ static private int int_nf_digits;
+ static private boolean int_nf_commas;
+
+
+ static public String[] nf(int num[], int digits) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nf(num[i], digits);
+ }
+ return formatted;
+ }
+
+
+ static public String nf(int num, int digits) {
+ if ((int_nf != null) &&
+ (int_nf_digits == digits) &&
+ !int_nf_commas) {
+ return int_nf.format(num);
+ }
+
+ int_nf = NumberFormat.getInstance();
+ int_nf.setGroupingUsed(false); // no commas
+ int_nf_commas = false;
+ int_nf.setMinimumIntegerDigits(digits);
+ int_nf_digits = digits;
+ return int_nf.format(num);
+ }
+
+
+ static public String[] nfc(int num[]) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfc(num[i]);
+ }
+ return formatted;
+ }
+
+
+ static public String nfc(int num) {
+ if ((int_nf != null) &&
+ (int_nf_digits == 0) &&
+ int_nf_commas) {
+ return int_nf.format(num);
+ }
+
+ int_nf = NumberFormat.getInstance();
+ int_nf.setGroupingUsed(true);
+ int_nf_commas = true;
+ int_nf.setMinimumIntegerDigits(0);
+ int_nf_digits = 0;
+ return int_nf.format(num);
+ }
+
+
+ /**
+ * number format signed (or space)
+ * Formats a number but leaves a blank space in the front
+ * when it's positive so that it can be properly aligned with
+ * numbers that have a negative sign in front of them.
+ */
+ static public String nfs(int num, int digits) {
+ return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
+ }
+
+ static public String[] nfs(int num[], int digits) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfs(num[i], digits);
+ }
+ return formatted;
+ }
+
+ //
+
+ /**
+ * number format positive (or plus)
+ * Formats a number, always placing a - or + sign
+ * in the front when it's negative or positive.
+ */
+ static public String nfp(int num, int digits) {
+ return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
+ }
+
+ static public String[] nfp(int num[], int digits) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfp(num[i], digits);
+ }
+ return formatted;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FLOAT NUMBER FORMATTING
+
+
+ static private NumberFormat float_nf;
+ static private int float_nf_left, float_nf_right;
+ static private boolean float_nf_commas;
+
+
+ static public String[] nf(float num[], int left, int right) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nf(num[i], left, right);
+ }
+ return formatted;
+ }
+
+
+ static public String nf(float num, int left, int right) {
+ if ((float_nf != null) &&
+ (float_nf_left == left) &&
+ (float_nf_right == right) &&
+ !float_nf_commas) {
+ return float_nf.format(num);
+ }
+
+ float_nf = NumberFormat.getInstance();
+ float_nf.setGroupingUsed(false);
+ float_nf_commas = false;
+
+ if (left != 0) float_nf.setMinimumIntegerDigits(left);
+ if (right != 0) {
+ float_nf.setMinimumFractionDigits(right);
+ float_nf.setMaximumFractionDigits(right);
+ }
+ float_nf_left = left;
+ float_nf_right = right;
+ return float_nf.format(num);
+ }
+
+
+ static public String[] nfc(float num[], int right) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfc(num[i], right);
+ }
+ return formatted;
+ }
+
+
+ static public String nfc(float num, int right) {
+ if ((float_nf != null) &&
+ (float_nf_left == 0) &&
+ (float_nf_right == right) &&
+ float_nf_commas) {
+ return float_nf.format(num);
+ }
+
+ float_nf = NumberFormat.getInstance();
+ float_nf.setGroupingUsed(true);
+ float_nf_commas = true;
+
+ if (right != 0) {
+ float_nf.setMinimumFractionDigits(right);
+ float_nf.setMaximumFractionDigits(right);
+ }
+ float_nf_left = 0;
+ float_nf_right = right;
+ return float_nf.format(num);
+ }
+
+
+ /**
+ * Number formatter that takes into account whether the number
+ * has a sign (positive, negative, etc) in front of it.
+ */
+ static public String[] nfs(float num[], int left, int right) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfs(num[i], left, right);
+ }
+ return formatted;
+ }
+
+ static public String nfs(float num, int left, int right) {
+ return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
+ }
+
+
+ static public String[] nfp(float num[], int left, int right) {
+ String formatted[] = new String[num.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfp(num[i], left, right);
+ }
+ return formatted;
+ }
+
+ static public String nfp(float num, int left, int right) {
+ return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // HEX/BINARY CONVERSION
+
+
+ /**
+ * Convert a byte into a two digit hex string.
+ */
+ static final public String hex(byte what) {
+ return hex(what, 2);
+ }
+
+ /**
+ * Convert a Unicode character into a four digit hex string.
+ */
+ static final public String hex(char what) {
+ return hex(what, 4);
+ }
+
+ /**
+ * Convert an integer into an eight digit hex string.
+ */
+ static final public String hex(int what) {
+ return hex(what, 8);
+ }
+
+ /**
+ * Format an integer as a hex string using the specified number of digits.
+ * @param what the value to format
+ * @param digits the number of digits (maximum 8)
+ * @return a String object with the formatted values
+ */
+ static final public String hex(int what, int digits) {
+ String stuff = Integer.toHexString(what).toUpperCase();
+ if (digits > 8) {
+ digits = 8;
+ }
+
+ 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. If you want a specific number
+ * of digits use binary(int what, int digits) to specify how many.
+ */
+ static final public String binary(int 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);
+ if (digits > 32) {
+ digits = 32;
+ }
+
+ 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)
+ */
+ 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);
+ }
+
+
+ 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);
+ }
+
+
+ static public int blendColor(int c1, int c2, int mode) {
+ return PImage.blendColor(c1, c2, mode);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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) {
+// 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:
+ *
+ * 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[]) {
+ // just do a no-op for now
+ }
+
+// 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);
+// }
+//
+// try {
+// 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);
+//
+//// Class c = Class.forName(name);
+// Class> c = Thread.currentThread().getContextClassLoader().loadClass(name);
+// final PApplet applet = (PApplet) c.newInstance();
+//
+// // 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);
+// 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);
+// }
+//
+//// frame.setLayout(null);
+//// frame.add(applet);
+//
+// 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()");
+//
+// } catch (Exception e) {
+// e.printStackTrace();
+// System.exit(1);
+// }
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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) {
+// PGraphics.showMethodWarning("beginRecord");
+// }
+
+
+// public void endRecord() {
+// PGraphics.showMethodWarning("endRecord");
+// }
+
+
+ /**
+ * 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();
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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[].
+ */
+ public void loadPixels() {
+ g.loadPixels();
+ pixels = g.pixels;
+ }
+
+
+ public void updatePixels() {
+ g.updatePixels();
+ }
+
+
+ public void updatePixels(int x1, int y1, int x2, int y2) {
+ g.updatePixels(x1, y1, x2, y2);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ANDROID-SPECIFIC API
+
+
+ // Wallpaper and wear API
+
+
+ public boolean wallpaperPreview() {
+ return surface.getEngine().isPreview();
+ }
+
+
+ public float wallpaperOffset() {
+ return surface.getEngine().getXOffset();
+ }
+
+
+ public int wallpaperHomeCount() {
+ float step = surface.getEngine().getXOffsetStep();
+ if (0 < step) {
+ return (int)(1 + 1 / step);
+ } else {
+ return 1;
+ }
+ }
+
+
+ public boolean wearAmbient() {
+ return surface.getEngine().isInAmbientMode();
+ }
+
+
+ public boolean wearInteractive() {
+ return !surface.getEngine().isInAmbientMode();
+ }
+
+
+ public boolean wearRound() {
+ return surface.getEngine().isRound();
+ }
+
+
+ public boolean wearSquare() {
+ return !surface.getEngine().isRound();
+ }
+
+
+ public Rect wearInsets() {
+ return surface.getEngine().getInsets();
+ }
+
+
+ public boolean wearLowBit() {
+ return surface.getEngine().useLowBitAmbient();
+ }
+
+
+ public boolean wearBurnIn() {
+ return surface.getEngine().requireBurnInProtection();
+ }
+
+
+ // Ray casting API
+
+
+ public PVector[] getRayFromScreen(float screenX, float screenY, PVector[] ray) {
+ return g.getRayFromScreen(screenX, screenY, ray);
+ }
+
+
+ public void getRayFromScreen(float screenX, float screenY, PVector origin, PVector direction) {
+ g.getRayFromScreen(screenX, screenY, origin, direction);
+ }
+
+
+ public boolean intersectsSphere(float r, float screenX, float screenY) {
+ return g.intersectsSphere(r, screenX, screenY);
+ }
+
+
+ public boolean intersectsSphere(float r, PVector origin, PVector direction) {
+ return g.intersectsSphere(r, origin, direction);
+ }
+
+
+ public boolean intersectsBox(float w, float screenX, float screenY) {
+ return g.intersectsBox(w, screenX, screenY);
+ }
+
+
+ public boolean intersectsBox(float w, float h, float d, float screenX, float screenY) {
+ return g.intersectsBox(w, h, d, screenX, screenY);
+ }
+
+
+ public boolean intersectsBox(float size, PVector origin, PVector direction) {
+ return g.intersectsBox(size, origin, direction);
+ }
+
+
+ public boolean intersectsBox(float w, float h, float d, PVector origin, PVector direction) {
+ return g.intersectsBox(w, h, d, origin, direction);
+ }
+
+
+ public PVector intersectsPlane(float screenX, float screenY) {
+ return g.intersectsPlane(screenX, screenY);
+ }
+
+
+ public PVector intersectsPlane(PVector origin, PVector direction) {
+ return g.intersectsPlane(origin, direction);
+ }
+
+
+ public void eye() {
+ g.eye();
+ }
+
+
+ public void calculate() {
+ }
+
+
+ /**
+ * Sets the coordinate system in 3D centered at (width/2, height/2)
+ * and with the Y axis pointing up.
+ */
+
+ public void cameraUp() {
+ g.cameraUp();
+ }
+
+
+ /**
+ * Returns a copy of the current object matrix.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getObjectMatrix() {
+ return g.getObjectMatrix();
+ }
+
+
+ /**
+ * Copy the current object matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getObjectMatrix(PMatrix3D target) {
+ return g.getObjectMatrix(target);
+ }
+
+
+ /**
+ * Returns a copy of the current eye matrix.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getEyeMatrix() {
+ return g.getEyeMatrix();
+ }
+
+
+ /**
+ * Copy the current eye matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getEyeMatrix(PMatrix3D target) {
+ return g.getEyeMatrix(target);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH!
+ // This includes the Javadoc comments, which are automatically copied from
+ // the PImage and PGraphics source code files.
+
+ // public functions for processing.core
+
+
+ public PGL beginPGL() {
+ return g.beginPGL();
+ }
+
+
+ public void endPGL() {
+ g.endPGL();
+ }
+
+
+ public void flush() {
+ g.flush();
+ }
+
+
+ public void hint(int which) {
+ g.hint(which);
+ }
+
+
+ /**
+ * Start a new shape of type POLYGON
+ */
+ public void beginShape() {
+ g.beginShape();
+ }
+
+
+ /**
+ * ( begin auto-generated from beginShape.xml )
+ *
+ * Using the beginShape() and endShape() functions allow
+ * creating more complex forms. beginShape() begins recording
+ * vertices for a shape and endShape() stops recording. The value of
+ * the MODE parameter tells it which types of shapes to create from
+ * the provided vertices. With no mode specified, the shape can be any
+ * irregular polygon. The parameters available for beginShape() are POINTS,
+ * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP.
+ * After calling the beginShape() function, a series of
+ * vertex() commands must follow. To stop drawing the shape, call
+ * endShape(). The vertex() function with two parameters
+ * specifies a position in 2D and the vertex() function with three
+ * parameters specifies a position in 3D. Each shape will be outlined with
+ * the current stroke color and filled with the fill color.
+ *
+ * Transformations such as translate(), rotate(), and
+ * scale() do not work within beginShape(). It is also not
+ * possible to use other shapes, such as ellipse() or rect()
+ * within beginShape().
+ *
+ * The P3D renderer settings allow stroke() and fill()
+ * settings to be altered per-vertex, however the default P2D renderer does
+ * not. Settings such as strokeWeight(), strokeCap(), and
+ * strokeJoin() cannot be changed while inside a
+ * beginShape()/endShape() block with any renderer.
+ *
+ * ( end auto-generated )
+ * @webref shape:vertex
+ * @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP
+ * @see PShape
+ * @see PGraphics#endShape()
+ * @see PGraphics#vertex(float, float, float, float, float)
+ * @see PGraphics#curveVertex(float, float, float)
+ * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
+ */
+ public void beginShape(int 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) {
+ g.edge(edge);
+ }
+
+
+ /**
+ * ( begin auto-generated from normal.xml )
+ *
+ * Sets the current normal vector. This is for drawing three dimensional
+ * shapes and surfaces and specifies a vector perpendicular to the surface
+ * of the shape which determines how lighting affects it. Processing
+ * attempts to automatically assign normals to shapes, but since that's
+ * imperfect, this is a better option when you want more control. This
+ * function is identical to glNormal3f() in OpenGL.
+ *
+ * ( end auto-generated )
+ * @webref lights_camera:lights
+ * @param nx x direction
+ * @param ny y direction
+ * @param nz z direction
+ * @see PGraphics#beginShape(int)
+ * @see PGraphics#endShape(int)
+ * @see PGraphics#lights()
+ */
+ public void normal(float nx, float ny, float nz) {
+ g.normal(nx, ny, nz);
+ }
+
+
+ public void attribPosition(String name, float x, float y, float z) {
+ g.attribPosition(name, x, y, z);
+ }
+
+
+ public void attribNormal(String name, float nx, float ny, float nz) {
+ g.attribNormal(name, nx, ny, nz);
+ }
+
+
+ public void attribColor(String name, int color) {
+ g.attribColor(name, color);
+ }
+
+
+ public void attrib(String name, float... values) {
+ g.attrib(name, values);
+ }
+
+
+ public void attrib(String name, int... values) {
+ g.attrib(name, values);
+ }
+
+
+ public void attrib(String name, boolean... values) {
+ g.attrib(name, values);
+ }
+
+
+ /**
+ * ( begin auto-generated from textureMode.xml )
+ *
+ * Sets the coordinate space for texture mapping. There are two options,
+ * IMAGE, which refers to the actual coordinates of the image, and
+ * NORMAL, which refers to a normalized space of values ranging from 0
+ * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200
+ * pixels, mapping the image onto the entire size of a quad would require
+ * the points (0,0) (0,100) (100,200) (0,200). The same mapping in
+ * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1).
+ *
+ * ( end auto-generated )
+ * @webref image:textures
+ * @param mode either IMAGE or NORMAL
+ * @see PGraphics#texture(PImage)
+ * @see PGraphics#textureWrap(int)
+ */
+ public void textureMode(int mode) {
+ g.textureMode(mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from textureWrap.xml )
+ *
+ * Description to come...
+ *
+ * ( end auto-generated from textureWrap.xml )
+ *
+ * @webref image:textures
+ * @param wrap Either CLAMP (default) or REPEAT
+ * @see PGraphics#texture(PImage)
+ * @see PGraphics#textureMode(int)
+ */
+ public void textureWrap(int wrap) {
+ g.textureWrap(wrap);
+ }
+
+
+ /**
+ * ( begin auto-generated from texture.xml )
+ *
+ * Sets a texture to be applied to vertex points. The texture()
+ * function must be called between beginShape() and
+ * endShape() and before any calls to vertex().
+ *
+ * When textures are in use, the fill color is ignored. Instead, use tint()
+ * to specify the color of the texture as it is applied to the shape.
+ *
+ * ( end auto-generated )
+ * @webref image:textures
+ * @param image reference to a PImage object
+ * @see PGraphics#textureMode(int)
+ * @see PGraphics#textureWrap(int)
+ * @see PGraphics#beginShape(int)
+ * @see PGraphics#endShape(int)
+ * @see PGraphics#vertex(float, float, float, float, float)
+ */
+ public void texture(PImage image) {
+ g.texture(image);
+ }
+
+
+ /**
+ * Removes texture image for current shape.
+ * Needs to be called between beginShape and endShape
+ *
+ */
+ public void noTexture() {
+ g.noTexture();
+ }
+
+
+ public void vertex(float x, float y) {
+ g.vertex(x, y);
+ }
+
+
+ public void vertex(float x, float y, float 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) {
+ g.vertex(v);
+ }
+
+
+ public void vertex(float x, float y, float u, float v) {
+ g.vertex(x, y, u, v);
+ }
+
+
+ /**
+ * ( begin auto-generated from vertex.xml )
+ *
+ * All shapes are constructed by connecting a series of vertices.
+ * vertex() is used to specify the vertex coordinates for points,
+ * lines, triangles, quads, and polygons and is used exclusively within the
+ * beginShape() and endShape() function.
+ *
+ * Drawing a vertex in 3D using the z parameter requires the P3D
+ * parameter in combination with size as shown in the above example.
+ *
+ * This function is also used to map a texture onto the geometry. The
+ * texture() function declares the texture to apply to the geometry
+ * and the u and v coordinates set define the mapping of this
+ * texture to the form. By default, the coordinates used for u and
+ * v are specified in relation to the image's size in pixels, but
+ * this relation can be changed with textureMode().
+ *
+ * ( end auto-generated )
+ * @webref shape:vertex
+ * @param x x-coordinate of the vertex
+ * @param y y-coordinate of the vertex
+ * @param z z-coordinate of the vertex
+ * @param u horizontal coordinate for the texture mapping
+ * @param v vertical coordinate for the texture mapping
+ * @see PGraphics#beginShape(int)
+ * @see PGraphics#endShape(int)
+ * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#quadraticVertex(float, float, float, float, float, float)
+ * @see PGraphics#curveVertex(float, float, float)
+ * @see PGraphics#texture(PImage)
+ */
+ public void vertex(float x, float y, float z, float u, float v) {
+ g.vertex(x, y, z, u, v);
+ }
+
+
+ /**
+ * @webref shape:vertex
+ */
+ public void beginContour() {
+ g.beginContour();
+ }
+
+
+ /**
+ * @webref shape:vertex
+ */
+ public void endContour() {
+ g.endContour();
+ }
+
+
+ public void endShape() {
+ g.endShape();
+ }
+
+
+ /**
+ * ( begin auto-generated from endShape.xml )
+ *
+ * The endShape() function is the companion to beginShape()
+ * and may only be called after beginShape(). When endshape()
+ * is called, all of image data defined since the previous call to
+ * beginShape() is written into the image buffer. The constant CLOSE
+ * as the value for the MODE parameter to close the shape (to connect the
+ * beginning and the end).
+ *
+ * ( end auto-generated )
+ * @webref shape:vertex
+ * @param mode use CLOSE to close the shape
+ * @see PShape
+ * @see PGraphics#beginShape(int)
+ */
+ public void endShape(int mode) {
+ g.endShape(mode);
+ }
+
+
+ /**
+ * @webref shape
+ * @param filename name of file to load, can be .svg or .obj
+ * @see PShape
+ * @see PApplet#createShape()
+ */
+ public PShape loadShape(String filename) {
+ return g.loadShape(filename);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public PShape loadShape(String filename, String options) {
+ return g.loadShape(filename, options);
+ }
+
+
+ /**
+ * @webref shape
+ * @see PShape
+ * @see PShape#endShape()
+ * @see PApplet#loadShape(String)
+ */
+ public PShape createShape() {
+ return g.createShape();
+ }
+
+
+ public PShape createShape(int type) {
+ return g.createShape(type);
+ }
+
+
+ /**
+ * @param kind either POINT, LINE, TRIANGLE, QUAD, RECT, ELLIPSE, ARC, BOX, SPHERE
+ * @param p parameters that match the kind of shape
+ */
+ public PShape createShape(int kind, float... p) {
+ return g.createShape(kind, p);
+ }
+
+
+ /**
+ * ( begin auto-generated from loadShader.xml )
+ *
+ * This is a new reference entry for Processing 2.0. It will be updated shortly.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering:shaders
+ * @param fragFilename name of fragment shader file
+ */
+ public PShader loadShader(String fragFilename) {
+ return g.loadShader(fragFilename);
+ }
+
+
+ /**
+ * @param vertFilename name of vertex shader file
+ */
+ public PShader loadShader(String fragFilename, String vertFilename) {
+ return g.loadShader(fragFilename, vertFilename);
+ }
+
+
+ /**
+ * ( begin auto-generated from shader.xml )
+ *
+ * This is a new reference entry for Processing 2.0. It will be updated shortly.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering:shaders
+ * @param shader name of shader file
+ */
+ public void shader(PShader shader) {
+ g.shader(shader);
+ }
+
+
+ /**
+ * @param kind type of shader, either POINTS, LINES, or TRIANGLES
+ */
+ public void shader(PShader shader, int kind) {
+ g.shader(shader, kind);
+ }
+
+
+ /**
+ * ( begin auto-generated from resetShader.xml )
+ *
+ * This is a new reference entry for Processing 2.0. It will be updated shortly.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering:shaders
+ */
+ public void resetShader() {
+ g.resetShader();
+ }
+
+
+ /**
+ * @param kind type of shader, either POINTS, LINES, or TRIANGLES
+ */
+ public void resetShader(int kind) {
+ g.resetShader(kind);
+ }
+
+
+ /**
+ * @param shader the fragment shader to apply
+ */
+ public void filter(PShader shader) {
+ g.filter(shader);
+ }
+
+
+ /**
+ * ( begin auto-generated from clip.xml )
+ *
+ * Limits the rendering to the boundaries of a rectangle defined
+ * by the parameters. The boundaries are drawn based on the state
+ * of the imageMode() fuction, either CORNER, CORNERS, or CENTER.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering
+ * @param a x-coordinate of the rectangle, by default
+ * @param b y-coordinate of the rectangle, by default
+ * @param c width of the rectangle, by default
+ * @param d height of the rectangle, by default
+ */
+ public void clip(float a, float b, float c, float d) {
+ g.clip(a, b, c, d);
+ }
+
+
+ /**
+ * ( begin auto-generated from noClip.xml )
+ *
+ * Disables the clipping previously started by the clip() function.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering
+ */
+ public void noClip() {
+ g.noClip();
+ }
+
+
+ /**
+ * ( begin auto-generated from blendMode.xml )
+ *
+ * This is a new reference entry for Processing 2.0. It will be updated shortly.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering
+ * @param mode the blending mode to use
+ */
+ public void blendMode(int mode) {
+ g.blendMode(mode);
+ }
+
+
+ public void bezierVertex(float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ g.bezierVertex(x2, y2, x3, y3, x4, y4);
+ }
+
+
+ /**
+ * ( begin auto-generated from bezierVertex.xml )
+ *
+ * Specifies vertex coordinates for Bezier curves. Each call to
+ * bezierVertex() defines the position of two control points and one
+ * anchor point of a Bezier curve, adding a new segment to a line or shape.
+ * The first time bezierVertex() is used within a
+ * beginShape() call, it must be prefaced with a call to
+ * vertex() to set the first anchor point. This function must be
+ * used between beginShape() and endShape() and only when
+ * there is no MODE parameter specified to beginShape(). Using the
+ * 3D version requires rendering with P3D (see the Environment reference
+ * for more information).
+ *
+ * ( end auto-generated )
+ * @webref shape:vertex
+ * @param x2 the x-coordinate of the 1st control point
+ * @param y2 the y-coordinate of the 1st control point
+ * @param z2 the z-coordinate of the 1st control point
+ * @param x3 the x-coordinate of the 2nd control point
+ * @param y3 the y-coordinate of the 2nd control point
+ * @param z3 the z-coordinate of the 2nd control point
+ * @param x4 the x-coordinate of the anchor point
+ * @param y4 the y-coordinate of the anchor point
+ * @param z4 the z-coordinate of the anchor point
+ * @see PGraphics#curveVertex(float, float, float)
+ * @see PGraphics#vertex(float, float, float, float, float)
+ * @see PGraphics#quadraticVertex(float, float, float, float, float, float)
+ * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void bezierVertex(float x2, float y2, float z2,
+ float x3, float y3, float z3,
+ float x4, float y4, float z4) {
+ g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ }
+
+
+ /**
+ * @webref shape:vertex
+ * @param cx the x-coordinate of the control point
+ * @param cy the y-coordinate of the control point
+ * @param x3 the x-coordinate of the anchor point
+ * @param y3 the y-coordinate of the anchor point
+ * @see PGraphics#curveVertex(float, float, float)
+ * @see PGraphics#vertex(float, float, float, float, float)
+ * @see PGraphics#bezierVertex(float, float, float, float, float, float)
+ * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void quadraticVertex(float cx, float cy,
+ float x3, float y3) {
+ g.quadraticVertex(cx, cy, x3, y3);
+ }
+
+
+ /**
+ * @param cz the z-coordinate of the control point
+ * @param z3 the z-coordinate of the anchor point
+ */
+ public void quadraticVertex(float cx, float cy, float cz,
+ float x3, float y3, float z3) {
+ g.quadraticVertex(cx, cy, cz, x3, y3, z3);
+ }
+
+
+ /**
+ * ( begin auto-generated from curveVertex.xml )
+ *
+ * Specifies vertex coordinates for curves. This function may only be used
+ * between beginShape() and endShape() and only when there is
+ * no MODE parameter specified to beginShape(). The first and last
+ * points in a series of curveVertex() lines will be used to guide
+ * the beginning and end of a the curve. A minimum of four points is
+ * required to draw a tiny curve between the second and third points.
+ * Adding a fifth point with curveVertex() will draw the curve
+ * between the second, third, and fourth points. The curveVertex()
+ * function is an implementation of Catmull-Rom splines. Using the 3D
+ * version requires rendering with P3D (see the Environment reference for
+ * more information).
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:vertex
+ * @param x the x-coordinate of the vertex
+ * @param y the y-coordinate of the vertex
+ * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#beginShape(int)
+ * @see PGraphics#endShape(int)
+ * @see PGraphics#vertex(float, float, float, float, float)
+ * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#quadraticVertex(float, float, float, float, float, float)
+ */
+ public void curveVertex(float x, float y) {
+ g.curveVertex(x, y);
+ }
+
+
+ /**
+ * @param z the z-coordinate of the vertex
+ */
+ public void curveVertex(float x, float y, float z) {
+ g.curveVertex(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from point.xml )
+ *
+ * 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 with the z parameter
+ * requires the P3D parameter in combination with size() as shown in
+ * the above example.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:2d_primitives
+ * @param x x-coordinate of the point
+ * @param y y-coordinate of the point
+ * @see PGraphics#stroke(int)
+ */
+ public void point(float x, float y) {
+ g.point(x, y);
+ }
+
+
+ /**
+ * @param z z-coordinate of the point
+ */
+ public void point(float x, float y, float z) {
+ g.point(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from line.xml )
+ *
+ * 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() function 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 with the z parameter requires the P3D
+ * parameter in combination with size() as shown in the above example.
+ *
+ * ( end auto-generated )
+ * @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
+ * @see PGraphics#strokeWeight(float)
+ * @see PGraphics#strokeJoin(int)
+ * @see PGraphics#strokeCap(int)
+ * @see PGraphics#beginShape()
+ */
+ public void line(float x1, float y1, float x2, float y2) {
+ g.line(x1, y1, x2, y2);
+ }
+
+
+ /**
+ * @param z1 z-coordinate of the first point
+ * @param z2 z-coordinate of the second point
+ */
+ public void line(float x1, float y1, float z1,
+ float x2, float y2, float z2) {
+ g.line(x1, y1, z1, x2, y2, z2);
+ }
+
+
+ /**
+ * ( begin auto-generated from triangle.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @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) {
+ g.triangle(x1, y1, x2, y2, x3, y3);
+ }
+
+
+ /**
+ * ( begin auto-generated from quad.xml )
+ *
+ * A quad is a quadrilateral, a four sided polygon. It is similar to a
+ * rectangle, but the angles between its edges are not constrained to
+ * 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.
+ *
+ * ( end auto-generated )
+ * @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) {
+ g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+
+ /**
+ * ( begin auto-generated from rectMode.xml )
+ *
+ * Modifies the location from which rectangles draw. The default mode is
+ * rectMode(CORNER), which specifies the location to be the upper
+ * left corner of the shape and uses the third and fourth parameters of
+ * rect() to specify the width and height. The syntax
+ * rectMode(CORNERS) uses the first and second parameters of
+ * rect() to set the location of one corner and uses the third and
+ * fourth parameters to set the opposite corner. The syntax
+ * rectMode(CENTER) draws the image from its center point and uses
+ * the third and forth parameters of rect() to specify the image's
+ * width and height. The syntax rectMode(RADIUS) draws the image
+ * from its center point and uses the third and forth parameters of
+ * rect() to specify half of the image's width and height. The
+ * parameter must be written in ALL CAPS because Processing is a case
+ * sensitive language. Note: In version 125, the mode named CENTER_RADIUS
+ * was shortened to RADIUS.
+ *
+ * ( end auto-generated )
+ * @webref shape:attributes
+ * @param mode either CORNER, CORNERS, CENTER, or RADIUS
+ * @see PGraphics#rect(float, float, float, float)
+ */
+ public void rectMode(int mode) {
+ g.rectMode(mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from rect.xml )
+ *
+ * Draws a rectangle to the screen. A rectangle is a four-sided shape with
+ * every angle at ninety degrees. By default, the first two parameters set
+ * the location of the upper-left corner, the third sets the width, and the
+ * fourth sets the height. These parameters may be changed with the
+ * rectMode() function.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:2d_primitives
+ * @param a x-coordinate of the rectangle by default
+ * @param b y-coordinate of the rectangle by default
+ * @param c width of the rectangle by default
+ * @param d height of the rectangle by default
+ * @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) {
+ g.rect(a, b, c, d);
+ }
+
+
+ /**
+ * @param r radii for all four corners
+ */
+ public void rect(float a, float b, float c, float d, float r) {
+ g.rect(a, b, c, d, r);
+ }
+
+
+ /**
+ * @param tl radius for top-left corner
+ * @param tr radius for top-right corner
+ * @param br radius for bottom-right corner
+ * @param bl radius for bottom-left corner
+ */
+ public void rect(float a, float b, float c, float d,
+ float tl, float tr, float br, float bl) {
+ g.rect(a, b, c, d, tl, tr, br, bl);
+ }
+
+
+ /**
+ * ( begin auto-generated from square.xml )
+ *
+ * Draws a square to the screen. A square is a four-sided shape with
+ * every angle at ninety degrees and each side is the same length.
+ * By default, the first two parameters set the location of the
+ * upper-left corner, the third sets the width and height. The way
+ * these parameters are interpreted, however, may be changed with the
+ * rectMode() function.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:2d_primitives
+ * @param x x-coordinate of the rectangle by default
+ * @param y y-coordinate of the rectangle by default
+ * @param extent width and height of the rectangle by default
+ * @see PGraphics#rect(float, float, float, float)
+ * @see PGraphics#rectMode(int)
+ */
+ public void square(float x, float y, float extent) {
+ g.square(x, y, extent);
+ }
+
+
+ /**
+ * ( begin auto-generated from ellipseMode.xml )
+ *
+ * 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 is a case-sensitive language.
+ *
+ * ( end auto-generated )
+ * @webref shape:attributes
+ * @param mode either CENTER, RADIUS, CORNER, or CORNERS
+ * @see PApplet#ellipse(float, float, float, float)
+ * @see PApplet#arc(float, float, float, float, float, float)
+ */
+ public void ellipseMode(int mode) {
+ g.ellipseMode(mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from ellipse.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @webref shape:2d_primitives
+ * @param a x-coordinate of the ellipse
+ * @param b y-coordinate of the ellipse
+ * @param c width of the ellipse by default
+ * @param d height of the ellipse by default
+ * @see PApplet#ellipseMode(int)
+ * @see PApplet#arc(float, float, float, float, float, float)
+ */
+ public void ellipse(float a, float b, float c, float d) {
+ g.ellipse(a, b, c, d);
+ }
+
+
+ /**
+ * ( begin auto-generated from arc.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @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 by default
+ * @param d height of the arc's ellipse by default
+ * @param start angle to start the arc, specified in radians
+ * @param stop angle to stop the arc, specified in radians
+ * @see PApplet#ellipse(float, float, float, float)
+ * @see PApplet#ellipseMode(int)
+ * @see PApplet#radians(float)
+ * @see PApplet#degrees(float)
+ */
+ public void arc(float a, float b, float c, float d,
+ float start, float stop) {
+ g.arc(a, b, c, d, start, stop);
+ }
+
+
+ /*
+ * @param mode either OPEN, CHORD, or PIE
+ */
+ public void arc(float a, float b, float c, float d,
+ float start, float stop, int mode) {
+ g.arc(a, b, c, d, start, stop, mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from circle.xml )
+ *
+ * Draws a circle to the screen. By default, the first two parameters
+ * set the location of the center, and the third sets the shape's width
+ * and height. The origin may be changed with the ellipseMode()
+ * function.
+ *
+ * ( end auto-generated )
+ * @webref shape:2d_primitives
+ * @param x x-coordinate of the ellipse
+ * @param y y-coordinate of the ellipse
+ * @param extent width and height of the ellipse by default
+ * @see PApplet#ellipse(float, float, float, float)
+ * @see PApplet#ellipseMode(int)
+ */
+ public void circle(float x, float y, float extent) {
+ g.circle(x, y, extent);
+ }
+
+
+ /**
+ * ( begin auto-generated from box.xml )
+ *
+ * A box is an extruded rectangle. A box with equal dimension on all sides
+ * is a cube.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:3d_primitives
+ * @param size dimension of the box in all dimensions (creates a cube)
+ * @see PGraphics#sphere(float)
+ */
+ public void box(float size) {
+ g.box(size);
+ }
+
+
+ /**
+ * @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
+ */
+ public void box(float w, float h, float d) {
+ g.box(w, h, d);
+ }
+
+
+ /**
+ * ( begin auto-generated from sphereDetail.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Code for sphereDetail() submitted by toxi [031031].
+ * Code for enhanced u/v version from davbol [080801].
+ *
+ * @param res number of segments (minimum 3) used per full circle revolution
+ * @webref shape:3d_primitives
+ * @see PGraphics#sphere(float)
+ */
+ public void sphereDetail(int res) {
+ g.sphereDetail(res);
+ }
+
+
+ /**
+ * @param ures number of segments used longitudinally per full circle revolutoin
+ * @param vres number of segments used latitudinally from top to bottom
+ */
+ public void sphereDetail(int ures, int vres) {
+ g.sphereDetail(ures, vres);
+ }
+
+
+ /**
+ * ( begin auto-generated from sphere.xml )
+ *
+ * A sphere is a hollow ball made from tessellated triangles.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ *
+ * Implementation notes:
+ *
+ * cache all the points of the sphere in a static array
+ * top and bottom are just a bunch of triangles that land
+ * in the center point
+ *
+ * sphere is a series of concentric circles who radii vary
+ * along the shape, based on, er.. cos or something
+ *
+ * [toxi 031031] new sphere code. removed all multiplies with
+ * radius, as scale() will take care of that anyway
+ *
+ * [toxi 031223] updated sphere code (removed modulos)
+ * and introduced sphereAt(x,y,z,r)
+ * to avoid additional translate()'s on the user/sketch side
+ *
+ * [davbol 080801] now using separate sphereDetailU/V
+ *
+ *
+ * @webref shape:3d_primitives
+ * @param r the radius of the sphere
+ * @see PGraphics#sphereDetail(int)
+ */
+ public void sphere(float r) {
+ g.sphere(r);
+ }
+
+
+ /**
+ * ( begin auto-generated from bezierPoint.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * For instance, to convert the following example:
+ * stroke(255, 102, 0);
+ * line(85, 20, 10, 10);
+ * line(90, 90, 15, 80);
+ * stroke(0, 0, 0);
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ *
+ * // draw it in gray, using 10 steps instead of the default 20
+ * // this is a slower way to do it, but useful if you need
+ * // to do things with the coordinates at each step
+ * stroke(128);
+ * beginShape(LINE_STRIP);
+ * for (int i = 0; i <= 10; i++) {
+ * float t = i / 10.0f;
+ * float x = bezierPoint(85, 10, 90, 15, t);
+ * float y = bezierPoint(20, 10, 90, 80, t);
+ * vertex(x, y);
+ * }
+ * endShape();
+ *
+ * @webref shape:curves
+ * @param a coordinate of first point on the curve
+ * @param b coordinate of first control point
+ * @param c coordinate of second control point
+ * @param d coordinate of second point on the curve
+ * @param t value between 0 and 1
+ * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#bezierVertex(float, float, float, float, float, float)
+ * @see PGraphics#curvePoint(float, float, float, float, float)
+ */
+ public float bezierPoint(float a, float b, float c, float d, float t) {
+ return g.bezierPoint(a, b, c, d, t);
+ }
+
+
+ /**
+ * ( begin auto-generated from bezierTangent.xml )
+ *
+ * Calculates the tangent of a point on a Bezier curve. There is a good
+ * definition of tangent on Wikipedia.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Code submitted by Dave Bollinger (davol) for release 0136.
+ *
+ * @webref shape:curves
+ * @param a coordinate of first point on the curve
+ * @param b coordinate of first control point
+ * @param c coordinate of second control point
+ * @param d coordinate of second point on the curve
+ * @param t value between 0 and 1
+ * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#bezierVertex(float, float, float, float, float, float)
+ * @see PGraphics#curvePoint(float, float, float, float, float)
+ */
+ public float bezierTangent(float a, float b, float c, float d, float t) {
+ return g.bezierTangent(a, b, c, d, t);
+ }
+
+
+ /**
+ * ( begin auto-generated from bezierDetail.xml )
+ *
+ * Sets the resolution at which Beziers display. The default value is 20.
+ * This function is only useful when using the P3D renderer as the default
+ * P2D renderer does not use this information.
+ *
+ * ( end auto-generated )
+ *
+ * @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, float)
+ * @see PGraphics#curveTightness(float)
+ */
+ public void bezierDetail(int detail) {
+ g.bezierDetail(detail);
+ }
+
+
+ public void bezier(float x1, float y1,
+ float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+
+ /**
+ * ( begin auto-generated from bezier.xml )
+ *
+ * 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 requires rendering with P3D (see the
+ * Environment reference for more information).
+ *
+ * ( end auto-generated )
+ *
+ *
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.
+ *
+ * If you were to try and continue that curve like so:
+ *
curveto(x5, y5, x6, y6, x7, y7);
+ * This would be done in processing by adding these statements:
+ *
bezierVertex(x5, y5, x6, y6, x7, y7)
+ *
+ * To draw a quadratic (instead of cubic) curve,
+ * use the control point twice by doubling it:
+ *
bezier(x1, y1, cx, cy, cx, cy, x2, y2);
+ *
+ * @webref shape:curves
+ * @param x1 coordinates for the first anchor point
+ * @param y1 coordinates for the first anchor point
+ * @param z1 coordinates for the first anchor point
+ * @param x2 coordinates for the first control point
+ * @param y2 coordinates for the first control point
+ * @param z2 coordinates for the first control point
+ * @param x3 coordinates for the second control point
+ * @param y3 coordinates for the second control point
+ * @param z3 coordinates for the second control point
+ * @param x4 coordinates for the second anchor point
+ * @param y4 coordinates for the second anchor point
+ * @param z4 coordinates for the second anchor point
+ *
+ * @see PGraphics#bezierVertex(float, float, float, float, float, float)
+ * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void bezier(float x1, float y1, float z1,
+ float x2, float y2, float z2,
+ float x3, float y3, float z3,
+ float x4, float y4, float z4) {
+ g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ }
+
+
+ /**
+ * ( begin auto-generated from curvePoint.xml )
+ *
+ * Evalutes the curve at point t for points a, b, c, d. The parameter t
+ * varies between 0 and 1, a and d are the control points, and b and c are
+ * the points on the curve. 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.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:curves
+ * @param a coordinate of first control point
+ * @param b coordinate of first point on the curve
+ * @param c coordinate of second point on the curve
+ * @param d coordinate of second control point
+ * @param t value between 0 and 1
+ * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#curveVertex(float, float)
+ * @see PGraphics#bezierPoint(float, float, float, float, float)
+ */
+ public float curvePoint(float a, float b, float c, float d, float t) {
+ return g.curvePoint(a, b, c, d, t);
+ }
+
+
+ /**
+ * ( begin auto-generated from curveTangent.xml )
+ *
+ * Calculates the tangent of a point on a curve. There's a good definition
+ * of tangent on Wikipedia.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Code thanks to Dave Bollinger (Bug #715)
+ *
+ * @webref shape:curves
+ * @param a coordinate of first point on the curve
+ * @param b coordinate of first control point
+ * @param c coordinate of second control point
+ * @param d coordinate of second point on the curve
+ * @param t value between 0 and 1
+ * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#curveVertex(float, float)
+ * @see PGraphics#curvePoint(float, float, float, float, float)
+ * @see PGraphics#bezierTangent(float, float, float, float, float)
+ */
+ public float curveTangent(float a, float b, float c, float d, float t) {
+ return g.curveTangent(a, b, c, d, t);
+ }
+
+
+ /**
+ * ( begin auto-generated from curveDetail.xml )
+ *
+ * Sets the resolution at which curves display. The default value is 20.
+ * This function is only useful when using the P3D renderer as the default
+ * P2D renderer does not use this information.
+ *
+ * ( end auto-generated )
+ *
+ * @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) {
+ g.curveDetail(detail);
+ }
+
+
+ /**
+ * ( begin auto-generated from curveTightness.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ *
+ * @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) {
+ g.curveTightness(tightness);
+ }
+
+
+ /**
+ * ( begin auto-generated from curve.xml )
+ *
+ * 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 requires
+ * rendering with P3D (see the Environment reference for more information).
+ *
+ * ( end auto-generated )
+ *
+ *
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().
+ *
+ *
+ * @webref shape:curves
+ * @param x1 coordinates for the beginning control point
+ * @param y1 coordinates for the beginning control point
+ * @param x2 coordinates for the first point
+ * @param y2 coordinates for the first point
+ * @param x3 coordinates for the second point
+ * @param y3 coordinates for the second point
+ * @param x4 coordinates for the ending control point
+ * @param y4 coordinates for the ending control point
+ * @see PGraphics#curveVertex(float, float)
+ * @see PGraphics#curveTightness(float)
+ * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void curve(float x1, float y1,
+ float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+
+ /**
+ * @param z1 coordinates for the beginning control point
+ * @param z2 coordinates for the first point
+ * @param z3 coordinates for the second point
+ * @param z4 coordinates for the ending control point
+ */
+ 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) {
+ g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ }
+
+
+ /**
+ * ( begin auto-generated from imageMode.xml )
+ *
+ * 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 is a case-sensitive language.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:loading_displaying
+ * @param mode either CORNER, CORNERS, or CENTER
+ * @see PApplet#loadImage(String, String)
+ * @see PImage
+ * @see PGraphics#image(PImage, float, float, float, float)
+ * @see PGraphics#background(float, float, float, float)
+ */
+ public void imageMode(int mode) {
+ g.imageMode(mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from image.xml )
+ *
+ * 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 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. For
+ * example, 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.
+ *
+ * The color of an image may be modified with the tint() function.
+ * This function will maintain transparency for GIF and PNG images.
+ *
+ * ( end auto-generated )
+ *
+ *
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 img the image to display
+ * @param a x-coordinate of the image by default
+ * @param b y-coordinate of the image by default
+ * @see PApplet#loadImage(String, String)
+ * @see PImage
+ * @see PGraphics#imageMode(int)
+ * @see PGraphics#tint(float)
+ * @see PGraphics#background(float, float, float, float)
+ * @see PGraphics#alpha(int)
+ */
+ public void image(PImage img, float a, float b) {
+ g.image(img, a, b);
+ }
+
+
+ /**
+ * @param c width to display the image by default
+ * @param d height to display the image by default
+ */
+ public void image(PImage img, float a, float b, float c, float d) {
+ g.image(img, a, b, 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().
+ *
+ * @nowebref
+ */
+ public void image(PImage img,
+ float a, float b, float c, float d,
+ int u1, int v1, int u2, int v2) {
+ g.image(img, a, b, c, d, u1, v1, u2, v2);
+ }
+
+
+ /**
+ * ( begin auto-generated from shapeMode.xml )
+ *
+ * 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 is a case sensitive language.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:loading_displaying
+ * @param mode either CORNER, CORNERS, CENTER
+ * @see PShape
+ * @see PGraphics#shape(PShape)
+ * @see PGraphics#rectMode(int)
+ */
+ public void shapeMode(int mode) {
+ g.shapeMode(mode);
+ }
+
+
+ public void shape(PShape shape) {
+ g.shape(shape);
+ }
+
+
+ /**
+ * ( begin auto-generated from shape.xml )
+ *
+ * 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 P3D. This renderer does not
+ * yet support shapes that have holes or complicated breaks.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:loading_displaying
+ * @param shape the shape to display
+ * @param x x-coordinate of the shape
+ * @param y y-coordinate of the shape
+ * @see PShape
+ * @see PApplet#loadShape(String)
+ * @see PGraphics#shapeMode(int)
+ *
+ * Convenience method to draw at a particular location.
+ */
+ public void shape(PShape shape, float x, float y) {
+ g.shape(shape, x, y);
+ }
+
+
+ /**
+ * @param a x-coordinate of the shape
+ * @param b y-coordinate of the shape
+ * @param c width to display the shape
+ * @param d height to display the shape
+ */
+ public void shape(PShape shape, float a, float b, float c, float d) {
+ g.shape(shape, a, b, c, d);
+ }
+
+
+ public void textAlign(int alignX) {
+ g.textAlign(alignX);
+ }
+
+
+ /**
+ * ( begin auto-generated from textAlign.xml )
+ *
+ * Sets the current alignment for drawing text. The parameters LEFT,
+ * CENTER, and RIGHT set the display characteristics of the letters in
+ * relation to the values for the x and y parameters of the
+ * text() function.
+ *
+ * In Processing 0125 and later, an optional second parameter can be used
+ * to vertically align the text. BASELINE is the default, and the vertical
+ * alignment will be reset to BASELINE if the second parameter is not used.
+ * The TOP and CENTER parameters are straightforward. The BOTTOM parameter
+ * offsets the line based on the current textDescent(). For multiple
+ * lines, the final line will be aligned to the bottom, with the previous
+ * lines appearing above it.
+ *
+ * When using text() with width and height parameters, BASELINE is
+ * ignored, and treated as TOP. (Otherwise, text would by default draw
+ * outside the box, since BASELINE is the default setting. BASELINE is not
+ * a useful drawing mode for text drawn in a rectangle.)
+ *
+ * The vertical alignment is based on the value of textAscent(),
+ * which many fonts do not specify correctly. It may be necessary to use a
+ * hack and offset by a few pixels by hand so that the offset looks
+ * correct. To do this as less of a hack, use some percentage of
+ * textAscent() or textDescent() so that the hack works even
+ * if you change the size of the font.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:attributes
+ * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT
+ * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
+ * @see PApplet#loadFont(String)
+ * @see PFont
+ * @see PGraphics#text(String, float, float)
+ * @see PGraphics#textSize(float)
+ * @see PGraphics#textAscent()
+ * @see PGraphics#textDescent()
+ */
+ public void textAlign(int alignX, int alignY) {
+ g.textAlign(alignX, alignY);
+ }
+
+
+ /**
+ * ( begin auto-generated from textAscent.xml )
+ *
+ * Returns ascent of the current font at its current size. This information
+ * is useful for determining the height of the font above the baseline. For
+ * example, adding the textAscent() and textDescent() values
+ * will give you the total height of the line.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:metrics
+ * @see PGraphics#textDescent()
+ */
+ public float textAscent() {
+ return g.textAscent();
+ }
+
+
+ /**
+ * ( begin auto-generated from textDescent.xml )
+ *
+ * Returns descent of the current font at its current size. This
+ * information is useful for determining the height of the font below the
+ * baseline. For example, adding the textAscent() and
+ * textDescent() values will give you the total height of the line.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:metrics
+ * @see PGraphics#textAscent()
+ */
+ public float textDescent() {
+ return g.textDescent();
+ }
+
+
+ /**
+ * ( begin auto-generated from textFont.xml )
+ *
+ * Sets the current font that will be drawn with the text()
+ * function. Fonts must be loaded with loadFont() before it can be
+ * used. This font will be used in all subsequent calls to the
+ * text() function. If no size parameter is input, the font
+ * will appear at its original size (the size it was created at with the
+ * "Create Font..." tool) until it is changed with textSize().
Because fonts are usually bitmaped, you should create fonts at
+ * the sizes that will be used most commonly. Using textFont()
+ * without the size parameter will result in the cleanest-looking text.
With the default (JAVA2D) and PDF renderers, it's also possible
+ * to enable the use of native fonts via the command
+ * hint(ENABLE_NATIVE_FONTS). This will produce vector text in
+ * JAVA2D sketches and PDF output in cases where the vector data is
+ * available: when the font is still installed, or the font is created via
+ * the createFont() function (rather than the Create Font tool).
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:loading_displaying
+ * @param which any variable of the type PFont
+ * @see PApplet#createFont(String, float, boolean)
+ * @see PApplet#loadFont(String)
+ * @see PFont
+ * @see PGraphics#text(String, float, float)
+ * @see PGraphics#textSize(float)
+ */
+ public void textFont(PFont which) {
+ g.textFont(which);
+ }
+
+
+ /**
+ * @param size the size of the letters in units of pixels
+ */
+ public void textFont(PFont which, float size) {
+ g.textFont(which, size);
+ }
+
+
+ /**
+ * ( begin auto-generated from textLeading.xml )
+ *
+ * Sets the spacing between lines of text in units of pixels. This setting
+ * will be used in all subsequent calls to the text() function.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:attributes
+ * @param leading the size in pixels for spacing between lines
+ * @see PApplet#loadFont(String)
+ * @see PFont#PFont
+ * @see PGraphics#text(String, float, float)
+ * @see PGraphics#textFont(PFont)
+ * @see PGraphics#textSize(float)
+ */
+ public void textLeading(float leading) {
+ g.textLeading(leading);
+ }
+
+
+ /**
+ * ( begin auto-generated from textMode.xml )
+ *
+ * Sets the way text draws to the screen. In the default configuration, the
+ * MODEL mode, it's possible to rotate, scale, and place letters in
+ * two and three dimensional space.
+ *
+ * The SHAPE mode draws text using the the glyph outlines of
+ * individual characters rather than as textures. This mode is only
+ * supported with the PDF and P3D renderer settings. With the
+ * PDF renderer, you must call textMode(SHAPE) before any
+ * other drawing occurs. If the outlines are not available, then
+ * textMode(SHAPE) will be ignored and textMode(MODEL) will
+ * be used instead.
+ *
+ * The textMode(SHAPE) option in P3D can be combined with
+ * beginRaw() to write vector-accurate text to 2D and 3D output
+ * files, for instance DXF or PDF. The SHAPE mode is
+ * not currently optimized for P3D, so if recording shape data, use
+ * textMode(MODEL) until you're ready to capture the geometry with beginRaw().
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:attributes
+ * @param mode either MODEL or SHAPE
+ * @see PApplet#loadFont(String)
+ * @see PFont#PFont
+ * @see PGraphics#text(String, float, float)
+ * @see PGraphics#textFont(PFont)
+ * @see PGraphics#beginRaw(PGraphics)
+ * @see PApplet#createFont(String, float, boolean)
+ */
+ public void textMode(int mode) {
+ g.textMode(mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from textSize.xml )
+ *
+ * Sets the current font size. This size will be used in all subsequent
+ * calls to the text() function. Font size is measured in units of pixels.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:attributes
+ * @param size the size of the letters in units of pixels
+ * @see PApplet#loadFont(String)
+ * @see PFont#PFont
+ * @see PGraphics#text(String, float, float)
+ * @see PGraphics#textFont(PFont)
+ */
+ public void textSize(float size) {
+ g.textSize(size);
+ }
+
+
+ /**
+ * @param c the character to measure
+ */
+ public float textWidth(char c) {
+ return g.textWidth(c);
+ }
+
+
+ /**
+ * ( begin auto-generated from textWidth.xml )
+ *
+ * Calculates and returns the width of any character or text string.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:attributes
+ * @param str the String of characters to measure
+ * @see PApplet#loadFont(String)
+ * @see PFont#PFont
+ * @see PGraphics#text(String, float, float)
+ * @see PGraphics#textFont(PFont)
+ * @see PGraphics#textSize(float)
+ */
+ public float textWidth(String str) {
+ return g.textWidth(str);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public float textWidth(char[] chars, int start, int length) {
+ return g.textWidth(chars, start, length);
+ }
+
+
+ /**
+ * ( begin auto-generated from text.xml )
+ *
+ * Draws text to the screen. Displays the information specified in the
+ * data or stringdata parameters on the screen in the
+ * position specified by the x and y parameters and the
+ * optional z parameter. A default font will be used unless a font
+ * is set with the textFont() function. Change the color of the text
+ * with the fill() function. The text displays in relation to the
+ * textAlign() function, which gives the option to draw to the left,
+ * right, and center of the coordinates.
+ *
+ * The x2 and y2 parameters define a rectangular area to
+ * display within and may only be used with string data. For text drawn
+ * inside a rectangle, the coordinates are interpreted based on the current
+ * rectMode() setting.
+ *
+ * ( end auto-generated )
+ *
+ * @webref typography:loading_displaying
+ * @param c the alphanumeric character to be displayed
+ * @param x x-coordinate of text
+ * @param y y-coordinate of text
+ * @see PGraphics#textAlign(int, int)
+ * @see PGraphics#textFont(PFont)
+ * @see PGraphics#textMode(int)
+ * @see PGraphics#textSize(float)
+ * @see PGraphics#textLeading(float)
+ * @see PGraphics#textWidth(String)
+ * @see PGraphics#textAscent()
+ * @see PGraphics#textDescent()
+ * @see PGraphics#rectMode(int)
+ * @see PGraphics#fill(int, float)
+ * @see_external String
+ */
+ public void text(char c, float x, float y) {
+ g.text(c, x, y);
+ }
+
+
+ /**
+ * @param z z-coordinate of text
+ */
+ public void text(char c, float x, float y, float z) {
+ g.text(c, x, y, z);
+ }
+
+
+ /**
+ *
Advanced
+ * 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) {
+ g.text(str, x, y);
+ }
+
+
+ /**
+ *
Advanced
+ * 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.
+ * @param chars the alphanumberic symbols to be displayed
+ * @param start array index at which to start writing characters
+ * @param stop array index at which to stop writing characters
+ */
+ public void text(char[] chars, int start, int stop, float x, float 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) {
+ g.text(str, x, y, z);
+ }
+
+
+ public void text(char[] chars, int start, int stop,
+ float x, float y, float z) {
+ g.text(chars, start, stop, x, y, z);
+ }
+
+
+ /**
+ *
Advanced
+ * 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.
+ *
+ * @param x1 by default, the x-coordinate of text, see rectMode() for more info
+ * @param y1 by default, the y-coordinate of text, see rectMode() for more info
+ * @param x2 by default, the width of the text box, see rectMode() for more info
+ * @param y2 by default, the height of the text box, see rectMode() for more info
+ */
+ public void text(String str, float x1, float y1, float x2, float y2) {
+ g.text(str, x1, y1, x2, y2);
+ }
+
+
+ public void text(int num, float x, float y) {
+ g.text(num, x, y);
+ }
+
+
+ public void text(int num, float x, float y, float 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.
+ *
+ * @param num the numeric value to be displayed
+ */
+ public void text(float num, float x, float y) {
+ g.text(num, x, y);
+ }
+
+
+ public void text(float num, float x, float y, float z) {
+ g.text(num, x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from push.xml )
+ *
+ * The push() function saves the current drawing style
+ * settings and transformations, while pop() restores these
+ * settings. Note that these functions are always used together.
+ * They allow you to change the style and transformation settings
+ * and later return to what you had. When a new state is started
+ * with push(), it builds on the current style and transform
+ * information.
+ *
+ * push() stores information related to the current
+ * transformation state and style settings controlled by the
+ * following functions: rotate(), translate(),
+ * scale(), fill(), stroke(), tint(),
+ * strokeWeight(), strokeCap(), strokeJoin(),
+ * imageMode(), rectMode(), ellipseMode(),
+ * colorMode(), textAlign(), textFont(),
+ * textMode(), textSize(), textLeading().
+ *
+ * The push() and pop() functions were added with
+ * Processing 3.5. They can be used in place of pushMatrix(),
+ * popMatrix(), pushStyles(), and popStyles().
+ * The difference is that push() and pop() control both the
+ * transformations (rotate, scale, translate) and the drawing styles
+ * at the same time.
+ *
+ * ( end auto-generated )
+ *
+ * @webref structure
+ * @see PGraphics#pop()
+ */
+ public void push() {
+ g.push();
+ }
+
+
+ /**
+ * ( begin auto-generated from pop.xml )
+ *
+ * The pop() function restores the previous drawing style
+ * settings and transformations after push() has changed them.
+ * Note that these functions are always used together. They allow
+ * you to change the style and transformation settings and later
+ * return to what you had. When a new state is started with push(),
+ * it builds on the current style and transform information.
+ *
+ *
+ * push() stores information related to the current
+ * transformation state and style settings controlled by the
+ * following functions: rotate(), translate(),
+ * scale(), fill(), stroke(), tint(),
+ * strokeWeight(), strokeCap(), strokeJoin(),
+ * imageMode(), rectMode(), ellipseMode(),
+ * colorMode(), textAlign(), textFont(),
+ * textMode(), textSize(), textLeading().
+ *
+ * The push() and pop() functions were added with
+ * Processing 3.5. They can be used in place of pushMatrix(),
+ * popMatrix(), pushStyles(), and popStyles().
+ * The difference is that push() and pop() control both the
+ * transformations (rotate, scale, translate) and the drawing styles
+ * at the same time.
+ *
+ * ( end auto-generated )
+ *
+ * @webref structure
+ * @see PGraphics#push()
+ */
+ public void pop() {
+ g.pop();
+ }
+
+
+ /**
+ * ( begin auto-generated from pushMatrix.xml )
+ *
+ * Pushes the current transformation matrix onto the matrix stack.
+ * Understanding pushMatrix() and popMatrix() requires
+ * understanding the concept of a matrix stack. The pushMatrix()
+ * function saves the current coordinate system to the stack and
+ * popMatrix() restores the prior coordinate system.
+ * pushMatrix() and popMatrix() are used in conjuction with
+ * the other transformation functions and may be embedded to control the
+ * scope of the transformations.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#translate(float, float, float)
+ * @see PGraphics#scale(float)
+ * @see PGraphics#rotate(float)
+ * @see PGraphics#rotateX(float)
+ * @see PGraphics#rotateY(float)
+ * @see PGraphics#rotateZ(float)
+ */
+ public void pushMatrix() {
+ g.pushMatrix();
+ }
+
+
+ /**
+ * ( begin auto-generated from popMatrix.xml )
+ *
+ * Pops the current transformation matrix off the matrix stack.
+ * Understanding pushing and popping requires understanding the concept of
+ * a matrix stack. The pushMatrix() function saves the current
+ * coordinate system to the stack and popMatrix() restores the prior
+ * coordinate system. pushMatrix() and popMatrix() are used
+ * in conjuction with the other transformation functions and may be
+ * embedded to control the scope of the transformations.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @see PGraphics#pushMatrix()
+ */
+ public void popMatrix() {
+ g.popMatrix();
+ }
+
+
+ /**
+ * ( begin auto-generated from translate.xml )
+ *
+ * Specifies an amount to displace objects within the display window. 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. Using this function
+ * with the z parameter requires using P3D as a parameter in
+ * combination with size as shown in the above example. Transformations
+ * apply to everything that happens after and subsequent calls to the
+ * function accumulates the effect. For example, calling translate(50,
+ * 0) and then translate(20, 0) is the same as translate(70,
+ * 0). If translate() is called within draw(), the
+ * transformation is reset when the loop begins again. This function can be
+ * further controlled by the pushMatrix() and popMatrix().
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param x left/right translation
+ * @param y up/down translation
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#rotate(float)
+ * @see PGraphics#rotateX(float)
+ * @see PGraphics#rotateY(float)
+ * @see PGraphics#rotateZ(float)
+ * @see PGraphics#scale(float, float, float)
+ */
+ public void translate(float x, float y) {
+ g.translate(x, y);
+ }
+
+
+ /**
+ * @param z forward/backward translation
+ */
+ public void translate(float x, float y, float z) {
+ g.translate(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from rotate.xml )
+ *
+ * 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() function.
+ *
+ * Objects are always rotated around their relative position to the origin
+ * and positive numbers rotate objects in a clockwise direction.
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * rotate(HALF_PI) and then rotate(HALF_PI) is the same as
+ * rotate(PI). All tranformations are reset when draw()
+ * begins again.
+ *
+ * Technically, rotate() multiplies the current transformation
+ * matrix by a rotation matrix. This function can be further controlled by
+ * the pushMatrix() and popMatrix().
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param angle angle of rotation specified in radians
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#rotateX(float)
+ * @see PGraphics#rotateY(float)
+ * @see PGraphics#rotateZ(float)
+ * @see PGraphics#scale(float, float, float)
+ * @see PApplet#radians(float)
+ */
+ public void rotate(float angle) {
+ g.rotate(angle);
+ }
+
+
+ /**
+ * ( begin auto-generated from rotateX.xml )
+ *
+ * Rotates a shape around the x-axis the amount specified by the
+ * angle parameter. Angles should be specified in radians (values
+ * from 0 to PI*2) or converted to radians with the radians()
+ * function. Objects are always rotated around their relative position to
+ * the origin and positive numbers rotate objects in a counterclockwise
+ * direction. Transformations apply to everything that happens after and
+ * subsequent calls to the function accumulates the effect. For example,
+ * calling rotateX(PI/2) and then rotateX(PI/2) is the same
+ * as rotateX(PI). If rotateX() is called within the
+ * draw(), the transformation is reset when the loop begins again.
+ * This function requires using P3D as a third parameter to size()
+ * as shown in the example above.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param angle angle of rotation specified in radians
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#rotate(float)
+ * @see PGraphics#rotateY(float)
+ * @see PGraphics#rotateZ(float)
+ * @see PGraphics#scale(float, float, float)
+ * @see PGraphics#translate(float, float, float)
+ */
+ public void rotateX(float angle) {
+ g.rotateX(angle);
+ }
+
+
+ /**
+ * ( begin auto-generated from rotateY.xml )
+ *
+ * Rotates a shape around the y-axis the amount specified by the
+ * angle parameter. Angles should be specified in radians (values
+ * from 0 to PI*2) or converted to radians with the radians()
+ * function. Objects are always rotated around their relative position to
+ * the origin and positive numbers rotate objects in a counterclockwise
+ * direction. Transformations apply to everything that happens after and
+ * subsequent calls to the function accumulates the effect. For example,
+ * calling rotateY(PI/2) and then rotateY(PI/2) is the same
+ * as rotateY(PI). If rotateY() is called within the
+ * draw(), the transformation is reset when the loop begins again.
+ * This function requires using P3D as a third parameter to size()
+ * as shown in the examples above.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param angle angle of rotation specified in radians
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#rotate(float)
+ * @see PGraphics#rotateX(float)
+ * @see PGraphics#rotateZ(float)
+ * @see PGraphics#scale(float, float, float)
+ * @see PGraphics#translate(float, float, float)
+ */
+ public void rotateY(float angle) {
+ g.rotateY(angle);
+ }
+
+
+ /**
+ * ( begin auto-generated from rotateZ.xml )
+ *
+ * Rotates a shape around the z-axis the amount specified by the
+ * angle parameter. Angles should be specified in radians (values
+ * from 0 to PI*2) or converted to radians with the radians()
+ * function. Objects are always rotated around their relative position to
+ * the origin and positive numbers rotate objects in a counterclockwise
+ * direction. Transformations apply to everything that happens after and
+ * subsequent calls to the function accumulates the effect. For example,
+ * calling rotateZ(PI/2) and then rotateZ(PI/2) is the same
+ * as rotateZ(PI). If rotateZ() is called within the
+ * draw(), the transformation is reset when the loop begins again.
+ * This function requires using P3D as a third parameter to size()
+ * as shown in the examples above.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param angle angle of rotation specified in radians
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#rotate(float)
+ * @see PGraphics#rotateX(float)
+ * @see PGraphics#rotateY(float)
+ * @see PGraphics#scale(float, float, float)
+ * @see PGraphics#translate(float, float, float)
+ */
+ public void rotateZ(float angle) {
+ g.rotateZ(angle);
+ }
+
+
+ /**
+ *
Advanced
+ * Rotate about a vector in space. Same as the glRotatef() function.
+ * @nowebref
+ * @param x
+ * @param y
+ * @param z
+ */
+ public void rotate(float angle, float x, float y, float z) {
+ g.rotate(angle, x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from scale.xml )
+ *
+ * Increases or decreases the size of a shape by expanding and contracting
+ * vertices. Objects always scale from their relative origin to the
+ * coordinate system. Scale values are specified as decimal percentages.
+ * For example, the function call scale(2.0) increases the dimension
+ * of a shape by 200%. Transformations apply to everything that happens
+ * after and subsequent calls to the function multiply the effect. For
+ * example, calling scale(2.0) and then scale(1.5) is the
+ * same as scale(3.0). If scale() is called within
+ * draw(), the transformation is reset when the loop begins again.
+ * Using this fuction with the z parameter requires using P3D as a
+ * parameter for size() as shown in the example above. This function
+ * can be further controlled by pushMatrix() and popMatrix().
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param s percentage to scale the object
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#translate(float, float, float)
+ * @see PGraphics#rotate(float)
+ * @see PGraphics#rotateX(float)
+ * @see PGraphics#rotateY(float)
+ * @see PGraphics#rotateZ(float)
+ */
+ public void scale(float s) {
+ g.scale(s);
+ }
+
+
+ /**
+ *
Advanced
+ * 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.
+ *
+ * @param x percentage to scale the object in the x-axis
+ * @param y percentage to scale the object in the y-axis
+ */
+ public void scale(float x, float y) {
+ g.scale(x, y);
+ }
+
+
+ /**
+ * @param z percentage to scale the object in the z-axis
+ */
+ public void scale(float x, float y, float z) {
+ g.scale(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from shearX.xml )
+ *
+ * Shears a shape around the x-axis the amount specified by the
+ * angle parameter. Angles should be specified in radians (values
+ * from 0 to PI*2) or converted to radians with the radians()
+ * function. Objects are always sheared around their relative position to
+ * the origin and positive numbers shear objects in a clockwise direction.
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearX(PI/2) and then shearX(PI/2) is the same as
+ * shearX(PI). If shearX() is called within the
+ * draw(), the transformation is reset when the loop begins again.
+ *
+ * Technically, shearX() multiplies the current transformation
+ * matrix by a rotation matrix. This function can be further controlled by
+ * the pushMatrix() and popMatrix() functions.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param angle angle of shear specified in radians
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#shearY(float)
+ * @see PGraphics#scale(float, float, float)
+ * @see PGraphics#translate(float, float, float)
+ * @see PApplet#radians(float)
+ */
+ public void shearX(float angle) {
+ g.shearX(angle);
+ }
+
+
+ /**
+ * ( begin auto-generated from shearY.xml )
+ *
+ * Shears a shape around the y-axis the amount specified by the
+ * angle parameter. Angles should be specified in radians (values
+ * from 0 to PI*2) or converted to radians with the radians()
+ * function. Objects are always sheared around their relative position to
+ * the origin and positive numbers shear objects in a clockwise direction.
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearY(PI/2) and then shearY(PI/2) is the same as
+ * shearY(PI). If shearY() is called within the
+ * draw(), the transformation is reset when the loop begins again.
+ *
+ * Technically, shearY() multiplies the current transformation
+ * matrix by a rotation matrix. This function can be further controlled by
+ * the pushMatrix() and popMatrix() functions.
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @param angle angle of shear specified in radians
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#shearX(float)
+ * @see PGraphics#scale(float, float, float)
+ * @see PGraphics#translate(float, float, float)
+ * @see PApplet#radians(float)
+ */
+ public void shearY(float angle) {
+ g.shearY(angle);
+ }
+
+
+ /**
+ * ( begin auto-generated from resetMatrix.xml )
+ *
+ * Replaces the current matrix with the identity matrix. The equivalent
+ * function in OpenGL is glLoadIdentity().
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#applyMatrix(PMatrix)
+ * @see PGraphics#printMatrix()
+ */
+ public void resetMatrix() {
+ g.resetMatrix();
+ }
+
+
+ /**
+ * ( begin auto-generated from applyMatrix.xml )
+ *
+ * Multiplies the current matrix by the one specified through the
+ * parameters. This is very slow because it will try to calculate the
+ * inverse of the transform, so avoid it whenever possible. The equivalent
+ * function in OpenGL is glMultMatrix().
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @source
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#resetMatrix()
+ * @see PGraphics#printMatrix()
+ */
+ public void applyMatrix(PMatrix source) {
+ g.applyMatrix(source);
+ }
+
+
+ public void applyMatrix(PMatrix2D source) {
+ g.applyMatrix(source);
+ }
+
+
+ /**
+ * @param n00 numbers which define the 4x4 matrix to be multiplied
+ * @param n01 numbers which define the 4x4 matrix to be multiplied
+ * @param n02 numbers which define the 4x4 matrix to be multiplied
+ * @param n10 numbers which define the 4x4 matrix to be multiplied
+ * @param n11 numbers which define the 4x4 matrix to be multiplied
+ * @param n12 numbers which define the 4x4 matrix to be multiplied
+ */
+ public void applyMatrix(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ g.applyMatrix(n00, n01, n02, n10, n11, n12);
+ }
+
+
+ public void applyMatrix(PMatrix3D source) {
+ g.applyMatrix(source);
+ }
+
+
+ /**
+ * @param n03 numbers which define the 4x4 matrix to be multiplied
+ * @param n13 numbers which define the 4x4 matrix to be multiplied
+ * @param n20 numbers which define the 4x4 matrix to be multiplied
+ * @param n21 numbers which define the 4x4 matrix to be multiplied
+ * @param n22 numbers which define the 4x4 matrix to be multiplied
+ * @param n23 numbers which define the 4x4 matrix to be multiplied
+ * @param n30 numbers which define the 4x4 matrix to be multiplied
+ * @param n31 numbers which define the 4x4 matrix to be multiplied
+ * @param n32 numbers which define the 4x4 matrix to be multiplied
+ * @param n33 numbers which define the 4x4 matrix to be multiplied
+ */
+ 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) {
+ 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) {
+ g.setMatrix(source);
+ }
+
+
+ /**
+ * Set the current transformation to the contents of the specified source.
+ */
+ public void setMatrix(PMatrix2D source) {
+ g.setMatrix(source);
+ }
+
+
+ /**
+ * Set the current transformation to the contents of the specified source.
+ */
+ public void setMatrix(PMatrix3D source) {
+ g.setMatrix(source);
+ }
+
+
+ /**
+ * ( begin auto-generated from printMatrix.xml )
+ *
+ * Prints the current matrix to the Console (the text window at the bottom
+ * of Processing).
+ *
+ * ( end auto-generated )
+ *
+ * @webref transform
+ * @see PGraphics#pushMatrix()
+ * @see PGraphics#popMatrix()
+ * @see PGraphics#resetMatrix()
+ * @see PGraphics#applyMatrix(PMatrix)
+ */
+ public void printMatrix() {
+ g.printMatrix();
+ }
+
+
+ /**
+ * ( begin auto-generated from beginCamera.xml )
+ *
+ * The beginCamera() and endCamera() functions enable
+ * advanced customization of the camera space. The functions are useful if
+ * you want to more control over camera movement, however for most users,
+ * the camera() function will be sufficient.
The camera
+ * functions will replace any transformations (such as rotate() or
+ * translate()) that occur before them in draw(), but they
+ * will not automatically replace the camera transform itself. For this
+ * reason, camera functions should be placed at the beginning of
+ * draw() (so that transformations happen afterwards), and the
+ * camera() function can be used after beginCamera() if you
+ * want to reset the camera before applying transformations.
This function sets the matrix mode to the camera matrix so calls such
+ * as translate(), rotate(), applyMatrix() and resetMatrix()
+ * affect the camera. beginCamera() should always be used with a
+ * following endCamera() and pairs of beginCamera() and
+ * endCamera() cannot be nested.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ * @see PGraphics#camera()
+ * @see PGraphics#endCamera()
+ * @see PGraphics#applyMatrix(PMatrix)
+ * @see PGraphics#resetMatrix()
+ * @see PGraphics#translate(float, float, float)
+ * @see PGraphics#scale(float, float, float)
+ */
+ public void beginCamera() {
+ g.beginCamera();
+ }
+
+
+ /**
+ * ( begin auto-generated from endCamera.xml )
+ *
+ * The beginCamera() and endCamera() functions enable
+ * advanced customization of the camera space. Please see the reference for
+ * beginCamera() for a description of how the functions are used.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ * @see PGraphics#beginCamera()
+ * @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
+ */
+ public void endCamera() {
+ g.endCamera();
+ }
+
+
+ /**
+ * ( begin auto-generated from camera.xml )
+ *
+ * Sets the position of the camera through setting the eye position, the
+ * center of the scene, and which axis is facing upward. Moving the eye
+ * position and the direction it is pointing (the center of the scene)
+ * allows the images to be seen from different angles. The version without
+ * any parameters sets the camera to the default position, pointing to the
+ * center of the display window with the Y axis as up. The default values
+ * are camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 /
+ * 180.0), width/2.0, height/2.0, 0, 0, 1, 0). This function is similar
+ * to gluLookAt() in OpenGL, but it first clears the current camera settings.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ * @see PGraphics#beginCamera()
+ * @see PGraphics#endCamera()
+ * @see PGraphics#frustum(float, float, float, float, float, float)
+ */
+ public void camera() {
+ g.camera();
+ }
+
+
+ /**
+ * @param eyeX x-coordinate for the eye
+ * @param eyeY y-coordinate for the eye
+ * @param eyeZ z-coordinate for the eye
+ * @param centerX x-coordinate for the center of the scene
+ * @param centerY y-coordinate for the center of the scene
+ * @param centerZ z-coordinate for the center of the scene
+ * @param upX usually 0.0, 1.0, or -1.0
+ * @param upY usually 0.0, 1.0, or -1.0
+ * @param upZ usually 0.0, 1.0, or -1.0
+ */
+ public void camera(float eyeX, float eyeY, float eyeZ,
+ float centerX, float centerY, float centerZ,
+ float upX, float upY, float upZ) {
+ g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
+ }
+
+
+ /**
+ * ( begin auto-generated from printCamera.xml )
+ *
+ * Prints the current camera matrix to the Console (the text window at the
+ * bottom of Processing).
+ *
+ * ( end auto-generated )
+ * @webref lights_camera:camera
+ * @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
+ */
+ public void printCamera() {
+ g.printCamera();
+ }
+
+
+ /**
+ * ( begin auto-generated from ortho.xml )
+ *
+ * Sets an orthographic projection and defines a parallel clipping volume.
+ * All objects with the same dimension appear the same size, regardless of
+ * whether they are near or far from the camera. The parameters to this
+ * function specify the clipping volume where left and right are the
+ * minimum and maximum x values, top and bottom are the minimum and maximum
+ * y values, and near and far are the minimum and maximum z values. If no
+ * parameters are given, the default is used: ortho(0, width, 0, height,
+ * -10, 10).
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ */
+ public void ortho() {
+ g.ortho();
+ }
+
+
+ /**
+ * @param left left plane of the clipping volume
+ * @param right right plane of the clipping volume
+ * @param bottom bottom plane of the clipping volume
+ * @param top top plane of the clipping volume
+ */
+ public void ortho(float left, float right,
+ float bottom, float top) {
+ g.ortho(left, right, bottom, top);
+ }
+
+
+ /**
+ * @param near maximum distance from the origin to the viewer
+ * @param far maximum distance from the origin away from the viewer
+ */
+ public void ortho(float left, float right,
+ float bottom, float top,
+ float near, float far) {
+ g.ortho(left, right, bottom, top, near, far);
+ }
+
+
+ /**
+ * ( begin auto-generated from perspective.xml )
+ *
+ * Sets a perspective projection applying foreshortening, making distant
+ * objects appear smaller than closer ones. The parameters define a viewing
+ * volume with the shape of truncated pyramid. Objects near to the front of
+ * the volume appear their actual size, while farther objects appear
+ * smaller. This projection simulates the perspective of the world more
+ * accurately than orthographic projection. The version of perspective
+ * without parameters sets the default perspective and the version with
+ * four parameters allows the programmer to set the area precisely. The
+ * default values are: perspective(PI/3.0, width/height, cameraZ/10.0,
+ * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ */
+ public void perspective() {
+ g.perspective();
+ }
+
+
+ /**
+ * @param fovy field-of-view angle (in radians) for vertical direction
+ * @param aspect ratio of width to height
+ * @param zNear z-position of nearest clipping plane
+ * @param zFar z-position of farthest clipping plane
+ */
+ public void perspective(float fovy, float aspect, float zNear, float zFar) {
+ g.perspective(fovy, aspect, zNear, zFar);
+ }
+
+
+ /**
+ * ( begin auto-generated from frustum.xml )
+ *
+ * Sets a perspective matrix defined through the parameters. Works like
+ * glFrustum, except it wipes out the current perspective matrix rather
+ * than muliplying itself with it.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ * @param left left coordinate of the clipping plane
+ * @param right right coordinate of the clipping plane
+ * @param bottom bottom coordinate of the clipping plane
+ * @param top top coordinate of the clipping plane
+ * @param near near component of the clipping plane; must be greater than zero
+ * @param far far component of the clipping plane; must be greater than the near value
+ * @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#beginCamera()
+ * @see PGraphics#endCamera()
+ * @see PGraphics#perspective(float, float, float, float)
+ */
+ public void frustum(float left, float right,
+ float bottom, float top,
+ float near, float far) {
+ g.frustum(left, right, bottom, top, near, far);
+ }
+
+
+ /**
+ * ( begin auto-generated from printProjection.xml )
+ *
+ * Prints the current projection matrix to the Console (the text window at
+ * the bottom of Processing).
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:camera
+ * @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
+ */
+ public void printProjection() {
+ g.printProjection();
+ }
+
+
+ /**
+ * ( begin auto-generated from screenX.xml )
+ *
+ * Takes a three-dimensional X, Y, Z position and returns the X value for
+ * where it will appear on a (two-dimensional) screen.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:coordinates
+ * @param x 3D x-coordinate to be mapped
+ * @param y 3D y-coordinate to be mapped
+ * @see PGraphics#screenY(float, float, float)
+ * @see PGraphics#screenZ(float, float, float)
+ */
+ public float screenX(float x, float y) {
+ return g.screenX(x, y);
+ }
+
+
+ /**
+ * ( begin auto-generated from screenY.xml )
+ *
+ * Takes a three-dimensional X, Y, Z position and returns the Y value for
+ * where it will appear on a (two-dimensional) screen.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:coordinates
+ * @param x 3D x-coordinate to be mapped
+ * @param y 3D y-coordinate to be mapped
+ * @see PGraphics#screenX(float, float, float)
+ * @see PGraphics#screenZ(float, float, float)
+ */
+ public float screenY(float x, float y) {
+ return g.screenY(x, y);
+ }
+
+
+ /**
+ * @param z 3D z-coordinate to be mapped
+ */
+ public float screenX(float x, float y, float z) {
+ return g.screenX(x, y, z);
+ }
+
+
+ /**
+ * @param z 3D z-coordinate to be mapped
+ */
+ public float screenY(float x, float y, float z) {
+ return g.screenY(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from screenZ.xml )
+ *
+ * Takes a three-dimensional X, Y, Z position and returns the Z value for
+ * where it will appear on a (two-dimensional) screen.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:coordinates
+ * @param x 3D x-coordinate to be mapped
+ * @param y 3D y-coordinate to be mapped
+ * @param z 3D z-coordinate to be mapped
+ * @see PGraphics#screenX(float, float, float)
+ * @see PGraphics#screenY(float, float, float)
+ */
+ public float screenZ(float x, float y, float z) {
+ return g.screenZ(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from modelX.xml )
+ *
+ * Returns the three-dimensional X, Y, Z position in model space. This
+ * returns the X value for a given coordinate based on the current set of
+ * transformations (scale, rotate, translate, etc.) The X value can be used
+ * to place an object in space relative to the location of the original
+ * point once the transformations are no longer in use.
+ *
+ * In the example, the modelX(), modelY(), and
+ * modelZ() functions record the location of a box in space after
+ * being placed using a series of translate and rotate commands. After
+ * popMatrix() is called, those transformations no longer apply, but the
+ * (x, y, z) coordinate returned by the model functions is used to place
+ * another box in the same location.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:coordinates
+ * @param x 3D x-coordinate to be mapped
+ * @param y 3D y-coordinate to be mapped
+ * @param z 3D z-coordinate to be mapped
+ * @see PGraphics#modelY(float, float, float)
+ * @see PGraphics#modelZ(float, float, float)
+ */
+ public float modelX(float x, float y, float z) {
+ return g.modelX(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from modelY.xml )
+ *
+ * Returns the three-dimensional X, Y, Z position in model space. This
+ * returns the Y value for a given coordinate based on the current set of
+ * transformations (scale, rotate, translate, etc.) The Y value can be used
+ * to place an object in space relative to the location of the original
+ * point once the transformations are no longer in use.
+ *
+ * In the example, the modelX(), modelY(), and
+ * modelZ() functions record the location of a box in space after
+ * being placed using a series of translate and rotate commands. After
+ * popMatrix() is called, those transformations no longer apply, but the
+ * (x, y, z) coordinate returned by the model functions is used to place
+ * another box in the same location.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:coordinates
+ * @param x 3D x-coordinate to be mapped
+ * @param y 3D y-coordinate to be mapped
+ * @param z 3D z-coordinate to be mapped
+ * @see PGraphics#modelX(float, float, float)
+ * @see PGraphics#modelZ(float, float, float)
+ */
+ public float modelY(float x, float y, float z) {
+ return g.modelY(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from modelZ.xml )
+ *
+ * Returns the three-dimensional X, Y, Z position in model space. This
+ * returns the Z value for a given coordinate based on the current set of
+ * transformations (scale, rotate, translate, etc.) The Z value can be used
+ * to place an object in space relative to the location of the original
+ * point once the transformations are no longer in use.
+ *
+ * In the example, the modelX(), modelY(), and
+ * modelZ() functions record the location of a box in space after
+ * being placed using a series of translate and rotate commands. After
+ * popMatrix() is called, those transformations no longer apply, but the
+ * (x, y, z) coordinate returned by the model functions is used to place
+ * another box in the same location.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:coordinates
+ * @param x 3D x-coordinate to be mapped
+ * @param y 3D y-coordinate to be mapped
+ * @param z 3D z-coordinate to be mapped
+ * @see PGraphics#modelX(float, float, float)
+ * @see PGraphics#modelY(float, float, float)
+ */
+ public float modelZ(float x, float y, float z) {
+ return g.modelZ(x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from pushStyle.xml )
+ *
+ * The pushStyle() function saves the current style settings and
+ * popStyle() restores the prior settings. Note that these functions
+ * are always used together. They allow you to change the style settings
+ * and later return to what you had. When a new style is started with
+ * pushStyle(), it builds on the current style information. The
+ * pushStyle() and popStyle() functions can be embedded to
+ * provide more control (see the second example above for a demonstration.)
+ *
+ * The style information controlled by the following functions are included
+ * in the style:
+ * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
+ * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(),
+ * textAlign(), textFont(), textMode(), textSize(), textLeading(),
+ * emissive(), specular(), shininess(), ambient()
+ *
+ * ( end auto-generated )
+ *
+ * @webref structure
+ * @see PGraphics#popStyle()
+ */
+ public void pushStyle() {
+ g.pushStyle();
+ }
+
+
+ /**
+ * ( begin auto-generated from popStyle.xml )
+ *
+ * The pushStyle() function saves the current style settings and
+ * popStyle() restores the prior settings; these functions are
+ * always used together. They allow you to change the style settings and
+ * later return to what you had. When a new style is started with
+ * pushStyle(), it builds on the current style information. The
+ * pushStyle() and popStyle() functions can be embedded to
+ * provide more control (see the second example above for a demonstration.)
+ *
+ * ( end auto-generated )
+ *
+ * @webref structure
+ * @see PGraphics#pushStyle()
+ */
+ public void popStyle() {
+ g.popStyle();
+ }
+
+
+ public void style(PStyle s) {
+ g.style(s);
+ }
+
+
+ /**
+ * ( begin auto-generated from strokeWeight.xml )
+ *
+ * Sets the width of the stroke used for lines, points, and the border
+ * around shapes. All widths are set in units of pixels.
+ *
+ * When drawing with P3D, series of connected lines (such as the stroke
+ * around a polygon, triangle, or ellipse) produce unattractive results
+ * when a thick stroke weight is set (see
+ * Issue 123). With P3D, the minimum and maximum values for
+ * strokeWeight() are controlled by the graphics card and the
+ * operating system's OpenGL implementation. For instance, the thickness
+ * may not go higher than 10 pixels.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:attributes
+ * @param weight the weight (in pixels) of the stroke
+ * @see PGraphics#stroke(int, float)
+ * @see PGraphics#strokeJoin(int)
+ * @see PGraphics#strokeCap(int)
+ */
+ public void strokeWeight(float weight) {
+ g.strokeWeight(weight);
+ }
+
+
+ /**
+ * ( begin auto-generated from strokeJoin.xml )
+ *
+ * Sets the style of the joints which connect line segments. These joints
+ * are either mitered, beveled, or rounded and specified with the
+ * corresponding parameters MITER, BEVEL, and ROUND. The default joint is
+ * MITER.
+ *
+ * This function is not available with the P3D renderer, (see
+ * Issue 123). More information about the renderers can be found in the
+ * size() reference.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:attributes
+ * @param join either MITER, BEVEL, ROUND
+ * @see PGraphics#stroke(int, float)
+ * @see PGraphics#strokeWeight(float)
+ * @see PGraphics#strokeCap(int)
+ */
+ public void strokeJoin(int join) {
+ g.strokeJoin(join);
+ }
+
+
+ /**
+ * ( begin auto-generated from strokeCap.xml )
+ *
+ * Sets the style for rendering line endings. These ends are either
+ * squared, extended, or rounded and specified with the corresponding
+ * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND.
+ *
+ * This function is not available with the P3D renderer (see
+ * Issue 123). More information about the renderers can be found in the
+ * size() reference.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:attributes
+ * @param cap either SQUARE, PROJECT, or ROUND
+ * @see PGraphics#stroke(int, float)
+ * @see PGraphics#strokeWeight(float)
+ * @see PGraphics#strokeJoin(int)
+ * @see PApplet#size(int, int, String, String)
+ */
+ public void strokeCap(int cap) {
+ g.strokeCap(cap);
+ }
+
+
+ /**
+ * ( begin auto-generated from noStroke.xml )
+ *
+ * Disables drawing the stroke (outline). If both noStroke() and
+ * noFill() are called, nothing will be drawn to the screen.
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:setting
+ * @see PGraphics#stroke(int, float)
+ * @see PGraphics#fill(float, float, float, float)
+ * @see PGraphics#noFill()
+ */
+ public void noStroke() {
+ g.noStroke();
+ }
+
+
+ /**
+ * ( begin auto-generated from stroke.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ *
+ * @param rgb color value in hexadecimal notation
+ * @see PGraphics#noStroke()
+ * @see PGraphics#strokeWeight(float)
+ * @see PGraphics#strokeJoin(int)
+ * @see PGraphics#strokeCap(int)
+ * @see PGraphics#fill(int, float)
+ * @see PGraphics#noFill()
+ * @see PGraphics#tint(int, float)
+ * @see PGraphics#background(float, float, float, float)
+ * @see PGraphics#colorMode(int, float, float, float, float)
+ */
+ public void stroke(int rgb) {
+ g.stroke(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the stroke
+ */
+ public void stroke(int rgb, float alpha) {
+ g.stroke(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void stroke(float gray) {
+ g.stroke(gray);
+ }
+
+
+ public void stroke(float gray, float alpha) {
+ g.stroke(gray, alpha);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ * @webref color:setting
+ */
+ public void stroke(float v1, float v2, float v3) {
+ g.stroke(v1, v2, v3);
+ }
+
+
+ public void stroke(float v1, float v2, float v3, float alpha) {
+ g.stroke(v1, v2, v3, alpha);
+ }
+
+
+ /**
+ * ( begin auto-generated from noTint.xml )
+ *
+ * Removes the current fill value for displaying images and reverts to
+ * displaying images with their original hues.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:loading_displaying
+ * @usage web_application
+ * @see PGraphics#tint(float, float, float, float)
+ * @see PGraphics#image(PImage, float, float, float, float)
+ */
+ public void noTint() {
+ g.noTint();
+ }
+
+
+ /**
+ * ( begin auto-generated from tint.xml )
+ *
+ * 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() function is also used to control the coloring of
+ * textures in 3D.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:loading_displaying
+ * @usage web_application
+ * @param rgb color value in hexadecimal notation
+ * @see PGraphics#noTint()
+ * @see PGraphics#image(PImage, float, float, float, float)
+ */
+ public void tint(int rgb) {
+ g.tint(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the image
+ */
+ public void tint(int rgb, float alpha) {
+ g.tint(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void tint(float gray) {
+ g.tint(gray);
+ }
+
+
+ public void tint(float gray, float alpha) {
+ g.tint(gray, alpha);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ */
+ public void tint(float v1, float v2, float v3) {
+ g.tint(v1, v2, v3);
+ }
+
+
+ public void tint(float v1, float v2, float v3, float alpha) {
+ g.tint(v1, v2, v3, alpha);
+ }
+
+
+ /**
+ * ( begin auto-generated from noFill.xml )
+ *
+ * Disables filling geometry. If both noStroke() and noFill()
+ * are called, nothing will be drawn to the screen.
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:setting
+ * @usage web_application
+ * @see PGraphics#fill(float, float, float, float)
+ * @see PGraphics#stroke(int, float)
+ * @see PGraphics#noStroke()
+ */
+ public void noFill() {
+ g.noFill();
+ }
+
+
+ /**
+ * ( begin auto-generated from fill.xml )
+ *
+ * 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().
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:setting
+ * @usage web_application
+ * @param rgb color variable or hex value
+ * @see PGraphics#noFill()
+ * @see PGraphics#stroke(int, float)
+ * @see PGraphics#noStroke()
+ * @see PGraphics#tint(int, float)
+ * @see PGraphics#background(float, float, float, float)
+ * @see PGraphics#colorMode(int, float, float, float, float)
+ */
+ public void fill(int rgb) {
+ g.fill(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the fill
+ */
+ public void fill(int rgb, float alpha) {
+ g.fill(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray number specifying value between white and black
+ */
+ public void fill(float gray) {
+ g.fill(gray);
+ }
+
+
+ public void fill(float gray, float alpha) {
+ g.fill(gray, alpha);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ */
+ public void fill(float v1, float v2, float v3) {
+ g.fill(v1, v2, v3);
+ }
+
+
+ public void fill(float v1, float v2, float v3, float alpha) {
+ g.fill(v1, v2, v3, alpha);
+ }
+
+
+ /**
+ * ( begin auto-generated from ambient.xml )
+ *
+ * Sets the ambient reflectance for shapes drawn to the screen. This is
+ * combined with the ambient light component of environment. The color
+ * components set through the parameters define the reflectance. For
+ * example in the default color mode, setting v1=255, v2=126, v3=0, would
+ * cause all the red light to reflect and half of the green light to
+ * reflect. Used in combination with emissive(), specular(),
+ * and shininess() in setting the material properties of shapes.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:material_properties
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#emissive(float, float, float)
+ * @see PGraphics#specular(float, float, float)
+ * @see PGraphics#shininess(float)
+ */
+ public void ambient(int rgb) {
+ g.ambient(rgb);
+ }
+
+
+ /**
+ * @param gray number specifying value between white and black
+ */
+ public void ambient(float gray) {
+ g.ambient(gray);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ */
+ public void ambient(float v1, float v2, float v3) {
+ g.ambient(v1, v2, v3);
+ }
+
+
+ /**
+ * ( begin auto-generated from specular.xml )
+ *
+ * Sets the specular color of the materials used for shapes drawn to the
+ * screen, which sets the color of hightlights. Specular refers to light
+ * which bounces off a surface in a perferred direction (rather than
+ * bouncing in all directions like a diffuse light). Used in combination
+ * with emissive(), ambient(), and shininess() in
+ * setting the material properties of shapes.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:material_properties
+ * @usage web_application
+ * @param rgb color to set
+ * @see PGraphics#lightSpecular(float, float, float)
+ * @see PGraphics#ambient(float, float, float)
+ * @see PGraphics#emissive(float, float, float)
+ * @see PGraphics#shininess(float)
+ */
+ public void specular(int rgb) {
+ g.specular(rgb);
+ }
+
+
+ /**
+ * gray number specifying value between white and black
+ *
+ * @param gray value between black and white, by default 0 to 255
+ */
+ public void specular(float gray) {
+ g.specular(gray);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ */
+ public void specular(float v1, float v2, float v3) {
+ g.specular(v1, v2, v3);
+ }
+
+
+ /**
+ * ( begin auto-generated from shininess.xml )
+ *
+ * Sets the amount of gloss in the surface of shapes. Used in combination
+ * with ambient(), specular(), and emissive() in
+ * setting the material properties of shapes.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:material_properties
+ * @usage web_application
+ * @param shine degree of shininess
+ * @see PGraphics#emissive(float, float, float)
+ * @see PGraphics#ambient(float, float, float)
+ * @see PGraphics#specular(float, float, float)
+ */
+ public void shininess(float shine) {
+ g.shininess(shine);
+ }
+
+
+ /**
+ * ( begin auto-generated from emissive.xml )
+ *
+ * Sets the emissive color of the material used for drawing shapes drawn to
+ * the screen. Used in combination with ambient(),
+ * specular(), and shininess() in setting the material
+ * properties of shapes.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:material_properties
+ * @usage web_application
+ * @param rgb color to set
+ * @see PGraphics#ambient(float, float, float)
+ * @see PGraphics#specular(float, float, float)
+ * @see PGraphics#shininess(float)
+ */
+ public void emissive(int rgb) {
+ g.emissive(rgb);
+ }
+
+
+ /**
+ * gray number specifying value between white and black
+ *
+ * @param gray value between black and white, by default 0 to 255
+ */
+ public void emissive(float gray) {
+ g.emissive(gray);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ */
+ public void emissive(float v1, float v2, float v3) {
+ g.emissive(v1, v2, v3);
+ }
+
+
+ /**
+ * ( begin auto-generated from lights.xml )
+ *
+ * Sets the default ambient light, directional light, falloff, and specular
+ * values. The defaults are ambientLight(128, 128, 128) and
+ * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and
+ * lightSpecular(0, 0, 0). Lights need to be included in the draw() to
+ * remain persistent in a looping program. Placing them in the setup() of a
+ * looping program will cause them to only have an effect the first time
+ * through the loop.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @see PGraphics#ambientLight(float, float, float, float, float, float)
+ * @see PGraphics#directionalLight(float, float, float, float, float, float)
+ * @see PGraphics#pointLight(float, float, float, float, float, float)
+ * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#noLights()
+ */
+ public void lights() {
+ g.lights();
+ }
+
+
+ /**
+ * ( begin auto-generated from noLights.xml )
+ *
+ * Disable all lighting. Lighting is turned off by default and enabled with
+ * the lights() function. This function can be used to disable
+ * lighting so that 2D geometry (which does not require lighting) can be
+ * drawn after a set of lighted 3D geometry.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @see PGraphics#lights()
+ */
+ public void noLights() {
+ g.noLights();
+ }
+
+
+ /**
+ * ( begin auto-generated from ambientLight.xml )
+ *
+ * Adds an ambient light. Ambient light doesn't come from a specific
+ * direction, the rays have light have bounced around so much that objects
+ * are evenly lit from all sides. Ambient lights are almost always used in
+ * combination with other types of lights. Lights need to be included in
+ * the draw() to remain persistent in a looping program. Placing
+ * them in the setup() of a looping program will cause them to only
+ * have an effect the first time through the loop. The effect of the
+ * parameters is determined by the current color mode.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ * @see PGraphics#lights()
+ * @see PGraphics#directionalLight(float, float, float, float, float, float)
+ * @see PGraphics#pointLight(float, float, float, float, float, float)
+ * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void ambientLight(float v1, float v2, float v3) {
+ g.ambientLight(v1, v2, v3);
+ }
+
+
+ /**
+ * @param x x-coordinate of the light
+ * @param y y-coordinate of the light
+ * @param z z-coordinate of the light
+ */
+ public void ambientLight(float v1, float v2, float v3,
+ float x, float y, float z) {
+ g.ambientLight(v1, v2, v3, x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from directionalLight.xml )
+ *
+ * Adds a directional light. Directional light comes from one direction and
+ * is stronger when hitting a surface squarely and weaker if it hits at a a
+ * gentle angle. After hitting a surface, a directional lights scatters in
+ * all directions. Lights need to be included in the draw() to
+ * remain persistent in a looping program. Placing them in the
+ * setup() of a looping program will cause them to only have an
+ * effect the first time through the loop. The affect of the v1,
+ * v2, and v3 parameters is determined by the current color
+ * mode. The nx, ny, and nz parameters specify the
+ * direction the light is facing. For example, setting ny to -1 will
+ * cause the geometry to be lit from below (the light is facing directly upward).
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ * @param nx direction along the x-axis
+ * @param ny direction along the y-axis
+ * @param nz direction along the z-axis
+ * @see PGraphics#lights()
+ * @see PGraphics#ambientLight(float, float, float, float, float, float)
+ * @see PGraphics#pointLight(float, float, float, float, float, float)
+ * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void directionalLight(float v1, float v2, float v3,
+ float nx, float ny, float nz) {
+ g.directionalLight(v1, v2, v3, nx, ny, nz);
+ }
+
+
+ /**
+ * ( begin auto-generated from pointLight.xml )
+ *
+ * Adds a point light. Lights need to be included in the draw() to
+ * remain persistent in a looping program. Placing them in the
+ * setup() of a looping program will cause them to only have an
+ * effect the first time through the loop. The affect of the v1,
+ * v2, and v3 parameters is determined by the current color
+ * mode. The x, y, and z parameters set the position
+ * of the light.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ * @param x x-coordinate of the light
+ * @param y y-coordinate of the light
+ * @param z z-coordinate of the light
+ * @see PGraphics#lights()
+ * @see PGraphics#directionalLight(float, float, float, float, float, float)
+ * @see PGraphics#ambientLight(float, float, float, float, float, float)
+ * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void pointLight(float v1, float v2, float v3,
+ float x, float y, float z) {
+ g.pointLight(v1, v2, v3, x, y, z);
+ }
+
+
+ /**
+ * ( begin auto-generated from spotLight.xml )
+ *
+ * Adds a spot light. Lights need to be included in the draw() to
+ * remain persistent in a looping program. Placing them in the
+ * setup() of a looping program will cause them to only have an
+ * effect the first time through the loop. The affect of the v1,
+ * v2, and v3 parameters is determined by the current color
+ * mode. The x, y, and z parameters specify the
+ * position of the light and nx, ny, nz specify the
+ * direction or light. The angle parameter affects angle of the
+ * spotlight cone.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ * @param x x-coordinate of the light
+ * @param y y-coordinate of the light
+ * @param z z-coordinate of the light
+ * @param nx direction along the x axis
+ * @param ny direction along the y axis
+ * @param nz direction along the z axis
+ * @param angle angle of the spotlight cone
+ * @param concentration exponent determining the center bias of the cone
+ * @see PGraphics#lights()
+ * @see PGraphics#directionalLight(float, float, float, float, float, float)
+ * @see PGraphics#pointLight(float, float, float, float, float, float)
+ * @see PGraphics#ambientLight(float, float, float, float, float, float)
+ */
+ public void spotLight(float v1, float v2, float v3,
+ float x, float y, float z,
+ float nx, float ny, float nz,
+ float angle, float concentration) {
+ g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
+ }
+
+
+ /**
+ * ( begin auto-generated from lightFalloff.xml )
+ *
+ * Sets the falloff rates for point lights, spot lights, and ambient
+ * lights. The parameters are used to determine the falloff with the
+ * following equation:
d = distance from light position to
+ * vertex position falloff = 1 / (CONSTANT + d * LINEAR + (d*d) *
+ * QUADRATIC)
Like fill(), it affects only the elements
+ * which are created after it in the code. The default value if
+ * LightFalloff(1.0, 0.0, 0.0). Thinking about an ambient light with
+ * a falloff can be tricky. It is used, for example, if you wanted a region
+ * of your scene to be lit ambiently one color and another region to be lit
+ * ambiently by another color, you would use an ambient light with location
+ * and falloff. You can think of it as a point light that doesn't care
+ * which direction a surface is facing.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @param constant constant value or determining falloff
+ * @param linear linear value for determining falloff
+ * @param quadratic quadratic value for determining falloff
+ * @see PGraphics#lights()
+ * @see PGraphics#ambientLight(float, float, float, float, float, float)
+ * @see PGraphics#pointLight(float, float, float, float, float, float)
+ * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#lightSpecular(float, float, float)
+ */
+ public void lightFalloff(float constant, float linear, float quadratic) {
+ g.lightFalloff(constant, linear, quadratic);
+ }
+
+
+ /**
+ * ( begin auto-generated from lightSpecular.xml )
+ *
+ * Sets the specular color for lights. Like fill(), it affects only
+ * the elements which are created after it in the code. Specular refers to
+ * light which bounces off a surface in a perferred direction (rather than
+ * bouncing in all directions like a diffuse light) and is used for
+ * creating highlights. The specular quality of a light interacts with the
+ * specular material qualities set through the specular() and
+ * shininess() functions.
+ *
+ * ( end auto-generated )
+ *
+ * @webref lights_camera:lights
+ * @usage web_application
+ * @param v1 red or hue value (depending on current color mode)
+ * @param v2 green or saturation value (depending on current color mode)
+ * @param v3 blue or brightness value (depending on current color mode)
+ * @see PGraphics#specular(float, float, float)
+ * @see PGraphics#lights()
+ * @see PGraphics#ambientLight(float, float, float, float, float, float)
+ * @see PGraphics#pointLight(float, float, float, float, float, float)
+ * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
+ */
+ public void lightSpecular(float v1, float v2, float v3) {
+ g.lightSpecular(v1, v2, v3);
+ }
+
+
+ /**
+ * ( begin auto-generated from background.xml )
+ *
+ * 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().
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ *
Clear the background with a color that includes an alpha value. This can
+ * only be used with objects created by createGraphics(), because the main
+ * drawing surface cannot be set transparent.
+ *
It might be tempting to use this function to partially clear the screen
+ * on each frame, however that's not how this function works. When calling
+ * background(), the pixels will be replaced with pixels that have that level
+ * of transparency. To do a semi-transparent overlay, use fill() with alpha
+ * and draw a rectangle.
+ *
+ * @webref color:setting
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#stroke(float)
+ * @see PGraphics#fill(float)
+ * @see PGraphics#tint(float)
+ * @see PGraphics#colorMode(int)
+ */
+ public void background(int rgb) {
+ g.background(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the background
+ */
+ public void background(int rgb, float alpha) {
+ g.background(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void background(float gray) {
+ g.background(gray);
+ }
+
+
+ public void background(float gray, float alpha) {
+ g.background(gray, alpha);
+ }
+
+
+ /**
+ * @param v1 red or hue value (depending on the current color mode)
+ * @param v2 green or saturation value (depending on the current color mode)
+ * @param v3 blue or brightness value (depending on the current color mode)
+ */
+ public void background(float v1, float v2, float v3) {
+ g.background(v1, v2, v3);
+ }
+
+
+ public void background(float v1, float v2, float v3, float alpha) {
+ g.background(v1, v2, v3, alpha);
+ }
+
+
+ /**
+ * @webref color:setting
+ */
+ public void clear() {
+ g.clear();
+ }
+
+
+ /**
+ * 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. Use image.filter(OPAQUE) to handle this easily.
+ *
+ * When using 3D, this will also clear the zbuffer (if it exists).
+ *
+ * @param image PImage to set as background (must be same size as the sketch window)
+ */
+ public void background(PImage image) {
+ g.background(image);
+ }
+
+
+ /**
+ * ( begin auto-generated from colorMode.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:setting
+ * @usage web_application
+ * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness
+ * @see PGraphics#background(float)
+ * @see PGraphics#fill(float)
+ * @see PGraphics#stroke(float)
+ */
+ public void colorMode(int mode) {
+ g.colorMode(mode);
+ }
+
+
+ /**
+ * @param max range for all color elements
+ */
+ public void colorMode(int mode, float max) {
+ g.colorMode(mode, max);
+ }
+
+
+ /**
+ * @param max1 range for the red or hue depending on the current color mode
+ * @param max2 range for the green or saturation depending on the current color mode
+ * @param max3 range for the blue or brightness depending on the current color mode
+ */
+ public void colorMode(int mode, float max1, float max2, float max3) {
+ g.colorMode(mode, max1, max2, max3);
+ }
+
+
+ /**
+ * @param maxA range for the alpha
+ */
+ public void colorMode(int mode,
+ float max1, float max2, float max3, float maxA) {
+ g.colorMode(mode, max1, max2, max3, maxA);
+ }
+
+
+ /**
+ * ( begin auto-generated from alpha.xml )
+ *
+ * Extracts the alpha value from a color.
+ *
+ * ( end auto-generated )
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb 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)
+ * @see PGraphics#brightness(int)
+ */
+ public final float alpha(int rgb) {
+ return g.alpha(rgb);
+ }
+
+
+ /**
+ * ( begin auto-generated from red.xml )
+ *
+ * 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:
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#green(int)
+ * @see PGraphics#blue(int)
+ * @see PGraphics#alpha(int)
+ * @see PGraphics#hue(int)
+ * @see PGraphics#saturation(int)
+ * @see PGraphics#brightness(int)
+ * @see_external rightshift
+ */
+ public final float red(int rgb) {
+ return g.red(rgb);
+ }
+
+
+ /**
+ * ( begin auto-generated from green.xml )
+ *
+ * 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:
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#red(int)
+ * @see PGraphics#blue(int)
+ * @see PGraphics#alpha(int)
+ * @see PGraphics#hue(int)
+ * @see PGraphics#saturation(int)
+ * @see PGraphics#brightness(int)
+ * @see_external rightshift
+ */
+ public final float green(int rgb) {
+ return g.green(rgb);
+ }
+
+
+ /**
+ * ( begin auto-generated from blue.xml )
+ *
+ * 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:
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#red(int)
+ * @see PGraphics#green(int)
+ * @see PGraphics#alpha(int)
+ * @see PGraphics#hue(int)
+ * @see PGraphics#saturation(int)
+ * @see PGraphics#brightness(int)
+ * @see_external rightshift
+ */
+ public final float blue(int rgb) {
+ return g.blue(rgb);
+ }
+
+
+ /**
+ * ( begin auto-generated from hue.xml )
+ *
+ * Extracts the hue value from a color.
+ *
+ * ( end auto-generated )
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#red(int)
+ * @see PGraphics#green(int)
+ * @see PGraphics#blue(int)
+ * @see PGraphics#alpha(int)
+ * @see PGraphics#saturation(int)
+ * @see PGraphics#brightness(int)
+ */
+ public final float hue(int rgb) {
+ return g.hue(rgb);
+ }
+
+
+ /**
+ * ( begin auto-generated from saturation.xml )
+ *
+ * Extracts the saturation value from a color.
+ *
+ * ( end auto-generated )
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#red(int)
+ * @see PGraphics#green(int)
+ * @see PGraphics#blue(int)
+ * @see PGraphics#alpha(int)
+ * @see PGraphics#hue(int)
+ * @see PGraphics#brightness(int)
+ */
+ public final float saturation(int rgb) {
+ return g.saturation(rgb);
+ }
+
+
+ /**
+ * ( begin auto-generated from brightness.xml )
+ *
+ * Extracts the brightness value from a color.
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param rgb any value of the color datatype
+ * @see PGraphics#red(int)
+ * @see PGraphics#green(int)
+ * @see PGraphics#blue(int)
+ * @see PGraphics#alpha(int)
+ * @see PGraphics#hue(int)
+ * @see PGraphics#saturation(int)
+ */
+ public final float brightness(int rgb) {
+ return g.brightness(rgb);
+ }
+
+
+ /**
+ * @nowebref
+ * 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);
+ }
+
+
+ /**
+ * Display a warning that the specified method is only available with 3D.
+ * @param method The method name (no parentheses)
+ */
+ static public void showDepthWarning(String method) {
+ PGraphics.showDepthWarning(method);
+ }
+
+
+ /**
+ * 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 public void showDepthWarningXYZ(String method) {
+ PGraphics.showDepthWarningXYZ(method);
+ }
+
+
+ /**
+ * Display a warning that the specified method is simply unavailable.
+ */
+ static public void showMethodWarning(String method) {
+ PGraphics.showMethodWarning(method);
+ }
+
+
+ /**
+ * 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 public void showVariationWarning(String str) {
+ PGraphics.showVariationWarning(str);
+ }
+
+
+ /**
+ * 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 public void showMissingWarning(String method) {
+ PGraphics.showMissingWarning(method);
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_get.xml )
+ *
+ * Reads the color of any pixel or grabs a section of an image. If no
+ * parameters are specified, the entire image is returned. Use the x
+ * and y parameters to get the value of one pixel. Get a section of
+ * the display window by specifying an additional width and
+ * height parameter. When getting an image, the x and
+ * y parameters define the coordinates for the upper-left corner of
+ * the image, regardless of the current imageMode().
+ *
+ * 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. For example,
+ * even though you may have drawn a shape with colorMode(HSB), the
+ * numbers returned will be in RGB format.
+ *
+ * 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]. See the reference for pixels[] for more information.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * 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.
+ *
+ * @webref image:pixels
+ * @brief Reads the color of any pixel or grabs a rectangle of pixels
+ * @usage web_application
+ * @param x x-coordinate of the pixel
+ * @param y y-coordinate of the pixel
+ * @see PApplet#set(int, int, int)
+ * @see PApplet#pixels
+ * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int)
+ */
+ public int get(int x, int y) {
+ return g.get(x, y);
+ }
+
+
+ /**
+ * @param w width of pixel rectangle to get
+ * @param h height of pixel rectangle to get
+ */
+ 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).
+ * Deprecated, just use copy() instead.
+ */
+ public PImage get() {
+ return g.get();
+ }
+
+
+ public PImage copy() {
+ return g.copy();
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_set.xml )
+ *
+ * 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, regardless of
+ * the current imageMode().
+ *
+ * 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. See the reference for
+ * pixels[] for more information.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:pixels
+ * @brief writes a color to any pixel or writes an image into another
+ * @usage web_application
+ * @param x x-coordinate of the pixel
+ * @param y y-coordinate of the pixel
+ * @param c any value of the color datatype
+ * @see PImage#get(int, int, int, int)
+ * @see PImage#pixels
+ * @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
+ */
+ public void set(int x, int y, int c) {
+ g.set(x, y, c);
+ }
+
+
+ /**
+ *
Advanced
+ * 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.
+ *
+ * @param img image to copy into the original image
+ */
+ public void set(int x, int y, PImage img) {
+ g.set(x, y, img);
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_mask.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ *
+ * 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.
+ *
+ * @webref pimage:method
+ * @usage web_application
+ * @param img image to use as the mask
+ * @brief Masks part of an image with another image as an alpha channel
+ */
+ public void mask(PImage img) {
+ g.mask(img);
+ }
+
+
+ public void filter(int kind) {
+ g.filter(kind);
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_filter.xml )
+ *
+ * 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
+ *
+ * ( end auto-generated )
+ *
+ *
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 image:pixels
+ * @brief Converts the image to grayscale or black and white
+ * @usage web_application
+ * @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE
+ * @param param unique for each, see above
+ */
+ public void filter(int kind, float param) {
+ g.filter(kind, param);
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_copy.xml )
+ *
+ * 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().
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:pixels
+ * @brief Copies the entire image
+ * @usage web_application
+ * @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
+ * @see PGraphics#alpha(int)
+ * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int)
+ */
+ public void copy(int sx, int sy, int sw, int sh,
+ int dx, int dy, int dw, int dh) {
+ g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
+ }
+
+
+ /**
+ * @param src an image variable referring to the source image.
+ */
+ public void copy(PImage src,
+ int sx, int sy, int sw, int sh,
+ int dx, int dy, int dw, int dh) {
+ g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
+ }
+
+
+ public void blend(int sx, int sy, int sw, int sh,
+ int dx, int dy, int dw, int dh, int mode) {
+ g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_blend.xml )
+ *
+ * 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().
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:pixels
+ * @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 PApplet#alpha(int)
+ * @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
+ * @see 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) {
+ g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
+ }
+}
diff --git a/core-androidx/src/processing/core/PConstants.java b/core-androidx/src/processing/core/PConstants.java
new file mode 100644
index 000000000..a8be77fd0
--- /dev/null
+++ b/core-androidx/src/processing/core/PConstants.java
@@ -0,0 +1,465 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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 version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import android.view.KeyEvent;
+//import java.awt.Cursor;
+//import java.awt.event.KeyEvent;
+
+
+/**
+ * Numbers shared throughout processing.core.
+ *
+ * An attempt is made to keep the constants as short/non-verbose
+ * as possible. For instance, the constant is TIFF instead of
+ * FILE_TYPE_TIFF. We'll do this as long as we can get away with it.
+ */
+public interface PConstants {
+
+ // vertex fields
+ static public final int X = 0; // model coords xyz (formerly MX/MY/MZ)
+ static public final int Y = 1;
+ static public final int Z = 2;
+
+ // built-in rendering options
+ static final String JAVA2D = "processing.core.PGraphicsAndroid2D";
+ static final String P2D = "processing.opengl.PGraphics2D";
+ static final String P2DX = "processing.opengl.PGraphics2DX";
+ static final String P3D = "processing.opengl.PGraphics3D";
+ static final String OPENGL = P3D;
+ static final String STEREO = "processing.vr.VRGraphicsStereo";
+ static final String MONO = "processing.vr.VRGraphicsMono";
+ static final String VR = STEREO;
+ static final String AR = "processing.ar.ARGraphics";
+ static final String ARCORE = AR;
+
+ // The PDF and DXF renderers are not available for Android.
+
+
+ // platform IDs for PApplet.platform
+
+ static final int OTHER = 0;
+ static final int WINDOWS = 1;
+ static final int MACOSX = 2;
+ static final int LINUX = 3;
+
+ static final String[] platformNames = {
+ "other", "windows", "macosx", "linux"
+ };
+
+
+ static final float EPSILON = 0.0001f;
+
+
+ // max/min values for numbers
+
+ /**
+ * Same as Float.MAX_VALUE, but included for parity with MIN_VALUE,
+ * and to avoid teaching static methods on the first day.
+ */
+ static final float MAX_FLOAT = Float.MAX_VALUE;
+ /**
+ * Note that Float.MIN_VALUE is the smallest positive value
+ * for a floating point number, not actually the minimum (negative) value
+ * for a float. This constant equals 0xFF7FFFFF, the smallest (farthest
+ * negative) value a float can have before it hits NaN.
+ */
+ static final float MIN_FLOAT = -Float.MAX_VALUE;
+ /** Largest possible (positive) integer value */
+ static final int MAX_INT = Integer.MAX_VALUE;
+ /** Smallest possible (negative) integer value */
+ static final int MIN_INT = Integer.MIN_VALUE;
+
+
+ // shapes
+
+ static public final int VERTEX = 0;
+ static public final int BEZIER_VERTEX = 1;
+ static public final int QUADRATIC_VERTEX = 2;
+ static public final int CURVE_VERTEX = 3;
+ static public final int BREAK = 4;
+
+ @Deprecated
+ static public final int QUAD_BEZIER_VERTEX = 2; // should not have been exposed
+
+ // useful goodness
+
+ static final float PI = (float) Math.PI;
+ static final float HALF_PI = PI / 2.0f;
+ static final float THIRD_PI = PI / 3.0f;
+ static final float QUARTER_PI = PI / 4.0f;
+ static final float TWO_PI = PI * 2.0f;
+ static final float TAU = PI * 2.0f;
+
+ static final float DEG_TO_RAD = PI/180.0f;
+ static final float RAD_TO_DEG = 180.0f/PI;
+
+
+ // angle modes
+
+ //static final int RADIANS = 0;
+ //static final int DEGREES = 1;
+
+
+ // used by split, all the standard whitespace chars
+ // (also includes unicode nbsp, that little bostage)
+
+ static final String WHITESPACE = " \t\n\r\f\u00A0";
+
+
+ // for colors and/or images
+
+ static final int RGB = 1; // image & color
+ static final int ARGB = 2; // image
+ static final int HSB = 3; // color
+ static final int ALPHA = 4; // image
+ static final int CMYK = 5; // image & color (someday)
+ static final int YUV420 = 6; // Android video preview.
+
+
+ // image file types
+
+ static final int TIFF = 0;
+ static final int TARGA = 1;
+ static final int JPEG = 2;
+ static final int GIF = 3;
+
+
+ // filter/convert types
+
+ static final int BLUR = 11;
+ static final int GRAY = 12;
+ static final int INVERT = 13;
+ static final int OPAQUE = 14;
+ static final int POSTERIZE = 15;
+ static final int THRESHOLD = 16;
+ static final int ERODE = 17;
+ static final int DILATE = 18;
+
+
+ // blend mode keyword definitions
+ // @see processing.core.PImage#blendColor(int,int,int)
+
+ public final static int REPLACE = 0;
+ public final static int BLEND = 1 << 0;
+ public final static int ADD = 1 << 1;
+ public final static int SUBTRACT = 1 << 2;
+ public final static int LIGHTEST = 1 << 3;
+ public final static int DARKEST = 1 << 4;
+ public final static int DIFFERENCE = 1 << 5;
+ public final static int EXCLUSION = 1 << 6;
+ public final static int MULTIPLY = 1 << 7;
+ public final static int SCREEN = 1 << 8;
+ public final static int OVERLAY = 1 << 9;
+ public final static int HARD_LIGHT = 1 << 10;
+ public final static int SOFT_LIGHT = 1 << 11;
+ public final static int DODGE = 1 << 12;
+ public final static int BURN = 1 << 13;
+
+
+ // for messages
+
+ static final int CHATTER = 0;
+ static final int COMPLAINT = 1;
+ static final int PROBLEM = 2;
+
+ // types of transformation matrices
+
+ static final int PROJECTION = 0;
+ static final int MODELVIEW = 1;
+
+ // types of projection matrices
+
+ static final int CUSTOM = 0; // user-specified fanciness
+ static final int ORTHOGRAPHIC = 2; // 2D isometric projection
+ static final int PERSPECTIVE = 3; // perspective matrix
+
+
+ // shapes
+
+ // the low four bits set the variety,
+ // higher bits set the specific shape type
+
+ static final int GROUP = 0; // createShape()
+
+ static final int POINT = 2; // primitive
+ static final int POINTS = 3; // vertices
+
+ static final int LINE = 4; // primitive
+ static final int LINES = 5; // beginShape(), createShape()
+ static final int LINE_STRIP = 50; // beginShape()
+ static final int LINE_LOOP = 51;
+
+ static final int TRIANGLE = 8; // primitive
+ static final int TRIANGLES = 9; // vertices
+ static final int TRIANGLE_STRIP = 10; // vertices
+ static final int TRIANGLE_FAN = 11; // vertices
+
+ static final int QUAD = 16; // primitive
+ static final int QUADS = 17; // vertices
+ static final int QUAD_STRIP = 18; // vertices
+
+ static final int POLYGON = 20; // in the end, probably cannot
+ static final int PATH = 21; // separate these two
+
+ static final int RECT = 30; // primitive
+ static final int ELLIPSE = 31; // primitive
+ static final int ARC = 32; // primitive
+
+ static final int SPHERE = 40; // primitive
+ static final int BOX = 41; // primitive
+
+// static public final int LINE_STRIP = 50;
+// static public final int LINE_LOOP = 51;
+// static public final int POINT_SPRITES = 52;
+
+
+ // shape closing modes
+
+ static final int OPEN = 1;
+ static final int CLOSE = 2;
+
+
+ // shape drawing modes
+
+ /** Draw mode convention to use (x, y) to (width, height) */
+ static final int CORNER = 0;
+ /** Draw mode convention to use (x1, y1) to (x2, y2) coordinates */
+ static final int CORNERS = 1;
+ /** Draw mode from the center, and using the radius */
+ static final int RADIUS = 2;
+ /** @deprecated Use RADIUS instead. */
+ static final int CENTER_RADIUS = 2;
+ /**
+ * Draw from the center, using second pair of values as the diameter.
+ * Formerly called CENTER_DIAMETER in alpha releases.
+ */
+ static final int CENTER = 3;
+ /**
+ * Synonym for the CENTER constant. Draw from the center,
+ * using second pair of values as the diameter.
+ */
+ static final int DIAMETER = 3;
+ /** @deprecated Use DIAMETER instead. */
+ static final int CENTER_DIAMETER = 3;
+
+
+ // arc drawing modes
+
+ //static final int OPEN = 1; // shared
+ static final int CHORD = 2;
+ static final int PIE = 3;
+
+
+ // vertically alignment modes for text
+
+ /** Default vertical alignment for text placement */
+ static final int BASELINE = 0;
+ /** Align text to the top */
+ static final int TOP = 101;
+ /** Align text from the bottom, using the baseline. */
+ static final int BOTTOM = 102;
+
+
+ // uv texture orientation modes
+
+ /** texture coordinates in 0..1 range */
+ static final int NORMAL = 1;
+ /** texture coordinates based on image width/height */
+ static final int IMAGE = 2;
+
+
+ // texture wrapping modes
+
+ /** textures are clamped to their edges */
+ public static final int CLAMP = 0;
+ /** textures wrap around when uv values go outside 0..1 range */
+ public static final int REPEAT = 1;
+
+
+ // text placement modes
+
+ /**
+ * textMode(MODEL) is the default, meaning that characters
+ * will be affected by transformations like any other shapes.
+ *
+ * Changed value in 0093 to not interfere with LEFT, CENTER, and RIGHT.
+ */
+ static final int MODEL = 4;
+
+ /**
+ * textMode(SHAPE) draws text using the the glyph outlines of
+ * individual characters rather than as textures. If the outlines are
+ * not available, then textMode(SHAPE) will be ignored and textMode(MODEL)
+ * will be used instead. For this reason, be sure to call textMode()
+ * after calling textFont().
+ *
+ * Currently, textMode(SHAPE) is only supported by OPENGL mode.
+ * It also requires Java 1.2 or higher (OPENGL requires 1.4 anyway)
+ */
+ static final int SHAPE = 5;
+
+
+ // text alignment modes
+ // are inherited from LEFT, CENTER, RIGHT
+
+
+ // stroke modes
+
+ static final int SQUARE = 1 << 0; // called 'butt' in the svg spec
+ static final int ROUND = 1 << 1;
+ static final int PROJECT = 1 << 2; // called 'square' in the svg spec
+ static final int MITER = 1 << 3;
+ static final int BEVEL = 1 << 5;
+
+
+ // lighting
+
+ static final int AMBIENT = 0;
+ static final int DIRECTIONAL = 1;
+ //static final int POINT = 2; // shared with shape feature
+ static final int SPOT = 3;
+
+
+ // key constants
+
+ // only including the most-used of these guys
+ // if people need more esoteric keys, they can learn about
+ // the esoteric java KeyEvent api and of virtual keys
+
+ // both key and keyCode will equal these values
+ // for 0125, these were changed to 'char' values, because they
+ // can be upgraded to ints automatically by Java, but having them
+ // as ints prevented split(blah, TAB) from working
+ static final char BACKSPACE = KeyEvent.KEYCODE_DEL;
+ static final char TAB = KeyEvent.KEYCODE_TAB;
+ static final char ENTER = KeyEvent.KEYCODE_ENTER;
+ static final char RETURN = KeyEvent.KEYCODE_ENTER;
+ static final char ESC = KeyEvent.KEYCODE_ESCAPE;
+ static final char DELETE = KeyEvent.KEYCODE_DEL;
+
+ // i.e. if ((key == CODED) && (keyCode == UP))
+ static final int CODED = 0xffff;
+
+ // key will be CODED and keyCode will be this value
+ static final int UP = KeyEvent.KEYCODE_DPAD_UP;
+ static final int DOWN = KeyEvent.KEYCODE_DPAD_DOWN;
+ static final int LEFT = KeyEvent.KEYCODE_DPAD_LEFT;
+ static final int RIGHT = KeyEvent.KEYCODE_DPAD_RIGHT;
+
+ // These seem essential for most sketches, so they're included.
+ // Others can be found in the KeyEvent reference:
+ // http://developer.android.com/reference/android/view/KeyEvent.html
+ static final int BACK = KeyEvent.KEYCODE_BACK;
+ static final int MENU = KeyEvent.KEYCODE_MENU;
+ static final int DPAD = KeyEvent.KEYCODE_DPAD_CENTER;
+
+
+ // key will be CODED and keyCode will be this value
+// static final int ALT = KeyEvent.VK_ALT;
+// static final int CONTROL = KeyEvent.VK_CONTROL;
+ static final int SHIFT = KeyEvent.KEYCODE_SHIFT_LEFT;
+
+ // cursor types
+
+// static final int ARROW = Cursor.DEFAULT_CURSOR;
+// static final int CROSS = Cursor.CROSSHAIR_CURSOR;
+// static final int HAND = Cursor.HAND_CURSOR;
+// static final int MOVE = Cursor.MOVE_CURSOR;
+// static final int TEXT = Cursor.TEXT_CURSOR;
+// static final int WAIT = Cursor.WAIT_CURSOR;
+
+
+ /** Screen orientation constant for portrait (the hamburger way). */
+ static final int PORTRAIT = 1;
+ /** Screen orientation constant for landscape (the hot dog way). */
+ static final int LANDSCAPE = 2;
+
+
+ // hints - hint values are positive for the alternate version,
+ // negative of the same value returns to the normal/default state
+
+ @Deprecated
+ static final int ENABLE_NATIVE_FONTS = 1;
+ @Deprecated
+ static final int DISABLE_NATIVE_FONTS = -1;
+
+ static final int DISABLE_DEPTH_TEST = 2;
+ static final int ENABLE_DEPTH_TEST = -2;
+
+ static final int ENABLE_DEPTH_SORT = 3;
+ static final int DISABLE_DEPTH_SORT = -3;
+
+ static final int DISABLE_OPENGL_ERRORS = 4;
+ static final int ENABLE_OPENGL_ERRORS = -4;
+
+ static final int DISABLE_DEPTH_MASK = 5;
+ static final int ENABLE_DEPTH_MASK = -5;
+
+ static final int DISABLE_OPTIMIZED_STROKE = 6;
+ static final int ENABLE_OPTIMIZED_STROKE = -6;
+
+ static final int ENABLE_STROKE_PERSPECTIVE = 7;
+ static final int DISABLE_STROKE_PERSPECTIVE = -7;
+
+ static final int DISABLE_TEXTURE_MIPMAPS = 8;
+ static final int ENABLE_TEXTURE_MIPMAPS = -8;
+
+ static final int ENABLE_STROKE_PURE = 9;
+ static final int DISABLE_STROKE_PURE = -9;
+
+ static final int ENABLE_BUFFER_READING = 10;
+ static final int DISABLE_BUFFER_READING = -10;
+
+ static final int DISABLE_KEY_REPEAT = 11;
+ static final int ENABLE_KEY_REPEAT = -11;
+
+ static final int DISABLE_ASYNC_SAVEFRAME = 12;
+ static final int ENABLE_ASYNC_SAVEFRAME = -12;
+
+ static final int HINT_COUNT = 13;
+
+
+ // error messages
+
+ static final String ERROR_BACKGROUND_IMAGE_SIZE =
+ "background image must be the same size as your application";
+ static final String ERROR_BACKGROUND_IMAGE_FORMAT =
+ "background images should be RGB or ARGB";
+
+ static final String ERROR_TEXTFONT_NULL_PFONT =
+ "A null PFont was passed to textFont()";
+
+ static final String ERROR_PUSHMATRIX_OVERFLOW =
+ "Too many calls to pushMatrix().";
+ static final String ERROR_PUSHMATRIX_UNDERFLOW =
+ "Too many calls to popMatrix(), and not enough to pushMatrix().";
+
+
+ // Some currently missing GLES constants.
+
+// static final int GL_MIN_EXT = 0x8007;
+// static final int GL_MAX_EXT = 0x8008;
+}
diff --git a/core-androidx/src/processing/core/PFont.java b/core-androidx/src/processing/core/PFont.java
new file mode 100644
index 000000000..6d30c539c
--- /dev/null
+++ b/core-androidx/src/processing/core/PFont.java
@@ -0,0 +1,907 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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 version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.io.*;
+import java.util.*;
+
+import android.graphics.*;
+import android.graphics.Bitmap.Config;
+
+/**
+ * Grayscale bitmap font class used by Processing.
+ *
+ * Awful (and by that, I mean awesome) ASCII (non-)art for how this works:
+ *
+ * |
+ * | height is the full used height of the image
+ * |
+ * | ..XX.. }
+ * | ..XX.. }
+ * | ...... }
+ * | XXXX.. } topExtent (top y is baseline - topExtent)
+ * | ..XX.. }
+ * | ..XX.. } dotted areas are where the image data
+ * | ..XX.. } is actually located for the character
+ * +---XXXXXX---- } (it extends to the right and down
+ * | for power of two texture sizes)
+ * ^^^^ leftExtent (amount to move over before drawing the image
+ *
+ * ^^^^^^^^^^^^^^ setWidth (width displaced by char)
+ *
+ */
+public class PFont implements PConstants {
+
+ /** Number of character glyphs in this font. */
+ protected int glyphCount;
+
+ /**
+ * Actual glyph data. The length of this array won't necessarily be the
+ * same size as glyphCount, in cases where lazy font loading is in use.
+ */
+ protected Glyph[] glyphs;
+
+ /**
+ * Name of the font as seen by Java when it was created.
+ * If the font is available, the native version will be used.
+ */
+ protected String name;
+
+ /**
+ * Postscript name of the font that this bitmap was created from.
+ */
+ protected String psname;
+
+ /**
+ * The original size of the font when it was first created
+ */
+ protected int size;
+
+ /** true if smoothing was enabled for this font, used for native impl */
+ protected boolean smooth;
+
+ /**
+ * The ascent of the font. If the 'd' character is present in this PFont,
+ * this value is replaced with its pixel height, because the values returned
+ * by FontMetrics.getAscent() seem to be terrible.
+ */
+ protected int ascent;
+
+ /**
+ * The descent of the font. If the 'p' character is present in this PFont,
+ * this value is replaced with its lowest pixel height, because the values
+ * returned by FontMetrics.getDescent() are gross.
+ */
+ protected int descent;
+
+ /**
+ * A more efficient array lookup for straight ASCII characters. For Unicode
+ * characters, a QuickSort-style search is used.
+ */
+ protected int[] ascii;
+
+ /**
+ * True if this font is set to load dynamically. This is the default when
+ * createFont() method is called without a character set. Bitmap versions of
+ * characters are only created when prompted by an index() call.
+ */
+ protected boolean lazy;
+
+ /**
+ * Native Android version of the font. If possible, this allows the
+ * PGraphics subclass to just use Android's font rendering stuff
+ * in situations where that's faster.
+ */
+ protected Typeface typeface;
+
+ /**
+ * True if this font should return 'null' for getFont(), so that the native
+ * font will be used to create a subset, but the native version of the font
+ * will not be used.
+ */
+ protected boolean subsetting;
+
+ /**
+ * True if we've already tried to find the native version of this font.
+ */
+ protected boolean typefaceSearched;
+
+ /**
+ * Array of the native system fonts. Used to lookup native fonts by their
+ * PostScript name. This is a workaround for a several year old Apple Java
+ * bug that they can't be bothered to fix.
+ */
+ static protected Typeface[] typefaces;
+
+ // objects to handle creation of font characters only as they're needed
+ Bitmap lazyBitmap;
+ Canvas lazyCanvas;
+ Paint lazyPaint;
+// FontMetrics lazyMetrics;
+ int[] lazySamples;
+
+ /** for subclasses that need to store metadata about the font */
+ protected HashMap cacheMap;
+
+
+ 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(Typeface font, int size, boolean smooth) {
+ this(font, size, 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(Typeface font, int size, boolean smooth, char charset[]) {
+ // save this so that we can use the native version
+ this.typeface = font;
+ this.smooth = smooth;
+
+ name = ""; //font.getName();
+ psname = ""; //font.getPSName();
+ this.size = size; //font.getSize();
+
+ 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);
+ lazyBitmap = Bitmap.createBitmap(mbox3, mbox3, Config.ARGB_8888);
+// lazyGraphics = (Graphics2D) lazyImage.getGraphics();
+ lazyCanvas = new Canvas(lazyBitmap);
+
+// 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);
+ lazyPaint = new Paint();
+ lazyPaint.setAntiAlias(smooth);
+
+// lazyGraphics.setFont(font);
+ lazyPaint.setTypeface(font);
+// lazyMetrics = lazyGraphics.getFontMetrics();
+ lazyPaint.setTextSize(size);
+ lazySamples = new int[mbox3 * mbox3];
+
+// ascent = lazyMetrics.getAscent();
+// descent = lazyMetrics.getDescent();
+
+ if (charset == null) {
+ lazy = true;
+
+ } else {
+ // charset needs to be sorted to make index lookup run more quickly
+ // http://dev.processing.org/bugs/show_bug.cgi?id=494
+ Arrays.sort(charset);
+
+ glyphs = new Glyph[charset.length];
+
+ glyphCount = 0;
+ for (char c : charset) {
+ Glyph glyf = new Glyph(c);
+ if (glyf.value < 128) {
+ ascii[glyf.value] = glyphCount;
+ }
+ glyf.index = glyphCount;
+ glyphs[glyphCount++] = glyf;
+ }
+
+ // shorten the array if necessary
+// if (glyphCount != charset.length) {
+// glyphs = (Glyph[]) PApplet.subset(glyphs, 0, glyphCount);
+// }
+ }
+
+ // 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) {
+ new Glyph('d');
+ if (ascent == 0) { // character not valid
+ ascent = PApplet.round(lazyPaint.ascent());
+ }
+ }
+ if (descent == 0) {
+ new Glyph('p');
+ if (descent == 0) {
+ descent = PApplet.round(lazyPaint.descent());
+ }
+ }
+ }
+
+
+ public PFont(InputStream input) throws IOException {
+ DataInputStream is = new DataInputStream(input);
+
+ // number of character images stored in this font
+ glyphCount = is.readInt();
+
+ // used to be the bitCount, but now used for version number.
+ // version 8 is any font before 69, so 9 is anything from 83+
+ // 9 was buggy so gonna increment to 10.
+ int version = is.readInt();
+
+ // this was formerly ignored, now it's the actual font size
+ //mbox = is.readInt();
+ size = is.readInt();
+
+ // this was formerly mboxY, the one that was used
+ // this will make new fonts downward compatible
+ is.readInt(); // ignore the other mbox attribute
+
+ ascent = is.readInt(); // formerly baseHt (zero/ignored)
+ descent = is.readInt(); // formerly ignored struct padding
+
+ // allocate enough space for the character info
+ glyphs = new Glyph[glyphCount];
+
+ ascii = new int[128];
+ Arrays.fill(ascii, -1);
+
+ // read the information about the individual characters
+ for (int i = 0; i < glyphCount; i++) {
+ Glyph glyph = new Glyph(is);
+ // cache locations of the ascii charset
+ if (glyph.value < 128) {
+ ascii[glyph.value] = i;
+ }
+ glyph.index = i;
+ glyphs[i] = glyph;
+ }
+
+ // not a roman font, so throw an error and ask to re-build.
+ // that way can avoid a bunch of error checking hacks in here.
+ if ((ascent == 0) && (descent == 0)) {
+ throw new RuntimeException("Please use \"Create Font\" to " +
+ "re-create this font.");
+ }
+
+ for (Glyph glyph : glyphs) {
+ glyph.readBitmap(is);
+ }
+
+ if (version >= 10) { // includes the font name at the end of the file
+ name = is.readUTF();
+ psname = is.readUTF();
+ }
+ if (version == 11) {
+ smooth = is.readBoolean();
+ }
+ }
+
+
+ /**
+ * Write this PFont to an OutputStream.
+ *
+ * This is used by the Create Font tool, or whatever anyone else dreams
+ * up for messing with fonts themselves.
+ *
+ * It is assumed that the calling class will handle closing
+ * the stream when finished.
+ */
+ public void save(OutputStream output) throws IOException {
+ DataOutputStream os = new DataOutputStream(output);
+
+ os.writeInt(glyphCount);
+
+ if ((name == null) || (psname == null)) {
+ name = "";
+ psname = "";
+ }
+
+ os.writeInt(11); // formerly numBits, now used for version number
+ os.writeInt(size); // formerly mboxX (was 64, now 48)
+ os.writeInt(0); // formerly mboxY, now ignored
+ os.writeInt(ascent); // formerly baseHt (was ignored)
+ os.writeInt(descent); // formerly struct padding for c version
+
+ for (int i = 0; i < glyphCount; i++) {
+ glyphs[i].writeHeader(os);
+ }
+
+ for (int i = 0; i < glyphCount; i++) {
+ glyphs[i].writeBitmap(os);
+ }
+
+ // version 11
+ os.writeUTF(name);
+ os.writeUTF(psname);
+ os.writeBoolean(smooth);
+
+ os.flush();
+ }
+
+
+ /**
+ * Create a new glyph, and add the character to the current font.
+ * @param c character to create an image for.
+ */
+ protected void addGlyph(char c) {
+ Glyph glyph = new Glyph(c);
+
+ if (glyphCount == glyphs.length) {
+ glyphs = (Glyph[]) PApplet.expand(glyphs);
+ }
+ if (glyphCount == 0) {
+ glyph.index = 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;
+ }
+ }
+ glyph.index = i;
+ glyphs[i] = glyph;
+ // cache locations of the ascii charset
+ if (c < 128) ascii[c] = i;
+ break;
+ }
+ }
+ }
+ glyphCount++;
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+
+ /**
+ * Return size of this font.
+ */
+ public int getSize() {
+ return size;
+ }
+
+
+ /**
+ * Returns the size that will be used when textFont(font) is called.
+ */
+ public int getDefaultSize() {
+ return size;
+ }
+
+
+ public boolean isSmooth() {
+ return smooth;
+ }
+
+
+ public void setSubsetting() {
+ subsetting = true;
+ }
+
+
+ public String getPostScriptName() {
+ return psname;
+ }
+
+
+ /**
+ * Set the native complement of this font.
+ */
+ public void setNative(Object typeface) {
+ this.typeface = (Typeface) typeface;
+ }
+
+
+ /**
+ * Return the native Typeface object associated with this PFont (if any).
+ */
+ public Object getNative() {
+ if (subsetting) {
+ return null;
+ }
+ return typeface;
+ }
+
+
+ /**
+ * Attempt to find the native version of this font.
+ * (Public so that it can be used by OpenGL or other renderers.)
+ */
+ static public Object findNative(String name) {
+ loadTypefaces();
+ return typefaceMap.get(name);
+ }
+
+
+ public Glyph getGlyph(char c) {
+ int index = index(c);
+ return (index == -1) ? null : glyphs[index];
+ }
+
+
+ /**
+ * Get index for the character.
+ * @return index into arrays or -1 if not found
+ */
+ protected int index(char c) {
+ if (lazy) {
+ int index = indexActual(c);
+ if (index != -1) {
+ return index;
+ }
+// if (font.canDisplay(c)) {
+ // create the glyph
+ addGlyph(c);
+ // now where did i put that?
+ return indexActual(c);
+
+// } else {
+// return -1;
+// }
+
+ } else {
+ return indexActual(c);
+ }
+ }
+
+
+ protected int indexActual(char c) {
+ // degenerate case, but the find function will have trouble
+ // if there are somehow zero chars in the lookup
+ //if (value.length == 0) return -1;
+ if (glyphCount == 0) return -1;
+
+ // quicker lookup for the ascii fellers
+ if (c < 128) return ascii[c];
+
+ // some other unicode char, hunt it out
+ //return index_hunt(c, 0, value.length-1);
+ return indexHunt(c, 0, glyphCount-1);
+ }
+
+
+ protected int indexHunt(int c, int start, int stop) {
+ int pivot = (start + stop) / 2;
+
+ // if this is the char, then return it
+ if (c == glyphs[pivot].value) return pivot;
+
+ // char doesn't exist, otherwise would have been the pivot
+ //if (start == stop) return -1;
+ if (start >= stop) return -1;
+
+ // if it's in the lower half, continue searching that
+ if (c < glyphs[pivot].value) return indexHunt(c, start, pivot-1);
+
+ // if it's in the upper half, continue there
+ return indexHunt(c, pivot+1, stop);
+ }
+
+
+ /**
+ * Currently un-implemented for .vlw fonts,
+ * but honored for layout in case subclasses use it.
+ */
+ public float kern(char a, char b) {
+ return 0;
+ }
+
+
+ /**
+ * Returns the ascent of this font from the baseline.
+ * The value is based on a font of size 1.
+ */
+ public float ascent() {
+ return ((float) ascent / (float) size);
+ }
+
+
+ /**
+ * Returns how far this font descends from the baseline.
+ * The value is based on a font size of 1.
+ */
+ public float descent() {
+ return ((float) descent / (float) size);
+ }
+
+
+ /**
+ * Width of this character for a font of size 1.
+ */
+ public float width(char c) {
+ if (c == 32) return width('i');
+
+ int cc = index(c);
+ if (cc == -1) return 0;
+
+ return ((float) glyphs[cc].setWidth / (float) size);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // METADATA REQUIRED BY THE RENDERERS
+
+
+ /**
+ * Store data of some kind for a renderer that requires extra metadata of
+ * some kind. Usually this is a renderer-specific representation of the
+ * font data, for instance a custom OpenGL texture for PGraphicsOpenGL2.
+ * @param renderer The PGraphics renderer associated to the font
+ * @param storage The metadata required by the renderer
+ */
+ public void setCache(PGraphics renderer, Object storage) {
+ if (cacheMap == null) cacheMap = new HashMap();
+ cacheMap.put(renderer, 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 PGraphicsOpenGL2 will cause errors.
+ * @param renderer The PGraphics renderer associated to the font
+ * @return metadata stored for the specified renderer
+ */
+ public Object getCache(PGraphics renderer) {
+ if (cacheMap == null) return null;
+ return cacheMap.get(renderer);
+ }
+
+
+ /**
+ * Remove information associated with this renderer from the cache, if any.
+ * @param parent The PGraphics renderer whose cache data should be removed
+ */
+ public void removeCache(PGraphics renderer) {
+ if (cacheMap != null) {
+ cacheMap.remove(renderer);
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ public int getGlyphCount() {
+ return glyphCount;
+ }
+
+ public Glyph getGlyph(int i) {
+ return glyphs[i];
+ }
+
+ //////////////////////////////////////////////////////////////
+
+
+ static final char[] EXTRA_CHARS = {
+ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
+ 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F,
+ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
+ 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F,
+ 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+ 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+ 0x00B0, 0x00B1, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00BA,
+ 0x00BB, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5,
+ 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD,
+ 0x00CE, 0x00CF, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6,
+ 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DF,
+ 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
+ 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,
+ 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8,
+ 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FF, 0x0102, 0x0103,
+ 0x0104, 0x0105, 0x0106, 0x0107, 0x010C, 0x010D, 0x010E, 0x010F,
+ 0x0110, 0x0111, 0x0118, 0x0119, 0x011A, 0x011B, 0x0131, 0x0139,
+ 0x013A, 0x013D, 0x013E, 0x0141, 0x0142, 0x0143, 0x0144, 0x0147,
+ 0x0148, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0158,
+ 0x0159, 0x015A, 0x015B, 0x015E, 0x015F, 0x0160, 0x0161, 0x0162,
+ 0x0163, 0x0164, 0x0165, 0x016E, 0x016F, 0x0170, 0x0171, 0x0178,
+ 0x0179, 0x017A, 0x017B, 0x017C, 0x017D, 0x017E, 0x0192, 0x02C6,
+ 0x02C7, 0x02D8, 0x02D9, 0x02DA, 0x02DB, 0x02DC, 0x02DD, 0x03A9,
+ 0x03C0, 0x2013, 0x2014, 0x2018, 0x2019, 0x201A, 0x201C, 0x201D,
+ 0x201E, 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203A,
+ 0x2044, 0x20AC, 0x2122, 0x2202, 0x2206, 0x220F, 0x2211, 0x221A,
+ 0x221E, 0x222B, 0x2248, 0x2260, 0x2264, 0x2265, 0x25CA, 0xF8FF,
+ 0xFB01, 0xFB02
+ };
+
+
+ /**
+ * The default Processing character set.
+ *
+ * This is the union of the Mac Roman and Windows ANSI (CP1250)
+ * character sets. ISO 8859-1 Latin 1 is Unicode characters 0x80 -> 0xFF,
+ * and would seem a good standard, but in practice, most P5 users would
+ * rather have characters that they expect from their platform's fonts.
+ *
+ * This is more of an interim solution until a much better
+ * font solution can be determined. (i.e. create fonts on
+ * the fly from some sort of vector format).
+ *
+ * Not that I expect that to happen.
+ */
+ static public char[] CHARSET;
+ static {
+ CHARSET = new char[126-33+1 + EXTRA_CHARS.length];
+ int index = 0;
+ for (int i = 33; i <= 126; i++) {
+ CHARSET[index++] = (char)i;
+ }
+ for (int i = 0; i < EXTRA_CHARS.length; i++) {
+ CHARSET[index++] = EXTRA_CHARS[i];
+ }
+ };
+
+
+ static HashMap typefaceMap;
+ static String[] fontList;
+
+
+ /**
+ * Get a list of the built-in fonts.
+ */
+ static public String[] list() {
+ loadTypefaces();
+ return fontList;
+ }
+
+
+ static public void loadTypefaces() {
+ if (typefaceMap == null) {
+ typefaceMap = new HashMap();
+
+ typefaceMap.put("Serif",
+ Typeface.create(Typeface.SERIF, Typeface.NORMAL));
+ typefaceMap.put("Serif-Bold",
+ Typeface.create(Typeface.SERIF, Typeface.BOLD));
+ typefaceMap.put("Serif-Italic",
+ Typeface.create(Typeface.SERIF, Typeface.ITALIC));
+ typefaceMap.put("Serif-BoldItalic",
+ Typeface.create(Typeface.SERIF, Typeface.BOLD_ITALIC));
+
+ typefaceMap.put("SansSerif",
+ Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL));
+ typefaceMap.put("SansSerif-Bold",
+ Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD));
+ typefaceMap.put("SansSerif-Italic",
+ Typeface.create(Typeface.SANS_SERIF, Typeface.ITALIC));
+ typefaceMap.put("SansSerif-BoldItalic",
+ Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC));
+
+ typefaceMap.put("Monospaced",
+ Typeface.create(Typeface.MONOSPACE, Typeface.NORMAL));
+ typefaceMap.put("Monospaced-Bold",
+ Typeface.create(Typeface.MONOSPACE, Typeface.BOLD));
+ typefaceMap.put("Monospaced-Italic",
+ Typeface.create(Typeface.MONOSPACE, Typeface.ITALIC));
+ typefaceMap.put("Monospaced-BoldItalic",
+ Typeface.create(Typeface.MONOSPACE, Typeface.BOLD_ITALIC));
+
+ fontList = new String[typefaceMap.size()];
+ typefaceMap.keySet().toArray(fontList);
+ }
+ }
+
+
+ /////////////////////////////////////////////////////////////
+
+ /**
+ * A single character, and its visage.
+ */
+ public class Glyph {
+ public PImage image;
+ public int value;
+ public int height;
+ public int width;
+ public int index;
+ public int setWidth;
+ public int topExtent;
+ public int leftExtent;
+ public boolean fromStream = false;
+
+
+ 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();
+ }
+ fromStream = true;
+// 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);
+ lazyCanvas.drawColor(Color.WHITE); // fill canvas with white
+// lazyGraphics.setColor(Color.black);
+ lazyPaint.setColor(Color.BLACK);
+// lazyGraphics.drawString(String.valueOf(c), size, size * 2);
+ lazyCanvas.drawText(String.valueOf(c), size, size * 2, lazyPaint);
+
+// WritableRaster raster = lazyImage.getRaster();
+// raster.getDataElements(0, 0, mbox3, mbox3, lazySamples);
+ lazyBitmap.getPixels(lazySamples, 0, mbox3, 0, 0, mbox3, mbox3);
+
+ 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);
+ setWidth = (int) lazyPaint.measureText(String.valueOf(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-androidx/src/processing/core/PGraphics.java b/core-androidx/src/processing/core/PGraphics.java
new file mode 100644
index 000000000..e4ebe402d
--- /dev/null
+++ b/core-androidx/src/processing/core/PGraphics.java
@@ -0,0 +1,6134 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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 version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.util.HashMap;
+import java.util.WeakHashMap;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import processing.android.AppComponent;
+import processing.opengl.PGL;
+import processing.opengl.PShader;
+import android.graphics.Color;
+import android.view.SurfaceHolder;
+
+
+/**
+ * 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.
+ */
+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 int smooth;
+
+ // ........................................................
+
+ /// true if defaults() has been called a first time
+ protected boolean settingsInited;
+
+ /// true if settings should be re-applied on next beginDraw()
+ protected boolean reapplySettings;
+
+ /// 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 primaryGraphics;
+
+ // ........................................................
+
+ /**
+ * 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];
+
+ // ........................................................
+
+ /**
+ * Storage for renderer-specific image data. In 1.x, renderers wrote cache
+ * data into the image object. In 2.x, the renderer has a weak-referenced
+ * map that points at any of the images it has worked on already. When the
+ * images go out of scope, they will be properly garbage collected.
+ */
+ protected WeakHashMap cacheMap =
+ new WeakHashMap();
+
+
+ ////////////////////////////////////////////////////////////
+
+ // Vertex fields, moved from PConstants (after 2.0a8) because they're too
+ // general to show up in all sketches as defined variables.
+
+ // X, Y and Z are still stored in PConstants because of their general
+ // usefulness, and that X we'll always want to be 0, etc.
+
+ static public final int R = 3; // actual rgb, after lighting
+ static public final int G = 4; // fill stored here, transform in place
+ static public final int B = 5; // TODO don't do that anymore (?)
+ static public final int A = 6;
+
+ static public final int U = 7; // texture
+ static public final int V = 8;
+
+ static public final int NX = 9; // normal
+ static public final int NY = 10;
+ static public final int NZ = 11;
+
+ static public final int EDGE = 12;
+
+ // stroke
+
+ /** stroke argb values */
+ static public final int SR = 13;
+ static public final int SG = 14;
+ static public final int SB = 15;
+ static public final int SA = 16;
+
+ /** stroke weight */
+ static public final int SW = 17;
+
+ // transformations (2D and 3D)
+
+ static public final int TX = 18; // transformed xyzw
+ static public final int TY = 19;
+ static public final int TZ = 20;
+
+ static public final int VX = 21; // view space coords
+ static public final int VY = 22;
+ static public final int VZ = 23;
+ static public final int VW = 24;
+
+
+ // material properties
+
+ // Ambient color (usually to be kept the same as diffuse)
+ // fill(_) sets both ambient and diffuse.
+ static public final int AR = 25;
+ static public final int AG = 26;
+ static public final int AB = 27;
+
+ // Diffuse is shared with fill.
+ static public final int DR = 3; // TODO needs to not be shared, this is a material property
+ static public final int DG = 4;
+ static public final int DB = 5;
+ static public final int DA = 6;
+
+ // specular (by default kept white)
+ static public final int SPR = 28;
+ static public final int SPG = 29;
+ static public final int SPB = 30;
+
+ static public final int SHINE = 31;
+
+ // emissive (by default kept black)
+ static public final int ER = 32;
+ static public final int EG = 33;
+ static public final int EB = 34;
+
+ // has this vertex been lit yet
+ static public final int BEEN_LIT = 35;
+
+ // has this vertex been assigned a normal yet
+ static public final int HAS_NORMAL = 36;
+
+ static public final int VERTEX_FIELD_COUNT = 37;
+
+
+
+ ////////////////////////////////////////////////////////////
+
+ // 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 int ambientColor;
+ public float ambientR, ambientG, ambientB;
+ public boolean setAmbient;
+
+ public int specularColor;
+ public float specularR, specularG, specularB;
+
+ public int emissiveColor;
+ 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;
+
+
+ /** The current blending mode. */
+ protected int blendMode;
+
+
+ // ........................................................
+
+ /**
+ * 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;
+
+ // ........................................................
+
+ // 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;
+ public 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;
+
+ protected boolean autoNormal;
+
+ /** 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 = IMAGE;
+
+ /**
+ * 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 = null;
+
+ // ........................................................
+
+ // [toxi031031] new & faster sphere code w/ support flexibile resolutions
+ // will be set by sphereDetail() or 1st call to sphere()
+ protected 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;
+
+ // ........................................................
+
+ // Variables used to save the surface contents before the activity is taken to the background.
+ protected String restoreFilename;
+ protected int restoreWidth, restoreHeight;
+ protected int restoreCount;
+ protected boolean restartedLoopingAfterResume = false;
+ protected boolean restoredSurface = true;
+
+ // This auxiliary variable is used to implement a little hack that fixes
+ // https://github.com/processing/processing-android/issues/147
+ // on older devices where the last frame cannot be maintained after ending
+ // the rendering in GL. The trick consists in running one more frame after the
+ // noLoop() call, which ensures that the FBO layer is properly initialized
+ // and drawn with the contents of the previous frame.
+ protected boolean requestedNoLoop = false;
+
+ //////////////////////////////////////////////////////////////
+
+ // 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.primaryGraphics = 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 (primaryGraphics) {
+ format = RGB;
+ }
+ }
+
+
+ public void setPath(String path) { // ignore
+ this.path = path;
+ }
+
+
+ public void setFrameRate(float framerate) { // ignore
+ }
+
+
+ public void surfaceChanged() { // ignore
+ }
+
+
+ public void reset() { // ignore
+ }
+
+
+ /**
+ * 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;
+
+ pixelWidth = width * pixelDensity;
+ pixelHeight = height * pixelDensity;
+
+ reapplySettings = true;
+ }
+
+
+ /**
+ * 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
+ parent = null;
+ }
+
+
+ public PSurface createSurface(AppComponent component, SurfaceHolder holder, boolean reset) { // ignore
+ return null;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // IMAGE METADATA FOR THIS RENDERER
+
+ /**
+ * Store data of some kind for the 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.
+ * @param image The image to be stored
+ * @param storage The metadata required by the renderer
+ */
+ public void setCache(PImage image, Object storage) { // ignore
+ cacheMap.put(image, 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.
+ * @return metadata stored for the specified renderer
+ */
+ public Object getCache(PImage image) { // ignore
+ return cacheMap.get(image);
+ }
+
+
+ /**
+ * Remove information associated with this renderer from the cache, if any.
+ * @param image The image whose cache data should be removed
+ */
+ public void removeCache(PImage image) { // ignore
+ cacheMap.remove(image);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FRAME
+
+
+ /**
+ * Handle grabbing the focus from the parent applet. Other renderers can
+ * override this if handling needs to be different.
+ */
+ public void requestFocus() { // ignore
+ }
+
+
+ /**
+ * Some renderers have requirements re: when they are ready to draw.
+ */
+// public boolean canDraw() { // ignore
+// return true;
+// }
+
+
+ /**
+ * Try to draw, or put a draw request on the queue.
+ */
+// public void requestDraw() { // ignore
+// }
+
+
+ /**
+ * Prepares the PGraphics for drawing.
+ *
+ * When creating your own PGraphics, you should call this before
+ * drawing anything.
+ */
+ public void beginDraw() { // ignore
+ }
+
+
+ /**
+ * This will finalize rendering so that it can be shown on-screen.
+ *
+ * When creating your own PGraphics, you should call this when
+ * you're finished drawing.
+ */
+ public void endDraw() { // ignore
+ }
+
+
+ public void flush() {
+ // no-op, mostly for P3D to write sorted stuff
+ }
+
+
+ public PGL beginPGL() {
+ showMethodWarning("beginPGL");
+ return null;
+ }
+
+
+ public void endPGL() {
+ showMethodWarning("endPGL");
+ }
+
+
+ protected void checkSettings() {
+ if (!settingsInited) defaultSettings();
+ if (reapplySettings) reapplySettings();
+ }
+
+
+ /**
+ * 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
+ colorMode(RGB, 255);
+ fill(255);
+ stroke(0);
+
+ // added for 0178 for subclasses that need them
+ strokeWeight(DEFAULT_STROKE_WEIGHT);
+ strokeJoin(DEFAULT_STROKE_JOIN);
+ strokeCap(DEFAULT_STROKE_CAP);
+
+ // init shape stuff
+ shape = 0;
+
+ // init matrices (must do before lights)
+ //matrixStackDepth = 0;
+
+ rectMode(CORNER);
+ ellipseMode(DIAMETER);
+
+ autoNormal = true;
+
+ // 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 (primaryGraphics) {
+ //System.out.println("main drawing surface bg " + getClass().getName());
+ background(backgroundColor);
+ }
+
+ blendMode(BLEND);
+
+ 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() { // ignore
+// 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);
+
+ blendMode(blendMode);
+
+ reapplySettings = false;
+ }
+
+ //////////////////////////////////////////////////////////////
+
+ // RENDERER STATE
+
+
+ protected void clearState() { // ignore
+ // Nothing to do here, it depends on the renderer's implementation.
+ }
+
+
+ protected void saveState() { // ignore
+ // Nothing to do here, it depends on the renderer's implementation.
+ }
+
+
+ protected void restoreState() { // ignore
+ // This method probably does not need to be re-implemented in the subclasses. All we need to
+ // do is to check for the resume in no-loop state situation:
+ restoredSurface = false;
+ if (!parent.looping) {
+ // The sketch needs to draw a few frames after resuming so it has the chance to restore the
+ // screen contents:
+ // https://github.com/processing/processing-android/issues/492
+ // so we restart looping:
+ parent.loop();
+ // and flag this situation when the surface has been restored:
+ restartedLoopingAfterResume = true;
+ }
+ }
+
+
+ protected boolean restoringState() { // ignore
+ return !restoredSurface && restartedLoopingAfterResume;
+ }
+
+
+ protected void restoreSurface() { // ignore
+ // When implementing this method in a subclass of PGraphics, it should add a call to the super
+ // implementation, to make sure that the looping is stopped in the case where the sketch was
+ // resumed in no-loop state (see comment in restoreState() method above).
+ if (restoredSurface && restartedLoopingAfterResume) {
+ restartedLoopingAfterResume = false;
+ parent.noLoop();
+ }
+ }
+
+
+ protected boolean requestNoLoop() { // ignore
+ // Some renderers (OpenGL) cannot be set to no-loop right away, it has to be requested so
+ // any pending frames are properly rendered. Override as needed.
+ return false;
+ }
+
+
+ protected boolean isLooping() { // ignore
+ return parent.isLooping() && (!requestNoLoop() || !requestedNoLoop);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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.
+ *
+ */
+ @SuppressWarnings("deprecation")
+ public void hint(int which) {
+ if (which == ENABLE_NATIVE_FONTS ||
+ which == DISABLE_NATIVE_FONTS) {
+ showWarning("hint(ENABLE_NATIVE_FONTS) no longer supported. " +
+ "Use createFont() instead.");
+ }
+ if (which == ENABLE_KEY_REPEAT) {
+ parent.keyRepeatEnabled = true;
+ } else if (which == DISABLE_KEY_REPEAT) {
+ parent.keyRepeatEnabled = false;
+ }
+ 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 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) {
+ // 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;
+ }
+ }
+ }
+
+
+ public void attribPosition(String name, float x, float y, float z) {
+ showMissingWarning("attrib");
+ }
+
+
+ public void attribNormal(String name, float nx, float ny, float nz) {
+ showMissingWarning("attrib");
+ }
+
+
+ public void attribColor(String name, int color) {
+ showMissingWarning("attrib");
+ }
+
+
+ public void attrib(String name, float... values) {
+ showMissingWarning("attrib");
+ }
+
+
+ public void attrib(String name, int... values) {
+ showMissingWarning("attrib");
+ }
+
+
+ public void attrib(String name, boolean... values) {
+ showMissingWarning("attrib");
+ }
+
+
+ /**
+ * 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;
+ }
+
+
+ public void textureWrap(int wrap) {
+ showMissingWarning("textureWrap");
+ }
+
+
+ /**
+ * 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;
+ }
+
+
+ /**
+ * Removes texture image for current shape.
+ * Needs to be called between @see beginShape and @see endShape
+ *
+ */
+ public void noTexture() {
+ textureImage = null;
+ }
+
+
+ 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[Z] = 0;
+
+ vertex[EDGE] = edge ? 1 : 0;
+
+ boolean textured = textureImage != null;
+ if (fill || textured) {
+ if (!textured) {
+ 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;
+ }
+
+ vertex[U] = textureU;
+ vertex[V] = textureV;
+
+ if (autoNormal) {
+ float norm2 = normalX * normalX + normalY * normalY + normalZ * normalZ;
+ if (norm2 < EPSILON) {
+ vertex[HAS_NORMAL] = 0;
+ } else {
+ if (Math.abs(norm2 - 1) > EPSILON) {
+ // The normal vector is not normalized.
+ float norm = PApplet.sqrt(norm2);
+ normalX /= norm;
+ normalY /= norm;
+ normalZ /= norm;
+ }
+ vertex[HAS_NORMAL] = 1;
+ }
+ } else {
+ vertex[HAS_NORMAL] = 1;
+ }
+
+ vertex[NX] = normalX;
+ vertex[NY] = normalY;
+ vertex[NZ] = normalZ;
+
+ 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;
+
+ boolean textured = textureImage != null;
+ if (fill || textured) {
+ if (!textured) {
+ 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;
+ }
+
+ vertex[U] = textureU;
+ vertex[V] = textureV;
+
+ if (autoNormal) {
+ float norm2 = normalX * normalX + normalY * normalY + normalZ * normalZ;
+ if (norm2 < EPSILON) {
+ vertex[HAS_NORMAL] = 0;
+ } else {
+ if (Math.abs(norm2 - 1) > EPSILON) {
+ // The normal vector is not normalized.
+ float norm = PApplet.sqrt(norm2);
+ normalX /= norm;
+ normalY /= norm;
+ normalZ /= norm;
+ }
+ vertex[HAS_NORMAL] = 1;
+ }
+ } else {
+ vertex[HAS_NORMAL] = 1;
+ }
+
+ vertex[NX] = normalX;
+ vertex[NY] = normalY;
+ vertex[NZ] = normalZ;
+
+ 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;
+ }
+
+
+ /** 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 beginContour() {
+ showMissingWarning("beginContour");
+ }
+
+
+ public void endContour() {
+ showMissingWarning("endContour");
+ }
+
+
+ public void endShape() {
+ endShape(OPEN);
+ }
+
+
+ public void endShape(int mode) {
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CLIPPING
+
+
+ public void clip(float a, float b, float c, float d) {
+ 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;
+ }
+
+ clipImpl(a, b, a + c, b + d);
+
+ } 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;
+ }
+
+ clipImpl(a, b, c, d);
+
+ } 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;
+
+ clipImpl(x1, y1, x1 + c, y1 + d);
+ }
+ }
+
+
+ protected void clipImpl(float x1, float y1, float x2, float y2) {
+ showMissingWarning("clip");
+ }
+
+
+ public void noClip() {
+ showMissingWarning("noClip");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BLEND
+
+
+ public void blendMode(int mode) {
+ this.blendMode = mode;
+ blendModeImpl();
+ }
+
+
+ protected void blendModeImpl() {
+ if (blendMode != BLEND) {
+ showMissingWarning("blendMode");
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPE I/O
+
+
+ public PShape loadShape(String filename) {
+ showMissingWarning("loadShape");
+ return null;
+ }
+
+
+ public PShape loadShape(String filename, String options) {
+ showMissingWarning("loadShape");
+ return null;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPE CREATION
+
+
+ /**
+ * @webref shape
+ * @see PShape
+ * @see PShape#endShape()
+ * @see PApplet#loadShape(String)
+ */
+ public PShape createShape() {
+ // Defaults to GEOMETRY (rather than GROUP like the default constructor)
+ // because that's how people will use it within a sketch.
+ return createShape(PShape.GEOMETRY);
+ }
+
+
+ // POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP
+ public PShape createShape(int type) {
+ // If it's a PRIMITIVE, it needs the 'params' field anyway
+ if (type == PConstants.GROUP ||
+ type == PShape.PATH ||
+ type == PShape.GEOMETRY) {
+ return createShapeFamily(type);
+ }
+ final String msg =
+ "Only GROUP, PShape.PATH, and PShape.GEOMETRY work with createShape()";
+ throw new IllegalArgumentException(msg);
+ }
+
+
+ /** Override this method to return an appropriate shape for your renderer */
+ protected PShape createShapeFamily(int type) {
+ return new PShape(this, type);
+// showMethodWarning("createShape()");
+// return null;
+ }
+
+
+ /**
+ * @param kind either POINT, LINE, TRIANGLE, QUAD, RECT, ELLIPSE, ARC, BOX, SPHERE
+ * @param p parameters that match the kind of shape
+ */
+ public PShape createShape(int kind, float... p) {
+ int len = p.length;
+
+ if (kind == POINT) {
+ if (is3D() && len != 2 && len != 3) {
+ throw new IllegalArgumentException("Use createShape(POINT, x, y) or createShape(POINT, x, y, z)");
+ } else if (len != 2) {
+ throw new IllegalArgumentException("Use createShape(POINT, x, y)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == LINE) {
+ if (is3D() && len != 4 && len != 6) {
+ throw new IllegalArgumentException("Use createShape(LINE, x1, y1, x2, y2) or createShape(LINE, x1, y1, z1, x2, y2, z1)");
+ } else if (len != 4) {
+ throw new IllegalArgumentException("Use createShape(LINE, x1, y1, x2, y2)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == TRIANGLE) {
+ if (len != 6) {
+ throw new IllegalArgumentException("Use createShape(TRIANGLE, x1, y1, x2, y2, x3, y3)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == QUAD) {
+ if (len != 8) {
+ throw new IllegalArgumentException("Use createShape(QUAD, x1, y1, x2, y2, x3, y3, x4, y4)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == RECT) {
+ if (len != 4 && len != 5 && len != 8 && len != 9) {
+ throw new IllegalArgumentException("Wrong number of parameters for createShape(RECT), see the reference");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == ELLIPSE) {
+ if (len != 4 && len != 5) {
+ throw new IllegalArgumentException("Use createShape(ELLIPSE, x, y, w, h) or createShape(ELLIPSE, x, y, w, h, mode)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == ARC) {
+ if (len != 6 && len != 7) {
+ throw new IllegalArgumentException("Use createShape(ARC, x, y, w, h, start, stop)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == BOX) {
+ if (!is3D()) {
+ throw new IllegalArgumentException("createShape(BOX) is not supported in 2D");
+ } else if (len != 1 && len != 3) {
+ throw new IllegalArgumentException("Use createShape(BOX, size) or createShape(BOX, width, height, depth)");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == SPHERE) {
+ if (!is3D()) {
+ throw new IllegalArgumentException("createShape(SPHERE) is not supported in 2D");
+ } else if (len != 1) {
+ throw new IllegalArgumentException("Use createShape(SPHERE, radius)");
+ }
+ return createShapePrimitive(kind, p);
+ }
+ throw new IllegalArgumentException("Unknown shape type passed to createShape()");
+ }
+
+
+ /** Override this to have a custom shape object used by your renderer. */
+ protected PShape createShapePrimitive(int kind, float... p) {
+// showMethodWarning("createShape()");
+// return null;
+ return new PShape(this, kind, p);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHADERS
+
+
+ public PShader loadShader(String fragFilename) {
+ showMissingWarning("loadShader");
+ return null;
+ }
+
+
+ public PShader loadShader(String fragFilename, String vertFilename) {
+ showMissingWarning("loadShader");
+ return null;
+ }
+
+
+ public void shader(PShader shader) {
+ showMissingWarning("shader");
+ }
+
+
+ public void shader(PShader shader, int kind) {
+ showMissingWarning("shader");
+ }
+
+
+ public void resetShader() {
+ showMissingWarning("resetShader");
+ }
+
+
+ public void resetShader(int kind) {
+ showMissingWarning("resetShader");
+ }
+
+
+ public PShader getShader(int kind) {
+ showMissingWarning("getShader");
+ return null;
+ }
+
+
+ public void filter(PShader shader) {
+ showMissingWarning("filter");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CURVE/BEZIER VERTEX HANDLING
+
+
+ protected void bezierVertexCheck() {
+ bezierVertexCheck(shape, vertexCount);
+ }
+
+
+ protected void bezierVertexCheck(int shape, int vertexCount) {
+ if (shape == 0 || shape != POLYGON) {
+ throw new RuntimeException("beginShape() or beginShape(POLYGON) " +
+ "must be used before bezierVertex() or quadraticVertex()");
+ }
+ if (vertexCount == 0) {
+ throw new RuntimeException("vertex() must be used at least once" +
+ "before bezierVertex() or quadraticVertex()");
+ }
+ }
+
+
+ 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);
+ }
+ }
+
+
+ public void quadraticVertex(float cx, float cy,
+ float x3, float y3) {
+ bezierVertexCheck();
+ float[] prev = vertices[vertexCount-1];
+ float x1 = prev[X];
+ float y1 = prev[Y];
+
+ bezierVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f),
+ x3 + ((cx-x3)*2/3.0f), y3 + ((cy-y3)*2/3.0f),
+ x3, y3);
+ }
+
+
+ public void quadraticVertex(float cx, float cy, float cz,
+ float x3, float y3, float z3) {
+ bezierVertexCheck();
+ float[] prev = vertices[vertexCount-1];
+ float x1 = prev[X];
+ float y1 = prev[Y];
+ float z1 = prev[Z];
+
+ bezierVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f), z1 + ((cz-z1)*2/3.0f),
+ x3 + ((cx-x3)*2/3.0f), y3 + ((cy-y3)*2/3.0f), z3 + ((cz-z3)*2/3.0f),
+ x3, y3, z3);
+ }
+
+
+ protected void curveVertexCheck() {
+ curveVertexCheck(shape);
+ }
+
+
+ /**
+ * Perform initialization specific to curveVertex(), and handle standard
+ * error modes. Can be overridden by subclasses that need the flexibility.
+ */
+ protected void curveVertexCheck(int shape) {
+ 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);
+ }
+
+
+ public void rect(float a, float b, float c, float d, float r) {
+ rect(a, b, c, d, r, r, r, r);
+ }
+
+
+ public void rect(float a, float b, float c, float d,
+ float tl, float tr, float br, float bl) {
+ 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;
+ }
+
+ float maxRounding = PApplet.min((c - a) / 2, (d - b) / 2);
+ if (tl > maxRounding) tl = maxRounding;
+ if (tr > maxRounding) tr = maxRounding;
+ if (br > maxRounding) br = maxRounding;
+ if (bl > maxRounding) bl = maxRounding;
+
+ rectImpl(a, b, c, d, tl, tr, br, bl);
+ }
+
+
+ protected void rectImpl(float x1, float y1, float x2, float y2,
+ float tl, float tr, float br, float bl) {
+ beginShape();
+// vertex(x1+tl, y1);
+ if (tr != 0) {
+ vertex(x2-tr, y1);
+ quadraticVertex(x2, y1, x2, y1+tr);
+ } else {
+ vertex(x2, y1);
+ }
+ if (br != 0) {
+ vertex(x2, y2-br);
+ quadraticVertex(x2, y2, x2-br, y2);
+ } else {
+ vertex(x2, y2);
+ }
+ if (bl != 0) {
+ vertex(x1+bl, y2);
+ quadraticVertex(x1, y2, x1, y2-bl);
+ } else {
+ vertex(x1, y2);
+ }
+ if (tl != 0) {
+ vertex(x1, y1+tl);
+ quadraticVertex(x1, y1, x1+tl, y1);
+ } else {
+ vertex(x1, y1);
+ }
+// endShape();
+ endShape(CLOSE);
+ }
+
+
+ public void square(float x, float y, float extent) {
+ rect(x, y, extent, extent);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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) {
+ arc(a, b, c, d, start, stop, 0);
+ }
+
+
+ public void arc(float a, float b, float c, float d,
+ float start, float stop, int mode) {
+ 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 the loop will exit before starting while
+ if (!Float.isInfinite(start) && !Float.isInfinite(stop)) {
+ // ignore equal and degenerate cases
+ if (stop > start) {
+ // 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, mode);
+ }
+ }
+ }
+
+
+ /**
+ * 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, int mode) {
+ showMissingWarning("arc");
+ }
+
+
+ public void circle(float x, float y, float extent) {
+ ellipse(x, y, extent, extent);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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);
+ }
+
+ edge(false);
+
+ // 1st ring from south pole
+ beginShape(TRIANGLE_STRIP);
+ for (int i = 0; i < sphereDetailU; i++) {
+ normal(0, -1, 0);
+ vertex(0, -r, 0);
+ normal(sphereX[i], sphereY[i], sphereZ[i]);
+ vertex(r * sphereX[i], r * sphereY[i], r * sphereZ[i]);
+ }
+ normal(0, -r, 0);
+ vertex(0, -r, 0);
+ normal(sphereX[0], sphereY[0], sphereZ[0]);
+ vertex(r * sphereX[0], r * sphereY[0], r * 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(r * sphereX[v1], r * sphereY[v1], r * sphereZ[v1++]);
+ normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
+ vertex(r * sphereX[v2], r * sphereY[v2], r * sphereZ[v2++]);
+ }
+ // close each ring
+ v1 = v11;
+ v2 = voff;
+ normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
+ vertex(r * sphereX[v1], r * sphereY[v1], r * sphereZ[v1]);
+ normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
+ vertex(r * sphereX[v2], r * sphereY[v2], r * 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(r * sphereX[v2], r * sphereY[v2], r * sphereZ[v2]);
+ normal(0, 1, 0);
+ vertex(0, r, 0);
+ }
+ normal(sphereX[voff], sphereY[voff], sphereZ[voff]);
+ vertex(r * sphereX[voff], r * sphereY[voff], r * sphereZ[voff]);
+ normal(0, 1, 0);
+ vertex(0, r, 0);
+ endShape();
+
+ edge(true);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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 = t-1.0f;
+ return t * ( 3*t1*(b*t1-c*t) + d*t*t ) - a*t1*t1*t1;
+ }
+
+ /**
+ * 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.
+ *
+ * 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().
+ *
+ */
+ 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
+
+
+ public void smooth() { // ignore
+ smooth(1);
+ }
+
+
+ public void smooth(int quality) { // ignore
+ if (primaryGraphics) {
+ parent.smooth(quality);
+ } else {
+ // for createGraphics(), make sure beginDraw() not called yet
+ if (settingsInited) {
+ // ignore if it's just a repeat of the current state
+ if (this.smooth != quality) {
+ smoothWarning("smooth");
+ }
+ } else {
+ this.smooth = quality;
+ }
+ }
+ }
+
+
+ public void noSmooth() { // ignore
+ smooth(0);
+ }
+
+
+ private void smoothWarning(String method) {
+ PGraphics.showWarning("%s() can only be used before beginDraw()", method);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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 not loaded yet, don't try to draw
+ if (image.width == 0 || image.height == 0) 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();
+ }
+ }
+
+
+ // TODO unapproved
+ protected void shape(PShape shape, float x, float y, float z) {
+ showMissingWarning("shape");
+ }
+
+
+ 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();
+ }
+ }
+
+
+ // TODO unapproved
+ protected void shape(PShape shape, float x, float y, float z, float c, float d, float e) {
+ showMissingWarning("shape");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TEXT/FONTS
+
+
+ /**
+ * Sets the alignment of the text to one of LEFT, CENTER, or RIGHT.
+ * This will also reset the vertical text alignment to BASELINE.
+ */
+ public void textAlign(int align) {
+ textAlign(align, BASELINE);
+ }
+
+
+ /**
+ * Sets the horizontal and vertical alignment of the text. The horizontal
+ * alignment can be one of LEFT, CENTER, or RIGHT. The vertical alignment
+ * can be TOP, BOTTOM, CENTER, or the BASELINE (the default).
+ */
+ public void textAlign(int alignX, int alignY) {
+ textAlign = alignX;
+ textAlignY = alignY;
+ }
+
+
+ /**
+ * Returns the ascent of the current font at the current size.
+ * This is a method, rather than a variable inside the PGraphics object
+ * because it requires calculation.
+ */
+ public float textAscent() {
+ if (textFont == null) {
+ defaultFontOrDeath("textAscent");
+ }
+ return textFont.ascent() * textSize;
+ }
+
+
+ /**
+ * Returns the descent of the current font at the current size.
+ * This is a method, rather than a variable inside the PGraphics object
+ * because it requires calculation.
+ */
+ public float textDescent() {
+ if (textFont == null) {
+ defaultFontOrDeath("textDescent");
+ }
+ return textFont.descent() * 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) {
+ throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT);
+ }
+ textFontImpl(which, which.getDefaultSize());
+ }
+
+
+ /**
+ * Useful function to set the font and size at the same time.
+ */
+ public void textFont(PFont which, float size) {
+ if (which == null) {
+ throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT);
+ }
+ // https://github.com/processing/processing/issues/3110
+ if (size <= 0) {
+ // Using System.err instead of showWarning to avoid running out of
+ // memory with a bunch of textSize() variants (cause of this bug is
+ // usually something done with map() or in a loop).
+ System.err.println("textFont: ignoring size " + size + " px:" +
+ "the text size must be larger than zero");
+ size = textSize;
+ }
+ textFontImpl(which, size);
+ }
+
+
+ /**
+ * Called from textFont. Check the validity of args and
+ * print possible errors to the user before calling this.
+ * Subclasses will want to override this one.
+ *
+ * @param which font to set, not null
+ * @param size size to set, greater than zero
+ */
+ protected void textFontImpl(PFont which, float size) {
+ textFont = which;
+// if (hints[ENABLE_NATIVE_FONTS]) {
+// //if (which.font == null) {
+// which.findNative();
+// //}
+// }
+ /*
+ 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();
+ }
+ */
+
+ handleTextSize(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) {
+ showWarning("textMode(SCREEN) has been removed from Processing 2.0.");
+ }
+
+ if (textModeCheck(mode)) {
+ textMode = mode;
+ } else {
+ String modeStr = String.valueOf(mode);
+ switch (mode) {
+ case MODEL: modeStr = "MODEL"; break;
+ case SHAPE: modeStr = "SHAPE"; break;
+ }
+ showWarning("textMode(" + modeStr + ") is not supported by this renderer.");
+ }
+ }
+
+
+ protected boolean textModeCheck(int mode) {
+ return true;
+ }
+
+
+ /**
+ * Sets the text size, also resets the value for the leading.
+ */
+ public void textSize(float size) {
+ // https://github.com/processing/processing/issues/3110
+ if (size <= 0) {
+ // Using System.err instead of showWarning to avoid running out of
+ // memory with a bunch of textSize() variants (cause of this bug is
+ // usually something done with map() or in a loop).
+ System.err.println("textSize(" + size + ") ignored: " +
+ "the text size must be larger than zero");
+ return;
+ }
+ if (textFont == null) {
+ defaultFontOrDeath("textSize", size);
+ }
+ textSizeImpl(size);
+ }
+
+
+ /**
+ * Called from textSize() after validating size. Subclasses
+ * will want to override this one.
+ * @param size size of the text, greater than zero
+ */
+ protected void textSizeImpl(float size) {
+ handleTextSize(size);
+ }
+
+
+ /**
+ * Sets the actual size. Called from textSizeImpl and
+ * from textFontImpl after setting the font.
+ * @param size size of the text, greater than zero
+ */
+ protected void handleTextSize(float size) {
+ textSize = size;
+ textLeading = (textAscent() + textDescent()) * 1.275f;
+ }
+
+
+ // ........................................................
+
+
+ public float textWidth(char c) {
+ textWidthBuffer[0] = c;
+ return textWidthImpl(textWidthBuffer, 0, 1);
+ }
+
+
+ /**
+ * Return the width of a line of text. If the text has multiple
+ * lines, this returns the length of the longest line.
+ */
+ public float textWidth(String str) {
+ if (textFont == null) {
+ defaultFontOrDeath("textWidth");
+ }
+
+ int length = str.length();
+ if (length > textWidthBuffer.length) {
+ textWidthBuffer = new char[length + 10];
+ }
+ str.getChars(0, length, textWidthBuffer, 0);
+
+ float wide = 0;
+ int index = 0;
+ int start = 0;
+
+ while (index < length) {
+ if (textWidthBuffer[index] == '\n') {
+ wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
+ start = index+1;
+ }
+ index++;
+ }
+ if (start < length) {
+ wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
+ }
+ return wide;
+ }
+
+
+ public float textWidth(char[] chars, int start, int length) {
+ return textWidthImpl(chars, start, start + length);
+ }
+
+
+ /**
+ * Implementation of returning the text width of
+ * the chars [start, stop) in the buffer.
+ * Unlike the previous version that was inside PFont, this will
+ * return the size not of a 1 pixel font, but the actual current size.
+ */
+ protected float textWidthImpl(char buffer[], int start, int stop) {
+ float wide = 0;
+ for (int i = start; i < stop; i++) {
+ // could add kerning here, but it just ain't implemented
+ wide += textFont.width(buffer[i]) * textSize;
+ }
+ return wide;
+ }
+
+
+ // ........................................................
+
+
+// /**
+// * Write text where we just left off.
+// */
+// public void text(char c) {
+// text(c, textX, textY, textZ);
+// }
+
+
+ /**
+ * Draw a single character on screen.
+ * Extremely slow when used with textMode(SCREEN) and Java 2D,
+ * because loadPixels has to be called first and updatePixels last.
+ */
+ public void text(char c, float x, float y) {
+ if (textFont == null) {
+ defaultFontOrDeath("text");
+ }
+
+ if (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);
+ }
+
+
+ /**
+ * 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);
+ }
+
+
+ /**
+ * Draw a chunk of text.
+ * Newlines that are \n (Unix newline or linefeed char, ascii 10)
+ * are honored, but \r (carriage return, Windows and Mac OS) are
+ * ignored.
+ */
+ public void text(String str, float x, float y) {
+ if (textFont == null) {
+ defaultFontOrDeath("text");
+ }
+
+ int length = str.length();
+ if (length > textBuffer.length) {
+ textBuffer = new char[length + 10];
+ }
+ str.getChars(0, length, textBuffer, 0);
+
+ // If multiple lines, sum the height of the additional lines
+ float high = 0; //-textAscent();
+ for (int i = 0; i < length; i++) {
+ if (textBuffer[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 < length) {
+ if (textBuffer[index] == '\n') {
+ textLineAlignImpl(textBuffer, start, index, x, y);
+ start = index + 1;
+ y += textLeading;
+ }
+ index++;
+ }
+ if (start < length) {
+ textLineAlignImpl(textBuffer, start, index, 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);
+ }
+ }
+
+
+ /**
+ * Same as above but with a z coordinate.
+ */
+ public void text(String str, 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); // slow!
+
+ text(str, x, y);
+// textZ = z;
+
+ if (z != 0) translate(0, 0, -z);
+ }
+
+
+ public void text(char[] chars, int start, int stop,
+ float x, float y, float z) {
+ if (z != 0) translate(0, 0, z); // slow!
+
+ text(chars, start, stop, x, y);
+// textZ = z;
+
+ if (z != 0) translate(0, 0, -z); // inaccurate!
+ }
+
+
+ /**
+ * Draw text in a box that is constrained to a particular size.
+ * The current rectMode() determines what the coordinates mean
+ * (whether x1/y1/x2/y2 or x/y/w/h).
+ *
+ * Note that the x,y coords of the start of the box
+ * will align with the *ascent* of the text, not the baseline,
+ * as is the case for the other text() functions.
+ *
+ * Newlines that are \n (Unix newline or linefeed char, ascii 10)
+ * are honored, and \r (carriage return, Windows and Mac OS) are
+ * ignored.
+ */
+ public void text(String str, float x1, float y1, float x2, float y2) {
+ if (textFont == null) {
+ defaultFontOrDeath("text");
+ }
+
+ 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;
+ }
+ }
+ }
+
+
+ /**
+ * 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) {
+ PFont.Glyph glyph = textFont.getGlyph(ch);
+ if (glyph != null) {
+ if (textMode == MODEL) {
+ float high = glyph.height / (float) textFont.size;
+ float bwidth = glyph.width / (float) textFont.size;
+ float lextent = glyph.leftExtent / (float) textFont.size;
+ float textent = glyph.topExtent / (float) textFont.size;
+
+ float x1 = x + lextent * textSize;
+ float y1 = y - textent * textSize;
+ float x2 = x1 + bwidth * textSize;
+ float y2 = y1 + high * textSize;
+
+ textCharModelImpl(glyph.image,
+ x1, y1, x2, y2,
+ glyph.width, glyph.height);
+ }
+ }
+ }
+
+
+ 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;
+ tint(fillColor);
+
+ imageImpl(glyph, x1, y1, x2, y2, 0, 0, u2, v2);
+
+ if (savedTint) {
+ tint(savedTintColor);
+ } else {
+ noTint();
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // PARITY WITH P5.JS
+
+
+ public void push() {
+ pushStyle();
+ pushMatrix();
+ }
+
+
+ public void pop() {
+ popStyle();
+ popMatrix();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX STACK
+
+
+ /**
+ * Push a copy of the current transformation matrix onto the stack.
+ */
+ public void pushMatrix() {
+ showMethodWarning("pushMatrix");
+ }
+
+
+ /**
+ * Replace the current transformation matrix with the top of the stack.
+ */
+ public void popMatrix() {
+ showMethodWarning("popMatrix");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX TRANSFORMATIONS
+
+
+ /**
+ * Translate in X and Y.
+ */
+ public void translate(float tx, float ty) {
+ showMissingWarning("translate");
+ }
+
+
+ /**
+ * Translate in X, Y, and Z.
+ */
+ public void translate(float tx, float ty, float tz) {
+ showMissingWarning("translate");
+ }
+
+
+ /**
+ * Two dimensional rotation.
+ *
+ * Same as rotateZ (this is identical to a 3D rotation along the z-axis)
+ * but included for clarity. It'd be weird for people drawing 2D graphics
+ * to be using rotateZ. And they might kick our a-- for the confusion.
+ *
+ * Additional background.
+ */
+ public void rotate(float angle) {
+ showMissingWarning("rotate");
+ }
+
+
+ /**
+ * Rotate around the X axis.
+ */
+ public void rotateX(float angle) {
+ showMethodWarning("rotateX");
+ }
+
+
+ /**
+ * Rotate around the Y axis.
+ */
+ public void rotateY(float angle) {
+ showMethodWarning("rotateY");
+ }
+
+
+ /**
+ * Rotate around the Z axis.
+ *
+ * The functions rotate() and rotateZ() are identical, it's just that it make
+ * sense to have rotate() and then rotateX() and rotateY() when using 3D;
+ * nor does it make sense to use a function called rotateZ() if you're only
+ * doing things in 2D. so we just decided to have them both be the same.
+ */
+ public void rotateZ(float angle) {
+ showMethodWarning("rotateZ");
+ }
+
+
+ /**
+ * Rotate about a vector in space. Same as the glRotatef() function.
+ */
+ public void rotate(float angle, float vx, float vy, float vz) {
+ showMissingWarning("rotate");
+ }
+
+
+ /**
+ * Scale in all dimensions.
+ */
+ public void scale(float s) {
+ showMissingWarning("scale");
+ }
+
+
+ /**
+ * Scale in X and Y. Equivalent to scale(sx, sy, 1).
+ *
+ * Not recommended for use in 3D, because the z-dimension is just
+ * scaled by 1, since there's no way to know what else to scale it by.
+ */
+ public void scale(float sx, float sy) {
+ showMissingWarning("scale");
+ }
+
+
+ /**
+ * Scale in X, Y, and Z.
+ */
+ public void scale(float x, float y, float z) {
+ showMissingWarning("scale");
+ }
+
+
+ /**
+ * Shear along X axis
+ */
+ public void shearX(float angle) {
+ showMissingWarning("shearX");
+ }
+
+
+ /**
+ * Skew along Y axis
+ */
+ public void shearY(float angle) {
+ showMissingWarning("shearY");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX FULL MONTY
+
+
+ /**
+ * Set the current transformation matrix to identity.
+ */
+ public void resetMatrix() {
+ showMethodWarning("resetMatrix");
+ }
+
+
+ public void applyMatrix(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ applyMatrix((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ applyMatrix((PMatrix3D) source);
+ }
+ }
+
+
+ public void applyMatrix(PMatrix2D source) {
+ applyMatrix(source.m00, source.m01, source.m02,
+ source.m10, source.m11, source.m12);
+ }
+
+
+ /**
+ * Apply a 3x2 affine transformation matrix.
+ */
+ public void applyMatrix(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ showMissingWarning("applyMatrix");
+ }
+
+
+ public void applyMatrix(PMatrix3D source) {
+ applyMatrix(source.m00, source.m01, source.m02, source.m03,
+ source.m10, source.m11, source.m12, source.m13,
+ source.m20, source.m21, source.m22, source.m23,
+ source.m30, source.m31, source.m32, source.m33);
+ }
+
+
+ /**
+ * Apply a 4x4 transformation matrix.
+ */
+ public void applyMatrix(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+ showMissingWarning("applyMatrix");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX GET/SET/PRINT
+
+
+ public PMatrix getMatrix() {
+ showMissingWarning("getMatrix");
+ return null;
+ }
+
+
+ /**
+ * Copy the current transformation matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix2D getMatrix(PMatrix2D target) {
+ showMissingWarning("getMatrix");
+ return null;
+ }
+
+
+ /**
+ * Copy the current transformation matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getMatrix(PMatrix3D target) {
+ showMissingWarning("getMatrix");
+ return null;
+ }
+
+
+ /**
+ * Returns a copy of the current object matrix.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getObjectMatrix() {
+ showMissingWarning("getObjectMatrix");
+ return null;
+ }
+
+
+ /**
+ * Copy the current object matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getObjectMatrix(PMatrix3D target) {
+ showMissingWarning("getObjectMatrix");
+ return null;
+ }
+
+
+ /**
+ * Returns a copy of the current eye matrix.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getEyeMatrix() {
+ showMissingWarning("getEyeMatrix");
+ return null;
+ }
+
+
+ /**
+ * Copy the current eye matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getEyeMatrix(PMatrix3D target) {
+ showMissingWarning("getEyeMatrix");
+ 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 cameraUp() {
+ showMethodWarning("cameraUp");
+ }
+
+
+ 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");
+ }
+
+
+ public void eye() {
+ showMethodWarning("eye");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // PROJECTION
+
+
+ public void ortho() {
+ showMissingWarning("ortho");
+ }
+
+ public void ortho(float left, float right,
+ float bottom, float top) {
+ 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;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RAY CASTING
+
+
+ public PVector[] getRayFromScreen(float screenX, float screenY, PVector[] ray) {
+ showMissingWarning("getRayFromScreen");
+ return null;
+ }
+
+
+ public void getRayFromScreen(float screenX, float screenY, PVector origin, PVector direction) {
+ showMissingWarning("getRayFromScreen");
+ }
+
+
+ public boolean intersectsSphere(float r, float screenX, float screenY) {
+ showMissingWarning("intersectsSphere");
+ return false;
+ }
+
+
+ public boolean intersectsSphere(float r, PVector origin, PVector direction) {
+ showMissingWarning("intersectsSphere");
+ return false;
+ }
+
+
+ public boolean intersectsBox(float size, float screenX, float screenY) {
+ showMissingWarning("intersectsBox");
+ return false;
+ }
+
+
+ public boolean intersectsBox(float w, float h, float d, float screenX, float screenY) {
+ showMissingWarning("intersectsBox");
+ return false;
+ }
+
+
+ public boolean intersectsBox(float size, PVector origin, PVector direction) {
+ showMissingWarning("intersectsBox");
+ return false;
+ }
+
+
+ public boolean intersectsBox(float w, float h, float d, PVector origin, PVector direction) {
+ showMissingWarning("intersectsBox");
+ return false;
+ }
+
+
+ public PVector intersectsPlane(float screenX, float screenY) {
+ showMissingWarning("intersectsPlane");
+ return null;
+ }
+
+
+ public PVector intersectsPlane(PVector origin, PVector direction) {
+ showMissingWarning("intersectsPlane");
+ return null;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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);
+
+ blendMode(s.blendMode);
+
+ 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.blendMode = blendMode;
+
+ 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() {
+ ambientColor = calcColor;
+ ambientR = calcR;
+ ambientG = calcG;
+ ambientB = calcB;
+ setAmbient = true;
+ }
+
+
+ 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() {
+ specularColor = calcColor;
+ 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() {
+ emissiveColor = calcColor;
+ 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) {
+ colorCalc(x, y, z, a);
+ backgroundFromCalc();
+ }
+
+
+ public void clear() {
+ background(0, 0, 0, 0);
+ }
+
+
+ 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.RGBToHSV((what >> 16) & 0xff, (what >> 8) & 0xff,
+ what & 0xff, cacheHsbValue);
+ cacheHsbKey = what;
+ }
+ return (cacheHsbValue[0] / 360f) * colorModeX;
+ }
+
+
+ public final float saturation(int what) {
+ if (what != cacheHsbKey) {
+ Color.RGBToHSV((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.RGBToHSV((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;
+ static float[] lerpColorHSB3;
+
+ /**
+ * 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];
+ lerpColorHSB3 = new float[3];
+ }
+
+ float a1 = (c1 >> 24) & 0xff;
+ float a2 = (c2 >> 24) & 0xff;
+ int alfa = ((int) (a1 + (a2-a1)*amt)) << 24;
+
+ Color.RGBToHSV((c1 >> 16) & 0xff, (c1 >> 8) & 0xff, c1 & 0xff,
+ lerpColorHSB1);
+ Color.RGBToHSV((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 = PActivity.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt);
+// float so = PActivity.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt);
+// float bo = PActivity.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt);
+// return alfa | (Color.HSVtoRGB(ho, so, bo) & 0xFFFFFF);
+// return Color.HSVToColor(alfa, new float[] { ho, so, bo });
+
+ lerpColorHSB3[0] = PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt);
+ lerpColorHSB3[1] = PApplet.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt);
+ lerpColorHSB3[2] = PApplet.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt);
+ return Color.HSVToColor(alfa, lerpColorHSB3);
+ }
+ 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;
+ }
+ }
+
+
+ public boolean haveRaw() { // ignore
+ return raw != null;
+ }
+
+
+ public PGraphics getRaw() { // ignore
+ return raw;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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());
+ }
+ }
+
+
+ /**
+ * Version of showWarning() that takes a parsed String.
+ */
+ static public void showWarning(String msg, Object... args) { // ignore
+ showWarning(String.format(msg, args));
+ }
+
+
+ /**
+ * Display a warning that the specified method is only available with 3D.
+ * @param method The method name (no parentheses)
+ */
+ static public 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 public 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 public 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 public 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 public void showMissingWarning(String method) {
+ showWarning(method + "(), or this particular variation of it, " +
+ "is not available with this renderer.");
+ }
+
+
+ /**
+ * Show an renderer-related exception that halts the program. Currently just
+ * wraps the message as a RuntimeException and throws it, but might do
+ * something more specific might be used in the future.
+ */
+ static public void showException(String msg) { // ignore
+ throw new RuntimeException(msg);
+ }
+
+
+ /**
+ * Same as below, but defaults to a 12 point font, just as MacWrite intended.
+ */
+ protected void defaultFontOrDeath(String method) {
+ defaultFontOrDeath(method, 12);
+ }
+
+
+ /**
+ * First try to create a default font, but if that's not possible, throw
+ * an exception that halts the program because textFont() has not been used
+ * prior to the specified method.
+ */
+ protected void defaultFontOrDeath(String method, float size) {
+ if (parent != null) {
+ textFont = parent.createDefaultFont(size);
+ } else {
+ throw new RuntimeException("Use textFont() before " + method + "()");
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RENDERER SUPPORT QUERIES
+
+
+ /**
+ * Return true if this renderer should be drawn to the screen. Defaults to
+ * returning true, since nearly all renderers are on-screen beasts. But can
+ * be overridden for subclasses like PDF so that a window doesn't open up.
+ *
+ * A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
+ * what to call this?
+ */
+ public boolean displayable() {
+ return true;
+ }
+
+
+ /**
+ * Return true if this renderer supports 2D drawing. Defaults to true.
+ */
+ public boolean is2D() {
+ return true;
+ }
+
+
+ /**
+ * Return true if this renderer supports 2D drawing. Defaults to false.
+ */
+ public boolean is3D() {
+ return false;
+ }
+
+
+ /**
+ * Return true if this renderer does rendering through OpenGL. Defaults to false.
+ */
+ public boolean isGL() {
+ return false;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ASYNC IMAGE SAVING
+
+
+ @Override
+ public boolean save(String filename) { // ignore
+
+ if (hints[DISABLE_ASYNC_SAVEFRAME]) {
+ return super.save(filename);
+ }
+
+ if (asyncImageSaver == null) {
+ asyncImageSaver = new AsyncImageSaver();
+ }
+
+ if (!loaded) loadPixels();
+ PImage target = asyncImageSaver.getAvailableTarget(pixelWidth, pixelHeight,
+ format);
+ if (target == null) return false;
+ int count = PApplet.min(pixels.length, target.pixels.length);
+ System.arraycopy(pixels, 0, target.pixels, 0, count);
+ asyncImageSaver.saveTargetAsync(this, target, filename);
+
+ return true;
+ }
+
+ protected void processImageBeforeAsyncSave(PImage image) { }
+
+
+ protected static AsyncImageSaver asyncImageSaver;
+
+ protected static class AsyncImageSaver {
+
+ static final int TARGET_COUNT =
+ Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
+
+ BlockingQueue targetPool = new ArrayBlockingQueue<>(TARGET_COUNT);
+ ExecutorService saveExecutor = Executors.newFixedThreadPool(TARGET_COUNT);
+
+ int targetsCreated = 0;
+
+
+ static final int TIME_AVG_FACTOR = 32;
+
+ volatile long avgNanos = 0;
+ long lastTime = 0;
+ int lastFrameCount = 0;
+
+
+ public AsyncImageSaver() { } // ignore
+
+
+ public void dispose() { // ignore
+ saveExecutor.shutdown();
+ try {
+ saveExecutor.awaitTermination(5000, TimeUnit.SECONDS);
+ } catch (InterruptedException e) { }
+ }
+
+
+ public boolean hasAvailableTarget() { // ignore
+ return targetsCreated < TARGET_COUNT || targetPool.isEmpty();
+ }
+
+
+ /**
+ * After taking a target, you must call saveTargetAsync() or
+ * returnUnusedTarget(), otherwise one thread won't be able to run
+ */
+ public PImage getAvailableTarget(int requestedWidth, int requestedHeight, // ignore
+ int format) {
+ try {
+ PImage target;
+ if (targetsCreated < TARGET_COUNT && targetPool.isEmpty()) {
+ target = new PImage(requestedWidth, requestedHeight);
+ targetsCreated++;
+ } else {
+ target = targetPool.take();
+ if (target.width != requestedWidth ||
+ target.height != requestedHeight) {
+ target.width = requestedWidth;
+ target.height = requestedHeight;
+ // TODO: this kills performance when saving different sizes
+ target.pixels = new int[requestedWidth * requestedHeight];
+ }
+ }
+ target.format = format;
+ return target;
+ } catch (InterruptedException e) {
+ return null;
+ }
+ }
+
+
+ public void returnUnusedTarget(PImage target) { // ignore
+ targetPool.offer(target);
+ }
+
+
+ public void saveTargetAsync(final PGraphics renderer, final PImage target, // ignore
+ final String filename) {
+ target.parent = renderer.parent;
+
+ // if running every frame, smooth the framerate
+ if (target.parent.frameCount - 1 == lastFrameCount && TARGET_COUNT > 1) {
+
+ // count with one less thread to reduce jitter
+ // 2 cores - 1 save thread - no wait
+ // 4 cores - 3 save threads - wait 1/2 of save time
+ // 8 cores - 7 save threads - wait 1/6 of save time
+ long avgTimePerFrame = avgNanos / (Math.max(1, TARGET_COUNT - 1));
+ long now = System.nanoTime();
+ long delay = PApplet.round((lastTime + avgTimePerFrame - now) / 1e6f);
+ try {
+ if (delay > 0) Thread.sleep(delay);
+ } catch (InterruptedException e) { }
+ }
+
+ lastFrameCount = target.parent.frameCount;
+ lastTime = System.nanoTime();
+
+ try {
+ saveExecutor.submit(new Runnable() {
+ @Override
+ public void run() { // ignore
+ try {
+ long startTime = System.nanoTime();
+ renderer.processImageBeforeAsyncSave(target);
+ target.save(filename);
+ long saveNanos = System.nanoTime() - startTime;
+ synchronized (AsyncImageSaver.this) {
+ if (avgNanos == 0) {
+ avgNanos = saveNanos;
+ } else if (saveNanos < avgNanos) {
+ avgNanos = (avgNanos * (TIME_AVG_FACTOR - 1) + saveNanos) /
+ (TIME_AVG_FACTOR);
+ } else {
+ avgNanos = saveNanos;
+ }
+ }
+ } finally {
+ targetPool.offer(target);
+ }
+ }
+ });
+ } catch (RejectedExecutionException e) {
+ // the executor service was probably shut down, no more saving for us
+ }
+ }
+ }
+
+}
diff --git a/core-androidx/src/processing/core/PImage.java b/core-androidx/src/processing/core/PImage.java
new file mode 100644
index 000000000..221e42bfa
--- /dev/null
+++ b/core-androidx/src/processing/core/PImage.java
@@ -0,0 +1,2881 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2004-12 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 version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.io.*;
+import java.util.HashMap;
+
+import android.graphics.Bitmap;
+import android.graphics.Bitmap.CompressFormat;
+import android.graphics.Bitmap.Config;
+
+
+/**
+ * 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.
+ *
+ */
+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;
+
+ public int[] pixels;
+ public int width, height;
+
+ /**
+ * For the time being, simply to ensure compatibility with Java mode code
+ */
+ public int pixelDensity = 1;
+ public int pixelWidth;
+ public int pixelHeight;
+
+ /**
+ * Path to parent object that will be used with save().
+ * This prevents users from needing savePath() to use PImage.save().
+ */
+ public PApplet parent;
+
+ protected Bitmap bitmap;
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /** for renderers that need to store info about the image */
+ protected HashMap cacheMap;
+
+ /** for renderers that need to store parameters about the image */
+ protected HashMap paramMap;
+
+
+ /** modified portion of the image */
+ protected boolean modified;
+ protected int mx1, my1, mx2, my2;
+
+ /** Loaded pixels flag */
+ public boolean loaded = false;
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ // 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;
+
+ // colour component bitmasks (moved from PConstants in 2.0b7)
+ public static final int ALPHA_MASK = 0xff000000;
+ public static final int RED_MASK = 0x00ff0000;
+ public static final int GREEN_MASK = 0x0000ff00;
+ public static final int BLUE_MASK = 0x000000ff;
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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);
+ }
+
+
+ public PImage(int width, int height, int format) {
+ init(width, height, format);
+ }
+
+
+ /**
+ * Function to be used by subclasses of PImage to init later than
+ * at the constructor, or re-init later when things changes.
+ * Used by Capture and Movie classes (and perhaps others),
+ * because the width/height will not be known when super() is called.
+ * (Leave this public so that other libraries can do the same.)
+ */
+ public void init(int width, int height, int format) { // ignore
+ this.width = width;
+ this.height = height;
+ this.pixels = new int[width*height];
+ this.format = format;
+// this.cache = null;
+
+ pixelWidth = width * pixelDensity;
+ pixelHeight = height * pixelDensity;
+ this.pixels = new int[pixelWidth * pixelHeight];
+ }
+
+
+ /**
+ * Check the alpha on an image, using a really primitive loop.
+ */
+ protected void checkAlpha() {
+ if (pixels == null) return;
+
+ for (int i = 0; i < pixels.length; i++) {
+ // since transparency is often at corners, hopefully this
+ // will find a non-transparent pixel quickly and exit
+ if ((pixels[i] & 0xff000000) != 0xff000000) {
+ format = ARGB;
+ break;
+ }
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Construct a new PImage from an Android bitmap. The pixels[] array is not
+ * initialized, nor is data copied to it, until loadPixels() is called.
+ */
+ public PImage(Object nativeObject) {
+ Bitmap bitmap = (Bitmap) nativeObject;
+ this.bitmap = bitmap;
+ this.width = bitmap.getWidth();
+ this.height = bitmap.getHeight();
+ this.pixels = null;
+ this.format = bitmap.hasAlpha() ? ARGB : RGB;
+ this.pixelDensity = 1;
+ this.pixelWidth = width;
+ this.pixelHeight = height;
+ }
+
+
+ /**
+ * Returns the native Bitmap object for this PImage.
+ */
+ public Object getNative() {
+ return bitmap;
+ }
+
+
+ public void setNative(Object nativeObject) {
+ Bitmap bitmap = (Bitmap) nativeObject;
+ this.bitmap = bitmap;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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;
+ }
+
+ public int getModifiedX1() { // ignore
+ return mx1;
+ }
+
+
+ public int getModifiedX2() { // ignore
+ return mx2;
+ }
+
+
+ public int getModifiedY1() { // ignore
+ return my1;
+ }
+
+
+ public int getModifiedY2() { // ignore
+ return my2;
+ }
+
+
+ /**
+ * 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
+ */
+ public void loadPixels() { // ignore
+ if (pixels == null || pixels.length != width*height) {
+ pixels = new int[width*height];
+ }
+
+ if (bitmap != null) {
+ if (modified) {
+ // The pixels array has been used to do color manipulations, so
+ // the bitmap should be updated
+ if (!bitmap.isMutable()) {
+ // create a mutable version of this bitmap
+ bitmap = bitmap.copy(Config.ARGB_8888, true);
+ }
+ bitmap.setPixels(pixels, 0, width, mx1, my1, mx2 - mx1, my2 - my1);
+ modified = false;
+ } else {
+ // Get wherever it is in the bitmap right now, we assume is the most
+ // up-to-date version of the image.
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
+ }
+ }
+
+ setLoaded();
+ }
+
+
+ /**
+ * Call this when finished messing with the pixels[] array.
+ *
+ * Mark all pixels as needing update.
+ */
+ public void updatePixels() { // ignore
+ updatePixelsImpl(0, 0, width, height);
+ }
+
+
+ /**
+ * 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.
+ */
+ 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 = PApplet.max(0, x);
+ //mx2 = PApplet.min(width - 1, x2);
+ mx2 = PApplet.min(width, x2);
+ my1 = PApplet.max(0, y);
+ //my2 = PApplet.min(height - 1, y2);
+ my2 = PApplet.min(height, y2);
+ modified = true;
+
+ } else {
+ if (x < mx1) mx1 = PApplet.max(0, x);
+ //if (x > mx2) mx2 = PApplet.min(width - 1, x);
+ if (x > mx2) mx2 = PApplet.min(width, x);
+ if (y < my1) my1 = PApplet.max(0, y);
+ //if (y > my2) my2 = y;
+ if (y > my2) my2 = PApplet.min(height, y);
+
+ if (x2 < mx1) mx1 = PApplet.max(0, x2);
+ //if (x2 > mx2) mx2 = PApplet.min(width - 1, x2);
+ if (x2 > mx2) mx2 = PApplet.min(width, x2);
+ if (y2 < my1) my1 = PApplet.max(0, y2);
+ //if (y2 > my2) my2 = PApplet.min(height - 1, y2);
+ if (y2 > my2) my2 = PApplet.min(height, 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.
+ */
+ @Override
+ public Object clone() throws CloneNotSupportedException { // ignore
+ return get();
+ }
+
+
+ /**
+ * Resize this image to a new width and height.
+ * Use 0 for wide or high to make that dimension scale proportionally.
+ */
+ public void resize(int w, int h) { // ignore
+ if (bitmap == null) {
+ return; // Cannot resize an image not backed by a bitmap
+ }
+
+ if (w <= 0 && h <= 0) {
+ throw new IllegalArgumentException("width or height must be > 0 for resize");
+ }
+
+ if (w == 0) { // Use height to determine relative size
+ float diff = (float) h / (float) height;
+ w = (int) (width * diff);
+ } else if (h == 0) { // Use the width to determine relative size
+ float diff = (float) w / (float) width;
+ h = (int) (height * diff);
+ }
+ bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
+ if (pixels != null) {
+ // Resize pixels array, if in use.
+ pixels = new int[w * h];
+ bitmap.getPixels(pixels, 0, w, 0, 0, w, h);
+ }
+ this.width = w;
+ this.height = h;
+ this.pixelWidth = w * pixelDensity;
+ this.pixelHeight = h * pixelDensity;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MARKING IMAGE AS LOADED / FOR USE IN RENDERERS
+
+
+ public boolean isLoaded() { // ignore
+ return loaded;
+ }
+
+
+ public void setLoaded() { // ignore
+ loaded = true;
+ }
+
+
+ public void setLoaded(boolean l) { // ignore
+ loaded = l;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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;
+
+ if (pixels == null) {
+ return bitmap.getPixel(x, y);
+
+ } else {
+ // If the pixels array exists, it's fairly safe to assume that it's
+ // the most up to date, and that it's faster for access.
+ 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;
+ }
+
+
+ /**
+ * Grab a subsection of a PImage, and copy it into a fresh PImage.
+ * As of release 0149, no longer honors imageMode() for the coordinates.
+ */
+ /**
+ * @param w width of pixel rectangle to get
+ * @param h height of pixel rectangle to get
+ */
+ public PImage get(int x, int y, int w, int h) {
+ int targetX = 0;
+ int targetY = 0;
+ int targetWidth = w;
+ int targetHeight = h;
+ boolean cropped = false;
+
+ if (x < 0) {
+ w += x; // x is negative, removes the left edge from the width
+ targetX = -x;
+ cropped = true;
+ x = 0;
+ }
+ if (y < 0) {
+ h += y; // y is negative, clip the number of rows
+ targetY = -y;
+ cropped = true;
+ y = 0;
+ }
+
+ if (x + w > width) {
+ w = width - x;
+ cropped = true;
+ }
+ if (y + h > height) {
+ h = height - y;
+ cropped = true;
+ }
+
+ if (w < 0) {
+ w = 0;
+ }
+ if (h < 0) {
+ h = 0;
+ }
+
+ int targetFormat = format;
+ if (cropped && format == RGB) {
+ targetFormat = ARGB;
+ }
+
+ PImage target = new PImage(targetWidth, targetHeight, targetFormat);
+ target.parent = parent; // parent may be null so can't use createImage()
+ if (w > 0 && h > 0) {
+ getImpl(x, y, w, h, target, targetX, targetY);
+ Bitmap nat = Bitmap.createBitmap(target.pixels, targetWidth, targetHeight, Config.ARGB_8888);
+ target.setNative(nat);
+ }
+ return target;
+ }
+
+
+ /**
+ * 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 void getImpl(int sourceX, int sourceY,
+ int sourceWidth, int sourceHeight,
+ PImage target, int targetX, int targetY) {
+ if (bitmap != null) {
+ bitmap.getPixels(target.pixels,
+ targetY*target.width + targetX, target.width,
+ sourceX, sourceY, sourceWidth, sourceHeight);
+ } else if (pixels != null) {
+ int sourceIndex = sourceY*width + sourceX;
+ int targetIndex = targetY*target.width + targetX;
+ for (int row = 0; row < sourceHeight; row++) {
+ System.arraycopy(pixels, sourceIndex, target.pixels, targetIndex, sourceWidth);
+ sourceIndex += width;
+ targetIndex += target.width;
+ }
+ }
+ }
+
+
+ /**
+ * Returns a copy of this PImage. Equivalent to get(0, 0, width, height).
+ */
+ public PImage get() {
+ // Formerly this used clone(), which caused memory problems.
+ // http://code.google.com/p/processing/issues/detail?id=42
+ return get(0, 0, width, height);
+ }
+
+
+ public PImage copy() {
+ return get(0, 0, pixelWidth, pixelHeight);
+ }
+
+
+ /**
+ * Set a single pixel to the specified color.
+ */
+ public void set(int x, int y, int c) {
+ if (pixels == null) {
+ bitmap.setPixel(x, y, c);
+
+ } else {
+ if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return;
+ pixels[y*width + x] = c;
+ updatePixelsImpl(x, y, 1, 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 img) {
+ if (img.format == ALPHA) {
+ // set() doesn't really make sense for an ALPHA image, since it
+ // directly replaces pixels and does no blending.
+ throw new IllegalArgumentException("set() not available for ALPHA images");
+ }
+
+ int sx = 0;
+ int sy = 0;
+ int sw = img.width;
+ int sh = img.height;
+
+ 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 nonexistent
+ if ((sw <= 0) || (sh <= 0)) return;
+
+ setImpl(img, sx, sy, sw, sh, x, y);
+ }
+
+
+ /**
+ * 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(PImage sourceImage,
+ int sourceX, int sourceY,
+ int sourceWidth, int sourceHeight,
+ int targetX, int targetY) {
+ if (sourceImage.pixels == null) {
+ sourceImage.loadPixels();
+ }
+
+ // if this.pixels[] is null, copying directly into this.bitmap
+ if (pixels == null) {
+ // if this.pixels[] is null, this.bitmap cannot be null
+ // make sure the bitmap is writable
+ if (!bitmap.isMutable()) {
+ // create a mutable version of this bitmap
+ bitmap = bitmap.copy(Config.ARGB_8888, true);
+ }
+
+ // copy from src.pixels to this.bitmap
+ int offset = sourceY * sourceImage.width + sourceX;
+ bitmap.setPixels(sourceImage.pixels,
+ offset, sourceImage.width,
+ targetX, targetY, sourceWidth, sourceHeight);
+
+ } else { // pixels != null
+ // copy into this.pixels[] and mark as modified
+ int srcOffset = sourceY * sourceImage.width + sourceX;
+ int dstOffset = targetY * width + targetX;
+ for (int y = sourceY; y < sourceY + sourceHeight; y++) {
+ System.arraycopy(sourceImage.pixels, srcOffset, pixels, dstOffset, sourceWidth);
+ srcOffset += sourceImage.width;
+ dstOffset += width;
+ }
+ updatePixelsImpl(targetX, targetY, sourceWidth, sourceHeight);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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" grayscake by
+ * performing a proper luminance-based conversion.
+ */
+ public void mask(int alpha[]) {
+ loadPixels();
+ // don't execute if mask image is different size
+ if (alpha.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);
+ }
+ format = ARGB;
+ updatePixels();
+ }
+
+
+ /**
+ * Set alpha channel for an image using another image as the source.
+ */
+ public void mask(PImage alpha) {
+ if (alpha.pixels == null) {
+ // if pixels haven't been loaded by the user, then only load them
+ // temporarily to save memory when finished.
+ alpha.loadPixels();
+ mask(alpha.pixels);
+ alpha.pixels = null;
+ } else {
+ mask(alpha.pixels);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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();
+
+ 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 RGB:
+ 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
+ }
+
+
+ /**
+ * 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.
+ *
+ * Gaussian blur code contributed by
+ * Mario Klingemann
+ * and later updated by toxi for better speed.
+ */
+ 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
+ *
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".
+ *
+ *
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) { // ignore
+ 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);
+ }
+
+
+ /**
+ * Copies area of one image into another PImage object.
+ * @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) {
+ 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, sw, sh),
+ 0, 0, sw, sh,
+ pixels, pixelWidth, pixelHeight, 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, pixelWidth, pixelHeight, dx, dy, dx2, dy2, mode);
+ }
+ } else {
+ src.loadPixels();
+ blit_resize(src, sx, sy, sx2, sy2,
+ pixels, pixelWidth, pixelHeight, 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.pixelWidth) srcX2 = img.pixelWidth;
+ if (srcY2 > img.pixelHeight) srcY2 = img.pixelHeight;
+
+ 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.pixelWidth || srcY1 >= img.pixelHeight) {
+ return;
+ }
+
+ int dx = (int) (srcW / (float) destW * PRECISIONF);
+ int dy = (int) (srcH / (float) destH * PRECISIONF);
+
+ srcXOffset = destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF;
+ srcYOffset = destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF;
+
+ if (destX1 < 0) {
+ destW += destX1;
+ destX1 = 0;
+ }
+ if (destY1 < 0) {
+ destH += destY1;
+ destY1 = 0;
+ }
+
+ destW = min(destW, screenW - destX1);
+ destH = min(destH, screenH - destY1);
+
+ int destOffset = destY1 * screenW + destX1;
+ srcBuffer = img.pixels;
+
+ if (smooth) {
+ // use bilinear filtering
+ iw = img.pixelWidth;
+ iw1 = img.pixelWidth - 1;
+ ih1 = img.pixelHeight - 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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.pixelWidth;
+ 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 + 1;
+ v1 = (srcYOffset >> PRECISIONB) * iw;
+ v2 = min((srcYOffset >> PRECISIONB) + 1, ih1) * iw;
+ }
+
+
+ private int filter_bilinear() {
+ fracU = sX & PREC_MAXVAL;
+ ifU = PREC_MAXVAL - fracU + 1;
+ ul = (ifU * ifV) >> PRECISIONB;
+ ll = ifU - ul;
+ ur = ifV - ul;
+ lr = PREC_MAXVAL + 1 - ul - ll - ur;
+ u1 = (sX >> PRECISIONB);
+ u2 = min(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 min(int a, int b) {
+ return (a < b) ? a : b;
+ }
+
+
+ private static int max(int a, int b) {
+ return (a > b) ? a : b;
+ }
+
+
+ /////////////////////////////////////////////////////////////
+
+ // BLEND MODE IMPLEMENTATIONS
+
+ /*
+ * Jakub Valtar
+ *
+ * All modes use SRC alpha to interpolate between DST and the result of
+ * the operation:
+ *
+ * R = (1 - SRC_ALPHA) * DST + SRC_ALPHA *
+ *
+ * Comments above each mode only specify the formula of its operation.
+ *
+ * These implementations treat alpha 127 (=255/2) as a perfect 50 % mix.
+ *
+ * One alpha value between 126 and 127 is intentionally left out,
+ * so the step 126 -> 127 is twice as big compared to other steps.
+ * This is because our colors are in 0..255 range, but we divide
+ * by right shifting 8 places (=256) which is much faster than
+ * (correct) float division by 255.0f. The missing value was placed
+ * between 126 and 127, because limits of the range (near 0 and 255) and
+ * the middle value (127) have to blend correctly.
+ *
+ * Below you will often see RED and BLUE channels (RB) manipulated together
+ * and GREEN channel (GN) manipulated separately. It is sometimes possible
+ * because the operation won't use more than 16 bits, so we process the RED
+ * channel in the upper 16 bits and BLUE channel in the lower 16 bits. This
+ * decreases the number of operations per pixel and thus makes things faster.
+ *
+ * Some of the modes are hand tweaked (various +1s etc.) to be more accurate
+ * and to produce correct values in extremes. Below is a sketch you can use
+ * to check any blending function for
+ *
+ * 1) Discrepancies between color channels:
+ * - highlighted by the offending color
+ * 2) Behavior at extremes (set colorCount to 256):
+ * - values of all corners are printed to the console
+ * 3) Rounding errors:
+ * - set colorCount to lower value to better see color bands
+ *
+
+// use powers of 2 in range 2..256
+// to better see color bands
+final int colorCount = 256;
+
+final int blockSize = 3;
+
+void settings() {
+ size(blockSize * 256, blockSize * 256);
+}
+
+void setup() { }
+
+void draw() {
+ noStroke();
+ colorMode(RGB, colorCount-1);
+ int alpha = (mouseX / blockSize) << 24;
+ int r, g, b, r2, g2, b2 = 0;
+ for (int x = 0; x <= 0xFF; x++) {
+ for (int y = 0; y <= 0xFF; y++) {
+ int dst = (x << 16) | (x << 8) | x;
+ int src = (y << 16) | (y << 8) | y | alpha;
+ int result = testFunction(dst, src);
+ r = r2 = (result >> 16 & 0xFF);
+ g = g2 = (result >> 8 & 0xFF);
+ b = b2 = (result >> 0 & 0xFF);
+ if (r != g && r != b) r2 = (128 + r2) % 255;
+ if (g != r && g != b) g2 = (128 + g2) % 255;
+ if (b != r && b != g) b2 = (128 + b2) % 255;
+ fill(r2 % colorCount, g2 % colorCount, b2 % colorCount);
+ rect(x * blockSize, y * blockSize, blockSize, blockSize);
+ }
+ }
+ println(
+ "alpha:", mouseX/blockSize,
+ "TL:", hex(get(0, 0)),
+ "TR:", hex(get(width-1, 0)),
+ "BR:", hex(get(width-1, height-1)),
+ "BL:", hex(get(0, height-1)));
+}
+
+int testFunction(int dst, int src) {
+ // your function here
+ return dst;
+}
+
+ *
+ *
+ */
+
+ private static final int RB_MASK = 0x00FF00FF;
+ private static final int GN_MASK = 0x0000FF00;
+
+ /**
+ * Blend
+ * O = S
+ */
+ private static int blend_blend(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + (src & RB_MASK) * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + (src & GN_MASK) * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Add
+ * O = MIN(D + S, 1)
+ */
+ private static int blend_add_pin(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+
+ int rb = (dst & RB_MASK) + ((src & RB_MASK) * s_a >>> 8 & RB_MASK);
+ int gn = (dst & GN_MASK) + ((src & GN_MASK) * s_a >>> 8);
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ min(rb & 0xFFFF0000, RED_MASK) |
+ min(gn & 0x00FFFF00, GREEN_MASK) |
+ min(rb & 0x0000FFFF, BLUE_MASK);
+ }
+
+
+ /**
+ * Subtract
+ * O = MAX(0, D - S)
+ */
+ private static int blend_sub_pin(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+
+ int rb = ((src & RB_MASK) * s_a >>> 8);
+ int gn = ((src & GREEN_MASK) * s_a >>> 8);
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ max((dst & RED_MASK) - (rb & RED_MASK), 0) |
+ max((dst & GREEN_MASK) - (gn & GREEN_MASK), 0) |
+ max((dst & BLUE_MASK) - (rb & BLUE_MASK), 0);
+ }
+
+
+ /**
+ * Lightest
+ * O = MAX(D, S)
+ */
+ private static int blend_lightest(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int rb = max(src & RED_MASK, dst & RED_MASK) |
+ max(src & BLUE_MASK, dst & BLUE_MASK);
+ int gn = max(src & GREEN_MASK, dst & GREEN_MASK);
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + rb * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + gn * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Darkest
+ * O = MIN(D, S)
+ */
+ private static int blend_darkest(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int rb = min(src & RED_MASK, dst & RED_MASK) |
+ min(src & BLUE_MASK, dst & BLUE_MASK);
+ int gn = min(src & GREEN_MASK, dst & GREEN_MASK);
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + rb * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + gn * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Difference
+ * O = ABS(D - S)
+ */
+ private static int blend_difference(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int r = (dst & RED_MASK) - (src & RED_MASK);
+ int b = (dst & BLUE_MASK) - (src & BLUE_MASK);
+ int g = (dst & GREEN_MASK) - (src & GREEN_MASK);
+
+ int rb = (r < 0 ? -r : r) |
+ (b < 0 ? -b : b);
+ int gn = (g < 0 ? -g : g);
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + rb * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + gn * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Exclusion
+ * O = (1 - S)D + S(1 - D)
+ * O = D + S - 2DS
+ */
+ private static int blend_exclusion(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int d_rb = dst & RB_MASK;
+ int d_gn = dst & GN_MASK;
+
+ int s_gn = src & GN_MASK;
+
+ int f_r = (dst & RED_MASK) >> 16;
+ int f_b = (dst & BLUE_MASK);
+
+ int rb_sub =
+ ((src & RED_MASK) * (f_r + (f_r >= 0x7F ? 1 : 0)) |
+ (src & BLUE_MASK) * (f_b + (f_b >= 0x7F ? 1 : 0)))
+ >>> 7 & 0x01FF01FF;
+ int gn_sub = s_gn * (d_gn + (d_gn >= 0x7F00 ? 0x100 : 0))
+ >>> 15 & 0x0001FF00;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ (d_rb * d_a + (d_rb + (src & RB_MASK) - rb_sub) * s_a) >>> 8 & RB_MASK |
+ (d_gn * d_a + (d_gn + s_gn - gn_sub) * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /*
+ * Multiply
+ * O = DS
+ */
+ private static int blend_multiply(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int d_gn = dst & GN_MASK;
+
+ int f_r = (dst & RED_MASK) >> 16;
+ int f_b = (dst & BLUE_MASK);
+
+ int rb =
+ ((src & RED_MASK) * (f_r + 1) |
+ (src & BLUE_MASK) * (f_b + 1))
+ >>> 8 & RB_MASK;
+ int gn =
+ (src & GREEN_MASK) * (d_gn + 0x100)
+ >>> 16 & GN_MASK;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + rb * s_a) >>> 8 & RB_MASK |
+ (d_gn * d_a + gn * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Screen
+ * O = 1 - (1 - D)(1 - S)
+ * O = D + S - DS
+ */
+ private static int blend_screen(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int d_rb = dst & RB_MASK;
+ int d_gn = dst & GN_MASK;
+
+ int s_gn = src & GN_MASK;
+
+ int f_r = (dst & RED_MASK) >> 16;
+ int f_b = (dst & BLUE_MASK);
+
+ int rb_sub =
+ ((src & RED_MASK) * (f_r + 1) |
+ (src & BLUE_MASK) * (f_b + 1))
+ >>> 8 & RB_MASK;
+ int gn_sub = s_gn * (d_gn + 0x100)
+ >>> 16 & GN_MASK;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ (d_rb * d_a + (d_rb + (src & RB_MASK) - rb_sub) * s_a) >>> 8 & RB_MASK |
+ (d_gn * d_a + (d_gn + s_gn - gn_sub) * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Overlay
+ * O = 2 * MULTIPLY(D, S) = 2DS for D < 0.5
+ * O = 2 * SCREEN(D, S) - 1 = 2(S + D - DS) - 1 otherwise
+ */
+ private static int blend_overlay(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int d_r = dst & RED_MASK;
+ int d_g = dst & GREEN_MASK;
+ int d_b = dst & BLUE_MASK;
+
+ int s_r = src & RED_MASK;
+ int s_g = src & GREEN_MASK;
+ int s_b = src & BLUE_MASK;
+
+ int r = (d_r < 0x800000) ?
+ d_r * ((s_r >>> 16) + 1) >>> 7 :
+ 0xFF0000 - ((0x100 - (s_r >>> 16)) * (RED_MASK - d_r) >>> 7);
+ int g = (d_g < 0x8000) ?
+ d_g * (s_g + 0x100) >>> 15 :
+ (0xFF00 - ((0x10000 - s_g) * (GREEN_MASK - d_g) >>> 15));
+ int b = (d_b < 0x80) ?
+ d_b * (s_b + 1) >>> 7 :
+ (0xFF00 - ((0x100 - s_b) * (BLUE_MASK - d_b) << 1)) >>> 8;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + ((r | b) & RB_MASK) * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + (g & GN_MASK) * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Hard Light
+ * O = OVERLAY(S, D)
+ *
+ * O = 2 * MULTIPLY(D, S) = 2DS for S < 0.5
+ * O = 2 * SCREEN(D, S) - 1 = 2(S + D - DS) - 1 otherwise
+ */
+ private static int blend_hard_light(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int d_r = dst & RED_MASK;
+ int d_g = dst & GREEN_MASK;
+ int d_b = dst & BLUE_MASK;
+
+ int s_r = src & RED_MASK;
+ int s_g = src & GREEN_MASK;
+ int s_b = src & BLUE_MASK;
+
+ int r = (s_r < 0x800000) ?
+ s_r * ((d_r >>> 16) + 1) >>> 7 :
+ 0xFF0000 - ((0x100 - (d_r >>> 16)) * (RED_MASK - s_r) >>> 7);
+ int g = (s_g < 0x8000) ?
+ s_g * (d_g + 0x100) >>> 15 :
+ (0xFF00 - ((0x10000 - d_g) * (GREEN_MASK - s_g) >>> 15));
+ int b = (s_b < 0x80) ?
+ s_b * (d_b + 1) >>> 7 :
+ (0xFF00 - ((0x100 - d_b) * (BLUE_MASK - s_b) << 1)) >>> 8;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + ((r | b) & RB_MASK) * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + (g & GN_MASK) * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Soft Light (Pegtop)
+ * O = (1 - D) * MULTIPLY(D, S) + D * SCREEN(D, S)
+ * O = (1 - D) * DS + D * (1 - (1 - D)(1 - S))
+ * O = 2DS + DD - 2DDS
+ */
+ private static int blend_soft_light(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int d_r = dst & RED_MASK;
+ int d_g = dst & GREEN_MASK;
+ int d_b = dst & BLUE_MASK;
+
+ int s_r1 = src & RED_MASK >> 16;
+ int s_g1 = src & GREEN_MASK >> 8;
+ int s_b1 = src & BLUE_MASK;
+
+ int d_r1 = (d_r >> 16) + (s_r1 < 7F ? 1 : 0);
+ int d_g1 = (d_g >> 8) + (s_g1 < 7F ? 1 : 0);
+ int d_b1 = d_b + (s_b1 < 7F ? 1 : 0);
+
+ int r = (s_r1 * d_r >> 7) + 0xFF * d_r1 * (d_r1 + 1) -
+ ((s_r1 * d_r1 * d_r1) << 1) & RED_MASK;
+ int g = (s_g1 * d_g << 1) + 0xFF * d_g1 * (d_g1 + 1) -
+ ((s_g1 * d_g1 * d_g1) << 1) >>> 8 & GREEN_MASK;
+ int b = (s_b1 * d_b << 9) + 0xFF * d_b1 * (d_b1 + 1) -
+ ((s_b1 * d_b1 * d_b1) << 1) >>> 16;
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + (r | b) * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + g * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Dodge
+ * O = D / (1 - S)
+ */
+ private static int blend_dodge(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int r = (dst & RED_MASK) / (256 - ((src & RED_MASK) >> 16));
+ int g = ((dst & GREEN_MASK) << 8) / (256 - ((src & GREEN_MASK) >> 8));
+ int b = ((dst & BLUE_MASK) << 8) / (256 - (src & BLUE_MASK));
+
+ int rb =
+ (r > 0xFF00 ? 0xFF0000 : ((r << 8) & RED_MASK)) |
+ (b > 0x00FF ? 0x0000FF : b);
+ int gn =
+ (g > 0xFF00 ? 0x00FF00 : (g & GREEN_MASK));
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + rb * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + gn * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ /**
+ * Burn
+ * O = 1 - (1 - A) / B
+ */
+ private static int blend_burn(int dst, int src) {
+ int a = src >>> 24;
+
+ int s_a = a + (a >= 0x7F ? 1 : 0);
+ int d_a = 0x100 - s_a;
+
+ int r = ((0xFF0000 - (dst & RED_MASK))) / (1 + (src & RED_MASK >> 16));
+ int g = ((0x00FF00 - (dst & GREEN_MASK)) << 8) / (1 + (src & GREEN_MASK >> 8));
+ int b = ((0x0000FF - (dst & BLUE_MASK)) << 8) / (1 + (src & BLUE_MASK));
+
+ int rb = RB_MASK -
+ (r > 0xFF00 ? 0xFF0000 : ((r << 8) & RED_MASK)) -
+ (b > 0x00FF ? 0x0000FF : b);
+ int gn = GN_MASK -
+ (g > 0xFF00 ? 0x00FF00 : (g & GREEN_MASK));
+
+ return min((dst >>> 24) + a, 0xFF) << 24 |
+ ((dst & RB_MASK) * d_a + rb * s_a) >>> 8 & RB_MASK |
+ ((dst & GN_MASK) * d_a + gn * s_a) >>> 8 & GN_MASK;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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);
+
+ // Not possible because this method is static, so careful when using it.
+ // outgoing.parent = parent;
+
+ 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);
+//
+// bimage.setRGB(0, 0, width, height, pixels, 0, width);
+//
+// File file = new File(path);
+// String extension = path.substring(path.lastIndexOf('.') + 1);
+//
+// ImageIO.write(bimage, extension, file);
+//
+// } catch (Exception e) {
+// e.printStackTrace();
+// throw new IOException("image save failed.");
+// }
+// }
+
+
+ protected String[] saveImageFormats;
+
+ /**
+ * 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.
+ */
+ public boolean save(String path) { // ignore
+ boolean success = false;
+
+ // Make sure the pixel data is ready to go
+ loadPixels();
+
+ try {
+ OutputStream output =
+ new BufferedOutputStream(parent.createOutput(path), 16 * 1024);
+
+ String lower = path.toLowerCase();
+ String extension = lower.substring(lower.lastIndexOf('.') + 1);
+ if (extension.equals("jpg") || extension.equals("jpeg")) {
+ // TODO probably not necessary to create another bitmap
+ Bitmap outgoing = Bitmap.createBitmap(pixels, width, height, Config.ARGB_8888);
+ success = outgoing.compress(CompressFormat.JPEG, 100, output);
+
+ } else if (extension.equals("png")) {
+ Bitmap outgoing = Bitmap.createBitmap(pixels, width, height, Config.ARGB_8888);
+ success = outgoing.compress(CompressFormat.PNG, 100, output);
+
+ } else if (extension.equals("tga")) {
+ success = saveTGA(output); //, pixels, width, height, format);
+
+ } else {
+ if (!extension.equals("tif") && !extension.equals("tiff")) {
+ // if no .tif extension, add it..
+ path += ".tif";
+ }
+ success = saveTIFF(output);
+ }
+ output.flush();
+ output.close();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ if (!success) {
+ System.err.println("Could not write the image to " + path);
+ }
+ return success;
+ }
+}
diff --git a/core-androidx/src/processing/core/PMatrix.java b/core-androidx/src/processing/core/PMatrix.java
new file mode 100644
index 000000000..52e14a823
--- /dev/null
+++ b/core-androidx/src/processing/core/PMatrix.java
@@ -0,0 +1,170 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2005-12 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+
+public interface PMatrix {
+
+ public void reset();
+
+ /**
+ * Returns a copy of this PMatrix.
+ */
+ public PMatrix get();
+
+ /**
+ * Copies the matrix contents into a float array.
+ * If target is null (or not the correct size), a new array will be created.
+ */
+ public float[] get(float[] target);
+
+
+ public void set(PMatrix src);
+
+ public void set(float[] source);
+
+ public void set(float m00, float m01, float m02,
+ float m10, float m11, float m12);
+
+ public void set(float m00, float m01, float m02, float m03,
+ float m10, float m11, float m12, float m13,
+ float m20, float m21, float m22, float m23,
+ float m30, float m31, float m32, float m33);
+
+
+ public void translate(float tx, float ty);
+
+ public void translate(float tx, float ty, float tz);
+
+ public void rotate(float angle);
+
+ public void rotateX(float angle);
+
+ public void rotateY(float angle);
+
+ public void rotateZ(float angle);
+
+ public void rotate(float angle, float v0, float v1, float v2);
+
+ public void scale(float s);
+
+ public void scale(float sx, float sy);
+
+ public void scale(float x, float y, float z);
+
+ public void shearX(float angle);
+
+ public void shearY(float angle);
+
+ /**
+ * Multiply this matrix by another.
+ */
+ public void apply(PMatrix source);
+
+ public void apply(PMatrix2D source);
+
+ public void apply(PMatrix3D source);
+
+ public void apply(float n00, float n01, float n02,
+ float n10, float n11, float n12);
+
+ public void apply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33);
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(PMatrix left);
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(PMatrix2D left);
+
+ /**
+ * Apply another matrix to the left of this one. 3D only.
+ */
+ public void preApply(PMatrix3D left);
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(float n00, float n01, float n02,
+ float n10, float n11, float n12);
+
+ /**
+ * Apply another matrix to the left of this one. 3D only.
+ */
+ public void preApply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33);
+
+
+ /**
+ * Multiply source by this matrix, and return the result.
+ * The result will be stored in target if target is non-null, and target
+ * will then be the matrix returned. This improves performance if you reuse
+ * target, so it's recommended if you call this many times in draw().
+ */
+ public PVector mult(PVector source, PVector target);
+
+
+ /**
+ * Multiply a multi-element vector against this matrix.
+ * Supplying and recycling a target array improves performance, so it's
+ * recommended if you call this many times in draw().
+ */
+ public float[] mult(float[] source, float[] target);
+
+
+// public float multX(float x, float y);
+// public float multY(float x, float y);
+
+// public float multX(float x, float y, float z);
+// public float multY(float x, float y, float z);
+// public float multZ(float x, float y, float z);
+
+
+ /**
+ * Transpose this matrix; rows become columns and columns rows.
+ */
+ public void transpose();
+
+
+ /**
+ * Invert this matrix. Will not necessarily succeed, because some matrices
+ * map more than one point to the same image point, and so are irreversible.
+ * @return true if successful
+ */
+ public boolean invert();
+
+
+ /**
+ * @return the determinant of the matrix
+ */
+ public float determinant();
+}
\ No newline at end of file
diff --git a/core-androidx/src/processing/core/PMatrix2D.java b/core-androidx/src/processing/core/PMatrix2D.java
new file mode 100644
index 000000000..31226e78a
--- /dev/null
+++ b/core-androidx/src/processing/core/PMatrix2D.java
@@ -0,0 +1,467 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2005-12 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+
+/**
+ * 3x2 affine matrix implementation.
+ */
+public class PMatrix2D implements PMatrix {
+
+ public float m00, m01, m02;
+ public float m10, m11, m12;
+
+
+ public PMatrix2D() {
+ reset();
+ }
+
+
+ public PMatrix2D(float m00, float m01, float m02,
+ float m10, float m11, float m12) {
+ set(m00, m01, m02,
+ m10, m11, m12);
+ }
+
+
+ public PMatrix2D(PMatrix matrix) {
+ set(matrix);
+ }
+
+
+ public void reset() {
+ set(1, 0, 0,
+ 0, 1, 0);
+ }
+
+
+ /**
+ * Returns a copy of this PMatrix.
+ */
+ public PMatrix2D get() {
+ PMatrix2D outgoing = new PMatrix2D();
+ outgoing.set(this);
+ return outgoing;
+ }
+
+
+ /**
+ * Copies the matrix contents into a 6 entry float array.
+ * If target is null (or not the correct size), a new array will be created.
+ */
+ public float[] get(float[] target) {
+ if ((target == null) || (target.length != 6)) {
+ target = new float[6];
+ }
+ target[0] = m00;
+ target[1] = m01;
+ target[2] = m02;
+
+ target[3] = m10;
+ target[4] = m11;
+ target[5] = m12;
+
+ return target;
+ }
+
+
+ public void set(PMatrix matrix) {
+ if (matrix instanceof PMatrix2D) {
+ PMatrix2D src = (PMatrix2D) matrix;
+ set(src.m00, src.m01, src.m02,
+ src.m10, src.m11, src.m12);
+ } else {
+ throw new IllegalArgumentException("PMatrix2D.set() only accepts PMatrix2D objects.");
+ }
+ }
+
+
+ public void set(PMatrix3D src) {
+ }
+
+
+ public void set(float[] source) {
+ m00 = source[0];
+ m01 = source[1];
+ m02 = source[2];
+
+ m10 = source[3];
+ m11 = source[4];
+ m12 = source[5];
+ }
+
+
+ public void set(float m00, float m01, float m02,
+ float m10, float m11, float m12) {
+ this.m00 = m00; this.m01 = m01; this.m02 = m02;
+ this.m10 = m10; this.m11 = m11; this.m12 = m12;
+ }
+
+
+ public void set(float m00, float m01, float m02, float m03,
+ float m10, float m11, float m12, float m13,
+ float m20, float m21, float m22, float m23,
+ float m30, float m31, float m32, float m33) {
+
+ }
+
+
+ public void translate(float tx, float ty) {
+ m02 = tx*m00 + ty*m01 + m02;
+ m12 = tx*m10 + ty*m11 + m12;
+ }
+
+
+ public void translate(float x, float y, float z) {
+ throw new IllegalArgumentException("Cannot use translate(x, y, z) on a PMatrix2D.");
+ }
+
+
+ // Implementation roughly based on AffineTransform.
+ public void rotate(float angle) {
+ float s = sin(angle);
+ float c = cos(angle);
+
+ float temp1 = m00;
+ float temp2 = m01;
+ m00 = c * temp1 + s * temp2;
+ m01 = -s * temp1 + c * temp2;
+ temp1 = m10;
+ temp2 = m11;
+ m10 = c * temp1 + s * temp2;
+ m11 = -s * temp1 + c * temp2;
+ }
+
+
+ public void rotateX(float angle) {
+ throw new IllegalArgumentException("Cannot use rotateX() on a PMatrix2D.");
+ }
+
+
+ public void rotateY(float angle) {
+ throw new IllegalArgumentException("Cannot use rotateY() on a PMatrix2D.");
+ }
+
+
+ public void rotateZ(float angle) {
+ rotate(angle);
+ }
+
+
+ public void rotate(float angle, float v0, float v1, float v2) {
+ throw new IllegalArgumentException("Cannot use this version of rotate() on a PMatrix2D.");
+ }
+
+
+ public void scale(float s) {
+ scale(s, s);
+ }
+
+
+ public void scale(float sx, float sy) {
+ m00 *= sx; m01 *= sy;
+ m10 *= sx; m11 *= sy;
+ }
+
+
+ public void scale(float x, float y, float z) {
+ throw new IllegalArgumentException("Cannot use this version of scale() on a PMatrix2D.");
+ }
+
+
+ public void shearX(float angle) {
+ apply(1, 0, 1, tan(angle), 0, 0);
+ }
+
+
+ public void shearY(float angle) {
+ apply(1, 0, 1, 0, tan(angle), 0);
+ }
+
+
+ public void apply(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ apply((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ apply((PMatrix3D) source);
+ }
+ }
+
+
+ public void apply(PMatrix2D source) {
+ apply(source.m00, source.m01, source.m02,
+ source.m10, source.m11, source.m12);
+ }
+
+
+ public void apply(PMatrix3D source) {
+ throw new IllegalArgumentException("Cannot use apply(PMatrix3D) on a PMatrix2D.");
+ }
+
+
+ public void apply(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ float t0 = m00;
+ float t1 = m01;
+ m00 = n00 * t0 + n10 * t1;
+ m01 = n01 * t0 + n11 * t1;
+ m02 += n02 * t0 + n12 * t1;
+
+ t0 = m10;
+ t1 = m11;
+ m10 = n00 * t0 + n10 * t1;
+ m11 = n01 * t0 + n11 * t1;
+ m12 += n02 * t0 + n12 * t1;
+ }
+
+
+ public void apply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+ throw new IllegalArgumentException("Cannot use this version of apply() on a PMatrix2D.");
+ }
+
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ preApply((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ preApply((PMatrix3D) source);
+ }
+ }
+
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(PMatrix2D left) {
+ preApply(left.m00, left.m01, left.m02,
+ left.m10, left.m11, left.m12);
+ }
+
+
+ public void preApply(PMatrix3D left) {
+ throw new IllegalArgumentException("Cannot use preApply(PMatrix3D) on a PMatrix2D.");
+ }
+
+
+ public void preApply(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ float t0 = m02;
+ float t1 = m12;
+ n02 += t0 * n00 + t1 * n01;
+ n12 += t0 * n10 + t1 * n11;
+
+ m02 = n02;
+ m12 = n12;
+
+ t0 = m00;
+ t1 = m10;
+ m00 = t0 * n00 + t1 * n01;
+ m10 = t0 * n10 + t1 * n11;
+
+ t0 = m01;
+ t1 = m11;
+ m01 = t0 * n00 + t1 * n01;
+ m11 = t0 * n10 + t1 * n11;
+ }
+
+
+ public void preApply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+ throw new IllegalArgumentException("Cannot use this version of preApply() on a PMatrix2D.");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Multiply the x and y coordinates of a PVector against this matrix.
+ */
+ public PVector mult(PVector source, PVector target) {
+ if (target == null) {
+ target = new PVector();
+ }
+ target.x = m00*source.x + m01*source.y + m02;
+ target.y = m10*source.x + m11*source.y + m12;
+ return target;
+ }
+
+
+ /**
+ * Multiply a two element vector against this matrix.
+ * If out is null or not length four, a new float array will be returned.
+ * The values for vec and out can be the same (though that's less efficient).
+ */
+ public float[] mult(float vec[], float out[]) {
+ if (out == null || out.length != 2) {
+ out = new float[2];
+ }
+
+ if (vec == out) {
+ float tx = m00*vec[0] + m01*vec[1] + m02;
+ float ty = m10*vec[0] + m11*vec[1] + m12;
+
+ out[0] = tx;
+ out[1] = ty;
+
+ } else {
+ out[0] = m00*vec[0] + m01*vec[1] + m02;
+ out[1] = m10*vec[0] + m11*vec[1] + m12;
+ }
+
+ return out;
+ }
+
+
+ public float multX(float x, float y) {
+ return m00*x + m01*y + m02;
+ }
+
+
+ public float multY(float x, float y) {
+ return m10*x + m11*y + m12;
+ }
+
+
+ /**
+ * Transpose this matrix.
+ */
+ public void transpose() {
+ }
+
+
+ /**
+ * Invert this matrix. Implementation stolen from OpenJDK.
+ * @return true if successful
+ */
+ public boolean invert() {
+ float determinant = determinant();
+ if (Math.abs(determinant) <= Float.MIN_VALUE) {
+ return false;
+ }
+
+ float t00 = m00;
+ float t01 = m01;
+ float t02 = m02;
+ float t10 = m10;
+ float t11 = m11;
+ float t12 = m12;
+
+ m00 = t11 / determinant;
+ m10 = -t10 / determinant;
+ m01 = -t01 / determinant;
+ m11 = t00 / determinant;
+ m02 = (t01 * t12 - t11 * t02) / determinant;
+ m12 = (t10 * t02 - t00 * t12) / determinant;
+
+ return true;
+ }
+
+
+ /**
+ * @return the determinant of the matrix
+ */
+ public float determinant() {
+ return m00 * m11 - m01 * m10;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ public void print() {
+ int big = (int) abs(max(PApplet.max(abs(m00), abs(m01), abs(m02)),
+ PApplet.max(abs(m10), abs(m11), abs(m12))));
+
+ int digits = 1;
+ if (Float.isNaN(big) || Float.isInfinite(big)) { // avoid infinite loop
+ digits = 5;
+ } else {
+ while ((big /= 10) != 0) digits++; // cheap log()
+ }
+
+ System.out.println(PApplet.nfs(m00, digits, 4) + " " +
+ PApplet.nfs(m01, digits, 4) + " " +
+ PApplet.nfs(m02, digits, 4));
+
+ System.out.println(PApplet.nfs(m10, digits, 4) + " " +
+ PApplet.nfs(m11, digits, 4) + " " +
+ PApplet.nfs(m12, digits, 4));
+
+ System.out.println();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TODO these need to be added as regular API, but the naming and
+ // implementation needs to be improved first. (e.g. actually keeping track
+ // of whether the matrix is in fact identity internally.)
+
+
+ protected boolean isIdentity() {
+ return ((m00 == 1) && (m01 == 0) && (m02 == 0) &&
+ (m10 == 0) && (m11 == 1) && (m12 == 0));
+ }
+
+
+ // TODO make this more efficient, or move into PMatrix2D
+ protected boolean isWarped() {
+ // was &&, but changed so shearX and shearY will work
+ return ((m00 != 1) || (m01 != 0) ||
+ (m10 != 0) || (m11 != 1));
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ private final float max(float a, float b) {
+ return (a > b) ? a : b;
+ }
+
+ private final float abs(float a) {
+ return (a < 0) ? -a : a;
+ }
+
+ private final float sin(float angle) {
+ return (float)Math.sin(angle);
+ }
+
+ private final float cos(float angle) {
+ return (float)Math.cos(angle);
+ }
+
+ private final float tan(float angle) {
+ return (float)Math.tan(angle);
+ }
+}
diff --git a/core-androidx/src/processing/core/PMatrix3D.java b/core-androidx/src/processing/core/PMatrix3D.java
new file mode 100644
index 000000000..fbd662821
--- /dev/null
+++ b/core-androidx/src/processing/core/PMatrix3D.java
@@ -0,0 +1,806 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+ Copyright (c) 2005-12 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+
+/**
+ * 4x4 matrix implementation.
+ */
+public final class PMatrix3D implements PMatrix /*, PConstants*/ {
+
+ public float m00, m01, m02, m03;
+ public float m10, m11, m12, m13;
+ public float m20, m21, m22, m23;
+ public float m30, m31, m32, m33;
+
+
+ // locally allocated version to avoid creating new memory
+ protected PMatrix3D inverseCopy;
+
+
+ public PMatrix3D() {
+ reset();
+ }
+
+
+ public PMatrix3D(float m00, float m01, float m02,
+ float m10, float m11, float m12) {
+ set(m00, m01, m02, 0,
+ m10, m11, m12, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public PMatrix3D(float m00, float m01, float m02, float m03,
+ float m10, float m11, float m12, float m13,
+ float m20, float m21, float m22, float m23,
+ float m30, float m31, float m32, float m33) {
+ set(m00, m01, m02, m03,
+ m10, m11, m12, m13,
+ m20, m21, m22, m23,
+ m30, m31, m32, m33);
+ }
+
+
+ public PMatrix3D(PMatrix matrix) {
+ set(matrix);
+ }
+
+
+ public void reset() {
+ set(1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ /**
+ * Returns a copy of this PMatrix.
+ */
+ public PMatrix3D get() {
+ PMatrix3D outgoing = new PMatrix3D();
+ outgoing.set(this);
+ return outgoing;
+ }
+
+
+ /**
+ * Copies the matrix contents into a 16 entry float array.
+ * If target is null (or not the correct size), a new array will be created.
+ */
+ public float[] get(float[] target) {
+ if ((target == null) || (target.length != 16)) {
+ target = new float[16];
+ }
+ target[0] = m00;
+ target[1] = m01;
+ target[2] = m02;
+ target[3] = m03;
+
+ target[4] = m10;
+ target[5] = m11;
+ target[6] = m12;
+ target[7] = m13;
+
+ target[8] = m20;
+ target[9] = m21;
+ target[10] = m22;
+ target[11] = m23;
+
+ target[12] = m30;
+ target[13] = m31;
+ target[14] = m32;
+ target[15] = m33;
+
+ return target;
+ }
+
+
+ public void set(PMatrix matrix) {
+ if (matrix instanceof PMatrix3D) {
+ PMatrix3D src = (PMatrix3D) matrix;
+ set(src.m00, src.m01, src.m02, src.m03,
+ src.m10, src.m11, src.m12, src.m13,
+ src.m20, src.m21, src.m22, src.m23,
+ src.m30, src.m31, src.m32, src.m33);
+ } else {
+ PMatrix2D src = (PMatrix2D) matrix;
+ set(src.m00, src.m01, 0, src.m02,
+ src.m10, src.m11, 0, src.m12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+ }
+
+
+ public void set(float[] source) {
+ if (source.length == 6) {
+ set(source[0], source[1], source[2],
+ source[3], source[4], source[5]);
+
+ } else if (source.length == 16) {
+ m00 = source[0];
+ m01 = source[1];
+ m02 = source[2];
+ m03 = source[3];
+
+ m10 = source[4];
+ m11 = source[5];
+ m12 = source[6];
+ m13 = source[7];
+
+ m20 = source[8];
+ m21 = source[9];
+ m22 = source[10];
+ m23 = source[11];
+
+ m30 = source[12];
+ m31 = source[13];
+ m32 = source[14];
+ m33 = source[15];
+ }
+ }
+
+
+ public void set(float m00, float m01, float m02,
+ float m10, float m11, float m12) {
+ set(m00, m01, 0, m02,
+ m10, m11, 0, m12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void set(float m00, float m01, float m02, float m03,
+ float m10, float m11, float m12, float m13,
+ float m20, float m21, float m22, float m23,
+ float m30, float m31, float m32, float m33) {
+ this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03;
+ this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13;
+ this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23;
+ this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33;
+ }
+
+
+ public void translate(float tx, float ty) {
+ translate(tx, ty, 0);
+ }
+
+// public void invTranslate(float tx, float ty) {
+// invTranslate(tx, ty, 0);
+// }
+
+
+ public void translate(float tx, float ty, float tz) {
+ m03 += tx*m00 + ty*m01 + tz*m02;
+ m13 += tx*m10 + ty*m11 + tz*m12;
+ m23 += tx*m20 + ty*m21 + tz*m22;
+ m33 += tx*m30 + ty*m31 + tz*m32;
+ }
+
+
+ public void rotate(float angle) {
+ rotateZ(angle);
+ }
+
+
+ public void rotateX(float angle) {
+ float c = cos(angle);
+ float s = sin(angle);
+ apply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
+ }
+
+
+ public void rotateY(float angle) {
+ float c = cos(angle);
+ float s = sin(angle);
+ apply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
+ }
+
+
+ public void rotateZ(float angle) {
+ float c = cos(angle);
+ float s = sin(angle);
+ apply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
+ }
+
+
+ public void rotate(float angle, float v0, float v1, float v2) {
+ float norm2 = v0 * v0 + v1 * v1 + v2 * v2;
+ if (norm2 < PConstants.EPSILON) {
+ // The vector is zero, cannot apply rotation.
+ return;
+ }
+
+ if (Math.abs(norm2 - 1) > PConstants.EPSILON) {
+ // The rotation vector is not normalized.
+ float norm = PApplet.sqrt(norm2);
+ v0 /= norm;
+ v1 /= norm;
+ v2 /= norm;
+ }
+
+ float c = cos(angle);
+ float s = sin(angle);
+ float t = 1.0f - c;
+
+ apply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0,
+ (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0,
+ (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void scale(float s) {
+ //apply(s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1);
+ scale(s, s, s);
+ }
+
+
+ public void scale(float sx, float sy) {
+ //apply(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
+ scale(sx, sy, 1);
+ }
+
+
+ public void scale(float x, float y, float z) {
+ //apply(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
+ m00 *= x; m01 *= y; m02 *= z;
+ m10 *= x; m11 *= y; m12 *= z;
+ m20 *= x; m21 *= y; m22 *= z;
+ m30 *= x; m31 *= y; m32 *= z;
+ }
+
+
+ public void shearX(float angle) {
+ float t = (float) Math.tan(angle);
+ apply(1, t, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void shearY(float angle) {
+ float t = (float) Math.tan(angle);
+ apply(1, 0, 0, 0,
+ t, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void apply(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ apply((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ apply((PMatrix3D) source);
+ }
+ }
+
+
+ public void apply(PMatrix2D source) {
+ apply(source.m00, source.m01, 0, source.m02,
+ source.m10, source.m11, 0, source.m12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void apply(PMatrix3D source) {
+ apply(source.m00, source.m01, source.m02, source.m03,
+ source.m10, source.m11, source.m12, source.m13,
+ source.m20, source.m21, source.m22, source.m23,
+ source.m30, source.m31, source.m32, source.m33);
+ }
+
+
+ public void apply(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ apply(n00, n01, 0, n02,
+ n10, n11, 0, n12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void apply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+
+ float r00 = m00*n00 + m01*n10 + m02*n20 + m03*n30;
+ float r01 = m00*n01 + m01*n11 + m02*n21 + m03*n31;
+ float r02 = m00*n02 + m01*n12 + m02*n22 + m03*n32;
+ float r03 = m00*n03 + m01*n13 + m02*n23 + m03*n33;
+
+ float r10 = m10*n00 + m11*n10 + m12*n20 + m13*n30;
+ float r11 = m10*n01 + m11*n11 + m12*n21 + m13*n31;
+ float r12 = m10*n02 + m11*n12 + m12*n22 + m13*n32;
+ float r13 = m10*n03 + m11*n13 + m12*n23 + m13*n33;
+
+ float r20 = m20*n00 + m21*n10 + m22*n20 + m23*n30;
+ float r21 = m20*n01 + m21*n11 + m22*n21 + m23*n31;
+ float r22 = m20*n02 + m21*n12 + m22*n22 + m23*n32;
+ float r23 = m20*n03 + m21*n13 + m22*n23 + m23*n33;
+
+ float r30 = m30*n00 + m31*n10 + m32*n20 + m33*n30;
+ float r31 = m30*n01 + m31*n11 + m32*n21 + m33*n31;
+ float r32 = m30*n02 + m31*n12 + m32*n22 + m33*n32;
+ float r33 = m30*n03 + m31*n13 + m32*n23 + m33*n33;
+
+ m00 = r00; m01 = r01; m02 = r02; m03 = r03;
+ m10 = r10; m11 = r11; m12 = r12; m13 = r13;
+ m20 = r20; m21 = r21; m22 = r22; m23 = r23;
+ m30 = r30; m31 = r31; m32 = r32; m33 = r33;
+ }
+
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ preApply((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ preApply((PMatrix3D) source);
+ }
+ }
+
+
+ public void preApply(PMatrix2D left) {
+ preApply(left.m00, left.m01, 0, left.m02,
+ left.m10, left.m11, 0, left.m12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ public void preApply(PMatrix3D left) {
+ preApply(left.m00, left.m01, left.m02, left.m03,
+ left.m10, left.m11, left.m12, left.m13,
+ left.m20, left.m21, left.m22, left.m23,
+ left.m30, left.m31, left.m32, left.m33);
+ }
+
+
+ public void preApply(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ preApply(n00, n01, 0, n02,
+ n10, n11, 0, n12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void preApply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+
+ float r00 = n00*m00 + n01*m10 + n02*m20 + n03*m30;
+ float r01 = n00*m01 + n01*m11 + n02*m21 + n03*m31;
+ float r02 = n00*m02 + n01*m12 + n02*m22 + n03*m32;
+ float r03 = n00*m03 + n01*m13 + n02*m23 + n03*m33;
+
+ float r10 = n10*m00 + n11*m10 + n12*m20 + n13*m30;
+ float r11 = n10*m01 + n11*m11 + n12*m21 + n13*m31;
+ float r12 = n10*m02 + n11*m12 + n12*m22 + n13*m32;
+ float r13 = n10*m03 + n11*m13 + n12*m23 + n13*m33;
+
+ float r20 = n20*m00 + n21*m10 + n22*m20 + n23*m30;
+ float r21 = n20*m01 + n21*m11 + n22*m21 + n23*m31;
+ float r22 = n20*m02 + n21*m12 + n22*m22 + n23*m32;
+ float r23 = n20*m03 + n21*m13 + n22*m23 + n23*m33;
+
+ float r30 = n30*m00 + n31*m10 + n32*m20 + n33*m30;
+ float r31 = n30*m01 + n31*m11 + n32*m21 + n33*m31;
+ float r32 = n30*m02 + n31*m12 + n32*m22 + n33*m32;
+ float r33 = n30*m03 + n31*m13 + n32*m23 + n33*m33;
+
+ m00 = r00; m01 = r01; m02 = r02; m03 = r03;
+ m10 = r10; m11 = r11; m12 = r12; m13 = r13;
+ m20 = r20; m21 = r21; m22 = r22; m23 = r23;
+ m30 = r30; m31 = r31; m32 = r32; m33 = r33;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ public PVector mult(PVector source, PVector target) {
+ if (target == null) {
+ target = new PVector();
+ }
+ target.set(m00*source.x + m01*source.y + m02*source.z + m03,
+ m10*source.x + m11*source.y + m12*source.z + m13,
+ m20*source.x + m21*source.y + m22*source.z + m23);
+// float tw = m30*source.x + m31*source.y + m32*source.z + m33;
+// if (tw != 0 && tw != 1) {
+// target.div(tw);
+// }
+ return target;
+ }
+
+
+ /*
+ public PVector cmult(PVector source, PVector target) {
+ if (target == null) {
+ target = new PVector();
+ }
+ target.x = m00*source.x + m10*source.y + m20*source.z + m30;
+ target.y = m01*source.x + m11*source.y + m21*source.z + m31;
+ target.z = m02*source.x + m12*source.y + m22*source.z + m32;
+ float tw = m03*source.x + m13*source.y + m23*source.z + m33;
+ if (tw != 0 && tw != 1) {
+ target.div(tw);
+ }
+ return target;
+ }
+ */
+
+
+ /**
+ * Multiply a three or four element vector against this matrix. If out is
+ * null or not length 3 or 4, a new float array (length 3) will be returned.
+ */
+ public float[] mult(float[] source, float[] target) {
+ if (target == null || target.length < 3) {
+ target = new float[3];
+ }
+ if (source == target) {
+ throw new RuntimeException("The source and target vectors used in " +
+ "PMatrix3D.mult() cannot be identical.");
+ }
+ if (target.length == 3) {
+ target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03;
+ target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13;
+ target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23;
+ //float w = m30*source[0] + m31*source[1] + m32*source[2] + m33;
+ //if (w != 0 && w != 1) {
+ // target[0] /= w; target[1] /= w; target[2] /= w;
+ //}
+ } else if (target.length > 3) {
+ target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03*source[3];
+ target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13*source[3];
+ target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23*source[3];
+ target[3] = m30*source[0] + m31*source[1] + m32*source[2] + m33*source[3];
+ }
+ return target;
+ }
+
+
+ public float multX(float x, float y) {
+ return m00*x + m01*y + m03;
+ }
+
+
+ public float multY(float x, float y) {
+ return m10*x + m11*y + m13;
+ }
+
+
+ public float multX(float x, float y, float z) {
+ return m00*x + m01*y + m02*z + m03;
+ }
+
+
+ public float multY(float x, float y, float z) {
+ return m10*x + m11*y + m12*z + m13;
+ }
+
+
+ public float multZ(float x, float y, float z) {
+ return m20*x + m21*y + m22*z + m23;
+ }
+
+
+ public float multW(float x, float y, float z) {
+ return m30*x + m31*y + m32*z + m33;
+ }
+
+
+ public float multX(float x, float y, float z, float w) {
+ return m00*x + m01*y + m02*z + m03*w;
+ }
+
+
+ public float multY(float x, float y, float z, float w) {
+ return m10*x + m11*y + m12*z + m13*w;
+ }
+
+
+ public float multZ(float x, float y, float z, float w) {
+ return m20*x + m21*y + m22*z + m23*w;
+ }
+
+
+ public float multW(float x, float y, float z, float w) {
+ return m30*x + m31*y + m32*z + m33*w;
+ }
+
+
+ /**
+ * Transpose this matrix.
+ */
+ public void transpose() {
+ float temp;
+ temp = m01; m01 = m10; m10 = temp;
+ temp = m02; m02 = m20; m20 = temp;
+ temp = m03; m03 = m30; m30 = temp;
+ temp = m12; m12 = m21; m21 = temp;
+ temp = m13; m13 = m31; m31 = temp;
+ temp = m23; m23 = m32; m32 = temp;
+ }
+
+
+ /**
+ * Invert this matrix.
+ * @return true if successful
+ */
+ public boolean invert() {
+ float determinant = determinant();
+ if (determinant == 0) {
+ return false;
+ }
+
+ // first row
+ float t00 = determinant3x3(m11, m12, m13, m21, m22, m23, m31, m32, m33);
+ float t01 = -determinant3x3(m10, m12, m13, m20, m22, m23, m30, m32, m33);
+ float t02 = determinant3x3(m10, m11, m13, m20, m21, m23, m30, m31, m33);
+ float t03 = -determinant3x3(m10, m11, m12, m20, m21, m22, m30, m31, m32);
+
+ // second row
+ float t10 = -determinant3x3(m01, m02, m03, m21, m22, m23, m31, m32, m33);
+ float t11 = determinant3x3(m00, m02, m03, m20, m22, m23, m30, m32, m33);
+ float t12 = -determinant3x3(m00, m01, m03, m20, m21, m23, m30, m31, m33);
+ float t13 = determinant3x3(m00, m01, m02, m20, m21, m22, m30, m31, m32);
+
+ // third row
+ float t20 = determinant3x3(m01, m02, m03, m11, m12, m13, m31, m32, m33);
+ float t21 = -determinant3x3(m00, m02, m03, m10, m12, m13, m30, m32, m33);
+ float t22 = determinant3x3(m00, m01, m03, m10, m11, m13, m30, m31, m33);
+ float t23 = -determinant3x3(m00, m01, m02, m10, m11, m12, m30, m31, m32);
+
+ // fourth row
+ float t30 = -determinant3x3(m01, m02, m03, m11, m12, m13, m21, m22, m23);
+ float t31 = determinant3x3(m00, m02, m03, m10, m12, m13, m20, m22, m23);
+ float t32 = -determinant3x3(m00, m01, m03, m10, m11, m13, m20, m21, m23);
+ float t33 = determinant3x3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
+
+ // transpose and divide by the determinant
+ m00 = t00 / determinant;
+ m01 = t10 / determinant;
+ m02 = t20 / determinant;
+ m03 = t30 / determinant;
+
+ m10 = t01 / determinant;
+ m11 = t11 / determinant;
+ m12 = t21 / determinant;
+ m13 = t31 / determinant;
+
+ m20 = t02 / determinant;
+ m21 = t12 / determinant;
+ m22 = t22 / determinant;
+ m23 = t32 / determinant;
+
+ m30 = t03 / determinant;
+ m31 = t13 / determinant;
+ m32 = t23 / determinant;
+ m33 = t33 / determinant;
+
+ return true;
+ }
+
+
+ /**
+ * Calculate the determinant of a 3x3 matrix.
+ * @return result
+ */
+ private float determinant3x3(float t00, float t01, float t02,
+ float t10, float t11, float t12,
+ float t20, float t21, float t22) {
+ return (t00 * (t11 * t22 - t12 * t21) +
+ t01 * (t12 * t20 - t10 * t22) +
+ t02 * (t10 * t21 - t11 * t20));
+ }
+
+
+ /**
+ * @return the determinant of the matrix
+ */
+ public float determinant() {
+ float f =
+ m00
+ * ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32)
+ - m13 * m22 * m31
+ - m11 * m23 * m32
+ - m12 * m21 * m33);
+ f -= m01
+ * ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32)
+ - m13 * m22 * m30
+ - m10 * m23 * m32
+ - m12 * m20 * m33);
+ f += m02
+ * ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31)
+ - m13 * m21 * m30
+ - m10 * m23 * m31
+ - m11 * m20 * m33);
+ f -= m03
+ * ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31)
+ - m12 * m21 * m30
+ - m10 * m22 * m31
+ - m11 * m20 * m32);
+ return f;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // REVERSE VERSIONS OF MATRIX OPERATIONS
+
+ // These functions should not be used, as they will be removed in the future.
+
+
+ protected void invTranslate(float tx, float ty, float tz) {
+ preApply(1, 0, 0, -tx,
+ 0, 1, 0, -ty,
+ 0, 0, 1, -tz,
+ 0, 0, 0, 1);
+ }
+
+
+ protected void invRotateX(float angle) {
+ float c = cos(-angle);
+ float s = sin(-angle);
+ preApply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
+ }
+
+
+ protected void invRotateY(float angle) {
+ float c = cos(-angle);
+ float s = sin(-angle);
+ preApply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
+ }
+
+
+ protected void invRotateZ(float angle) {
+ float c = cos(-angle);
+ float s = sin(-angle);
+ preApply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
+ }
+
+
+ protected void invRotate(float angle, float v0, float v1, float v2) {
+ //TODO should make sure this vector is normalized
+
+ float c = cos(-angle);
+ float s = sin(-angle);
+ float t = 1.0f - c;
+
+ preApply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0,
+ (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0,
+ (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ protected void invScale(float x, float y, float z) {
+ preApply(1/x, 0, 0, 0, 0, 1/y, 0, 0, 0, 0, 1/z, 0, 0, 0, 0, 1);
+ }
+
+
+ protected boolean invApply(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+ if (inverseCopy == null) {
+ inverseCopy = new PMatrix3D();
+ }
+ inverseCopy.set(n00, n01, n02, n03,
+ n10, n11, n12, n13,
+ n20, n21, n22, n23,
+ n30, n31, n32, n33);
+ if (!inverseCopy.invert()) {
+ return false;
+ }
+ preApply(inverseCopy);
+ return true;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ public void print() {
+ /*
+ System.out.println(m00 + " " + m01 + " " + m02 + " " + m03 + "\n" +
+ m10 + " " + m11 + " " + m12 + " " + m13 + "\n" +
+ m20 + " " + m21 + " " + m22 + " " + m23 + "\n" +
+ m30 + " " + m31 + " " + m32 + " " + m33 + "\n");
+ */
+ int big = (int) Math.abs(max(max(max(max(abs(m00), abs(m01)),
+ max(abs(m02), abs(m03))),
+ max(max(abs(m10), abs(m11)),
+ max(abs(m12), abs(m13)))),
+ max(max(max(abs(m20), abs(m21)),
+ max(abs(m22), abs(m23))),
+ max(max(abs(m30), abs(m31)),
+ max(abs(m32), abs(m33))))));
+
+ int digits = 1;
+ if (Float.isNaN(big) || Float.isInfinite(big)) { // avoid infinite loop
+ digits = 5;
+ } else {
+ while ((big /= 10) != 0) digits++; // cheap log()
+ }
+
+ System.out.println(PApplet.nfs(m00, digits, 4) + " " +
+ PApplet.nfs(m01, digits, 4) + " " +
+ PApplet.nfs(m02, digits, 4) + " " +
+ PApplet.nfs(m03, digits, 4));
+
+ System.out.println(PApplet.nfs(m10, digits, 4) + " " +
+ PApplet.nfs(m11, digits, 4) + " " +
+ PApplet.nfs(m12, digits, 4) + " " +
+ PApplet.nfs(m13, digits, 4));
+
+ System.out.println(PApplet.nfs(m20, digits, 4) + " " +
+ PApplet.nfs(m21, digits, 4) + " " +
+ PApplet.nfs(m22, digits, 4) + " " +
+ PApplet.nfs(m23, digits, 4));
+
+ System.out.println(PApplet.nfs(m30, digits, 4) + " " +
+ PApplet.nfs(m31, digits, 4) + " " +
+ PApplet.nfs(m32, digits, 4) + " " +
+ PApplet.nfs(m33, digits, 4));
+
+ System.out.println();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ static private final float max(float a, float b) {
+ return (a > b) ? a : b;
+ }
+
+ static private final float abs(float a) {
+ return (a < 0) ? -a : a;
+ }
+
+ static private final float sin(float angle) {
+ return (float) Math.sin(angle);
+ }
+
+ static private final float cos(float angle) {
+ return (float) Math.cos(angle);
+ }
+}
diff --git a/core-androidx/src/processing/core/PShape.java b/core-androidx/src/processing/core/PShape.java
new file mode 100644
index 000000000..4703aab4b
--- /dev/null
+++ b/core-androidx/src/processing/core/PShape.java
@@ -0,0 +1,3571 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-19 The Processing Foundation
+ Copyright (c) 2006-12 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import processing.core.PApplet;
+
+
+/**
+ * ( begin auto-generated from PShape.xml )
+ *
+ * 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() function 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.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ *
+ * In-progress class to handle shape data, currently to be considered of
+ * alpha or beta quality. Major structural work may be performed on this class
+ * after the release of Processing 1.0. Such changes may include:
+ *
+ *
+ *
addition of proper accessors to read shape vertex and coloring data
+ * (this is the second most important part of having a PShape class after all).
+ *
a means of creating PShape objects ala beginShape() and endShape().
+ *
load(), update(), and cache methods ala PImage, so that shapes can
+ * have renderer-specific optimizations, such as vertex arrays in OpenGL.
+ *
splitting this class into multiple classes to handle different
+ * varieties of shape data (primitives vs collections of vertices vs paths)
+ *
change of package declaration, for instance moving the code into
+ * package processing.shape (if the code grows too much).
+ *
+ *
+ *
For the time being, this class and its shape() and loadShape() friends in
+ * PApplet exist as placeholders for more exciting things to come. If you'd
+ * like to work with this class, make a subclass (see how PShapeSVG works)
+ * and you can play with its internal methods all you like.
+ *
+ *
Library developers are encouraged to create PShape objects when loading
+ * shape data, so that they can eventually hook into the bounty that will be
+ * the PShape interface, and the ease of loadShape() and shape().
+ *
+ * @webref shape
+ * @usage Web & Application
+ * @see PApplet#loadShape(String)
+ * @see PApplet#createShape()
+ * @see PApplet#shapeMode(int)
+ * @instanceName sh any variable of type PShape
+ */
+public class PShape implements PConstants {
+ protected String name;
+ protected Map nameTable;
+
+// /** Generic, only draws its child objects. */
+// static public final int GROUP = 0;
+ // GROUP now inherited from PConstants, and is still zero
+
+ // These constants were updated in 3.0b6 so that they could be distinguished
+ // from others in PConstants and improve how some typos were handled.
+ // https://github.com/processing/processing/issues/3776
+ /** A line, ellipse, arc, image, etc. */
+ static public final int PRIMITIVE = 101;
+ /** A series of vertex, curveVertex, and bezierVertex calls. */
+ static public final int PATH = 102;
+ /** Collections of vertices created with beginShape(). */
+ static public final int GEOMETRY = 103;
+ /** The shape type, one of GROUP, PRIMITIVE, PATH, or GEOMETRY. */
+ protected int family;
+
+ /** ELLIPSE, LINE, QUAD; TRIANGLE_FAN, QUAD_STRIP; etc. */
+ protected int kind;
+
+ protected PMatrix matrix;
+
+ protected int textureMode;
+
+ /** Texture or image data associated with this shape. */
+ protected PImage image;
+ protected String imagePath = null;
+
+ public static final String OUTSIDE_BEGIN_END_ERROR =
+ "%1$s can only be called between beginShape() and endShape()";
+
+ public static final String INSIDE_BEGIN_END_ERROR =
+ "%1$s can only be called outside beginShape() and endShape()";
+
+ public static final String NO_SUCH_VERTEX_ERROR =
+ "%1$s vertex index does not exist";
+
+ static public final String NO_VERTICES_ERROR =
+ "getVertexCount() only works with PATH or GEOMETRY shapes";
+
+ public static final String NOT_A_SIMPLE_VERTEX =
+ "%1$s can not be called on quadratic or bezier vertices";
+
+ static public final String PER_VERTEX_UNSUPPORTED =
+ "This renderer does not support %1$s for individual vertices";
+
+ /**
+ * ( begin auto-generated from PShape_width.xml )
+ *
+ * The width of the PShape document.
+ *
+ * ( end auto-generated )
+ * @webref pshape:field
+ * @usage web_application
+ * @brief Shape document width
+ * @see PShape#height
+ */
+ public float width;
+ /**
+ * ( begin auto-generated from PShape_height.xml )
+ *
+ * The height of the PShape document.
+ *
+ * ( end auto-generated )
+ * @webref pshape:field
+ * @usage web_application
+ * @brief Shape document height
+ * @see PShape#width
+ */
+ public float height;
+
+ public float depth;
+
+ PGraphics g;
+
+ // set to false if the object is hidden in the layers palette
+ protected boolean visible = true;
+
+ /** Retained shape being created with beginShape/endShape */
+ protected boolean openShape = false;
+
+ protected boolean openContour = false;
+
+ protected boolean stroke;
+ protected int strokeColor;
+ protected float strokeWeight; // default is 1
+ protected int strokeCap;
+ protected int strokeJoin;
+
+ protected boolean fill;
+ protected int fillColor;
+
+ protected boolean tint;
+ protected int tintColor;
+
+ protected int ambientColor;
+ protected boolean setAmbient;
+ protected int specularColor;
+ protected int emissiveColor;
+ protected float shininess;
+
+ protected int sphereDetailU, sphereDetailV;
+ protected int rectMode;
+ protected int ellipseMode;
+
+ /** Temporary toggle for whether styles should be honored. */
+ protected boolean style = true;
+
+ /** For primitive shapes in particular, params like x/y/w/h or x1/y1/x2/y2. */
+ protected float[] params;
+
+ protected int vertexCount;
+ /**
+ * When drawing POLYGON shapes, the second param is an array of length
+ * VERTEX_FIELD_COUNT. When drawing PATH shapes, the second param has only
+ * two variables.
+ */
+ protected float[][] vertices;
+
+ protected PShape parent;
+ protected int childCount;
+ protected PShape[] children;
+
+
+ /** Array of VERTEX, BEZIER_VERTEX, and CURVE_VERTEX calls. */
+ protected int vertexCodeCount;
+ protected int[] vertexCodes;
+ /** True if this is a closed path. */
+ protected boolean close;
+
+ // ........................................................
+
+ // internal color for setting/calculating
+ protected float calcR, calcG, calcB, calcA;
+ protected int calcRi, calcGi, calcBi, calcAi;
+ protected int calcColor;
+ protected boolean calcAlpha;
+
+ /** 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;
+
+ /** True if contains 3D data */
+ protected boolean is3D = false;
+
+ protected boolean perVertexStyles = false;
+
+
+ // should this be called vertices (consistent with PGraphics internals)
+ // or does that hurt flexibility?
+
+
+ // POINTS, LINES, xLINE_STRIP, xLINE_LOOP
+ // TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN
+ // QUADS, QUAD_STRIP
+ // xPOLYGON
+// static final int PATH = 1; // POLYGON, LINE_LOOP, LINE_STRIP
+// static final int GROUP = 2;
+
+ // how to handle rectmode/ellipsemode?
+ // are they bitshifted into the constant?
+ // CORNER, CORNERS, CENTER, (CENTER_RADIUS?)
+// static final int RECT = 3; // could just be QUAD, but would be x1/y1/x2/y2
+// static final int ELLIPSE = 4;
+//
+// static final int VERTEX = 7;
+// static final int CURVE = 5;
+// static final int BEZIER = 6;
+
+
+ // fill and stroke functions will need a pointer to the parent
+ // PGraphics object.. may need some kind of createShape() fxn
+ // or maybe the values are stored until draw() is called?
+
+ // attaching images is very tricky.. it's a different type of data
+
+ // material parameters will be thrown out,
+ // except those currently supported (kinds of lights)
+
+ // pivot point for transformations
+// public float px;
+// public float py;
+
+
+ /**
+ * @nowebref
+ */
+ public PShape() {
+ this.family = GROUP;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public PShape(int family) {
+ this.family = family;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public PShape(PGraphics g, int family) {
+ this.g = g;
+ this.family = family;
+
+ // Style parameters are retrieved from the current values in the renderer.
+ textureMode = g.textureMode;
+
+ colorMode(g.colorMode,
+ g.colorModeX, g.colorModeY, g.colorModeZ, g.colorModeA);
+
+ // Initial values for fill, stroke and tint colors are also imported from
+ // the renderer. This is particular relevant for primitive shapes, since is
+ // not possible to set their color separately when creating them, and their
+ // input vertices are actually generated at rendering time, by which the
+ // color configuration of the renderer might have changed.
+ fill = g.fill;
+ fillColor = g.fillColor;
+
+ stroke = g.stroke;
+ strokeColor = g.strokeColor;
+ strokeWeight = g.strokeWeight;
+ strokeCap = g.strokeCap;
+ strokeJoin = g.strokeJoin;
+
+ tint = g.tint;
+ tintColor = g.tintColor;
+
+ setAmbient = g.setAmbient;
+ ambientColor = g.ambientColor;
+ specularColor = g.specularColor;
+ emissiveColor = g.emissiveColor;
+ shininess = g.shininess;
+
+ sphereDetailU = g.sphereDetailU;
+ sphereDetailV = g.sphereDetailV;
+
+// bezierDetail = pg.bezierDetail;
+// curveDetail = pg.curveDetail;
+// curveTightness = pg.curveTightness;
+
+ rectMode = g.rectMode;
+ ellipseMode = g.ellipseMode;
+
+// normalX = normalY = 0;
+// normalZ = 1;
+//
+// normalMode = NORMAL_MODE_AUTO;
+
+ // To make sure that the first vertex is marked as a break.
+ // Same behavior as in the immediate mode.
+// breakShape = false;
+
+ if (family == GROUP) {
+ // GROUP shapes are always marked as ended.
+// shapeCreated = true;
+ // TODO why was this commented out?
+ }
+ }
+
+
+ public PShape(PGraphics g, int kind, float... params) {
+ this(g, PRIMITIVE);
+ setKind(kind);
+ setParams(params);
+ }
+
+
+ public void setFamily(int family) {
+ this.family = family;
+ }
+
+
+ public void setKind(int kind) {
+ this.kind = kind;
+ }
+
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * ( begin auto-generated from PShape_isVisible.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Returns a boolean value "true" if the image is set to be visible, "false" if not
+ * @see PShape#setVisible(boolean)
+ */
+ public boolean isVisible() {
+ return visible;
+ }
+
+
+ /**
+ * ( begin auto-generated from PShape_setVisible.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @webref pshape:mathod
+ * @usage web_application
+ * @brief Sets the shape to be visible or invisible
+ * @param visible "false" makes the shape invisible and "true" makes it visible
+ * @see PShape#isVisible()
+ */
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+
+
+ /**
+ * ( begin auto-generated from PShape_disableStyle.xml )
+ *
+ * Disables the shape's style data and uses Processing's current styles.
+ * Styles include attributes such as colors, stroke weight, and stroke
+ * joints.
+ *
+ * ( end auto-generated )
+ *
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 pshape:method
+ * @usage web_application
+ * @brief Disables the shape's style data and uses Processing styles
+ * @see PShape#enableStyle()
+ */
+ public void disableStyle() {
+ style = false;
+
+ for (int i = 0; i < childCount; i++) {
+ children[i].disableStyle();
+ }
+ }
+
+
+ /**
+ * ( begin auto-generated from PShape_enableStyle.xml )
+ *
+ * Enables the shape's style data and ignores Processing's current styles.
+ * Styles include attributes such as colors, stroke weight, and stroke
+ * joints.
+ *
+ * ( end auto-generated )
+ *
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Enables the shape's style data and ignores the Processing styles
+ * @see PShape#disableStyle()
+ */
+ public void enableStyle() {
+ style = true;
+
+ for (int i = 0; i < childCount; i++) {
+ children[i].enableStyle();
+ }
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+// protected void checkBounds() {
+// if (width == 0 || height == 0) {
+// // calculate bounds here (also take kids into account)
+// width = 1;
+// height = 1;
+// }
+// }
+
+
+ /**
+ * Get the width of the drawing area (not necessarily the shape boundary).
+ */
+ public float getWidth() {
+ //checkBounds();
+ return width;
+ }
+
+
+ /**
+ * Get the height of the drawing area (not necessarily the shape boundary).
+ */
+ public float getHeight() {
+ //checkBounds();
+ return height;
+ }
+
+
+ /**
+ * Get the depth of the shape area (not necessarily the shape boundary). Only makes sense for 3D PShape subclasses,
+ * such as PShape3D.
+ */
+ public float getDepth() {
+ //checkBounds();
+ return depth;
+ }
+
+
+
+ /*
+ // TODO unapproved
+ protected PVector getTop() {
+ return getTop(null);
+ }
+
+
+ protected PVector getTop(PVector top) {
+ if (top == null) {
+ top = new PVector();
+ }
+ return top;
+ }
+
+
+ protected PVector getBottom() {
+ return getBottom(null);
+ }
+
+
+ protected PVector getBottom(PVector bottom) {
+ if (bottom == null) {
+ bottom = new PVector();
+ }
+ return bottom;
+ }
+ */
+
+
+ /**
+ * Return true if this shape is 2D. Defaults to true.
+ */
+ public boolean is2D() {
+ return !is3D;
+ }
+
+
+ /**
+ * Return true if this shape is 3D. Defaults to false.
+ */
+ public boolean is3D() {
+ return is3D;
+ }
+
+
+ public void set3D(boolean val) {
+ is3D = val;
+ }
+
+
+// /**
+// * Return true if this shape requires rendering through OpenGL. Defaults to false.
+// */
+// // TODO unapproved
+// public boolean isGL() {
+// return false;
+// }
+
+
+ ///////////////////////////////////////////////////////////
+
+ //
+
+ // Drawing methods
+
+ public void textureMode(int mode) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "textureMode()");
+ return;
+ }
+
+ textureMode = mode;
+ }
+
+ public void texture(PImage tex) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "texture()");
+ return;
+ }
+
+ image = tex;
+ }
+
+ public void noTexture() {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "noTexture()");
+ return;
+ }
+
+ image = null;
+ }
+
+
+ // TODO unapproved
+ protected void solid(boolean solid) {
+ }
+
+
+ /**
+ * @webref shape:vertex
+ * @brief Starts a new contour
+ * @see PShape#endContour()
+ */
+ public void beginContour() {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "beginContour()");
+ return;
+ }
+
+ if (family == GROUP) {
+ PGraphics.showWarning("Cannot begin contour in GROUP shapes");
+ return;
+ }
+
+ if (openContour) {
+ PGraphics.showWarning("Already called beginContour().");
+ return;
+ }
+ openContour = true;
+ beginContourImpl();
+ }
+
+
+ protected void beginContourImpl() {
+ if (vertexCodes == null) {
+ vertexCodes = new int[10];
+ } else if (vertexCodes.length == vertexCodeCount) {
+ vertexCodes = PApplet.expand(vertexCodes);
+ }
+ vertexCodes[vertexCodeCount++] = BREAK;
+ }
+
+
+ /**
+ * @webref shape:vertex
+ * @brief Ends a contour
+ * @see PShape#beginContour()
+ */
+ public void endContour() {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "endContour()");
+ return;
+ }
+
+ if (family == GROUP) {
+ PGraphics.showWarning("Cannot end contour in GROUP shapes");
+ return;
+ }
+
+ if (!openContour) {
+ PGraphics.showWarning("Need to call beginContour() first.");
+ return;
+ }
+ endContourImpl();
+ openContour = false;
+ }
+
+
+ protected void endContourImpl() {
+ }
+
+
+ public void vertex(float x, float y) {
+ if (vertices == null) {
+ vertices = new float[10][2];
+ } else if (vertices.length == vertexCount) {
+ vertices = (float[][]) PApplet.expand(vertices);
+ }
+ vertices[vertexCount++] = new float[] { x, y };
+
+ if (vertexCodes == null) {
+ vertexCodes = new int[10];
+ } else if (vertexCodes.length == vertexCodeCount) {
+ vertexCodes = PApplet.expand(vertexCodes);
+ }
+ vertexCodes[vertexCodeCount++] = VERTEX;
+
+ if (x > width) {
+ width = x;
+ }
+ if (y > height) {
+ height = y;
+ }
+ }
+
+
+ public void vertex(float x, float y, float u, float v) {
+ }
+
+
+ public void vertex(float x, float y, float z) {
+ vertex(x, y); // maybe? maybe not?
+ }
+
+
+ public void vertex(float x, float y, float z, float u, float v) {
+ }
+
+
+ public void normal(float nx, float ny, float nz) {
+ }
+
+
+ public void attribPosition(String name, float x, float y, float z) {
+ }
+
+ public void attribNormal(String name, float nx, float ny, float nz) {
+ }
+
+
+ public void attribColor(String name, int color) {
+ }
+
+
+ public void attrib(String name, float... values) {
+ }
+
+
+ public void attrib(String name, int... values) {
+ }
+
+
+ public void attrib(String name, boolean... values) {
+ }
+
+
+ /**
+ * @webref pshape:method
+ * @brief Starts the creation of a new PShape
+ * @see PApplet#endShape()
+ */
+ public void beginShape() {
+ beginShape(POLYGON);
+ }
+
+
+ public void beginShape(int kind) {
+ this.kind = kind;
+ openShape = true;
+ }
+
+ /**
+ * @webref pshape:method
+ * @brief Finishes the creation of a new PShape
+ * @see PApplet#beginShape()
+ */
+ public void endShape() {
+ endShape(OPEN);
+ }
+
+
+ public void endShape(int mode) {
+ if (family == GROUP) {
+ PGraphics.showWarning("Cannot end GROUP shape");
+ return;
+ }
+
+ if (!openShape) {
+ PGraphics.showWarning("Need to call beginShape() first");
+ return;
+ }
+
+ close = (mode==CLOSE);
+
+ // this is the state of the shape
+ openShape = false;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STROKE CAP/JOIN/WEIGHT
+
+
+ public void strokeWeight(float weight) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "strokeWeight()");
+ return;
+ }
+
+ strokeWeight = weight;
+ }
+
+ public void strokeJoin(int join) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "strokeJoin()");
+ return;
+ }
+
+ strokeJoin = join;
+ }
+
+ public void strokeCap(int cap) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "strokeCap()");
+ return;
+ }
+
+ strokeCap = cap;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILL COLOR
+
+
+ public void noFill() {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "noFill()");
+ return;
+ }
+
+ fill = false;
+ fillColor = 0x0;
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ public void fill(int rgb) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "fill()");
+ return;
+ }
+
+ fill = true;
+ colorCalc(rgb);
+ fillColor = calcColor;
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ public void fill(int rgb, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "fill()");
+ return;
+ }
+
+ fill = true;
+ colorCalc(rgb, alpha);
+ fillColor = calcColor;
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ public void fill(float gray) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "fill()");
+ return;
+ }
+
+ fill = true;
+ colorCalc(gray);
+ fillColor = calcColor;
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ public void fill(float gray, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "fill()");
+ return;
+ }
+
+ fill = true;
+ colorCalc(gray, alpha);
+ fillColor = calcColor;
+
+ if (!setAmbient) {
+ ambient(fillColor);
+ setAmbient = false;
+ }
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ public void fill(float x, float y, float z) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "fill()");
+ return;
+ }
+
+ fill = true;
+ colorCalc(x, y, z);
+ fillColor = calcColor;
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ public void fill(float x, float y, float z, float a) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "fill()");
+ return;
+ }
+
+ fill = true;
+ colorCalc(x, y, z, a);
+ fillColor = calcColor;
+
+ if (!setAmbient) {
+ ambientColor = fillColor;
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STROKE COLOR
+
+
+ public void noStroke() {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "noStroke()");
+ return;
+ }
+
+ stroke = false;
+ }
+
+
+ public void stroke(int rgb) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "stroke()");
+ return;
+ }
+
+ stroke = true;
+ colorCalc(rgb);
+ strokeColor = calcColor;
+ }
+
+
+ public void stroke(int rgb, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "stroke()");
+ return;
+ }
+
+ stroke = true;
+ colorCalc(rgb, alpha);
+ strokeColor = calcColor;
+ }
+
+
+ public void stroke(float gray) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "stroke()");
+ return;
+ }
+
+ stroke = true;
+ colorCalc(gray);
+ strokeColor = calcColor;
+ }
+
+
+ public void stroke(float gray, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "stroke()");
+ return;
+ }
+
+ stroke = true;
+ colorCalc(gray, alpha);
+ strokeColor = calcColor;
+ }
+
+
+ public void stroke(float x, float y, float z) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "stroke()");
+ return;
+ }
+
+ stroke = true;
+ colorCalc(x, y, z);
+ strokeColor = calcColor;
+ }
+
+
+ public void stroke(float x, float y, float z, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "stroke()");
+ return;
+ }
+
+ stroke = true;
+ colorCalc(x, y, z, alpha);
+ strokeColor = calcColor;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TINT COLOR
+
+
+ public void noTint() {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "noTint()");
+ return;
+ }
+
+ tint = false;
+ }
+
+
+ public void tint(int rgb) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "tint()");
+ return;
+ }
+
+ tint = true;
+ colorCalc(rgb);
+ tintColor = calcColor;
+ }
+
+
+ public void tint(int rgb, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "tint()");
+ return;
+ }
+
+ tint = true;
+ colorCalc(rgb, alpha);
+ tintColor = calcColor;
+ }
+
+
+ public void tint(float gray) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "tint()");
+ return;
+ }
+
+ tint = true;
+ colorCalc(gray);
+ tintColor = calcColor;
+ }
+
+
+ public void tint(float gray, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "tint()");
+ return;
+ }
+
+ tint = true;
+ colorCalc(gray, alpha);
+ tintColor = calcColor;
+ }
+
+
+ public void tint(float x, float y, float z) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "tint()");
+ return;
+ }
+
+ tint = true;
+ colorCalc(x, y, z);
+ tintColor = calcColor;
+ }
+
+
+ public void tint(float x, float y, float z, float alpha) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "tint()");
+ return;
+ }
+
+ tint = true;
+ colorCalc(x, y, z, alpha);
+ tintColor = calcColor;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // Ambient set/update
+
+ public void ambient(int rgb) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "ambient()");
+ return;
+ }
+
+ setAmbient = true;
+ colorCalc(rgb);
+ ambientColor = calcColor;
+ }
+
+
+ public void ambient(float gray) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "ambient()");
+ return;
+ }
+
+ setAmbient = true;
+ colorCalc(gray);
+ ambientColor = calcColor;
+ }
+
+
+ public void ambient(float x, float y, float z) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "ambient()");
+ return;
+ }
+
+ setAmbient = true;
+ colorCalc(x, y, z);
+ ambientColor = calcColor;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // Specular set/update
+
+ public void specular(int rgb) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "specular()");
+ return;
+ }
+
+ colorCalc(rgb);
+ specularColor = calcColor;
+ }
+
+
+ public void specular(float gray) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "specular()");
+ return;
+ }
+
+ colorCalc(gray);
+ specularColor = calcColor;
+ }
+
+
+ public void specular(float x, float y, float z) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "specular()");
+ return;
+ }
+
+ colorCalc(x, y, z);
+ specularColor = calcColor;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // Emissive set/update
+
+ public void emissive(int rgb) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "emissive()");
+ return;
+ }
+
+ colorCalc(rgb);
+ emissiveColor = calcColor;
+ }
+
+
+ public void emissive(float gray) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "emissive()");
+ return;
+ }
+
+ colorCalc(gray);
+ emissiveColor = calcColor;
+ }
+
+
+ public void emissive(float x, float y, float z) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "emissive()");
+ return;
+ }
+
+ colorCalc(x, y, z);
+ emissiveColor = calcColor;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // Shininess set/update
+
+ public void shininess(float shine) {
+ if (!openShape) {
+ PGraphics.showWarning(OUTSIDE_BEGIN_END_ERROR, "shininess()");
+ return;
+ }
+
+ shininess = shine;
+ }
+
+ ///////////////////////////////////////////////////////////
+
+ //
+
+ // Bezier curves
+
+
+ public void bezierDetail(int detail) {
+ }
+
+
+ public void bezierVertex(float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ if (vertices == null) {
+ vertices = new float[10][];
+ } else if (vertexCount + 2 >= vertices.length) {
+ vertices = (float[][]) PApplet.expand(vertices);
+ }
+ vertices[vertexCount++] = new float[] { x2, y2 };
+ vertices[vertexCount++] = new float[] { x3, y3 };
+ vertices[vertexCount++] = new float[] { x4, y4 };
+
+ // vertexCodes must be allocated because a vertex() call is required
+ if (vertexCodes.length == vertexCodeCount) {
+ vertexCodes = PApplet.expand(vertexCodes);
+ }
+ vertexCodes[vertexCodeCount++] = BEZIER_VERTEX;
+
+ if (x4 > width) {
+ width = x4;
+ }
+ if (y4 > height) {
+ height = y4;
+ }
+ }
+
+
+ public void bezierVertex(float x2, float y2, float z2,
+ float x3, float y3, float z3,
+ float x4, float y4, float z4) {
+ }
+
+
+ public void quadraticVertex(float cx, float cy,
+ float x3, float y3) {
+ if (vertices == null) {
+ vertices = new float[10][];
+ } else if (vertexCount + 1 >= vertices.length) {
+ vertices = (float[][]) PApplet.expand(vertices);
+ }
+ vertices[vertexCount++] = new float[] { cx, cy };
+ vertices[vertexCount++] = new float[] { x3, y3 };
+
+ // vertexCodes must be allocated because a vertex() call is required
+ if (vertexCodes.length == vertexCodeCount) {
+ vertexCodes = PApplet.expand(vertexCodes);
+ }
+ vertexCodes[vertexCodeCount++] = QUADRATIC_VERTEX;
+
+ if (x3 > width) {
+ width = x3;
+ }
+ if (y3 > height) {
+ height = y3;
+ }
+ }
+
+
+ public void quadraticVertex(float cx, float cy, float cz,
+ float x3, float y3, float z3) {
+ }
+
+
+ ///////////////////////////////////////////////////////////
+
+ //
+
+ // Catmull-Rom curves
+
+ public void curveDetail(int detail) {
+ }
+
+ public void curveTightness(float tightness) {
+ }
+
+ public void curveVertex(float x, float y) {
+ }
+
+ public void curveVertex(float x, float y, float z) {
+ }
+
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /*
+ boolean strokeSaved;
+ int strokeColorSaved;
+ float strokeWeightSaved;
+ int strokeCapSaved;
+ int strokeJoinSaved;
+
+ boolean fillSaved;
+ int fillColorSaved;
+
+ int rectModeSaved;
+ int ellipseModeSaved;
+ int shapeModeSaved;
+ */
+
+
+ protected void pre(PGraphics g) {
+ if (matrix != null) {
+ g.pushMatrix();
+ g.applyMatrix(matrix);
+ }
+
+ /*
+ strokeSaved = g.stroke;
+ strokeColorSaved = g.strokeColor;
+ strokeWeightSaved = g.strokeWeight;
+ strokeCapSaved = g.strokeCap;
+ strokeJoinSaved = g.strokeJoin;
+
+ fillSaved = g.fill;
+ fillColorSaved = g.fillColor;
+
+ rectModeSaved = g.rectMode;
+ ellipseModeSaved = g.ellipseMode;
+ shapeModeSaved = g.shapeMode;
+ */
+ if (style) {
+ g.pushStyle();
+ styles(g);
+ }
+ }
+
+
+ protected void styles(PGraphics g) {
+ // should not be necessary because using only the int version of color
+ //parent.colorMode(PConstants.RGB, 255);
+
+ if (stroke) {
+ g.stroke(strokeColor);
+ g.strokeWeight(strokeWeight);
+ g.strokeCap(strokeCap);
+ g.strokeJoin(strokeJoin);
+ } else {
+ g.noStroke();
+ }
+
+ if (fill) {
+ //System.out.println("filling " + PApplet.hex(fillColor));
+ g.fill(fillColor);
+ } else {
+ g.noFill();
+ }
+ }
+
+
+ protected void post(PGraphics g) {
+// for (int i = 0; i < childCount; i++) {
+// children[i].draw(g);
+// }
+
+ /*
+ // TODO this is not sufficient, since not saving fillR et al.
+ g.stroke = strokeSaved;
+ g.strokeColor = strokeColorSaved;
+ g.strokeWeight = strokeWeightSaved;
+ g.strokeCap = strokeCapSaved;
+ g.strokeJoin = strokeJoinSaved;
+
+ g.fill = fillSaved;
+ g.fillColor = fillColorSaved;
+
+ g.ellipseMode = ellipseModeSaved;
+ */
+
+ if (matrix != null) {
+ g.popMatrix();
+ }
+
+ if (style) {
+ g.popStyle();
+ }
+ }
+
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // Shape copy
+
+
+ // TODO unapproved
+ static protected PShape createShape(PApplet parent, PShape src) {
+ PShape dest = null;
+ if (src.family == GROUP) {
+ dest = parent.createShape(GROUP);
+ PShape.copyGroup(parent, src, dest);
+ } else if (src.family == PRIMITIVE) {
+ dest = parent.createShape(src.kind, src.params);
+ PShape.copyPrimitive(src, dest);
+ } else if (src.family == GEOMETRY) {
+ dest = parent.createShape(src.kind);
+ PShape.copyGeometry(src, dest);
+ } else if (src.family == PATH) {
+ dest = parent.createShape(PATH);
+ PShape.copyPath(src, dest);
+ }
+ dest.setName(src.name);
+ return dest;
+ }
+
+
+ // TODO unapproved
+ static protected void copyGroup(PApplet parent, PShape src, PShape dest) {
+ copyMatrix(src, dest);
+ copyStyles(src, dest);
+ copyImage(src, dest);
+ for (int i = 0; i < src.childCount; i++) {
+ PShape c = PShape.createShape(parent, src.children[i]);
+ dest.addChild(c);
+ }
+ }
+
+
+ // TODO unapproved
+ static protected void copyPrimitive(PShape src, PShape dest) {
+ copyMatrix(src, dest);
+ copyStyles(src, dest);
+ copyImage(src, dest);
+ }
+
+
+ // TODO unapproved
+ static protected void copyGeometry(PShape src, PShape dest) {
+ dest.beginShape(src.getKind());
+
+ copyMatrix(src, dest);
+ copyStyles(src, dest);
+ copyImage(src, dest);
+
+ if (src.style) {
+ for (int i = 0; i < src.vertexCount; i++) {
+ float[] vert = src.vertices[i];
+
+ dest.fill((int)(vert[PGraphics.A] * 255) << 24 |
+ (int)(vert[PGraphics.R] * 255) << 16 |
+ (int)(vert[PGraphics.G] * 255) << 8 |
+ (int)(vert[PGraphics.B] * 255));
+
+ // Do we need to copy these as well?
+// dest.ambient(vert[PGraphics.AR] * 255, vert[PGraphics.AG] * 255, vert[PGraphics.AB] * 255);
+// dest.specular(vert[PGraphics.SPR] * 255, vert[PGraphics.SPG] * 255, vert[PGraphics.SPB] * 255);
+// dest.emissive(vert[PGraphics.ER] * 255, vert[PGraphics.EG] * 255, vert[PGraphics.EB] * 255);
+// dest.shininess(vert[PGraphics.SHINE]);
+
+ if (0 < PApplet.dist(vert[PGraphics.NX],
+ vert[PGraphics.NY],
+ vert[PGraphics.NZ], 0, 0, 0)) {
+ dest.normal(vert[PGraphics.NX],
+ vert[PGraphics.NY],
+ vert[PGraphics.NZ]);
+ }
+ dest.vertex(vert[X], vert[Y], vert[Z],
+ vert[PGraphics.U],
+ vert[PGraphics.V]);
+ }
+ } else {
+ for (int i = 0; i < src.vertexCount; i++) {
+ float[] vert = src.vertices[i];
+ if (vert[Z] == 0) {
+ dest.vertex(vert[X], vert[Y]);
+ } else {
+ dest.vertex(vert[X], vert[Y], vert[Z]);
+ }
+ }
+ }
+
+ dest.endShape();
+ }
+
+
+ // TODO unapproved
+ static protected void copyPath(PShape src, PShape dest) {
+ copyMatrix(src, dest);
+ copyStyles(src, dest);
+ copyImage(src, dest);
+ dest.close = src.close;
+ dest.setPath(src.vertexCount, src.vertices, src.vertexCodeCount, src.vertexCodes);
+ }
+
+
+ // TODO unapproved
+ static protected void copyMatrix(PShape src, PShape dest) {
+ if (src.matrix != null) {
+ dest.applyMatrix(src.matrix);
+ }
+ }
+
+
+ // TODO unapproved
+ static protected void copyStyles(PShape src, PShape dest) {
+ dest.ellipseMode = src.ellipseMode;
+ dest.rectMode = src.rectMode;
+
+ if (src.stroke) {
+ dest.stroke = true;
+ dest.strokeColor = src.strokeColor;
+ dest.strokeWeight = src.strokeWeight;
+ dest.strokeCap = src.strokeCap;
+ dest.strokeJoin = src.strokeJoin;
+ } else {
+ dest.stroke = false;
+ }
+
+ if (src.fill) {
+ dest.fill = true;
+ dest.fillColor = src.fillColor;
+ } else {
+ dest.fill = false;
+ }
+ }
+
+
+ // TODO unapproved
+ static protected void copyImage(PShape src, PShape dest) {
+ if (src.image != null) {
+ dest.texture(src.image);
+ }
+ }
+
+
+
+ ////////////////////////////////////////////////////////////////////////
+
+
+ /**
+ * Called by the following (the shape() command adds the g)
+ * PShape s = loadShape("blah.svg");
+ * shape(s);
+ */
+ public void draw(PGraphics g) {
+ if (visible) {
+ pre(g);
+ drawImpl(g);
+ post(g);
+ }
+ }
+
+
+ /**
+ * Draws the SVG document.
+ */
+ protected void drawImpl(PGraphics g) {
+ if (family == GROUP) {
+ drawGroup(g);
+ } else if (family == PRIMITIVE) {
+ drawPrimitive(g);
+ } else if (family == GEOMETRY) {
+ // Not same as path: `kind` matters.
+// drawPath(g);
+ drawGeometry(g);
+ } else if (family == PATH) {
+ drawPath(g);
+ }
+ }
+
+
+ protected void drawGroup(PGraphics g) {
+ for (int i = 0; i < childCount; i++) {
+ children[i].draw(g);
+ }
+ }
+
+
+ protected void drawPrimitive(PGraphics g) {
+ if (kind == POINT) {
+ g.point(params[0], params[1]);
+
+ } else if (kind == LINE) {
+ if (params.length == 4) { // 2D
+ g.line(params[0], params[1],
+ params[2], params[3]);
+ } else { // 3D
+ g.line(params[0], params[1], params[2],
+ params[3], params[4], params[5]);
+ }
+
+ } else if (kind == TRIANGLE) {
+ g.triangle(params[0], params[1],
+ params[2], params[3],
+ params[4], params[5]);
+
+ } else if (kind == QUAD) {
+ g.quad(params[0], params[1],
+ params[2], params[3],
+ params[4], params[5],
+ params[6], params[7]);
+
+ } else if (kind == RECT) {
+
+ if (imagePath != null){
+ loadImage(g);
+ }
+ if (image != null) {
+ int oldMode = g.imageMode;
+ g.imageMode(CORNER);
+ g.image(image, params[0], params[1], params[2], params[3]);
+ g.imageMode(oldMode);
+ } else {
+ int oldMode = g.rectMode;
+ g.rectMode(rectMode);
+ if (params.length == 4) {
+ g.rect(params[0], params[1],
+ params[2], params[3]);
+ } else if (params.length == 5) {
+ g.rect(params[0], params[1],
+ params[2], params[3],
+ params[4]);
+ } else if (params.length == 8) {
+ g.rect(params[0], params[1],
+ params[2], params[3],
+ params[4], params[5],
+ params[6], params[7]);
+ }
+ g.rectMode(oldMode);
+ }
+ } else if (kind == ELLIPSE) {
+ int oldMode = g.ellipseMode;
+ g.ellipseMode(ellipseMode);
+ g.ellipse(params[0], params[1],
+ params[2], params[3]);
+ g.ellipseMode(oldMode);
+
+ } else if (kind == ARC) {
+ int oldMode = g.ellipseMode;
+ g.ellipseMode(ellipseMode);
+ if (params.length == 6) {
+ g.arc(params[0], params[1],
+ params[2], params[3],
+ params[4], params[5]);
+ } else if (params.length == 7) {
+ g.arc(params[0], params[1],
+ params[2], params[3],
+ params[4], params[5],
+ (int) params[6]);
+ }
+ g.ellipseMode(oldMode);
+
+ } else if (kind == BOX) {
+ if (params.length == 1) {
+ g.box(params[0]);
+ } else {
+ g.box(params[0], params[1], params[2]);
+ }
+
+ } else if (kind == SPHERE) {
+ g.sphere(params[0]);
+ }
+ }
+
+
+ protected void drawGeometry(PGraphics g) {
+ // get cache object using g.
+ g.beginShape(kind);
+ if (style) {
+ for (int i = 0; i < vertexCount; i++) {
+ g.vertex(vertices[i]);
+ }
+ } else {
+ for (int i = 0; i < vertexCount; i++) {
+ float[] vert = vertices[i];
+ if (vert[Z] == 0) {
+ g.vertex(vert[X], vert[Y]);
+ } else {
+ g.vertex(vert[X], vert[Y], vert[Z]);
+ }
+ }
+ }
+ g.endShape(close ? CLOSE : OPEN);
+ }
+
+
+ /*
+ protected void drawPath(PGraphics g) {
+ g.beginShape();
+ for (int j = 0; j < childCount; j++) {
+ if (j > 0) g.breakShape();
+ int count = children[j].vertexCount;
+ float[][] vert = children[j].vertices;
+ int[] code = children[j].vertexCodes;
+
+ for (int i = 0; i < count; i++) {
+ if (style) {
+ if (children[j].fill) {
+ g.fill(vert[i][R], vert[i][G], vert[i][B]);
+ } else {
+ g.noFill();
+ }
+ if (children[j].stroke) {
+ g.stroke(vert[i][R], vert[i][G], vert[i][B]);
+ } else {
+ g.noStroke();
+ }
+ }
+ g.edge(vert[i][EDGE] == 1);
+
+ if (code[i] == VERTEX) {
+ g.vertex(vert[i]);
+
+ } else if (code[i] == BEZIER_VERTEX) {
+ float z0 = vert[i+0][Z];
+ float z1 = vert[i+1][Z];
+ float z2 = vert[i+2][Z];
+ if (z0 == 0 && z1 == 0 && z2 == 0) {
+ g.bezierVertex(vert[i+0][X], vert[i+0][Y], z0,
+ vert[i+1][X], vert[i+1][Y], z1,
+ vert[i+2][X], vert[i+2][Y], z2);
+ } else {
+ g.bezierVertex(vert[i+0][X], vert[i+0][Y],
+ vert[i+1][X], vert[i+1][Y],
+ vert[i+2][X], vert[i+2][Y]);
+ }
+ } else if (code[i] == CURVE_VERTEX) {
+ float z = vert[i][Z];
+ if (z == 0) {
+ g.curveVertex(vert[i][X], vert[i][Y]);
+ } else {
+ g.curveVertex(vert[i][X], vert[i][Y], z);
+ }
+ }
+ }
+ }
+ g.endShape();
+ }
+ */
+
+ protected void drawPath(PGraphics g) {
+ // Paths might be empty (go figure)
+ // http://dev.processing.org/bugs/show_bug.cgi?id=982
+ if (vertices == null) return;
+
+ boolean insideContour = false;
+ g.beginShape();
+
+ if (vertexCodeCount == 0) { // each point is a simple vertex
+ if (vertices[0].length == 2) { // drawing 2D vertices
+ for (int i = 0; i < vertexCount; i++) {
+ g.vertex(vertices[i][X], vertices[i][Y]);
+ }
+ } else { // drawing 3D vertices
+ for (int i = 0; i < vertexCount; i++) {
+ g.vertex(vertices[i][X], vertices[i][Y], vertices[i][Z]);
+ }
+ }
+
+ } else { // coded set of vertices
+ int index = 0;
+
+ if (vertices[0].length == 2) { // drawing a 2D path
+ for (int j = 0; j < vertexCodeCount; j++) {
+ switch (vertexCodes[j]) {
+
+ case VERTEX:
+ g.vertex(vertices[index][X], vertices[index][Y]);
+ index++;
+ break;
+
+ case QUADRATIC_VERTEX:
+ g.quadraticVertex(vertices[index+0][X], vertices[index+0][Y],
+ vertices[index+1][X], vertices[index+1][Y]);
+ index += 2;
+ break;
+
+ case BEZIER_VERTEX:
+ g.bezierVertex(vertices[index+0][X], vertices[index+0][Y],
+ vertices[index+1][X], vertices[index+1][Y],
+ vertices[index+2][X], vertices[index+2][Y]);
+ index += 3;
+ break;
+
+ case CURVE_VERTEX:
+ g.curveVertex(vertices[index][X], vertices[index][Y]);
+ index++;
+ break;
+
+ case BREAK:
+ if (insideContour) {
+ g.endContour();
+ }
+ g.beginContour();
+ insideContour = true;
+ }
+ }
+ } else { // drawing a 3D path
+ for (int j = 0; j < vertexCodeCount; j++) {
+ switch (vertexCodes[j]) {
+
+ case VERTEX:
+ g.vertex(vertices[index][X], vertices[index][Y], vertices[index][Z]);
+ index++;
+ break;
+
+ case QUADRATIC_VERTEX:
+ g.quadraticVertex(vertices[index+0][X], vertices[index+0][Y], vertices[index+0][Z],
+ vertices[index+1][X], vertices[index+1][Y], vertices[index+0][Z]);
+ index += 2;
+ break;
+
+
+ case BEZIER_VERTEX:
+ g.bezierVertex(vertices[index+0][X], vertices[index+0][Y], vertices[index+0][Z],
+ vertices[index+1][X], vertices[index+1][Y], vertices[index+1][Z],
+ vertices[index+2][X], vertices[index+2][Y], vertices[index+2][Z]);
+ index += 3;
+ break;
+
+ case CURVE_VERTEX:
+ g.curveVertex(vertices[index][X], vertices[index][Y], vertices[index][Z]);
+ index++;
+ break;
+
+ case BREAK:
+ if (insideContour) {
+ g.endContour();
+ }
+ g.beginContour();
+ insideContour = true;
+ }
+ }
+ }
+ }
+ if (insideContour) {
+ g.endContour();
+ }
+ g.endShape(close ? CLOSE : OPEN);
+ }
+
+
+ private void loadImage(PGraphics g){
+ if (this.imagePath.startsWith("data:image")){
+ loadBase64Image();
+ }
+
+ if (this.imagePath.startsWith("file://")){
+ loadFileSystemImage(g);
+ }
+ this.imagePath = null;
+ }
+
+ private void loadFileSystemImage(PGraphics g){
+ imagePath = imagePath.substring(7);
+ PImage loadedImage = g.parent.loadImage(imagePath);
+ if (loadedImage == null){
+ System.err.println("Error loading image file: " + imagePath);
+ } else{
+ setTexture(loadedImage);
+ }
+ }
+
+ private void loadBase64Image(){
+ String[] parts = this.imagePath.split(";base64,");
+ String extension = parts[0].substring(11);
+ String encodedData = parts[1];
+
+// byte[] decodedBytes = DatatypeConverter.parseBase64Binary(encodedData);
+ byte[] decodedBytes = parseHexBinary(encodedData);
+
+ if(decodedBytes == null){
+ System.err.println("Decode Error on image: " + imagePath.substring(0, 20));
+ return;
+ }
+
+// Image awtImage = new ImageIcon(decodedBytes).getImage();
+ BitmapFactory.Options options = new BitmapFactory.Options();
+ options.inMutable = true;
+ Bitmap bmp = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, options);
+
+// if (awtImage instanceof BufferedImage) {
+// BufferedImage buffImage = (BufferedImage) awtImage;
+// int space = buffImage.getColorModel().getColorSpace().getType();
+// if (space == ColorSpace.TYPE_CMYK) {
+// return;
+// }
+// }
+
+ PImage loadedImage = new PImage(bmp);
+ if (loadedImage.width == -1) {
+ // error...
+ }
+
+ // if it's a .gif image, test to see if it has transparency
+ if (extension.equals("gif") || extension.equals("png") ||
+ extension.equals("unknown")) {
+ loadedImage.checkAlpha();
+ }
+
+ setTexture(loadedImage);
+ }
+
+
+ // Replacement for DatatypeConverter
+ // https://github.com/hierynomus/sshj/issues/366#issue-261511648
+ private static byte[] parseHexBinary(String s)
+ throws IllegalArgumentException {
+ if (s == null) {
+ return new byte[0];
+ }
+ s = s.trim();
+ int length = s.length();
+
+ if (length % 2 != 0) {
+ throw new IllegalArgumentException("Invalid hex string length.");
+ }
+
+ byte[] result = new byte[length / 2];
+ for (int i = 0; i < length; i += 2) {
+ result[i/2] = (byte) Integer.parseInt(s.substring(i, i + 2), 16);
+ }
+ return result;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public PShape getParent() {
+ return parent;
+ }
+
+ /**
+ * @webref
+ * @brief Returns the number of children
+ */
+ public int getChildCount() {
+ return childCount;
+ }
+
+
+ /** Resize the children[] array to be in line with childCount */
+ protected void crop() {
+ // https://github.com/processing/processing/issues/3347
+ if (children.length != childCount) {
+ children = (PShape[]) PApplet.subset(children, 0, childCount);
+ }
+ }
+
+
+ public PShape[] getChildren() {
+ crop();
+ return children;
+ }
+
+ /**
+ * ( begin auto-generated from PShape_getChild.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Returns a child element of a shape as a PShape object
+ * @param index the layer position of the shape to get
+ * @see PShape#addChild(PShape)
+ */
+ public PShape getChild(int index) {
+ crop();
+ return children[index];
+ }
+
+ /**
+ * @param target the name of the shape to get
+ */
+ public PShape getChild(String target) {
+ if (name != null && name.equals(target)) {
+ return this;
+ }
+ if (nameTable != null) {
+ PShape found = nameTable.get(target);
+ if (found != null) return found;
+ }
+ for (int i = 0; i < childCount; i++) {
+ PShape found = children[i].getChild(target);
+ if (found != null) return found;
+ }
+ return null;
+ }
+
+
+ /**
+ * Same as getChild(name), except that it first walks all the way up the
+ * hierarchy to the eldest grandparent, so that children can be found anywhere.
+ */
+ public PShape findChild(String target) {
+ if (parent == null) {
+ return getChild(target);
+
+ } else {
+ return parent.findChild(target);
+ }
+ }
+
+
+ // can't be just 'add' because that suggests additive geometry
+ /**
+ * @webref pshape:method
+ * @brief Adds a new child
+ * @param who any variable of type PShape
+ * @see PShape#getChild(int)
+ */
+ public void addChild(PShape who) {
+ if (children == null) {
+ children = new PShape[1];
+ }
+ if (childCount == children.length) {
+ children = (PShape[]) PApplet.expand(children);
+ }
+ children[childCount++] = who;
+ who.parent = this;
+
+ if (who.getName() != null) {
+ addName(who.getName(), who);
+ }
+ }
+
+
+ // adds child who exactly at position idx in the array of children.
+ /**
+ * @param idx the layer position in which to insert the new child
+ */
+ public void addChild(PShape who, int idx) {
+ if (idx < childCount) {
+ if (childCount == children.length) {
+ children = (PShape[]) PApplet.expand(children);
+ }
+
+ // Copy [idx, childCount - 1] to [idx + 1, childCount]
+ for (int i = childCount - 1; i >= idx; i--) {
+ children[i + 1] = children[i];
+ }
+ childCount++;
+
+ children[idx] = who;
+
+ who.parent = this;
+
+ if (who.getName() != null) {
+ addName(who.getName(), who);
+ }
+ }
+ }
+
+
+ /**
+ * Remove the child shape with index idx.
+ */
+ public void removeChild(int idx) {
+ if (idx < childCount) {
+ PShape child = children[idx];
+
+ // Copy [idx + 1, childCount - 1] to [idx, childCount - 2]
+ for (int i = idx; i < childCount - 1; i++) {
+ children[i] = children[i + 1];
+ }
+ childCount--;
+
+ if (child.getName() != null && nameTable != null) {
+ nameTable.remove(child.getName());
+ }
+ }
+ }
+
+
+ /**
+ * Add a shape to the name lookup table.
+ */
+ public void addName(String nom, PShape shape) {
+ if (parent != null) {
+ parent.addName(nom, shape);
+ } else {
+ if (nameTable == null) {
+ nameTable = new HashMap<>();
+ }
+ nameTable.put(nom, shape);
+ }
+ }
+
+
+ /**
+ * Returns the index of child who.
+ */
+ public int getChildIndex(PShape who) {
+ for (int i = 0; i < childCount; i++) {
+ if (children[i] == who) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+
+ public PShape getTessellation() {
+ return null;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /** The shape type, one of GROUP, PRIMITIVE, PATH, or GEOMETRY. */
+ public int getFamily() {
+ return family;
+ }
+
+
+ public int getKind() {
+ return kind;
+ }
+
+
+ public float[] getParams() {
+ return getParams(null);
+ }
+
+
+ public float[] getParams(float[] target) {
+ if (target == null || target.length != params.length) {
+ target = new float[params.length];
+ }
+ PApplet.arrayCopy(params, target);
+ return target;
+ }
+
+
+ public float getParam(int index) {
+ return params[index];
+ }
+
+
+ protected void setParams(float[] source) {
+ if (params == null) {
+ params = new float[source.length];
+ }
+ if (source.length != params.length) {
+ PGraphics.showWarning("Wrong number of parameters");
+ return;
+ }
+ PApplet.arrayCopy(source, params);
+ }
+
+
+ public void setPath(int vcount, float[][] verts) {
+ setPath(vcount, verts, 0, null);
+ }
+
+
+ protected void setPath(int vcount, float[][] verts, int ccount, int[] codes) {
+ if (verts == null || verts.length < vcount) return;
+ if (0 < ccount && (codes == null || codes.length < ccount)) return;
+
+ int ndim = verts[0].length;
+ vertexCount = vcount;
+ vertices = new float[vertexCount][ndim];
+ for (int i = 0; i < vertexCount; i++) {
+ PApplet.arrayCopy(verts[i], vertices[i]);
+ }
+
+ vertexCodeCount = ccount;
+ if (0 < vertexCodeCount) {
+ vertexCodes = new int[vertexCodeCount];
+ PApplet.arrayCopy(codes, vertexCodes, vertexCodeCount);
+ }
+ }
+
+ /**
+ * @webref pshape:method
+ * @brief Returns the total number of vertices as an int
+ * @see PShape#getVertex(int)
+ * @see PShape#setVertex(int, float, float)
+ */
+ public int getVertexCount() {
+ if (family == GROUP || family == PRIMITIVE) {
+ PGraphics.showWarning(NO_VERTICES_ERROR);
+ }
+ return vertexCount;
+ }
+
+
+ /**
+ * @webref pshape:method
+ * @brief Returns the vertex at the index position
+ * @param index the location of the vertex
+ * @see PShape#setVertex(int, float, float)
+ * @see PShape#getVertexCount()
+ */
+ public PVector getVertex(int index) {
+ return getVertex(index, null);
+ }
+
+
+ /**
+ * @param vec PVector to assign the data to
+ */
+ public PVector getVertex(int index, PVector vec) {
+ if (vec == null) {
+ vec = new PVector();
+ }
+ float[] vert = vertices[index];
+ vec.x = vert[X];
+ vec.y = vert[Y];
+ if (vert.length > 2) {
+ vec.z = vert[Z];
+ } else {
+ vec.z = 0; // in case this isn't a new vector
+ }
+ return vec;
+ }
+
+
+ public float getVertexX(int index) {
+ return vertices[index][X];
+ }
+
+
+ public float getVertexY(int index) {
+ return vertices[index][Y];
+ }
+
+
+ public float getVertexZ(int index) {
+ return vertices[index][Z];
+ }
+
+
+ /**
+ * @webref pshape:method
+ * @brief Sets the vertex at the index position
+ * @param index the location of the vertex
+ * @param x the x value for the vertex
+ * @param y the y value for the vertex
+ * @see PShape#getVertex(int)
+ * @see PShape#getVertexCount()
+ */
+ public void setVertex(int index, float x, float y) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setVertex()");
+ return;
+ }
+
+ vertices[index][X] = x;
+ vertices[index][Y] = y;
+ }
+
+
+ /**
+ * @param z the z value for the vertex
+ */
+ public void setVertex(int index, float x, float y, float z) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setVertex()");
+ return;
+ }
+
+ vertices[index][X] = x;
+ vertices[index][Y] = y;
+ vertices[index][Z] = z;
+ }
+
+
+ /**
+ * @param vec the PVector to define the x, y, z coordinates
+ */
+ public void setVertex(int index, PVector vec) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setVertex()");
+ return;
+ }
+
+ vertices[index][X] = vec.x;
+ vertices[index][Y] = vec.y;
+
+ if (vertices[index].length > 2) {
+ vertices[index][Z] = vec.z;
+ } else if (vec.z != 0 && vec.z == vec.z) {
+ throw new IllegalArgumentException("Cannot set a z-coordinate on a 2D shape");
+ }
+ }
+
+
+ public PVector getNormal(int index) {
+ return getNormal(index, null);
+ }
+
+
+ public PVector getNormal(int index, PVector vec) {
+ if (vec == null) {
+ vec = new PVector();
+ }
+ vec.x = vertices[index][PGraphics.NX];
+ vec.y = vertices[index][PGraphics.NY];
+ vec.z = vertices[index][PGraphics.NZ];
+ return vec;
+ }
+
+
+ public float getNormalX(int index) {
+ return vertices[index][PGraphics.NX];
+ }
+
+
+ public float getNormalY(int index) {
+ return vertices[index][PGraphics.NY];
+ }
+
+
+ public float getNormalZ(int index) {
+ return vertices[index][PGraphics.NZ];
+ }
+
+
+ public void setNormal(int index, float nx, float ny, float nz) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setNormal()");
+ return;
+ }
+
+ vertices[index][PGraphics.NX] = nx;
+ vertices[index][PGraphics.NY] = ny;
+ vertices[index][PGraphics.NZ] = nz;
+ }
+
+
+
+ public void setAttrib(String name, int index, float... values) {
+ }
+
+
+ public void setAttrib(String name, int index, int... values) {
+ }
+
+
+ public void setAttrib(String name, int index, boolean... values) {
+ }
+
+
+ public float getTextureU(int index) {
+ return vertices[index][PGraphics.U];
+ }
+
+
+ public float getTextureV(int index) {
+ return vertices[index][PGraphics.V];
+ }
+
+
+ public void setTextureUV(int index, float u, float v) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setTextureUV()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setTextureUV()");
+ return;
+ }
+
+
+ vertices[index][PGraphics.U] = u;
+ vertices[index][PGraphics.V] = v;
+ }
+
+
+ public void setTextureMode(int mode) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setTextureMode()");
+ return;
+ }
+
+ textureMode = mode;
+ }
+
+
+ public void setTexture(PImage tex) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setTexture()");
+ return;
+ }
+
+ image = tex;
+ }
+
+
+ public int getFill(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getFill()");
+ return fillColor;
+ }
+
+ if (image == null) {
+ int a = (int) (vertices[index][PGraphics.A] * 255);
+ int r = (int) (vertices[index][PGraphics.R] * 255);
+ int g = (int) (vertices[index][PGraphics.G] * 255);
+ int b = (int) (vertices[index][PGraphics.B] * 255);
+ return (a << 24) | (r << 16) | (g << 8) | b;
+ } else {
+ return 0;
+ }
+ }
+
+ /**
+ * @nowebref
+ */
+ public void setFill(boolean fill) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setFill()");
+ return;
+ }
+
+ this.fill = fill;
+ }
+
+
+ /**
+ * ( begin auto-generated from PShape_setFill.xml )
+ *
+ * The setFill() method defines the fill color of a PShape.
+ * This method is used after shapes are created or when a shape is defined explicitly
+ * (e.g. createShape(RECT, 20, 20, 80, 80)) as shown in the above example.
+ * When a shape is created with beginShape() and endShape(), its
+ * attributes may be changed with fill() and stroke() within
+ * beginShape() and endShape(). However, after the shape is
+ * created, only the setFill() method can define a new fill value for
+ * the PShape.
+ *
+ * ( end auto-generated )
+ *
+ * @webref
+ * @param fill
+ * @brief Set the fill value
+ */
+ public void setFill(int fill) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setFill()");
+ return;
+ }
+
+ this.fillColor = fill;
+
+ if (vertices != null && perVertexStyles) {
+ for (int i = 0; i < vertexCount; i++) {
+ setFill(i, fill);
+ }
+ }
+ }
+
+ /**
+ * @nowebref
+ */
+ public void setFill(int index, int fill) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setFill()");
+ return;
+ }
+
+ if (!perVertexStyles) {
+ PGraphics.showWarning(PER_VERTEX_UNSUPPORTED, "setFill()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getFill()");
+ return;
+ }
+
+ if (image == null) {
+ vertices[index][PGraphics.A] = ((fill >> 24) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.R] = ((fill >> 16) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.G] = ((fill >> 8) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.B] = ((fill >> 0) & 0xFF) / 255.0f;
+ }
+ }
+
+
+ public int getTint(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getTint()");
+ return this.tintColor;
+ }
+
+ if (image != null) {
+ int a = (int) (vertices[index][PGraphics.A] * 255);
+ int r = (int) (vertices[index][PGraphics.R] * 255);
+ int g = (int) (vertices[index][PGraphics.G] * 255);
+ int b = (int) (vertices[index][PGraphics.B] * 255);
+ return (a << 24) | (r << 16) | (g << 8) | b;
+ } else {
+ return 0;
+ }
+ }
+
+
+ public void setTint(boolean tint) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setTint()");
+ return;
+ }
+
+ this.tint = tint;
+ }
+
+
+ public void setTint(int fill) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setTint()");
+ return;
+ }
+
+ tintColor = fill;
+
+ if (vertices != null) {
+ for (int i = 0; i < vertices.length; i++) {
+ setFill(i, fill);
+ }
+ }
+ }
+
+
+ public void setTint(int index, int tint) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setTint()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setTint()");
+ return;
+ }
+
+ if (image != null) {
+ vertices[index][PGraphics.A] = ((tint >> 24) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.R] = ((tint >> 16) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.G] = ((tint >> 8) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.B] = ((tint >> 0) & 0xFF) / 255.0f;
+ }
+ }
+
+
+ public int getStroke(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getStroke()");
+ return strokeColor;
+ }
+
+ int a = (int) (vertices[index][PGraphics.SA] * 255);
+ int r = (int) (vertices[index][PGraphics.SR] * 255);
+ int g = (int) (vertices[index][PGraphics.SG] * 255);
+ int b = (int) (vertices[index][PGraphics.SB] * 255);
+ return (a << 24) | (r << 16) | (g << 8) | b;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public void setStroke(boolean stroke) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStroke()");
+ return;
+ }
+
+ this.stroke = stroke;
+ }
+
+
+ /**
+ * ( begin auto-generated from PShape_setStroke.xml )
+ *
+ * The setStroke() method defines the outline color of a PShape.
+ * This method is used after shapes are created or when a shape is defined
+ * explicitly (e.g. createShape(RECT, 20, 20, 80, 80)) as shown in
+ * the above example. When a shape is created with beginShape() and
+ * endShape(), its attributes may be changed with fill() and
+ * stroke() within beginShape() and endShape().
+ * However, after the shape is created, only the setStroke() method
+ * can define a new stroke value for the PShape.
+ *
+ * ( end auto-generated )
+ *
+ * @webref
+ * @param stroke
+ * @brief Set the stroke value
+ */
+ public void setStroke(int stroke) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStroke()");
+ return;
+ }
+
+ strokeColor = stroke;
+
+ if (vertices != null && perVertexStyles) {
+ for (int i = 0; i < vertices.length; i++) {
+ setStroke(i, stroke);
+ }
+ }
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public void setStroke(int index, int stroke) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStroke()");
+ return;
+ }
+
+ if (!perVertexStyles) {
+ PGraphics.showWarning(PER_VERTEX_UNSUPPORTED, "setStroke()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setStroke()");
+ return;
+ }
+
+ vertices[index][PGraphics.SA] = ((stroke >> 24) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.SR] = ((stroke >> 16) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.SG] = ((stroke >> 8) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.SB] = ((stroke >> 0) & 0xFF) / 255.0f;
+ }
+
+
+ public float getStrokeWeight(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getStrokeWeight()");
+ return strokeWeight;
+ }
+
+
+ return vertices[index][PGraphics.SW];
+ }
+
+
+ public void setStrokeWeight(float weight) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStrokeWeight()");
+ return;
+ }
+
+ strokeWeight = weight;
+
+ if (vertices != null && perVertexStyles) {
+ for (int i = 0; i < vertexCount; i++) {
+ setStrokeWeight(i, weight);
+ }
+ }
+ }
+
+
+ public void setStrokeWeight(int index, float weight) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStrokeWeight()");
+ return;
+ }
+
+ if (!perVertexStyles) {
+ PGraphics.showWarning(PER_VERTEX_UNSUPPORTED, "setStrokeWeight()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setStrokeWeight()");
+ return;
+ }
+
+ vertices[index][PGraphics.SW] = weight;
+ }
+
+
+ public void setStrokeJoin(int join) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStrokeJoin()");
+ return;
+ }
+
+ strokeJoin = join;
+ }
+
+
+ public void setStrokeCap(int cap) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setStrokeCap()");
+ return;
+ }
+
+ strokeCap = cap;
+ }
+
+
+ public int getAmbient(int index) {
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getAmbient()");
+ return ambientColor;
+ }
+
+ int r = (int) (vertices[index][PGraphics.AR] * 255);
+ int g = (int) (vertices[index][PGraphics.AG] * 255);
+ int b = (int) (vertices[index][PGraphics.AB] * 255);
+ return 0xff000000 | (r << 16) | (g << 8) | b;
+ }
+
+
+ public void setAmbient(int ambient) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setAmbient()");
+ return;
+ }
+
+ ambientColor = ambient;
+
+ if (vertices != null) {
+ for (int i = 0; i < vertices.length; i++) {
+ setAmbient(i, ambient);
+ }
+ }
+ }
+
+
+ public void setAmbient(int index, int ambient) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setAmbient()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setAmbient()");
+ return;
+ }
+
+ vertices[index][PGraphics.AR] = ((ambient >> 16) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.AG] = ((ambient >> 8) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.AB] = ((ambient >> 0) & 0xFF) / 255.0f;
+ }
+
+
+ public int getSpecular(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getSpecular()");
+ return specularColor;
+ }
+
+ int r = (int) (vertices[index][PGraphics.SPR] * 255);
+ int g = (int) (vertices[index][PGraphics.SPG] * 255);
+ int b = (int) (vertices[index][PGraphics.SPB] * 255);
+ return 0xff000000 | (r << 16) | (g << 8) | b;
+ }
+
+
+ public void setSpecular(int specular) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setSpecular()");
+ return;
+ }
+
+ specularColor = specular;
+
+ if (vertices != null) {
+ for (int i = 0; i < vertices.length; i++) {
+ setSpecular(i, specular);
+ }
+ }
+ }
+
+
+ public void setSpecular(int index, int specular) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setSpecular()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setSpecular()");
+ return;
+ }
+
+ vertices[index][PGraphics.SPR] = ((specular >> 16) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.SPG] = ((specular >> 8) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.SPB] = ((specular >> 0) & 0xFF) / 255.0f;
+ }
+
+
+ public int getEmissive(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null || index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getEmissive()");
+ return emissiveColor;
+ }
+
+ int r = (int) (vertices[index][PGraphics.ER] * 255);
+ int g = (int) (vertices[index][PGraphics.EG] * 255);
+ int b = (int) (vertices[index][PGraphics.EB] * 255);
+ return 0xff000000 | (r << 16) | (g << 8) | b;
+ }
+
+
+ public void setEmissive(int emissive) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setEmissive()");
+ return;
+ }
+
+ emissiveColor = emissive;
+
+ if (vertices != null) {
+ for (int i = 0; i < vertices.length; i++) {
+ setEmissive(i, emissive);
+ }
+ }
+ }
+
+
+ public void setEmissive(int index, int emissive) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setEmissive()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setEmissive()");
+ return;
+ }
+
+ vertices[index][PGraphics.ER] = ((emissive >> 16) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.EG] = ((emissive >> 8) & 0xFF) / 255.0f;
+ vertices[index][PGraphics.EB] = ((emissive >> 0) & 0xFF) / 255.0f;
+ }
+
+
+ public float getShininess(int index) {
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "getShininess()");
+ return shininess;
+ }
+
+ return vertices[index][PGraphics.SHINE];
+ }
+
+
+ public void setShininess(float shine) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setShininess()");
+ return;
+ }
+
+ shininess = shine;
+
+ if (vertices != null) {
+ for (int i = 0; i < vertices.length; i++) {
+ setShininess(i, shine);
+ }
+ }
+ }
+
+
+ public void setShininess(int index, float shine) {
+ if (openShape) {
+ PGraphics.showWarning(INSIDE_BEGIN_END_ERROR, "setShininess()");
+ return;
+ }
+
+ // make sure we allocated the vertices array and that vertex exists
+ if (vertices == null ||
+ index >= vertices.length) {
+ PGraphics.showWarning(NO_SUCH_VERTEX_ERROR + " (" + index + ")", "setShininess()");
+ return;
+ }
+
+
+ vertices[index][PGraphics.SHINE] = shine;
+ }
+
+
+ public int[] getVertexCodes() {
+ if (vertexCodes == null) {
+ return null;
+ }
+ if (vertexCodes.length != vertexCodeCount) {
+ vertexCodes = PApplet.subset(vertexCodes, 0, vertexCodeCount);
+ }
+ return vertexCodes;
+ }
+
+
+ public int getVertexCodeCount() {
+ return vertexCodeCount;
+ }
+
+
+ /**
+ * One of VERTEX, BEZIER_VERTEX, CURVE_VERTEX, or BREAK.
+ */
+ public int getVertexCode(int index) {
+ return vertexCodes[index];
+ }
+
+
+ public boolean isClosed() {
+ return close;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /**
+ * Return true if this x, y coordinate is part of this shape. Only works
+ * with PATH shapes or GROUP shapes that contain other GROUPs or PATHs.
+ */
+ public boolean contains(float x, float y) {
+ if (family == PATH) {
+ PVector p = new PVector(x, y);
+ if (matrix != null) {
+ // apply the inverse transformation matrix to the point coordinates
+ PMatrix inverseCoords = matrix.get();
+ // TODO why is this called twice? [fry 190724]
+ // commit was https://github.com/processing/processing/commit/027fc7a4f8e8d0a435366eae754304eea282512a
+ inverseCoords.invert(); // maybe cache this?
+ inverseCoords.invert(); // maybe cache this?
+ inverseCoords.mult(new PVector(x, y), p);
+ }
+
+ // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
+ boolean c = false;
+ for (int i = 0, j = vertexCount-1; i < vertexCount; j = i++) {
+ if (((vertices[i][Y] > p.y) != (vertices[j][Y] > p.y)) &&
+ (p.x <
+ (vertices[j][X]-vertices[i][X]) *
+ (y-vertices[i][Y]) /
+ (vertices[j][1]-vertices[i][Y]) +
+ vertices[i][X])) {
+ c = !c;
+ }
+ }
+ return c;
+
+ } else if (family == GROUP) {
+ // If this is a group, loop through children until we find one that
+ // contains the supplied coordinates. If a child does not support
+ // contains() throw a warning and continue.
+ for (int i = 0; i < childCount; i++) {
+ if (children[i].contains(x, y)) return true;
+ }
+ return false;
+
+ } else {
+ // https://github.com/processing/processing/issues/1280
+ throw new IllegalArgumentException("The contains() method is only implemented for paths.");
+ }
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ // translate, rotate, scale, apply (no push/pop)
+ // these each call matrix.translate, etc
+ // if matrix is null when one is called,
+ // it is created and set to identity
+
+
+/**
+ * ( begin auto-generated from PShape_translate.xml )
+ *
+ * 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
+ * parameter in combination with size.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Displaces the shape
+ * @param x left/right translation
+ * @param y up/down translation
+ * @see PShape#rotate(float)
+ * @see PShape#scale(float)
+ * @see PShape#resetMatrix()
+ */
+ public void translate(float x, float y) {
+ checkMatrix(2);
+ matrix.translate(x, y);
+ }
+
+ /**
+ * @param z forward/back translation
+ */
+ public void translate(float x, float y, float z) {
+ checkMatrix(3);
+ matrix.translate(x, y, z);
+ }
+
+ /**
+ * ( begin auto-generated from PShape_rotateX.xml )
+ *
+ * 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 use P3D as a third
+ * parameter for the size() function as shown in the example above.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Rotates the shape around the x-axis
+ * @param angle angle of rotation specified in radians
+ * @see PShape#rotate(float)
+ * @see PShape#rotateY(float)
+ * @see PShape#rotateZ(float)
+ * @see PShape#scale(float)
+ * @see PShape#translate(float, float)
+ * @see PShape#resetMatrix()
+ */
+ public void rotateX(float angle) {
+ rotate(angle, 1, 0, 0);
+ }
+
+ /**
+ * ( begin auto-generated from PShape_rotateY.xml )
+ *
+ * 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 use P3D as a third
+ * parameter for the size() function as shown in the example above.
+ *
+ * ( end auto-generated )
+ *
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Rotates the shape around the y-axis
+ * @param angle angle of rotation specified in radians
+ * @see PShape#rotate(float)
+ * @see PShape#rotateX(float)
+ * @see PShape#rotateZ(float)
+ * @see PShape#scale(float)
+ * @see PShape#translate(float, float)
+ * @see PShape#resetMatrix()
+ */
+ public void rotateY(float angle) {
+ rotate(angle, 0, 1, 0);
+ }
+
+
+ /**
+ * ( begin auto-generated from PShape_rotateZ.xml )
+ *
+ * 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 use P3D as a third
+ * parameter for the size() function as shown in the example above.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Rotates the shape around the z-axis
+ * @param angle angle of rotation specified in radians
+ * @see PShape#rotate(float)
+ * @see PShape#rotateX(float)
+ * @see PShape#rotateY(float)
+ * @see PShape#scale(float)
+ * @see PShape#translate(float, float)
+ * @see PShape#resetMatrix()
+ */
+ public void rotateZ(float angle) {
+ rotate(angle, 0, 0, 1);
+ }
+
+ /**
+ * ( begin auto-generated from PShape_rotate.xml )
+ *
+ * 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.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Rotates the shape
+ * @param angle angle of rotation specified in radians
+ * @see PShape#rotateX(float)
+ * @see PShape#rotateY(float)
+ * @see PShape#rotateZ(float)
+ * @see PShape#scale(float)
+ * @see PShape#translate(float, float)
+ * @see PShape#resetMatrix()
+ */
+ public void rotate(float angle) {
+ checkMatrix(2); // at least 2...
+ matrix.rotate(angle);
+ }
+
+/**
+ * @nowebref
+ */
+ public void rotate(float angle, float v0, float v1, float v2) {
+ checkMatrix(3);
+ float norm2 = v0 * v0 + v1 * v1 + v2 * v2;
+ if (Math.abs(norm2 - 1) > EPSILON) {
+ // The rotation vector is not normalized.
+ float norm = PApplet.sqrt(norm2);
+ v0 /= norm;
+ v1 /= norm;
+ v2 /= norm;
+ }
+ matrix.rotate(angle, v0, v1, v2);
+ }
+
+
+ //
+
+ /**
+ * ( begin auto-generated from PShape_scale.xml )
+ *
+ * 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 method with the z parameter requires using the P3D
+ * parameter in combination with size.
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @usage web_application
+ * @brief Increases and decreases the size of a shape
+ * @param s percentate to scale the object
+ * @see PShape#rotate(float)
+ * @see PShape#translate(float, float)
+ * @see PShape#resetMatrix()
+ */
+ public void scale(float s) {
+ checkMatrix(2); // at least 2...
+ matrix.scale(s);
+ }
+
+
+ public void scale(float x, float y) {
+ checkMatrix(2);
+ matrix.scale(x, y);
+ }
+
+/**
+ * @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
+ */
+ public void scale(float x, float y, float z) {
+ checkMatrix(3);
+ matrix.scale(x, y, z);
+ }
+
+
+ //
+
+/**
+ * ( begin auto-generated from PShape_resetMatrix.xml )
+ *
+ * Replaces the current matrix of a shape with the identity matrix. The
+ * equivalent function in OpenGL is glLoadIdentity().
+ *
+ * ( end auto-generated )
+ * @webref pshape:method
+ * @brief Replaces the current matrix of a shape with the identity matrix
+ * @usage web_application
+ * @see PShape#rotate(float)
+ * @see PShape#scale(float)
+ * @see PShape#translate(float, float)
+ */
+ public void resetMatrix() {
+ checkMatrix(2);
+ matrix.reset();
+ }
+
+
+ public void applyMatrix(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ applyMatrix((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ applyMatrix((PMatrix3D) source);
+ }
+ }
+
+
+ public void applyMatrix(PMatrix2D source) {
+ applyMatrix(source.m00, source.m01, 0, source.m02,
+ source.m10, source.m11, 0, source.m12,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+ }
+
+
+ public void applyMatrix(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ checkMatrix(2);
+ matrix.apply(n00, n01, n02,
+ n10, n11, n12);
+ }
+
+
+ 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);
+ }
+
+
+ public void applyMatrix(float n00, float n01, float n02, float n03,
+ float n10, float n11, float n12, float n13,
+ float n20, float n21, float n22, float n23,
+ float n30, float n31, float n32, float n33) {
+ checkMatrix(3);
+ matrix.apply(n00, n01, n02, n03,
+ n10, n11, n12, n13,
+ n20, n21, n22, n23,
+ n30, n31, n32, n33);
+ }
+
+
+ //
+
+
+ /**
+ * Make sure that the shape's matrix is 1) not null, and 2) has a matrix
+ * that can handle at least the specified number of dimensions.
+ */
+ protected void checkMatrix(int dimensions) {
+ if (matrix == null) {
+ if (dimensions == 2) {
+ matrix = new PMatrix2D();
+ } else {
+ matrix = new PMatrix3D();
+ }
+ } else if (dimensions == 3 && (matrix instanceof PMatrix2D)) {
+ // time for an upgrayedd for a double dose of my pimpin'
+ matrix = new PMatrix3D(matrix);
+ }
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /**
+ * Center the shape based on its bounding box. Can't assume
+ * that the bounding box is 0, 0, width, height. Common case will be
+ * opening a letter size document in Illustrator, and drawing something
+ * in the middle, then reading it in as an svg file.
+ * This will also need to flip the y axis (scale(1, -1)) in cases
+ * like Adobe Illustrator where the coordinates start at the bottom.
+ */
+// public void center() {
+// }
+
+
+ /**
+ * Set the pivot point for all transformations.
+ */
+// public void pivot(float x, float y) {
+// px = x;
+// py = y;
+// }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public void colorMode(int mode) {
+ colorMode(mode, colorModeX, colorModeY, colorModeZ, colorModeA);
+ }
+
+ /**
+ * @param max range for all color elements
+ */
+ public void colorMode(int mode, float max) {
+ colorMode(mode, max, max, max, max);
+ }
+
+
+ /**
+ * @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
+ */
+ public void colorMode(int mode, float maxX, float maxY, float maxZ) {
+ colorMode(mode, maxX, maxY, maxZ, colorModeA);
+ }
+
+/**
+ * @param maxA range for the alpha
+ */
+ 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);
+ }
+
+
+ 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);
+ }
+
+
+ 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 = calcAi / 255.0f;
+ calcR = calcRi / 255.0f;
+ calcG = calcGi / 255.0f;
+ calcB = calcBi / 255.0f;
+ calcAlpha = (calcAi != 255);
+ }
+
+}
diff --git a/core-androidx/src/processing/core/PShapeOBJ.java b/core-androidx/src/processing/core/PShapeOBJ.java
new file mode 100644
index 000000000..935634741
--- /dev/null
+++ b/core-androidx/src/processing/core/PShapeOBJ.java
@@ -0,0 +1,467 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-16 The Processing Foundation
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+/**
+ * This class is not part of the Processing API and should not be used
+ * directly. Instead, use loadShape() and methods like it, which will make
+ * use of this class. Using this class directly will cause your code to break
+ * when combined with future versions of Processing.
+ *
+ * OBJ loading implemented using code from Saito's OBJLoader library:
+ * http://code.google.com/p/saitoobjloader/
+ * and OBJReader from Ahmet Kizilay
+ * http://www.openprocessing.org/visuals/?visualID=191
+ *
+ */
+public class PShapeOBJ extends PShape {
+
+ /**
+ * Initializes a new OBJ Object with the given filename.
+ */
+ public PShapeOBJ(PApplet parent, String filename) {
+ this(parent, parent.createReader(filename), getBasePath(parent, filename));
+ }
+
+ public PShapeOBJ(PApplet parent, BufferedReader reader) {
+ this(parent, reader, "");
+ }
+
+ public PShapeOBJ(PApplet parent, BufferedReader reader, String basePath) {
+ ArrayList faces = new ArrayList();
+ ArrayList materials = new ArrayList();
+ ArrayList coords = new ArrayList();
+ ArrayList normals = new ArrayList();
+ ArrayList texcoords = new ArrayList();
+ parseOBJ(parent, basePath,
+ reader, faces, materials, coords, normals, texcoords);
+
+ // The OBJ geometry is stored with each face in a separate child shape.
+ parent = null;
+ family = GROUP;
+ addChildren(faces, materials, coords, normals, texcoords);
+ }
+
+
+ protected PShapeOBJ(OBJFace face, OBJMaterial mtl,
+ ArrayList coords,
+ ArrayList normals,
+ ArrayList texcoords) {
+ family = GEOMETRY;
+ if (face.vertIdx.size() == 3) {
+ kind = TRIANGLES;
+ } else if (face.vertIdx.size() == 4) {
+ kind = QUADS;
+ } else {
+ kind = POLYGON;
+ }
+
+ stroke = false;
+ fill = true;
+
+ // Setting material properties for the new face
+ fillColor = rgbaValue(mtl.kd);
+ ambientColor = rgbaValue(mtl.ka);
+ specularColor = rgbaValue(mtl.ks);
+ shininess = mtl.ns;
+ if (mtl.kdMap != null) {
+ // If current material is textured, then tinting the texture using the
+ // diffuse color.
+ tintColor = rgbaValue(mtl.kd, mtl.d);
+ }
+
+ vertexCount = face.vertIdx.size();
+ vertices = new float[vertexCount][12];
+ for (int j = 0; j < face.vertIdx.size(); j++){
+ int vertIdx, normIdx;
+ PVector vert, norms;
+
+ vert = norms = null;
+
+ vertIdx = face.vertIdx.get(j).intValue() - 1;
+ vert = coords.get(vertIdx);
+
+ if (j < face.normIdx.size()) {
+ normIdx = face.normIdx.get(j).intValue() - 1;
+ if (-1 < normIdx) {
+ norms = normals.get(normIdx);
+ }
+ }
+
+ vertices[j][X] = vert.x;
+ vertices[j][Y] = vert.y;
+ vertices[j][Z] = vert.z;
+
+ vertices[j][PGraphics.R] = mtl.kd.x;
+ vertices[j][PGraphics.G] = mtl.kd.y;
+ vertices[j][PGraphics.B] = mtl.kd.z;
+ vertices[j][PGraphics.A] = 1;
+
+ if (norms != null) {
+ vertices[j][PGraphics.NX] = norms.x;
+ vertices[j][PGraphics.NY] = norms.y;
+ vertices[j][PGraphics.NZ] = norms.z;
+ }
+
+ if (mtl != null && mtl.kdMap != null) {
+ // This face is textured.
+ int texIdx;
+ PVector tex = null;
+
+ if (j < face.texIdx.size()) {
+ texIdx = face.texIdx.get(j).intValue() - 1;
+ if (-1 < texIdx) {
+ tex = texcoords.get(texIdx);
+ }
+ }
+
+ image = mtl.kdMap;
+ if (tex != null) {
+ vertices[j][PGraphics.U] = tex.x;
+ vertices[j][PGraphics.V] = tex.y;
+ }
+ }
+ }
+ }
+
+
+ protected void addChildren(ArrayList faces,
+ ArrayList materials,
+ ArrayList coords,
+ ArrayList normals,
+ ArrayList texcoords) {
+ int mtlIdxCur = -1;
+ OBJMaterial mtl = null;
+ for (int i = 0; i < faces.size(); i++) {
+ OBJFace face = faces.get(i);
+
+ // Getting current material.
+ if (mtlIdxCur != face.matIdx || face.matIdx == -1) {
+ // To make sure that at least we get the default material
+ mtlIdxCur = PApplet.max(0, face.matIdx);
+ mtl = materials.get(mtlIdxCur);
+ }
+
+ // Creating child shape for current face.
+ PShape child = new PShapeOBJ(face, mtl, coords, normals, texcoords);
+ addChild(child);
+ }
+ }
+
+
+ static protected void parseOBJ(PApplet parent, String path,
+ BufferedReader reader,
+ ArrayList faces,
+ ArrayList materials,
+ ArrayList coords,
+ ArrayList normals,
+ ArrayList texcoords) {
+ Hashtable mtlTable = new Hashtable();
+ int mtlIdxCur = -1;
+ boolean readv, readvn, readvt;
+ try {
+
+ readv = readvn = readvt = false;
+ String line;
+ String gname = "object";
+ while ((line = reader.readLine()) != null) {
+ // Parse the line.
+ line = line.trim();
+ if (line.equals("") || line.indexOf('#') == 0) {
+ // Empty line of comment, ignore line
+ continue;
+ }
+
+ // The below patch/hack comes from Carlos Tomas Marti and is a
+ // fix for single backslashes in Rhino obj files
+
+ // BEGINNING OF RHINO OBJ FILES HACK
+ // Statements can be broken in multiple lines using '\' at the
+ // end of a line.
+ // In regular expressions, the backslash is also an escape
+ // character.
+ // The regular expression \\ matches a single backslash. This
+ // regular expression as a Java string, becomes "\\\\".
+ // That's right: 4 backslashes to match a single one.
+ while (line.contains("\\")) {
+ line = line.split("\\\\")[0];
+ final String s = reader.readLine();
+ if (s != null)
+ line += s;
+ }
+ // END OF RHINO OBJ FILES HACK
+
+ String[] parts = line.split("\\s+");
+ // if not a blank line, process the line.
+ if (parts.length > 0) {
+ if (parts[0].equals("v")) {
+ // vertex
+ PVector tempv = new PVector(Float.valueOf(parts[1]).floatValue(),
+ Float.valueOf(parts[2]).floatValue(),
+ Float.valueOf(parts[3]).floatValue());
+ coords.add(tempv);
+ readv = true;
+ } else if (parts[0].equals("vn")) {
+ // normal
+ PVector tempn = new PVector(Float.valueOf(parts[1]).floatValue(),
+ Float.valueOf(parts[2]).floatValue(),
+ Float.valueOf(parts[3]).floatValue());
+ normals.add(tempn);
+ readvn = true;
+ } else if (parts[0].equals("vt")) {
+ // uv, inverting v to take into account Processing's inverted Y axis
+ // with respect to OpenGL.
+ PVector tempv = new PVector(Float.valueOf(parts[1]).floatValue(),
+ 1 - Float.valueOf(parts[2]).floatValue());
+ texcoords.add(tempv);
+ readvt = true;
+ } else if (parts[0].equals("o")) {
+ // Object name is ignored, for now.
+ } else if (parts[0].equals("mtllib")) {
+ if (parts[1] != null) {
+ String fn = parts[1];
+ if (fn.indexOf(File.separator) == -1 && !path.equals("")) {
+ // Relative file name, adding the base path.
+ fn = path + File.separator + fn;
+ }
+ BufferedReader mreader = parent.createReader(fn);
+ if (mreader != null) {
+ parseMTL(parent, path,
+ mreader, materials, mtlTable);
+ }
+ }
+ } else if (parts[0].equals("g")) {
+ gname = 1 < parts.length ? parts[1] : "";
+ } else if (parts[0].equals("usemtl")) {
+ // Getting index of current active material (will be applied on
+ // all subsequent faces).
+ if (parts[1] != null) {
+ String mtlname = parts[1];
+ if (mtlTable.containsKey(mtlname)) {
+ Integer tempInt = mtlTable.get(mtlname);
+ mtlIdxCur = tempInt.intValue();
+ } else {
+ mtlIdxCur = -1;
+ }
+ }
+ } else if (parts[0].equals("f")) {
+ // Face setting
+ OBJFace face = new OBJFace();
+ face.matIdx = mtlIdxCur;
+ face.name = gname;
+
+ for (int i = 1; i < parts.length; i++) {
+ String seg = parts[i];
+
+ if (seg.indexOf("/") > 0) {
+ String[] forder = seg.split("/");
+
+ if (forder.length > 2) {
+ // Getting vertex and texture and normal indexes.
+ if (forder[0].length() > 0 && readv) {
+ face.vertIdx.add(Integer.valueOf(forder[0]));
+ }
+
+ if (forder[1].length() > 0 && readvt) {
+ face.texIdx.add(Integer.valueOf(forder[1]));
+ }
+
+ if (forder[2].length() > 0 && readvn) {
+ face.normIdx.add(Integer.valueOf(forder[2]));
+ }
+ } else if (forder.length > 1) {
+ // Getting vertex and texture/normal indexes.
+ if (forder[0].length() > 0 && readv) {
+ face.vertIdx.add(Integer.valueOf(forder[0]));
+ }
+
+ if (forder[1].length() > 0) {
+ if (readvt) {
+ face.texIdx.add(Integer.valueOf(forder[1]));
+ } else if (readvn) {
+ face.normIdx.add(Integer.valueOf(forder[1]));
+ }
+
+ }
+
+ } else if (forder.length > 0) {
+ // Getting vertex index only.
+ if (forder[0].length() > 0 && readv) {
+ face.vertIdx.add(Integer.valueOf(forder[0]));
+ }
+ }
+ } else {
+ // Getting vertex index only.
+ if (seg.length() > 0 && readv) {
+ face.vertIdx.add(Integer.valueOf(seg));
+ }
+ }
+ }
+
+ faces.add(face);
+ }
+ }
+ }
+
+ if (materials.size() == 0) {
+ // No materials definition so far. Adding one default material.
+ OBJMaterial defMtl = new OBJMaterial();
+ materials.add(defMtl);
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ static protected void parseMTL(PApplet parent, String path,
+ BufferedReader reader,
+ ArrayList materials,
+ Hashtable materialsHash) {
+ try {
+ String line;
+ OBJMaterial currentMtl = null;
+ while ((line = reader.readLine()) != null) {
+ // Parse the line
+ line = line.trim();
+ String parts[] = line.split("\\s+");
+ if (parts.length > 0) {
+ // Extract the material data.
+ if (parts[0].equals("newmtl")) {
+ // Starting new material.
+ String mtlname = parts[1];
+ currentMtl = new OBJMaterial(mtlname);
+ materialsHash.put(mtlname, new Integer(materials.size()));
+ materials.add(currentMtl);
+ } else if (parts[0].equals("map_Kd") && parts.length > 1) {
+ // Loading texture map.
+ String texname = parts[1];
+ if (texname.indexOf(File.separator) == -1 && !path.equals("")) {
+ // Relative file name, adding the base path.
+ texname = path + File.separator + texname;
+ }
+ currentMtl.kdMap = parent.loadImage(texname);
+ } else if (parts[0].equals("Ka") && parts.length > 3) {
+ // The ambient color of the material
+ currentMtl.ka.x = Float.valueOf(parts[1]).floatValue();
+ currentMtl.ka.y = Float.valueOf(parts[2]).floatValue();
+ currentMtl.ka.z = Float.valueOf(parts[3]).floatValue();
+ } else if (parts[0].equals("Kd") && parts.length > 3) {
+ // The diffuse color of the material
+ currentMtl.kd.x = Float.valueOf(parts[1]).floatValue();
+ currentMtl.kd.y = Float.valueOf(parts[2]).floatValue();
+ currentMtl.kd.z = Float.valueOf(parts[3]).floatValue();
+ } else if (parts[0].equals("Ks") && parts.length > 3) {
+ // The specular color weighted by the specular coefficient
+ currentMtl.ks.x = Float.valueOf(parts[1]).floatValue();
+ currentMtl.ks.y = Float.valueOf(parts[2]).floatValue();
+ currentMtl.ks.z = Float.valueOf(parts[3]).floatValue();
+ } else if ((parts[0].equals("d") ||
+ parts[0].equals("Tr")) && parts.length > 1) {
+ // Reading the alpha transparency.
+ currentMtl.d = Float.valueOf(parts[1]).floatValue();
+ } else if (parts[0].equals("Ns") && parts.length > 1) {
+ // The specular component of the Phong shading model
+ currentMtl.ns = Float.valueOf(parts[1]).floatValue();
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ protected static int rgbaValue(PVector color) {
+ return 0xFF000000 | ((int)(color.x * 255) << 16) |
+ ((int)(color.y * 255) << 8) |
+ (int)(color.z * 255);
+ }
+
+
+ protected static int rgbaValue(PVector color, float alpha) {
+ return ((int)(alpha * 255) << 24) |
+ ((int)(color.x * 255) << 16) |
+ ((int)(color.y * 255) << 8) |
+ (int)(color.z * 255);
+ }
+
+
+ // Stores a face from an OBJ file
+ static protected class OBJFace {
+ ArrayList vertIdx;
+ ArrayList texIdx;
+ ArrayList normIdx;
+ int matIdx;
+ String name;
+
+ OBJFace() {
+ vertIdx = new ArrayList();
+ texIdx = new ArrayList();
+ normIdx = new ArrayList();
+ matIdx = -1;
+ name = "";
+ }
+ }
+
+
+ static protected String getBasePath(PApplet parent, String filename) {
+ if (-1 < filename.indexOf(File.separator)) {
+ return filename.substring(0, filename.lastIndexOf(File.separator));
+ }
+ return "";
+ }
+
+
+ // Stores a material defined in an MTL file.
+ static protected class OBJMaterial {
+ String name;
+ PVector ka;
+ PVector kd;
+ PVector ks;
+ float d;
+ float ns;
+ PImage kdMap;
+
+ OBJMaterial() {
+ this("default");
+ }
+
+ OBJMaterial(String name) {
+ this.name = name;
+ ka = new PVector(0.5f, 0.5f, 0.5f);
+ kd = new PVector(0.5f, 0.5f, 0.5f);
+ ks = new PVector(0.5f, 0.5f, 0.5f);
+ d = 1.0f;
+ ns = 0.0f;
+ kdMap = null;
+ }
+ }
+}
+
diff --git a/core-androidx/src/processing/core/PShapeSVG.java b/core-androidx/src/processing/core/PShapeSVG.java
new file mode 100644
index 000000000..ce83a6951
--- /dev/null
+++ b/core-androidx/src/processing/core/PShapeSVG.java
@@ -0,0 +1,2031 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-19 The Processing Foundation
+ Copyright (c) 2006-12 Ben Fry and Casey Reas
+ Copyright (c) 2004-06 Michael Chang
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+//import static java.awt.Font.BOLD;
+//import static java.awt.Font.ITALIC;
+//import static java.awt.Font.PLAIN;
+import processing.data.*;
+
+// TODO replace these with PMatrix2D
+import android.graphics.Matrix;
+//import java.awt.geom.AffineTransform;
+//import java.awt.geom.Point2D;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+/**
+ * This class is not part of the Processing API and should not be used
+ * directly. Instead, use loadShape() and methods like it, which will make
+ * use of this class. Using this class directly will cause your code to break
+ * when combined with future versions of Processing.
+ *
+ * SVG stands for Scalable Vector Graphics, a portable graphics format.
+ * It is a vector format so it allows for "infinite" resolution and relatively
+ * small file sizes. Most modern media software can view SVG files, including
+ * Adobe products, Firefox, etc. Illustrator and Inkscape can edit SVG files.
+ * View the SVG specification here.
+ *
+ * We have no intention of turning this into a full-featured SVG library.
+ * The goal of this project is a basic shape importer that originally was small
+ * enough to be included with applets, meaning that its download size should be
+ * in the neighborhood of 25-30 Kb. Though we're far less limited nowadays on
+ * size constraints, we remain extremely limited in terms of time, and do not
+ * have volunteers who are available to maintain a larger SVG library.
+ *
+ * For more sophisticated import/export, consider the
+ * Batik
+ * library from the Apache Software Foundation.
+ *
+ * Batik is used in the SVG Export library in Processing 3, however using it
+ * for full SVG import is still a considerable amount of work. Wiring it to
+ * Java2D wouldn't be too bad, but using it with OpenGL, JavaFX, and features
+ * like begin/endRecord() and begin/endRaw() would be considerable effort.
+ *
+ * Future improvements to this library may focus on this properly supporting
+ * a specific subset of SVG, for instance the simpler SVG profiles known as
+ * SVG Tiny or Basic,
+ * although we still would not support the interactivity options.
+ *
+ *
+ *
+ * A minimal example program using SVG:
+ * (assuming a working moo.svg is in your data folder)
+ *
+ *
+ */
+public class PShapeSVG extends PShape {
+ XML element;
+
+ /// Values between 0 and 1.
+ protected float opacity;
+ float strokeOpacity;
+ float fillOpacity;
+
+ /** Width of containing SVG (used for percentages). */
+ protected float svgWidth;
+
+ /** Height of containing SVG (used for percentages). */
+ protected float svgHeight;
+
+ /** √((w² + h²)/2) of containing SVG (used for percentages). */
+ protected float svgSizeXY;
+
+ protected Gradient strokeGradient;
+ String strokeName; // id of another object, gradients only?
+
+ protected Gradient fillGradient;
+ String fillName; // id of another object
+
+
+ /**
+ * Initializes a new SVG object from the given XML object.
+ */
+ public PShapeSVG(XML svg) {
+ this(null, svg, true);
+
+ if (!svg.getName().equals("svg")) {
+ if (svg.getName().toLowerCase().equals("html")) {
+ // Common case is that files aren't downloaded properly
+ throw new RuntimeException("This appears to be a web page, not an SVG file.");
+ } else {
+ throw new RuntimeException("The root node is not