diff --git a/CHANGELOG.md b/CHANGELOG.md
index d792ec2..5518d3b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,5 @@
+**v2.9.0** No-one helped with think_open branch, that was trying to get ready for jdk9 (as compilable), so I'm abandoning 2.8.0 series, the 2.9.0 version will create an integrated jar and concentrate on compatibility, rather be future looking (but I'm not sure that think_different is any use or will work in future).
+
**v2.7.2** Slight re-factor of control_panel, fix virgin install of libraries folder, add grafica library examples suggest upgrade to jruby-9.1.17.0
**v2.7.1** Avoid calling protected method in control_panel (ready for jdk9)
diff --git a/README.md b/README.md
index 19f4421..1e50036 100644
--- a/README.md
+++ b/README.md
@@ -7,10 +7,10 @@ adjust above for your OS/distro setup.
## Requirements
-- jdk8+ (jdk9 mostly works, see changelog, but is noisy)
-- jruby-9.1.16.0
-- mvn-3.5.0+
-- processing-core.jar (_build only_) see [propane-core](https://github.com/ruby-processing/processing-core)
+- `jdk8_u172`
+- `jruby-9.1.16.0`
+- `mvn-3.5.0+`
+- `apple.jar` (_build only_) see [vanilla-processing](https://github.com/processing/processing/blob/master/core/apple.jar)
## Building and testing
@@ -23,7 +23,7 @@ rake javadoc
## Installation
```bash
jgem install propane # from rubygems
-jgem install propane-2.7.1-java.gem # local install requires a custom processing-core
+jgem install propane-2.9.0-java.gem # local install requires a custom processing-core
```
## Usage
diff --git a/Rakefile b/Rakefile
index f01bde5..e84abe6 100644
--- a/Rakefile
+++ b/Rakefile
@@ -7,7 +7,7 @@ def create_manifest
File.open('MANIFEST.MF', 'w') do |f|
f.puts(title)
f.puts(version)
- f.puts('Class-Path: processing-core.jar gluegen-rt-2.3.2.jar jog-all-2.3.2.jar')
+ f.puts('Class-Path: gluegen-rt-2.3.2.jar jog-all-2.3.2.jar')
end
end
@@ -21,7 +21,7 @@ end
desc 'Install'
task :install do
sh 'mvn dependency:copy'
- sh 'mv target/propane.jar lib'
+ sh 'mv target/propane-2.9.0.jar lib'
end
desc 'Gem'
diff --git a/lib/propane/version.rb b/lib/propane/version.rb
index d9306d9..9758341 100644
--- a/lib/propane/version.rb
+++ b/lib/propane/version.rb
@@ -1,4 +1,4 @@
# frozen_string_literal: true
module Propane
- VERSION = '2.7.2'.freeze
+ VERSION = '2.9.0'.freeze
end
diff --git a/license.txt b/license.txt
new file mode 100644
index 0000000..f9b24c5
--- /dev/null
+++ b/license.txt
@@ -0,0 +1,508 @@
+We use GPL v2 for the parts of the project that we've developed ourselves.
+For the 'core' library, it's LGPL, for everything else, it's GPL.
+
+Over the course of many years of development, files being moved around,
+and other code being added and removed, the license information has become
+quite a mess. Please help us clean this up so that others are properly
+credited and licenses are consistently/correctly noted:
+https://github.com/processing/processing/issues/224
+
+
+.....................................................................
+
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+
+.....................................................................
+
+
+the original document can be found at:
+http://oss.software.ibm.com/developerworks/opensource/license10.html
+
+
+IBM Public License Version 1.0
+
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS IBM
+PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
+THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
+
+
+1. DEFINITIONS
+
+"Contribution" means:
+
+a) in the case of International Business Machines Corporation ("IBM"),
+the Original Program, and
+
+b) in the case of each Contributor,
+
+i) changes to the Program, and
+
+ii) additions to the Program;
+where such changes and/or additions to the Program originate from and
+are distributed by that particular Contributor. A Contribution
+'originates' from a Contributor if it was added to the Program by such
+Contributor itself or anyone acting on such Contributor's
+behalf. Contributions do not include additions to the Program which:
+(i) are separate modules of software distributed in conjunction with
+the Program under their own license agreement, and (ii) are not
+derivative works of the Program.
+
+"Contributor" means IBM and any other entity that distributes the
+Program.
+
+"Licensed Patents " mean patent claims licensable by a Contributor
+which are necessarily infringed by the use or sale of its Contribution
+alone or when combined with the Program.
+
+
+"Original Program" means the original version of the software
+accompanying this Agreement as released by IBM, including source code,
+object code and documentation, if any.
+
+"Program" means the Original Program and Contributions.
+
+"Recipient" means anyone who receives the Program under this
+Agreement, including all Contributors.
+
+
+2. GRANT OF RIGHTS
+
+a) Subject to the terms of this Agreement, each Contributor hereby
+grants Recipient a non-exclusive, worldwide, royalty-free copyright
+license to reproduce, prepare derivative works of, publicly display,
+publicly perform, distribute and sublicense the Contribution of such
+Contributor, if any, and such derivative works, in source code and
+object code form.
+
+b) Subject to the terms of this Agreement, each Contributor hereby
+grants Recipient a non-exclusive, worldwide, royalty-free patent
+license under Licensed Patents to make, use, sell, offer to sell,
+import and otherwise transfer the Contribution of such Contributor, if
+any, in source code and object code form. This patent license shall
+apply to the combination of the Contribution and the Program if, at
+the time the Contribution is added by the Contributor, such addition
+of the Contribution causes such combination to be covered by the
+Licensed Patents. The patent license shall not apply to any other
+combinations which include the Contribution. No hardware per se is
+licensed hereunder.
+
+c) Recipient understands that although each Contributor grants the
+licenses to its Contributions set forth herein, no assurances are
+provided by any Contributor that the Program does not infringe the
+patent or other intellectual property rights of any other entity. Each
+Contributor disclaims any liability to Recipient for claims brought by
+any other entity based on infringement of intellectual property rights
+or otherwise. As a condition to exercising the rights and licenses
+granted hereunder, each Recipient hereby assumes sole responsibility
+to secure any other intellectual property rights needed, if any. For
+example, if a third party patent license is required to allow
+Recipient to distribute the Program, it is Recipient's responsibility
+to acquire that license before distributing the Program.
+
+d) Each Contributor represents that to its knowledge it has sufficient
+copyright rights in its Contribution, if any, to grant the copyright
+license set forth in this Agreement.
+
+
+3. REQUIREMENTS
+
+A Contributor may choose to distribute the Program in object code form
+under its own license agreement, provided that:
+
+a) it complies with the terms and conditions of this Agreement; and
+
+b) its license agreement:
+
+i) effectively disclaims on behalf of all Contributors all warranties
+and conditions, express and implied, including warranties or
+conditions of title and non-infringement, and implied warranties or
+conditions of merchantability and fitness for a particular purpose;
+
+ii) effectively excludes on behalf of all Contributors all liability
+for damages, including direct, indirect, special, incidental and
+consequential damages, such as lost profits;
+
+iii) states that any provisions which differ from this Agreement are
+offered by that Contributor alone and not by any other party; and
+
+iv) states that source code for the Program is available from such
+Contributor, and informs licensees how to obtain it in a reasonable
+manner on or through a medium customarily used for software exchange.
+
+When the Program is made available in source code form:
+a) it must be made available under this Agreement; and
+b) a copy of this Agreement must be included with each copy of the
+Program.
+
+Each Contributor must include the following in a conspicuous location
+in the Program:
+
+Copyright 2003, International Business Machines Corporation and
+others. All Rights Reserved.
+
+In addition, each Contributor must identify itself as the originator
+of its Contribution, if any, in a manner that reasonably allows
+subsequent Recipients to identify the originator of the Contribution.
+
+
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain
+responsibilities with respect to end users, business partners and the
+like. While this license is intended to facilitate the commercial use
+of the Program, the Contributor who includes the Program in a
+commercial product offering should do so in a manner which does not
+create potential liability for other Contributors. Therefore, if a
+Contributor includes the Program in a commercial product offering,
+such Contributor ("Commercial Contributor") hereby agrees to defend
+and indemnify every other Contributor ("Indemnified Contributor")
+against any losses, damages and costs (collectively "Losses") arising
+from claims, lawsuits and other legal actions brought by a third party
+against the Indemnified Contributor to the extent caused by the acts
+or omissions of such Commercial Contributor in connection with its
+distribution of the Program in a commercial product offering. The
+obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property
+infringement. In order to qualify, an Indemnified Contributor must: a)
+promptly notify the Commercial Contributor in writing of such claim,
+and b) allow the Commercial Contributor to control, and cooperate with
+the Commercial Contributor in, the defense and any related settlement
+negotiations. The Indemnified Contributor may participate in any such
+claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial
+product offering, Product X. That Contributor is then a Commercial
+Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance
+claims and warranties are such Commercial Contributor's responsibility
+alone. Under this section, the Commercial Contributor would have to
+defend claims against the other Contributors related to those
+performance claims and warranties, and if a court requires any other
+Contributor to pay any damages as a result, the Commercial Contributor
+must pay those damages.
+
+
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
+PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
+WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
+OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and
+distributing the Program and assumes all risks associated with its
+exercise of rights under this Agreement, including but not limited to
+the risks and costs of program errors, compliance with applicable
+laws, damage to or loss of data, programs or equipment, and
+unavailability or interruption of operations.
+
+
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
+ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
+WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
+DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
+HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under
+applicable law, it shall not affect the validity or enforceability of
+the remainder of the terms of this Agreement, and without further
+action by the parties hereto, such provision shall be reformed to the
+minimum extent necessary to make such provision valid and
+enforceable.
+
+If Recipient institutes patent litigation against a Contributor with
+respect to a patent applicable to software (including a cross-claim or
+counterclaim in a lawsuit), then any patent licenses granted by that
+Contributor to such Recipient under this Agreement shall terminate as
+of the date such litigation is filed. In addition, If Recipient
+institutes patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Program
+itself (excluding combinations of the Program with other software or
+hardware
diff --git a/pom.rb b/pom.rb
index fca2c78..3891043 100644
--- a/pom.rb
+++ b/pom.rb
@@ -1,17 +1,23 @@
require 'fileutils'
-project 'rp5extras', 'https://github.com/monkstone/propane' do
+project 'propane', 'https://github.com/monkstone/propane' do
model_version '4.0.0'
- id 'propane:propane', '2.7.2'
+ id 'propane:propane:2.9.0'
packaging 'jar'
- description 'rp5extras for propane'
+ description 'An integrated processing-core (somewhat hacked), with additional java code for a jruby version of processing.'
+
organization 'ruby-processing', 'https://ruby-processing.github.io'
- { 'monkstone' => 'Martin Prout' }.each do |key, value|
+
+ {
+ 'monkstone' => 'Martin Prout', 'benfry' => 'Ben Fry',
+ 'REAS' => 'Casey Reas', 'codeanticode' => 'Andres Colubri'
+ }.each do |key, value|
developer key do
name value
roles 'developer'
end
end
license 'GPL 3', 'http://www.gnu.org/licenses/gpl-3.0-standalone.html'
+ license 'LGPL 2', 'https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html'
issue_management 'https://github.com/ruby-processing/propane/issues', 'Github'
source_control(
@@ -100,8 +106,14 @@
end
build do
- default_goal 'package'
- source_directory 'src'
- final_name 'propane'
+ resource do
+ directory '${source.directory}/main/java'
+ includes ['**/**/*.glsl', '**/*.jnilib']
+ excludes '**/**/*.java'
+ end
+ resource do
+ directory '${source.directory}/main/resources'
+ includes ['**/*.png', '*.txt']
+ end
end
end
diff --git a/pom.xml b/pom.xml
index 615d619..b79fdf1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -11,9 +11,9 @@ DO NOT MODIFIY - GENERATED CODE
4.0.0propanepropane
- 2.7.2
- rp5extras
- rp5extras for propane
+ 2.9.0
+ propane
+ An integrated processing-core (somewhat hacked), with additional java code for a jruby version of processing.https://github.com/monkstone/propaneruby-processing
@@ -24,6 +24,10 @@ DO NOT MODIFIY - GENERATED CODE
GPL 3http://www.gnu.org/licenses/gpl-3.0-standalone.html
+
+ LGPL 2
+ https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
+
@@ -33,6 +37,27 @@ DO NOT MODIFIY - GENERATED CODE
developer
+
+ benfry
+ Ben Fry
+
+ developer
+
+
+
+ REAS
+ Casey Reas
+
+ developer
+
+
+
+ codeanticode
+ Andres Colubri
+
+ developer
+
+ scm:git:git://github.com/ruby-processing/propane.git
@@ -62,9 +87,9 @@ DO NOT MODIFIY - GENERATED CODE
pom
- org.processing
- core
- 3.3.7
+ com.apple.eawt
+ apple
+ 1.0org.processing
@@ -83,9 +108,25 @@ DO NOT MODIFIY - GENERATED CODE
- src
- package
- propane
+
+
+ ${source.directory}/main/java
+
+ **/**/*.glsl
+ **/*.jnilib
+
+
+ **/**/*.java
+
+
+
+ ${source.directory}/main/resources
+
+ **/*.png
+ *.txt
+
+
+
diff --git a/propane.gemspec b/propane.gemspec
index d886643..e292711 100644
--- a/propane.gemspec
+++ b/propane.gemspec
@@ -15,8 +15,7 @@ Gem::Specification.new do |gem|
gem.summary = %q{ruby wrapper for processing-3.4 on MacOS and linux64 bit only for opengl}
gem.homepage = 'https://ruby-processing.github.io/propane/'
gem.files = `git ls-files`.split($/)
- gem.files << 'lib/propane.jar'
- gem.files << 'lib/processing-core.jar'
+ gem.files << 'lib/propane-2.9.0.jar'
gem.files << 'lib/gluegen-rt-2.3.2.jar'
gem.files << 'lib/jogl-all-2.3.2.jar'
gem.files << 'lib/gluegen-rt-2.3.2-natives-linux-amd64.jar'
@@ -30,5 +29,5 @@ Gem::Specification.new do |gem|
gem.add_runtime_dependency 'arcball', '~> 1.0', '>= 1.0.0'
gem.require_paths = ['lib']
gem.platform = 'java'
- gem.requirements << 'java runtime >= 1.8.0_151+'
+ gem.requirements << 'java runtime >= 1.8.0_171+'
end
diff --git a/src/main/java/japplemenubar/JAppleMenuBar.java b/src/main/java/japplemenubar/JAppleMenuBar.java
new file mode 100644
index 0000000..148eed9
--- /dev/null
+++ b/src/main/java/japplemenubar/JAppleMenuBar.java
@@ -0,0 +1,88 @@
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2011-12 hansi raber, released under LGPL under agreement
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation, version 2.1.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+package japplemenubar;
+
+import java.io.*;
+
+import processing.core.PApplet;
+
+
+/**
+ * Starting point for the application. General initialization should be done
+ * inside the ApplicationController's init() method. If certain kinds of
+ * non-Swing initialization takes too long, it should happen in a new Thread
+ * and off the Swing event dispatch thread (EDT).
+ *
+ * @author hansi
+ */
+public class JAppleMenuBar {
+ static JAppleMenuBar instance;
+ static final String FILENAME = "libjAppleMenuBar.jnilib";
+
+ static {
+ try {
+ File temp = File.createTempFile("processing", "menubar");
+ temp.delete(); // remove the file itself
+ temp.mkdirs(); // create a directory out of it
+ temp.deleteOnExit();
+
+ File jnilibFile = new File(temp, FILENAME);
+ InputStream input = JAppleMenuBar.class.getResourceAsStream(FILENAME);
+ if (input != null) {
+ if (PApplet.saveStream(jnilibFile, input)) {
+ System.load(jnilibFile.getAbsolutePath());
+ instance = new JAppleMenuBar();
+
+ } else {
+ sadness("Problem saving " + FILENAME + " for full screen use.");
+ }
+ } else {
+ sadness("Could not load " + FILENAME + " from core.jar");
+ }
+ } catch (IOException e) {
+ sadness("Unknown error, here's the stack trace.");
+ e.printStackTrace();
+ }
+ }
+
+
+ static void sadness(String msg) {
+ System.err.println("Full screen mode disabled. " + msg);
+ }
+
+
+// static public void show() {
+// instance.setVisible(true);
+// }
+
+
+ static public void hide() {
+ instance.setVisible(false, false);
+ }
+
+
+ public native void setVisible(boolean visibility, boolean kioskMode);
+
+
+// public void setVisible(boolean visibility) {
+// // Keep original API in-tact. Default kiosk-mode to off.
+// setVisible(visibility, false);
+// }
+}
diff --git a/src/main/java/japplemenubar/libjAppleMenuBar.jnilib b/src/main/java/japplemenubar/libjAppleMenuBar.jnilib
new file mode 100755
index 0000000..2c57f64
Binary files /dev/null and b/src/main/java/japplemenubar/libjAppleMenuBar.jnilib differ
diff --git a/src/monkstone/ColorUtil.java b/src/main/java/monkstone/ColorUtil.java
similarity index 100%
rename from src/monkstone/ColorUtil.java
rename to src/main/java/monkstone/ColorUtil.java
diff --git a/src/monkstone/MathToolModule.java b/src/main/java/monkstone/MathToolModule.java
similarity index 100%
rename from src/monkstone/MathToolModule.java
rename to src/main/java/monkstone/MathToolModule.java
diff --git a/src/monkstone/PropaneLibrary.java b/src/main/java/monkstone/PropaneLibrary.java
similarity index 100%
rename from src/monkstone/PropaneLibrary.java
rename to src/main/java/monkstone/PropaneLibrary.java
diff --git a/src/monkstone/core/LibraryProxy.java b/src/main/java/monkstone/core/LibraryProxy.java
similarity index 100%
rename from src/monkstone/core/LibraryProxy.java
rename to src/main/java/monkstone/core/LibraryProxy.java
diff --git a/src/monkstone/fastmath/Deglut.java b/src/main/java/monkstone/fastmath/Deglut.java
similarity index 100%
rename from src/monkstone/fastmath/Deglut.java
rename to src/main/java/monkstone/fastmath/Deglut.java
diff --git a/src/monkstone/fastmath/package-info.java b/src/main/java/monkstone/fastmath/package-info.java
similarity index 100%
rename from src/monkstone/fastmath/package-info.java
rename to src/main/java/monkstone/fastmath/package-info.java
diff --git a/src/monkstone/filechooser/Chooser.java b/src/main/java/monkstone/filechooser/Chooser.java
similarity index 100%
rename from src/monkstone/filechooser/Chooser.java
rename to src/main/java/monkstone/filechooser/Chooser.java
diff --git a/src/monkstone/noise/SimplexNoise.java b/src/main/java/monkstone/noise/SimplexNoise.java
similarity index 100%
rename from src/monkstone/noise/SimplexNoise.java
rename to src/main/java/monkstone/noise/SimplexNoise.java
diff --git a/src/monkstone/slider/CustomHorizontalSlider.java b/src/main/java/monkstone/slider/CustomHorizontalSlider.java
similarity index 100%
rename from src/monkstone/slider/CustomHorizontalSlider.java
rename to src/main/java/monkstone/slider/CustomHorizontalSlider.java
diff --git a/src/monkstone/slider/CustomVerticalSlider.java b/src/main/java/monkstone/slider/CustomVerticalSlider.java
similarity index 100%
rename from src/monkstone/slider/CustomVerticalSlider.java
rename to src/main/java/monkstone/slider/CustomVerticalSlider.java
diff --git a/src/monkstone/slider/SimpleHorizontalSlider.java b/src/main/java/monkstone/slider/SimpleHorizontalSlider.java
similarity index 100%
rename from src/monkstone/slider/SimpleHorizontalSlider.java
rename to src/main/java/monkstone/slider/SimpleHorizontalSlider.java
diff --git a/src/monkstone/slider/SimpleSlider.java b/src/main/java/monkstone/slider/SimpleSlider.java
similarity index 100%
rename from src/monkstone/slider/SimpleSlider.java
rename to src/main/java/monkstone/slider/SimpleSlider.java
diff --git a/src/monkstone/slider/SimpleVerticalSlider.java b/src/main/java/monkstone/slider/SimpleVerticalSlider.java
similarity index 100%
rename from src/monkstone/slider/SimpleVerticalSlider.java
rename to src/main/java/monkstone/slider/SimpleVerticalSlider.java
diff --git a/src/monkstone/slider/Slider.java b/src/main/java/monkstone/slider/Slider.java
similarity index 100%
rename from src/monkstone/slider/Slider.java
rename to src/main/java/monkstone/slider/Slider.java
diff --git a/src/monkstone/slider/SliderBar.java b/src/main/java/monkstone/slider/SliderBar.java
similarity index 100%
rename from src/monkstone/slider/SliderBar.java
rename to src/main/java/monkstone/slider/SliderBar.java
diff --git a/src/monkstone/slider/SliderGroup.java b/src/main/java/monkstone/slider/SliderGroup.java
similarity index 100%
rename from src/monkstone/slider/SliderGroup.java
rename to src/main/java/monkstone/slider/SliderGroup.java
diff --git a/src/monkstone/slider/WheelHandler.java b/src/main/java/monkstone/slider/WheelHandler.java
similarity index 100%
rename from src/monkstone/slider/WheelHandler.java
rename to src/main/java/monkstone/slider/WheelHandler.java
diff --git a/src/monkstone/vecmath/AppRender.java b/src/main/java/monkstone/vecmath/AppRender.java
similarity index 100%
rename from src/monkstone/vecmath/AppRender.java
rename to src/main/java/monkstone/vecmath/AppRender.java
diff --git a/src/monkstone/vecmath/JRender.java b/src/main/java/monkstone/vecmath/JRender.java
similarity index 100%
rename from src/monkstone/vecmath/JRender.java
rename to src/main/java/monkstone/vecmath/JRender.java
diff --git a/src/monkstone/vecmath/ShapeRender.java b/src/main/java/monkstone/vecmath/ShapeRender.java
similarity index 100%
rename from src/monkstone/vecmath/ShapeRender.java
rename to src/main/java/monkstone/vecmath/ShapeRender.java
diff --git a/src/monkstone/vecmath/package-info.java b/src/main/java/monkstone/vecmath/package-info.java
similarity index 100%
rename from src/monkstone/vecmath/package-info.java
rename to src/main/java/monkstone/vecmath/package-info.java
diff --git a/src/monkstone/vecmath/vec2/Vec2.java b/src/main/java/monkstone/vecmath/vec2/Vec2.java
similarity index 100%
rename from src/monkstone/vecmath/vec2/Vec2.java
rename to src/main/java/monkstone/vecmath/vec2/Vec2.java
diff --git a/src/monkstone/vecmath/vec2/package-info.java b/src/main/java/monkstone/vecmath/vec2/package-info.java
similarity index 100%
rename from src/monkstone/vecmath/vec2/package-info.java
rename to src/main/java/monkstone/vecmath/vec2/package-info.java
diff --git a/src/monkstone/vecmath/vec3/Vec3.java b/src/main/java/monkstone/vecmath/vec3/Vec3.java
similarity index 100%
rename from src/monkstone/vecmath/vec3/Vec3.java
rename to src/main/java/monkstone/vecmath/vec3/Vec3.java
diff --git a/src/monkstone/vecmath/vec3/package-info.java b/src/main/java/monkstone/vecmath/vec3/package-info.java
similarity index 100%
rename from src/monkstone/vecmath/vec3/package-info.java
rename to src/main/java/monkstone/vecmath/vec3/package-info.java
diff --git a/src/monkstone/videoevent/VideoInterface.java b/src/main/java/monkstone/videoevent/VideoInterface.java
similarity index 100%
rename from src/monkstone/videoevent/VideoInterface.java
rename to src/main/java/monkstone/videoevent/VideoInterface.java
diff --git a/src/monkstone/videoevent/package-info.java b/src/main/java/monkstone/videoevent/package-info.java
similarity index 100%
rename from src/monkstone/videoevent/package-info.java
rename to src/main/java/monkstone/videoevent/package-info.java
diff --git a/src/main/java/processing/awt/PGraphicsJava2D.java b/src/main/java/processing/awt/PGraphicsJava2D.java
new file mode 100644
index 0000000..1fc3beb
--- /dev/null
+++ b/src/main/java/processing/awt/PGraphicsJava2D.java
@@ -0,0 +1,3029 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2013-15 The Processing Foundation
+ Copyright (c) 2005-13 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.awt;
+
+import java.awt.*;
+import java.awt.font.TextAttribute;
+import java.awt.geom.*;
+import java.awt.image.*;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import processing.core.*;
+
+
+/**
+ * Subclass for PGraphics that implements the graphics API using Java2D.
+ *
+ * To get access to the Java 2D "Graphics2D" object for the default
+ * renderer, use:
+ *
+ * This will let you do Graphics2D calls directly, but is not supported
+ * in any way shape or form. Which just means "have fun, but don't complain
+ * if it breaks."
+ *
+ * Advanced debugging notes for Java2D.
+ */
+public class PGraphicsJava2D extends PGraphics {
+//// BufferStrategy strategy;
+//// BufferedImage bimage;
+//// VolatileImage vimage;
+// Canvas canvas;
+//// boolean useCanvas = true;
+// boolean useCanvas = false;
+//// boolean useRetina = true;
+//// boolean useOffscreen = true; // ~40fps
+// boolean useOffscreen = false;
+
+ public Graphics2D g2;
+// protected BufferedImage offscreen;
+
+ Composite defaultComposite;
+
+ GeneralPath gpath;
+
+ // path for contours so gpath can be closed
+ GeneralPath auxPath;
+
+ boolean openContour;
+
+ /// break the shape at the next vertex (next vertex() call is a moveto())
+ boolean breakShape;
+
+ /// coordinates for internal curve calculation
+ float[] curveCoordX;
+ float[] curveCoordY;
+ float[] curveDrawX;
+ float[] curveDrawY;
+
+ int transformCount;
+ AffineTransform transformStack[] =
+ new AffineTransform[MATRIX_STACK_DEPTH];
+ double[] transform = new double[6];
+
+ Line2D.Float line = new Line2D.Float();
+ Ellipse2D.Float ellipse = new Ellipse2D.Float();
+ Rectangle2D.Float rect = new Rectangle2D.Float();
+ Arc2D.Float arc = new Arc2D.Float();
+
+ protected Color tintColorObject;
+
+ protected Color fillColorObject;
+ public boolean fillGradient;
+ public Paint fillGradientObject;
+
+ protected Stroke strokeObject;
+ protected Color strokeColorObject;
+ public boolean strokeGradient;
+ public Paint strokeGradientObject;
+
+ Font fontObject;
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // INTERNAL
+
+
+ public PGraphicsJava2D() { }
+
+
+ //public void setParent(PApplet parent)
+
+
+ //public void setPrimary(boolean primary)
+
+
+ //public void setPath(String path)
+
+
+// /**
+// * Called in response to a resize event, handles setting the
+// * new width and height internally, as well as re-allocating
+// * the pixel buffer for the new size.
+// *
+// * Note that this will nuke any cameraMode() settings.
+// */
+// @Override
+// public void setSize(int iwidth, int iheight) { // ignore
+// width = iwidth;
+// height = iheight;
+//
+// allocate();
+// reapplySettings();
+// }
+
+
+// @Override
+// protected void allocate() {
+// //surface.initImage(this, width, height);
+// surface.initImage(this);
+// }
+
+
+ /*
+ @Override
+ protected void allocate() {
+ // Tried this with RGB instead of ARGB for the primarySurface version,
+ // but didn't see any performance difference (OS X 10.6, Java 6u24).
+ // For 0196, also attempted RGB instead of ARGB, but that causes
+ // strange things to happen with blending.
+// image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+ if (primarySurface) {
+ if (useCanvas) {
+ if (canvas != null) {
+ parent.removeListeners(canvas);
+ parent.remove(canvas);
+ }
+ canvas = new Canvas();
+ canvas.setIgnoreRepaint(true);
+
+// parent.setLayout(new BorderLayout());
+// parent.add(canvas, BorderLayout.CENTER);
+ parent.add(canvas);
+// canvas.validate();
+// parent.doLayout();
+
+ if (canvas.getWidth() != width || canvas.getHeight() != height) {
+ PApplet.debug("PGraphicsJava2D comp size being set to " + width + "x" + height);
+ canvas.setSize(width, height);
+ } else {
+ PApplet.debug("PGraphicsJava2D comp size already " + width + "x" + height);
+ }
+
+ parent.addListeners(canvas);
+// canvas.createBufferStrategy(1);
+// g2 = (Graphics2D) canvas.getGraphics();
+
+ } else {
+ parent.updateListeners(parent); // in case they're already there
+
+ // using a compatible image here doesn't seem to provide any performance boost
+
+ if (useOffscreen) {
+ // Needs to be RGB otherwise there's a major performance hit [0204]
+ // http://code.google.com/p/processing/issues/detail?id=729
+ image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+// GraphicsConfiguration gc = parent.getGraphicsConfiguration();
+// image = gc.createCompatibleImage(width, height);
+ offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+// offscreen = gc.createCompatibleImage(width, height);
+ g2 = (Graphics2D) offscreen.getGraphics();
+
+ } else {
+// System.out.println("hopefully faster " + width + " " + height);
+// new Exception().printStackTrace(System.out);
+
+ GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
+ // If not realized (off-screen, i.e the Color Selector Tool),
+ // gc will be null.
+ if (gc == null) {
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
+ }
+
+ image = gc.createCompatibleImage(width, height);
+ g2 = (Graphics2D) image.getGraphics();
+ }
+ }
+ } else { // not the primary surface
+ // Since this buffer's offscreen anyway, no need for the extra offscreen
+ // buffer. However, unlike the primary surface, this feller needs to be
+ // ARGB so that blending ("alpha" compositing) will work properly.
+ image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+ g2 = (Graphics2D) image.getGraphics();
+ }
+ */
+
+ /*
+ if (primarySurface) {
+ Canvas canvas = ((PSurfaceAWT) surface).canvas;
+
+ GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
+ // If not realized (off-screen, i.e the Color Selector Tool),
+ // gc will be null.
+ if (gc == null) {
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
+ }
+
+ image = gc.createCompatibleImage(width, height);
+ g2 = (Graphics2D) image.getGraphics();
+
+ } else {
+
+ }
+ g2 = (Graphics2D) image.getGraphics();
+ }
+ */
+
+
+ //public void dispose()
+
+
+ @Override
+ public PSurface createSurface() {
+ return surface = new PSurfaceAWT(this);
+ }
+
+
+ /**
+ * Still need a means to get the java.awt.Image object, since getNative()
+ * is going to return the {@link Graphics2D} object.
+ */
+ @Override
+ public Image getImage() {
+ return image;
+ }
+
+
+ /** Returns the java.awt.Graphics2D object used by this renderer. */
+ @Override
+ public Object getNative() {
+ return g2;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FRAME
+
+
+// @Override
+// public boolean canDraw() {
+// return true;
+// }
+
+
+// @Override
+// public void requestDraw() {
+//// EventQueue.invokeLater(new Runnable() {
+//// public void run() {
+// parent.handleDraw();
+//// }
+//// });
+// }
+
+
+// Graphics2D g2old;
+
+ public Graphics2D checkImage() {
+ if (image == null ||
+ ((BufferedImage) image).getWidth() != width*pixelDensity ||
+ ((BufferedImage) image).getHeight() != height*pixelDensity) {
+// ((VolatileImage) image).getWidth() != width ||
+// ((VolatileImage) image).getHeight() != height) {
+// image = new BufferedImage(width * pixelFactor, height * pixelFactor
+// format == RGB ? BufferedImage.TYPE_INT_ARGB);
+
+ GraphicsConfiguration gc = null;
+ if (surface != null) {
+ Component comp = null; //surface.getComponent();
+ if (comp == null) {
+// System.out.println("component null, but parent.frame is " + parent.frame);
+ comp = parent.frame;
+ }
+ if (comp != null) {
+ gc = comp.getGraphicsConfiguration();
+ }
+ }
+ // If not realized (off-screen, i.e the Color Selector Tool), gc will be null.
+ if (gc == null) {
+ //System.err.println("GraphicsConfiguration null in initImage()");
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
+ }
+
+ // Formerly this was broken into separate versions based on offscreen or
+ // not, but we may as well create a compatible image; it won't hurt, right?
+ int wide = width * pixelDensity;
+ int high = height * pixelDensity;
+// System.out.println("re-creating image");
+ image = gc.createCompatibleImage(wide, high, Transparency.TRANSLUCENT);
+// image = gc.createCompatibleVolatileImage(wide, high);
+ //image = surface.getComponent().createImage(width, height);
+ }
+ return (Graphics2D) image.getGraphics();
+ }
+
+
+ @Override
+ public void beginDraw() {
+ g2 = checkImage();
+
+ // Calling getGraphics() seems to nuke several settings.
+ // It seems to be re-creating a new Graphics2D object each time.
+ // https://github.com/processing/processing/issues/3331
+ if (strokeObject != null) {
+ g2.setStroke(strokeObject);
+ }
+ // https://github.com/processing/processing/issues/2617
+ if (fontObject != null) {
+ g2.setFont(fontObject);
+ }
+ // https://github.com/processing/processing/issues/4019
+ if (blendMode != 0) {
+ blendMode(blendMode);
+ }
+ handleSmooth();
+
+ /*
+ // NOTE: Calling image.getGraphics() will create a new Graphics context,
+ // even if it's for the same image that's already had a context created.
+ // Seems like a speed/memory issue, and also requires that all smoothing,
+ // stroke, font and other props be reset. Can't find a good answer about
+ // whether getGraphics() and dispose() on each frame is 1) better practice
+ // and 2) minimal overhead, however. Instinct suggests #1 may be true,
+ // but #2 seems a problem.
+ if (primarySurface && !useOffscreen) {
+ GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
+ if (false) {
+ if (image == null || ((VolatileImage) image).validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE) {
+ image = gc.createCompatibleVolatileImage(width, height);
+ g2 = (Graphics2D) image.getGraphics();
+ reapplySettings = true;
+ }
+ } else {
+ if (image == null) {
+ image = gc.createCompatibleImage(width, height);
+ PApplet.debug("created new image, type is " + image);
+ g2 = (Graphics2D) image.getGraphics();
+ reapplySettings = true;
+ }
+ }
+ }
+
+ if (useCanvas && primarySurface) {
+ if (parent.frameCount == 0) {
+ canvas.createBufferStrategy(2);
+ strategy = canvas.getBufferStrategy();
+ PApplet.debug("PGraphicsJava2D.beginDraw() strategy is " + strategy);
+ BufferCapabilities caps = strategy.getCapabilities();
+ caps = strategy.getCapabilities();
+ PApplet.debug("PGraphicsJava2D.beginDraw() caps are " +
+ " flipping: " + caps.isPageFlipping() +
+ " front/back accel: " + caps.getFrontBufferCapabilities().isAccelerated() + " " +
+ "/" + caps.getBackBufferCapabilities().isAccelerated());
+ }
+ GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
+
+ if (bimage == null ||
+ bimage.getWidth() != width ||
+ bimage.getHeight() != height) {
+ PApplet.debug("PGraphicsJava2D creating new image");
+ bimage = gc.createCompatibleImage(width, height);
+// image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+ g2 = bimage.createGraphics();
+ defaultComposite = g2.getComposite();
+ reapplySettings = true;
+ }
+ }
+ */
+
+ checkSettings();
+ resetMatrix(); // reset model matrix
+ vertexCount = 0;
+ }
+
+
+ /**
+ * Smoothing for Java2D is 2 for bilinear, and 3 for bicubic (the default).
+ * Internally, smooth(1) is the default, smooth(0) is noSmooth().
+ */
+ protected void handleSmooth() {
+ if (smooth == 0) {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
+ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+ RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
+
+ } else {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+
+ if (smooth == 1 || smooth == 3) { // default is bicubic
+ g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_BICUBIC);
+ } else if (smooth == 2) {
+ g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+ }
+
+ // http://docs.oracle.com/javase/tutorial/2d/text/renderinghints.html
+ // Oracle Java text anti-aliasing on OS X looks like s*t compared to the
+ // text rendering with Apple's old Java 6. Below, several attempts to fix:
+ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+ RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ // Turns out this is the one that actually makes things work.
+ // Kerning is still screwed up, however.
+ g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
+ RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+// RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
+// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+// RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
+
+// g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
+// RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
+ }
+ }
+
+
+ @Override
+ public void endDraw() {
+ // hm, mark pixels as changed, because this will instantly do a full
+ // copy of all the pixels to the surface.. so that's kind of a mess.
+ //updatePixels();
+
+ if (primaryGraphics) {
+ /*
+ //if (canvas != null) {
+ if (useCanvas) {
+ //System.out.println(canvas);
+
+ // alternate version
+ //canvas.repaint(); // ?? what to do for swapping buffers
+
+// System.out.println("endDraw() frameCount is " + parent.frameCount);
+// if (parent.frameCount != 0) {
+ redraw();
+// }
+
+ } else if (useOffscreen) {
+ // don't copy the pixels/data elements of the buffered image directly,
+ // since it'll disable the nice speedy pipeline stuff, sending all drawing
+ // into a world of suck that's rough 6 trillion times slower.
+ synchronized (image) {
+ //System.out.println("inside j2d sync");
+ image.getGraphics().drawImage(offscreen, 0, 0, null);
+ }
+
+ } else {
+ // changed to not dispose and get on each frame,
+ // otherwise a new Graphics context is used on each frame
+// g2.dispose();
+// System.out.println("not doing anything special in endDraw()");
+ }
+ */
+ } 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();
+
+ // Marks pixels as modified so that the pixels will be updated.
+ // Also sets mx1/y1/x2/y2 so that OpenGL will pick it up.
+ setModified();
+
+ g2.dispose();
+ }
+
+
+ /*
+ private void redraw() {
+ // only need this check if the validate() call will use redraw()
+// if (strategy == null) return;
+ do {
+ PApplet.debug("PGraphicsJava2D.redraw() top of outer do { } block");
+ do {
+ PApplet.debug("PGraphicsJava2D.redraw() top of inner do { } block");
+ PApplet.debug("strategy is " + strategy);
+ Graphics bsg = strategy.getDrawGraphics();
+// if (vimage != null) {
+// bsg.drawImage(vimage, 0, 0, null);
+// } else {
+ bsg.drawImage(bimage, 0, 0, null);
+// if (parent.frameCount == 0) {
+// try {
+// ImageIO.write(image, "jpg", new java.io.File("/Users/fry/Desktop/buff.jpg"));
+// } catch (IOException e) {
+// e.printStackTrace();
+// }
+// }
+// }
+ bsg.dispose();
+
+ // the strategy version
+// g2.dispose();
+// if (!strategy.contentsLost()) {
+// if (parent.frameCount != 0) {
+// Toolkit.getDefaultToolkit().sync();
+// }
+// } else {
+// System.out.println("XXXXX strategy contents lost");
+// }
+// }
+// }
+ } while (strategy.contentsRestored());
+
+ PApplet.debug("PGraphicsJava2D.redraw() showing strategy");
+ strategy.show();
+
+ } while (strategy.contentsLost());
+ PApplet.debug("PGraphicsJava2D.redraw() out of do { } block");
+ }
+ */
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SETTINGS
+
+
+ //protected void checkSettings()
+
+
+ @Override
+ protected void defaultSettings() {
+// if (!useCanvas) {
+// // Papered over another threading issue...
+// // See if this comes back now that the other issue is fixed.
+//// while (g2 == null) {
+//// try {
+//// System.out.println("sleeping until g2 is available");
+//// Thread.sleep(5);
+//// } catch (InterruptedException e) { }
+//// }
+ defaultComposite = g2.getComposite();
+// }
+ super.defaultSettings();
+ }
+
+
+ //protected void reapplySettings()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // HINT
+
+
+ @Override
+ public void hint(int which) {
+ // take care of setting the hint
+ super.hint(which);
+
+ // Avoid badness when drawing shorter strokes.
+ // http://code.google.com/p/processing/issues/detail?id=1068
+ // Unfortunately cannot always be enabled, because it makes the
+ // stroke in many standard Processing examples really gross.
+ if (which == ENABLE_STROKE_PURE) {
+ g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
+ RenderingHints.VALUE_STROKE_PURE);
+ } else if (which == DISABLE_STROKE_PURE) {
+ g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
+ RenderingHints.VALUE_STROKE_DEFAULT);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPE CREATION
+
+
+ @Override
+ protected PShape createShapeFamily(int type) {
+ return new PShape(this, type);
+ }
+
+
+ @Override
+ protected PShape createShapePrimitive(int kind, float... p) {
+ return new PShape(this, kind, p);
+ }
+
+
+// @Override
+// public PShape createShape(PShape source) {
+// return PShapeOpenGL.createShape2D(this, source);
+// }
+
+
+ /*
+ protected PShape createShapeImpl(PGraphicsJava2D pg, int type) {
+ PShape shape = null;
+ if (type == PConstants.GROUP) {
+ shape = new PShape(pg, PConstants.GROUP);
+ } else if (type == PShape.PATH) {
+ shape = new PShape(pg, PShape.PATH);
+ } else if (type == PShape.GEOMETRY) {
+ shape = new PShape(pg, PShape.GEOMETRY);
+ }
+ // defaults to false, don't assign it and make complexity for overrides
+ //shape.set3D(false);
+ return shape;
+ }
+ */
+
+
+ /*
+ static protected PShape createShapeImpl(PGraphicsJava2D pg,
+ int kind, float... p) {
+ PShape shape = null;
+ int len = p.length;
+
+ if (kind == POINT) {
+ if (len != 2) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(POINT);
+ } else if (kind == LINE) {
+ if (len != 4) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(LINE);
+ } else if (kind == TRIANGLE) {
+ if (len != 6) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(TRIANGLE);
+ } else if (kind == QUAD) {
+ if (len != 8) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(QUAD);
+ } else if (kind == RECT) {
+ if (len != 4 && len != 5 && len != 8 && len != 9) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(RECT);
+ } else if (kind == ELLIPSE) {
+ if (len != 4 && len != 5) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(ELLIPSE);
+ } else if (kind == ARC) {
+ if (len != 6 && len != 7) {
+ showWarning("Wrong number of parameters");
+ return null;
+ }
+ shape = new PShape(pg, PShape.PRIMITIVE);
+ shape.setKind(ARC);
+ } else if (kind == BOX) {
+ showWarning("Primitive not supported in 2D");
+ } else if (kind == SPHERE) {
+ showWarning("Primitive not supported in 2D");
+ } else {
+ showWarning("Unrecognized primitive type");
+ }
+
+ if (shape != null) {
+ shape.setParams(p);
+ }
+
+ // defaults to false, don't assign it and make complexity for overrides
+ //shape.set3D(false);
+
+ return shape;
+ }
+ */
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPES
+
+
+ @Override
+ public void beginShape(int kind) {
+ //super.beginShape(kind);
+ shape = kind;
+ vertexCount = 0;
+ curveVertexCount = 0;
+
+ // set gpath to null, because when mixing curves and straight
+ // lines, vertexCount will be set back to zero, so vertexCount == 1
+ // is no longer a good indicator of whether the shape is new.
+ // this way, just check to see if gpath is null, and if it isn't
+ // then just use it to continue the shape.
+ gpath = null;
+ auxPath = null;
+ }
+
+
+ //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) {
+ curveVertexCount = 0;
+ //float vertex[];
+
+ if (vertexCount == vertices.length) {
+ float temp[][] = new float[vertexCount<<1][VERTEX_FIELD_COUNT];
+ System.arraycopy(vertices, 0, temp, 0, vertexCount);
+ vertices = temp;
+ //message(CHATTER, "allocating more vertices " + vertices.length);
+ }
+ // not everyone needs this, but just easier to store rather
+ // than adding another moving part to the code...
+ vertices[vertexCount][X] = x;
+ vertices[vertexCount][Y] = y;
+ vertexCount++;
+
+ switch (shape) {
+
+ case POINTS:
+ point(x, y);
+ break;
+
+ case LINES:
+ if ((vertexCount % 2) == 0) {
+ line(vertices[vertexCount-2][X],
+ vertices[vertexCount-2][Y], x, y);
+ }
+ break;
+
+ case TRIANGLES:
+ if ((vertexCount % 3) == 0) {
+ triangle(vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y],
+ vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, y);
+ }
+ break;
+
+ case TRIANGLE_STRIP:
+ if (vertexCount >= 3) {
+ triangle(vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ vertices[vertexCount - 1][X],
+ vertices[vertexCount - 1][Y],
+ vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y]);
+ }
+ break;
+
+ case TRIANGLE_FAN:
+ if (vertexCount >= 3) {
+ // This is an unfortunate implementation because the stroke for an
+ // adjacent triangle will be repeated. However, if the stroke is not
+ // redrawn, it will replace the adjacent line (when it lines up
+ // perfectly) or show a faint line (when off by a small amount).
+ // The alternative would be to wait, then draw the shape as a
+ // polygon fill, followed by a series of vertices. But that's a
+ // poor method when used with PDF, DXF, or other recording objects,
+ // since discrete triangles would likely be preferred.
+ 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);
+ }
+ break;
+
+ case QUAD_STRIP:
+ // 0---2---4
+ // | | |
+ // 1---3---5
+ if ((vertexCount >= 4) && ((vertexCount % 2) == 0)) {
+ quad(vertices[vertexCount - 4][X],
+ vertices[vertexCount - 4][Y],
+ vertices[vertexCount - 2][X],
+ vertices[vertexCount - 2][Y],
+ x, y,
+ vertices[vertexCount - 3][X],
+ vertices[vertexCount - 3][Y]);
+ }
+ break;
+
+ case POLYGON:
+ if (gpath == null) {
+ gpath = new GeneralPath();
+ gpath.moveTo(x, y);
+ } else if (breakShape) {
+ gpath.moveTo(x, y);
+ breakShape = false;
+ } else {
+ gpath.lineTo(x, y);
+ }
+ break;
+ }
+ }
+
+
+ @Override
+ public void vertex(float x, float y, float z) {
+ showDepthWarningXYZ("vertex");
+ }
+
+ @Override
+ public void vertex(float[] v) {
+ vertex(v[X], v[Y]);
+ }
+
+
+ @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 beginContour() {
+ if (openContour) {
+ PGraphics.showWarning("Already called beginContour()");
+ return;
+ }
+
+ // draw contours to auxiliary path so main path can be closed later
+ GeneralPath contourPath = auxPath;
+ auxPath = gpath;
+ gpath = contourPath;
+
+ if (contourPath != null) { // first contour does not break
+ breakShape = true;
+ }
+
+ openContour = true;
+ }
+
+
+ @Override
+ public void endContour() {
+ if (!openContour) {
+ PGraphics.showWarning("Need to call beginContour() first");
+ return;
+ }
+
+ // close this contour
+ if (gpath != null) gpath.closePath();
+
+ // switch back to main path
+ GeneralPath contourPath = gpath;
+ gpath = auxPath;
+ auxPath = contourPath;
+
+ openContour = false;
+ }
+
+
+ @Override
+ public void endShape(int mode) {
+ if (openContour) { // correct automagically, notify user
+ endContour();
+ PGraphics.showWarning("Missing endContour() before endShape()");
+ }
+ if (gpath != null) { // make sure something has been drawn
+ if (shape == POLYGON) {
+ if (mode == CLOSE) {
+ gpath.closePath();
+ }
+ if (auxPath != null) {
+ gpath.append(auxPath, false);
+ }
+ drawShape(gpath);
+ }
+ }
+ shape = 0;
+ }
+
+ //////////////////////////////////////////////////////////////
+
+ // CLIPPING
+
+
+ @Override
+ protected void clipImpl(float x1, float y1, float x2, float y2) {
+ g2.setClip(new Rectangle2D.Float(x1, y1, x2 - x1, y2 - y1));
+ }
+
+
+ @Override
+ public void noClip() {
+ g2.setClip(null);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BLEND
+
+ /**
+ * ( 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
+ */
+ @Override
+ protected void blendModeImpl() {
+ if (blendMode == BLEND) {
+ g2.setComposite(defaultComposite);
+
+ } else {
+ g2.setComposite(new Composite() {
+
+ @Override
+ public CompositeContext createContext(ColorModel srcColorModel,
+ ColorModel dstColorModel,
+ RenderingHints hints) {
+ return new BlendingContext(blendMode);
+ }
+ });
+ }
+ }
+
+
+ // Blending implementation cribbed from portions of Romain Guy's
+ // demo and terrific writeup on blending modes in Java 2D.
+ // http://www.curious-creature.org/2006/09/20/new-blendings-modes-for-java2d/
+ private static final class BlendingContext implements CompositeContext {
+ private int mode;
+
+ private BlendingContext(int mode) {
+ this.mode = mode;
+ }
+
+ public void dispose() { }
+
+ public void compose(Raster src, Raster dstIn, WritableRaster dstOut) {
+ // not sure if this is really necessary, since we control our buffers
+ if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT ||
+ dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT ||
+ dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) {
+ throw new IllegalStateException("Source and destination must store pixels as INT.");
+ }
+
+ int width = Math.min(src.getWidth(), dstIn.getWidth());
+ int height = Math.min(src.getHeight(), dstIn.getHeight());
+
+ int[] srcPixels = new int[width];
+ int[] dstPixels = new int[width];
+
+ for (int y = 0; y < height; y++) {
+ src.getDataElements(0, y, width, 1, srcPixels);
+ dstIn.getDataElements(0, y, width, 1, dstPixels);
+ for (int x = 0; x < width; x++) {
+ dstPixels[x] = blendColor(dstPixels[x], srcPixels[x], mode);
+ }
+ dstOut.setDataElements(0, y, width, 1, dstPixels);
+ }
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BEZIER VERTICES
+
+
+ @Override
+ public void bezierVertex(float x1, float y1,
+ float x2, float y2,
+ float x3, float y3) {
+ bezierVertexCheck();
+ gpath.curveTo(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();
+ Point2D cur = gpath.getCurrentPoint();
+
+ float x1 = (float) cur.getX();
+ float y1 = (float) cur.getY();
+
+ bezierVertex(x1 + ((ctrlX-x1)*2/3.0f), y1 + ((ctrlY-y1)*2/3.0f),
+ endX + ((ctrlX-endX)*2/3.0f), endY + ((ctrlY-endY)*2/3.0f),
+ 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 (gpath == null) {
+ gpath = new GeneralPath();
+ gpath.moveTo(curveDrawX[0], curveDrawY[0]);
+ }
+
+ gpath.curveTo(curveDrawX[1], curveDrawY[1],
+ curveDrawX[2], curveDrawY[2],
+ curveDrawX[3], curveDrawY[3]);
+ }
+
+
+ @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) {
+ if (stroke) {
+// if (strokeWeight > 1) {
+ line(x, y, x + EPSILON, y + EPSILON);
+// } else {
+// set((int) screenX(x, y), (int) screenY(x, y), strokeColor);
+// }
+ }
+ }
+
+
+ @Override
+ public void line(float x1, float y1, float x2, float y2) {
+ line.setLine(x1, y1, x2, y2);
+ strokeShape(line);
+ }
+
+
+ @Override
+ public void triangle(float x1, float y1, float x2, float y2,
+ float x3, float y3) {
+ gpath = new GeneralPath();
+ gpath.moveTo(x1, y1);
+ gpath.lineTo(x2, y2);
+ gpath.lineTo(x3, y3);
+ gpath.closePath();
+ drawShape(gpath);
+ }
+
+
+ @Override
+ public void quad(float x1, float y1, float x2, float y2,
+ float x3, float y3, float x4, float y4) {
+ GeneralPath gp = new GeneralPath();
+ gp.moveTo(x1, y1);
+ gp.lineTo(x2, y2);
+ gp.lineTo(x3, y3);
+ gp.lineTo(x4, y4);
+ gp.closePath();
+ drawShape(gp);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RECT
+
+
+ //public void rectMode(int mode)
+
+
+ //public void rect(float a, float b, float c, float d)
+
+
+ @Override
+ protected void rectImpl(float x1, float y1, float x2, float y2) {
+ rect.setFrame(x1, y1, x2-x1, y2-y1);
+ drawShape(rect);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ELLIPSE
+
+
+ //public void ellipseMode(int mode)
+
+
+ //public void ellipse(float a, float b, float c, float d)
+
+
+ @Override
+ protected void ellipseImpl(float x, float y, float w, float h) {
+ ellipse.setFrame(x, y, w, h);
+ drawShape(ellipse);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ARC
+
+
+ //public void arc(float a, float b, float c, float d,
+ // float start, float stop)
+
+
+ @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?
+
+ 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;
+
+ // The defaults, before 2.0b7, were to stroke as Arc2D.OPEN, and then fill
+ // using Arc2D.PIE. That's a little wonky, but it's here for compatability.
+ int fillMode = Arc2D.PIE;
+ int strokeMode = Arc2D.OPEN;
+
+ if (mode == OPEN) {
+ fillMode = Arc2D.OPEN;
+ //strokeMode = Arc2D.OPEN;
+
+ } else if (mode == PIE) {
+ //fillMode = Arc2D.PIE;
+ strokeMode = Arc2D.PIE;
+
+ } else if (mode == CHORD) {
+ fillMode = Arc2D.CHORD;
+ strokeMode = Arc2D.CHORD;
+ }
+
+ if (fill) {
+ //System.out.println("filla");
+ arc.setArc(x, y, w, h, start, sweep, fillMode);
+ fillShape(arc);
+ }
+ if (stroke) {
+ //System.out.println("strokey");
+ arc.setArc(x, y, w, h, start, sweep, strokeMode);
+ strokeShape(arc);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // JAVA2D SHAPE/PATH HANDLING
+
+
+ protected void fillShape(Shape s) {
+ if (fillGradient) {
+ g2.setPaint(fillGradientObject);
+ g2.fill(s);
+ } else if (fill) {
+ g2.setColor(fillColorObject);
+ g2.fill(s);
+ }
+ }
+
+
+ protected void strokeShape(Shape s) {
+ if (strokeGradient) {
+ g2.setPaint(strokeGradientObject);
+ g2.draw(s);
+ } else if (stroke) {
+ g2.setColor(strokeColorObject);
+ g2.draw(s);
+ }
+ }
+
+
+ protected void drawShape(Shape s) {
+ if (fillGradient) {
+ g2.setPaint(fillGradientObject);
+ g2.fill(s);
+ } else if (fill) {
+ g2.setColor(fillColorObject);
+ g2.fill(s);
+ }
+ if (strokeGradient) {
+ g2.setPaint(strokeGradientObject);
+ g2.draw(s);
+ } else if (stroke) {
+ g2.setColor(strokeColorObject);
+ g2.draw(s);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BOX
+
+
+ //public void box(float size)
+
+
+ @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() {
+// smooth = true;
+//
+// if (quality == 0) {
+// quality = 4; // change back to bicubic
+// }
+//
+// g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+// RenderingHints.VALUE_ANTIALIAS_ON);
+//
+// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+// quality == 4 ?
+// RenderingHints.VALUE_INTERPOLATION_BICUBIC :
+// RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+//
+// // http://docs.oracle.com/javase/tutorial/2d/text/renderinghints.html
+// // Oracle Java text anti-aliasing on OS X looks like s*t compared to the
+// // text rendering with Apple's old Java 6. Below, several attempts to fix:
+// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+// RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+// // Turns out this is the one that actually makes things work.
+// // Kerning is still screwed up, however.
+// g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
+// RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+//// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+//// RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
+//// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+//// RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
+//
+//// g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
+//// RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
+//
+// }
+//
+//
+// @Override
+// public void smooth(int quality) {
+// this.quality = quality;
+// if (quality == 0) {
+// noSmooth();
+// } else {
+// smooth();
+// }
+// }
+//
+//
+// @Override
+// public void noSmooth() {
+// smooth = false;
+// quality = 0; // https://github.com/processing/processing/issues/3113
+// g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+// RenderingHints.VALUE_ANTIALIAS_OFF);
+// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+// RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
+// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+// RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
+// }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // IMAGE
+
+
+ //public void imageMode(int mode)
+
+
+ //public void image(PImage image, float x, float y)
+
+
+ //public void image(PImage image, float x, float y, float c, float d)
+
+
+ //public void image(PImage image,
+ // float a, float b, float c, float d,
+ // int u1, int v1, int u2, int v2)
+
+
+ /**
+ * Handle renderer-specific image drawing.
+ */
+ @Override
+ protected void imageImpl(PImage who,
+ float x1, float y1, float x2, float y2,
+ int u1, int v1, int u2, int v2) {
+ // Image not ready yet, or an error
+ if (who.width <= 0 || who.height <= 0) return;
+
+ ImageCache cash = (ImageCache) getCache(who);
+
+ // Nuke the cache if the image was resized
+ if (cash != null) {
+ if (who.pixelWidth != cash.image.getWidth() ||
+ who.pixelHeight != cash.image.getHeight()) {
+ cash = null;
+ }
+ }
+
+ if (cash == null) {
+ //System.out.println("making new image cache");
+ cash = new ImageCache(); //who);
+ setCache(who, cash);
+ who.updatePixels(); // mark the whole thing for update
+ who.setModified();
+ }
+
+ // If image previously was tinted, or the color changed
+ // or the image was tinted, and tint is now disabled
+ if ((tint && !cash.tinted) ||
+ (tint && (cash.tintedColor != tintColor)) ||
+ (!tint && cash.tinted)) {
+ // For tint change, mark all pixels as needing update.
+ who.updatePixels();
+ }
+
+ if (who.isModified()) {
+ if (who.pixels == null) {
+ // This might be a PGraphics that hasn't been drawn to yet.
+ // Can't just bail because the cache has been created above.
+ // https://github.com/processing/processing/issues/2208
+ who.pixels = new int[who.pixelWidth * who.pixelHeight];
+ }
+ cash.update(who, tint, tintColor);
+ who.setModified(false);
+ }
+
+ u1 *= who.pixelDensity;
+ v1 *= who.pixelDensity;
+ u2 *= who.pixelDensity;
+ v2 *= who.pixelDensity;
+
+ g2.drawImage(((ImageCache) getCache(who)).image,
+ (int) x1, (int) y1, (int) x2, (int) y2,
+ u1, v1, u2, v2, null);
+
+ // Every few years I think "nah, Java2D couldn't possibly be that f*king
+ // slow, why are we doing this by hand?" then comes the affirmation:
+// Composite oldComp = null;
+// if (false && tint) {
+// oldComp = g2.getComposite();
+// int alpha = (tintColor >> 24) & 0xff;
+// System.out.println("using alpha composite");
+// Composite alphaComp =
+// AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha / 255f);
+// g2.setComposite(alphaComp);
+// }
+//
+// long t = System.currentTimeMillis();
+// g2.drawImage(who.getImage(),
+// (int) x1, (int) y1, (int) x2, (int) y2,
+// u1, v1, u2, v2, null);
+// System.out.println(System.currentTimeMillis() - t);
+//
+// if (oldComp != null) {
+// g2.setComposite(oldComp);
+// }
+ }
+
+
+ static class ImageCache {
+ boolean tinted;
+ int tintedColor;
+ int[] tintedTemp; // one row of tinted pixels
+ BufferedImage image;
+// BufferedImage compat;
+
+// public ImageCache(PImage source) {
+//// this.source = source;
+// // even if RGB, set the image type to ARGB, because the
+// // image may have an alpha value for its tint().
+//// int type = BufferedImage.TYPE_INT_ARGB;
+// //System.out.println("making new buffered image");
+//// image = new BufferedImage(source.width, source.height, type);
+// }
+
+ /**
+ * Update the pixels of the cache image. Already determined that the tint
+ * has changed, or the pixels have changed, so should just go through
+ * with the update without further checks.
+ */
+ public void update(PImage source, boolean tint, int tintColor) {
+ //int bufferType = BufferedImage.TYPE_INT_ARGB;
+ int targetType = ARGB;
+ boolean opaque = (tintColor & 0xFF000000) == 0xFF000000;
+ if (source.format == RGB) {
+ if (!tint || (tint && opaque)) {
+ //bufferType = BufferedImage.TYPE_INT_RGB;
+ targetType = RGB;
+ }
+ }
+// boolean wrongType = (image != null) && (image.getType() != bufferType);
+// if ((image == null) || wrongType) {
+// image = new BufferedImage(source.width, source.height, bufferType);
+// }
+ // Must always use an ARGB image, otherwise will write zeros
+ // in the alpha channel when drawn to the screen.
+ // https://github.com/processing/processing/issues/2030
+ if (image == null) {
+ image = new BufferedImage(source.pixelWidth, source.pixelHeight,
+ BufferedImage.TYPE_INT_ARGB);
+ }
+
+ WritableRaster wr = image.getRaster();
+ if (tint) {
+ if (tintedTemp == null || tintedTemp.length != source.pixelWidth) {
+ tintedTemp = new int[source.pixelWidth];
+ }
+ int a2 = (tintColor >> 24) & 0xff;
+// System.out.println("tint color is " + a2);
+// System.out.println("source.pixels[0] alpha is " + (source.pixels[0] >>> 24));
+ int r2 = (tintColor >> 16) & 0xff;
+ int g2 = (tintColor >> 8) & 0xff;
+ int b2 = (tintColor) & 0xff;
+
+ //if (bufferType == BufferedImage.TYPE_INT_RGB) {
+ if (targetType == RGB) {
+ // The target image is opaque, meaning that the source image has no
+ // alpha (is not ARGB), and the tint has no alpha.
+ int index = 0;
+ for (int y = 0; y < source.pixelHeight; y++) {
+ for (int x = 0; x < source.pixelWidth; x++) {
+ int argb1 = source.pixels[index++];
+ int r1 = (argb1 >> 16) & 0xff;
+ int g1 = (argb1 >> 8) & 0xff;
+ int b1 = (argb1) & 0xff;
+
+ // Prior to 2.1, the alpha channel was commented out here,
+ // but can't remember why (just thought unnecessary b/c of RGB?)
+ // https://github.com/processing/processing/issues/2030
+ tintedTemp[x] = 0xFF000000 |
+ (((r2 * r1) & 0xff00) << 8) |
+ ((g2 * g1) & 0xff00) |
+ (((b2 * b1) & 0xff00) >> 8);
+ }
+ wr.setDataElements(0, y, source.pixelWidth, 1, tintedTemp);
+ }
+ // could this be any slower?
+// float[] scales = { tintR, tintG, tintB };
+// float[] offsets = new float[3];
+// RescaleOp op = new RescaleOp(scales, offsets, null);
+// op.filter(image, image);
+
+ //} else if (bufferType == BufferedImage.TYPE_INT_ARGB) {
+ } else if (targetType == ARGB) {
+ if (source.format == RGB &&
+ (tintColor & 0xffffff) == 0xffffff) {
+ int hi = tintColor & 0xff000000;
+ int index = 0;
+ for (int y = 0; y < source.pixelHeight; y++) {
+ for (int x = 0; x < source.pixelWidth; x++) {
+ tintedTemp[x] = hi | (source.pixels[index++] & 0xFFFFFF);
+ }
+ wr.setDataElements(0, y, source.pixelWidth, 1, tintedTemp);
+ }
+ } else {
+ int index = 0;
+ for (int y = 0; y < source.pixelHeight; y++) {
+ if (source.format == RGB) {
+ int alpha = tintColor & 0xFF000000;
+ for (int x = 0; x < source.pixelWidth; x++) {
+ int argb1 = source.pixels[index++];
+ int r1 = (argb1 >> 16) & 0xff;
+ int g1 = (argb1 >> 8) & 0xff;
+ int b1 = (argb1) & 0xff;
+ tintedTemp[x] = alpha |
+ (((r2 * r1) & 0xff00) << 8) |
+ ((g2 * g1) & 0xff00) |
+ (((b2 * b1) & 0xff00) >> 8);
+ }
+ } else if (source.format == ARGB) {
+ for (int x = 0; x < source.pixelWidth; x++) {
+ int argb1 = source.pixels[index++];
+ int a1 = (argb1 >> 24) & 0xff;
+ int r1 = (argb1 >> 16) & 0xff;
+ int g1 = (argb1 >> 8) & 0xff;
+ int b1 = (argb1) & 0xff;
+ tintedTemp[x] =
+ (((a2 * a1) & 0xff00) << 16) |
+ (((r2 * r1) & 0xff00) << 8) |
+ ((g2 * g1) & 0xff00) |
+ (((b2 * b1) & 0xff00) >> 8);
+ }
+ } else if (source.format == ALPHA) {
+ int lower = tintColor & 0xFFFFFF;
+ for (int x = 0; x < source.pixelWidth; x++) {
+ int a1 = source.pixels[index++];
+ tintedTemp[x] =
+ (((a2 * a1) & 0xff00) << 16) | lower;
+ }
+ }
+ wr.setDataElements(0, y, source.pixelWidth, 1, tintedTemp);
+ }
+ }
+ // Not sure why ARGB images take the scales in this order...
+// float[] scales = { tintR, tintG, tintB, tintA };
+// float[] offsets = new float[4];
+// RescaleOp op = new RescaleOp(scales, offsets, null);
+// op.filter(image, image);
+ }
+ } else { // !tint
+ if (targetType == RGB && (source.pixels[0] >> 24 == 0)) {
+ // If it's an RGB image and the high bits aren't set, need to set
+ // the high bits to opaque because we're drawing ARGB images.
+ source.filter(OPAQUE);
+ // Opting to just manipulate the image here, since it shouldn't
+ // affect anything else (and alpha(get(x, y)) should return 0xff).
+ // Wel also make no guarantees about the values of the pixels array
+ // in a PImage and how the high bits will be set.
+ }
+ // If no tint, just shove the pixels on in there verbatim
+ wr.setDataElements(0, 0, source.pixelWidth, source.pixelHeight, source.pixels);
+ }
+ this.tinted = tint;
+ this.tintedColor = tintColor;
+
+// GraphicsConfiguration gc = parent.getGraphicsConfiguration();
+// compat = gc.createCompatibleImage(image.getWidth(),
+// image.getHeight(),
+// Transparency.TRANSLUCENT);
+//
+// Graphics2D g = compat.createGraphics();
+// g.drawImage(image, 0, 0, null);
+// g.dispose();
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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
+
+
+ //public PShape loadShape(String filename)
+
+
+ @Override
+ public PShape loadShape(String filename, String options) {
+ String extension = PApplet.getExtension(filename);
+ if (extension.equals("svg") || extension.equals("svgz")) {
+ return new PShapeJava2D(parent.loadXML(filename));
+ }
+ PGraphics.showWarning("Unsupported format: " + filename);
+ return null;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TEXT ATTRIBTUES
+
+
+ //public void textAlign(int align)
+
+
+ //public void textAlign(int alignX, int alignY)
+
+
+ @Override
+ public float textAscent() {
+ if (textFont == null) {
+ defaultFontOrDeath("textAscent");
+ }
+
+ Font font = (Font) textFont.getNative();
+ if (font != null) {
+ //return getFontMetrics(font).getAscent();
+ return g2.getFontMetrics(font).getAscent();
+ }
+ return super.textAscent();
+ }
+
+
+ @Override
+ public float textDescent() {
+ if (textFont == null) {
+ defaultFontOrDeath("textDescent");
+ }
+ Font font = (Font) textFont.getNative();
+ if (font != null) {
+ //return getFontMetrics(font).getDescent();
+ return g2.getFontMetrics(font).getDescent();
+ }
+ return super.textDescent();
+ }
+
+
+ //public void textFont(PFont which)
+
+
+ //public void textFont(PFont which, float 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.
+ *
+ * Called from textFontImpl and textSizeImpl, so the metrics
+ * will get recorded properly.
+ */
+ @Override
+ protected void handleTextSize(float size) {
+ // if a native version available, derive this font
+ Font font = (Font) textFont.getNative();
+ // don't derive again if the font size has not changed
+ if (font != null) {
+ if (font.getSize2D() != size) {
+ Map map =
+ new HashMap<>();
+ map.put(TextAttribute.SIZE, size);
+ map.put(TextAttribute.KERNING,
+ TextAttribute.KERNING_ON);
+// map.put(TextAttribute.TRACKING,
+// TextAttribute.TRACKING_TIGHT);
+ font = font.deriveFont(map);
+ }
+ g2.setFont(font);
+ textFont.setNative(font);
+ fontObject = font;
+
+ /*
+ Map attrs = font.getAttributes();
+ for (TextAttribute ta : attrs.keySet()) {
+ System.out.println(ta + " -> " + attrs.get(ta));
+ }
+ */
+ }
+
+ // take care of setting the textSize and textLeading vars
+ // this has to happen second, because it calls textAscent()
+ // (which requires the native font metrics to be set)
+ super.handleTextSize(size);
+ }
+
+
+ //public float textWidth(char c)
+
+
+ //public float textWidth(String str)
+
+
+ @Override
+ protected float textWidthImpl(char buffer[], int start, int stop) {
+ if (textFont == null) {
+ defaultFontOrDeath("textWidth");
+ }
+ // Avoid "Zero length string passed to TextLayout constructor" error
+ if (start == stop) {
+ return 0;
+ }
+
+ Font font = (Font) textFont.getNative();
+// System.out.println(font);
+ //if (font != null && (textFont.isStream() || hints[ENABLE_NATIVE_FONTS])) {
+ if (font != null) {
+// System.out.println("using charswidth for " + new String(buffer, start, stop-start));
+ // maybe should use one of the newer/fancier functions for this?
+// int length = stop - start;
+// FontMetrics metrics = getFontMetrics(font);
+ FontMetrics metrics = g2.getFontMetrics(font);
+ // Using fractional metrics makes the measurement worse, not better,
+ // at least on OS X 10.6 (November, 2010).
+ // TextLayout returns the same value as charsWidth().
+// System.err.println("using native");
+// g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
+// RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+// float m1 = metrics.charsWidth(buffer, start, length);
+// float m2 = (float) metrics.getStringBounds(buffer, start, stop, g2).getWidth();
+// TextLayout tl = new TextLayout(new String(buffer, start, length), font, g2.getFontRenderContext());
+// float m3 = (float) tl.getBounds().getWidth();
+// System.err.println(m1 + " " + m2 + " " + m3);
+////// return m1;
+//// return m2;
+//// return metrics.charsWidth(buffer, start, length);
+// return m2;
+ return (float)
+ metrics.getStringBounds(buffer, start, stop, g2).getWidth();
+ }
+// System.err.println("not native");
+ return super.textWidthImpl(buffer, start, stop);
+ }
+
+
+// protected void beginTextScreenMode() {
+// loadPixels();
+// }
+
+
+// protected void endTextScreenMode() {
+// updatePixels();
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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) {
+ Font font = (Font) textFont.getNative();
+// if (font != null && (textFont.isStream() || hints[ENABLE_NATIVE_FONTS])) {
+ if (font != null) {
+ /*
+ // save the current setting for text smoothing. note that this is
+ // different from the smooth() function, because the font smoothing
+ // is controlled when the font is created, not now as it's drawn.
+ // fixed a bug in 0116 that handled this incorrectly.
+ Object textAntialias =
+ g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
+
+ // override the current text smoothing setting based on the font
+ // (don't change the global smoothing settings)
+ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+ textFont.smooth ?
+ RenderingHints.VALUE_ANTIALIAS_ON :
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ */
+ Object antialias =
+ g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
+ if (antialias == null) {
+ // if smooth() and noSmooth() not called, this will be null (0120)
+ antialias = RenderingHints.VALUE_ANTIALIAS_DEFAULT;
+ }
+
+ // override the current smoothing setting based on the font
+ // also changes global setting for antialiasing, but this is because it's
+ // not possible to enable/disable them independently in some situations.
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ textFont.isSmooth() ?
+ RenderingHints.VALUE_ANTIALIAS_ON :
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+
+ g2.setColor(fillColorObject);
+
+ int length = stop - start;
+ if (length != 0) {
+ g2.drawChars(buffer, start, length, (int) (x + 0.5f), (int) (y + 0.5f));
+ // better to use round here? also, drawChars now just calls drawString
+// g2.drawString(new String(buffer, start, stop - start), Math.round(x), Math.round(y));
+
+ // better to use drawString() with floats? (nope, draws the same)
+ //g2.drawString(new String(buffer, start, length), x, y);
+
+ // this didn't seem to help the scaling issue, and creates garbage
+ // because of a fairly heavyweight new temporary object
+// java.awt.font.GlyphVector gv =
+// font.createGlyphVector(g2.getFontRenderContext(), new String(buffer, start, stop - start));
+// g2.drawGlyphVector(gv, x, y);
+ }
+
+ // return to previous smoothing state if it was changed
+ //g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialias);
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias);
+
+ } else { // otherwise just do the default
+ super.textLineImpl(buffer, start, stop, x, y);
+ }
+ }
+
+
+// /**
+// * Convenience method to get a legit FontMetrics object. Where possible,
+// * override this any renderer subclass so that you're not using what's
+// * returned by getDefaultToolkit() to get your metrics.
+// */
+// @SuppressWarnings("deprecation")
+// public FontMetrics getFontMetrics(Font font) { // ignore
+// Frame frame = parent.frame;
+// if (frame != null) {
+// return frame.getToolkit().getFontMetrics(font);
+// }
+// return Toolkit.getDefaultToolkit().getFontMetrics(font);
+// }
+//
+//
+// /**
+// * Convenience method to jump through some Java2D hoops and get an FRC.
+// */
+// public FontRenderContext getFontRenderContext(Font font) { // ignore
+// return getFontMetrics(font).getFontRenderContext();
+// }
+
+ /*
+ Toolkit toolkit;
+
+ @SuppressWarnings("deprecation")
+ protected FontMetrics getFontMetrics(Font font) {
+ if (toolkit == null) {
+ try {
+ Canvas canvas = (Canvas) surface.getNative();
+ toolkit = canvas.getToolkit();
+ } catch (Exception e) {
+ // May error out if it's a PSurfaceNone or similar
+ toolkit = Toolkit.getDefaultToolkit();
+ }
+ }
+ return toolkit.getFontMetrics(font);
+ //return (g2 != null) ? g2.getFontMetrics(font) : super.getFontMetrics(font);
+ }
+ */
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX STACK
+
+
+ @Override
+ public void pushMatrix() {
+ if (transformCount == transformStack.length) {
+ throw new RuntimeException("pushMatrix() cannot use push more than " +
+ transformStack.length + " times");
+ }
+ transformStack[transformCount] = g2.getTransform();
+ transformCount++;
+ }
+
+
+ @Override
+ public void popMatrix() {
+ if (transformCount == 0) {
+ throw new RuntimeException("missing a pushMatrix() " +
+ "to go with that popMatrix()");
+ }
+ transformCount--;
+ g2.setTransform(transformStack[transformCount]);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX TRANSFORMS
+
+
+ @Override
+ public void translate(float tx, float ty) {
+ g2.translate(tx, ty);
+ }
+
+
+ //public void translate(float tx, float ty, float tz)
+
+
+ @Override
+ public void rotate(float angle) {
+ g2.rotate(angle);
+ }
+
+
+ @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) {
+ g2.scale(s, s);
+ }
+
+
+ @Override
+ public void scale(float sx, float sy) {
+ g2.scale(sx, sy);
+ }
+
+
+ @Override
+ public void scale(float sx, float sy, float sz) {
+ showDepthWarningXYZ("scale");
+ }
+
+
+ @Override
+ public void shearX(float angle) {
+ g2.shear(Math.tan(angle), 0);
+ }
+
+
+ @Override
+ public void shearY(float angle) {
+ g2.shear(0, Math.tan(angle));
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX MORE
+
+
+ @Override
+ public void resetMatrix() {
+ g2.setTransform(new AffineTransform());
+ g2.scale(pixelDensity, pixelDensity);
+ }
+
+
+ //public void applyMatrix(PMatrix2D source)
+
+
+ @Override
+ public void applyMatrix(float n00, float n01, float n02,
+ float n10, float n11, float n12) {
+ //System.out.println("PGraphicsJava2D.applyMatrix()");
+ //System.out.println(new AffineTransform(n00, n10, n01, n11, n02, n12));
+ g2.transform(new AffineTransform(n00, n10, n01, n11, n02, n12));
+ //g2.transform(new AffineTransform(n00, n01, n02, n10, n11, n12));
+ }
+
+
+ //public void applyMatrix(PMatrix3D source)
+
+
+ @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();
+ }
+ g2.getTransform().getMatrix(transform);
+ target.set((float) transform[0], (float) transform[2], (float) transform[4],
+ (float) transform[1], (float) transform[3], (float) transform[5]);
+ return target;
+ }
+
+
+ @Override
+ public PMatrix3D getMatrix(PMatrix3D target) {
+ showVariationWarning("getMatrix");
+ return target;
+ }
+
+
+ //public void setMatrix(PMatrix source)
+
+
+ @Override
+ public void setMatrix(PMatrix2D source) {
+ g2.setTransform(new AffineTransform(source.m00, source.m10,
+ source.m01, source.m11,
+ source.m02, source.m12));
+ }
+
+
+ @Override
+ public void setMatrix(PMatrix3D source) {
+ showVariationWarning("setMatrix");
+ }
+
+
+ @Override
+ public void printMatrix() {
+ getMatrix((PMatrix2D) null).print();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CAMERA and PROJECTION
+
+ // Inherit the plaintive warnings from PGraphics
+
+
+ //public void beginCamera()
+ //public void endCamera()
+ //public void camera()
+ //public void camera(float eyeX, float eyeY, float eyeZ,
+ // float centerX, float centerY, float centerZ,
+ // float upX, float upY, float upZ)
+ //public void printCamera()
+
+ //public void ortho()
+ //public void ortho(float left, float right,
+ // float bottom, float top,
+ // float near, float far)
+ //public void perspective()
+ //public void perspective(float fov, float aspect, float near, float far)
+ //public void frustum(float left, float right,
+ // float bottom, float top,
+ // float near, float far)
+ //public void printProjection()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SCREEN and MODEL transforms
+
+
+ @Override
+ public float screenX(float x, float y) {
+ g2.getTransform().getMatrix(transform);
+ return (float)transform[0]*x + (float)transform[2]*y + (float)transform[4];
+ }
+
+
+ @Override
+ public float screenY(float x, float y) {
+ g2.getTransform().getMatrix(transform);
+ return (float)transform[1]*x + (float)transform[3]*y + (float)transform[5];
+ }
+
+
+ @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);
+ strokeImpl();
+ }
+
+
+ @Override
+ public void strokeJoin(int join) {
+ super.strokeJoin(join);
+ strokeImpl();
+ }
+
+
+ @Override
+ public void strokeWeight(float weight) {
+ super.strokeWeight(weight);
+ strokeImpl();
+ }
+
+
+ protected void strokeImpl() {
+ int cap = BasicStroke.CAP_BUTT;
+ if (strokeCap == ROUND) {
+ cap = BasicStroke.CAP_ROUND;
+ } else if (strokeCap == PROJECT) {
+ cap = BasicStroke.CAP_SQUARE;
+ }
+
+ int join = BasicStroke.JOIN_BEVEL;
+ if (strokeJoin == MITER) {
+ join = BasicStroke.JOIN_MITER;
+ } else if (strokeJoin == ROUND) {
+ join = BasicStroke.JOIN_ROUND;
+ }
+
+ strokeObject = new BasicStroke(strokeWeight, cap, join);
+ g2.setStroke(strokeObject);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STROKE
+
+ // noStroke() and stroke() inherited from PGraphics.
+
+
+ @Override
+ protected void strokeFromCalc() {
+ super.strokeFromCalc();
+ strokeColorObject = new Color(strokeColor, true);
+ strokeGradient = false;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TINT
+
+ // noTint() and tint() inherited from PGraphics.
+
+
+ @Override
+ protected void tintFromCalc() {
+ super.tintFromCalc();
+ // TODO actually implement tinted images
+ tintColorObject = new Color(tintColor, true);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILL
+
+ // noFill() and fill() inherited from PGraphics.
+
+
+ @Override
+ protected void fillFromCalc() {
+ super.fillFromCalc();
+ fillColorObject = new Color(fillColor, true);
+ fillGradient = false;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATERIAL PROPERTIES
+
+
+ //public void ambient(int rgb)
+ //public void ambient(float gray)
+ //public void ambient(float x, float y, float z)
+ //protected void ambientFromCalc()
+ //public void specular(int rgb)
+ //public void specular(float gray)
+ //public void specular(float x, float y, float z)
+ //protected void specularFromCalc()
+ //public void shininess(float shine)
+ //public void emissive(int rgb)
+ //public void emissive(float gray)
+ //public void emissive(float x, float y, float z )
+ //protected void emissiveFromCalc()
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // LIGHTS
+
+
+ //public void lights()
+ //public void noLights()
+ //public void ambientLight(float red, float green, float blue)
+ //public void ambientLight(float red, float green, float blue,
+ // float x, float y, float z)
+ //public void directionalLight(float red, float green, float blue,
+ // float nx, float ny, float nz)
+ //public void pointLight(float red, float green, float blue,
+ // float x, float y, float z)
+ //public void spotLight(float red, float green, float blue,
+ // float x, float y, float z,
+ // float nx, float ny, float nz,
+ // float angle, float concentration)
+ //public void lightFalloff(float constant, float linear, float quadratic)
+ //public void lightSpecular(float x, float y, float z)
+ //protected void lightPosition(int num, float x, float y, float z)
+ //protected void lightDirection(int num, float x, float y, float z)
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BACKGROUND
+
+
+ int[] clearPixels;
+
+ protected void clearPixels(int color) {
+ // On a hi-res display, image may be larger than width/height
+ int imageWidth = image.getWidth(null);
+ int imageHeight = image.getHeight(null);
+
+ // Create a small array that can be used to set the pixels several times.
+ // Using a single-pixel line of length 'width' is a tradeoff between
+ // speed (setting each pixel individually is too slow) and memory
+ // (an array for width*height would waste lots of memory if it stayed
+ // resident, and would terrify the gc if it were re-created on each trip
+ // to background().
+// WritableRaster raster = ((BufferedImage) image).getRaster();
+// WritableRaster raster = image.getRaster();
+ WritableRaster raster = getRaster();
+ if ((clearPixels == null) || (clearPixels.length < imageWidth)) {
+ clearPixels = new int[imageWidth];
+ }
+ Arrays.fill(clearPixels, 0, imageWidth, backgroundColor);
+ for (int i = 0; i < imageHeight; i++) {
+ raster.setDataElements(0, i, imageWidth, 1, clearPixels);
+ }
+ }
+
+ // background() methods inherited from PGraphics, along with the
+ // PImage version of backgroundImpl(), since it just calls set().
+
+
+ //public void backgroundImpl(PImage image)
+
+
+ @Override
+ public void backgroundImpl() {
+ if (backgroundAlpha) {
+ clearPixels(backgroundColor);
+
+ } else {
+ Color bgColor = new Color(backgroundColor);
+ // seems to fire an additional event that causes flickering,
+ // like an extra background erase on OS X
+// if (canvas != null) {
+// canvas.setBackground(bgColor);
+// }
+ //new Exception().printStackTrace(System.out);
+ // in case people do transformations before background(),
+ // need to handle this with a push/reset/pop
+ Composite oldComposite = g2.getComposite();
+ g2.setComposite(defaultComposite);
+
+ pushMatrix();
+ resetMatrix();
+ g2.setColor(bgColor); //, backgroundAlpha));
+// g2.fillRect(0, 0, width, height);
+ // On a hi-res display, image may be larger than width/height
+ if (image != null) {
+ // image will be null in subclasses (i.e. PDF)
+ g2.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
+ } else {
+ // hope for the best if image is null
+ g2.fillRect(0, 0, width, height);
+ }
+ popMatrix();
+
+ g2.setComposite(oldComposite);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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
+
+
+ protected WritableRaster getRaster() {
+ WritableRaster raster = null;
+ if (primaryGraphics) {
+ /*
+ // 'offscreen' will probably be removed in the next release
+ if (useOffscreen) {
+ raster = offscreen.getRaster();
+ } else*/ if (image instanceof VolatileImage) {
+ // when possible, we'll try VolatileImage
+ raster = ((VolatileImage) image).getSnapshot().getRaster();
+ }
+ }
+ if (raster == null) {
+ raster = ((BufferedImage) image).getRaster();
+ }
+
+ // On Raspberry Pi (and perhaps other platforms, the color buffer won't
+ // necessarily be the int array that we'd like. Need to convert it here.
+ // Not that this would probably mean getRaster() would need to work more
+ // like loadRaster/updateRaster because the pixels will need to be
+ // temporarily moved to (and later from) a buffer that's understood by
+ // the rest of the Processing source.
+ // https://github.com/processing/processing/issues/2010
+ if (raster.getTransferType() != DataBuffer.TYPE_INT) {
+ System.err.println("See https://github.com/processing/processing/issues/2010");
+ throw new RuntimeException("Pixel operations are not supported on this device.");
+ }
+ return raster;
+ }
+
+
+ @Override
+ public void loadPixels() {
+ if (pixels == null || (pixels.length != pixelWidth*pixelHeight)) {
+ pixels = new int[pixelWidth * pixelHeight];
+ }
+
+ WritableRaster raster = getRaster();
+ raster.getDataElements(0, 0, pixelWidth, pixelHeight, pixels);
+ if (raster.getNumBands() == 3) {
+ // Java won't set the high bits when RGB, returns 0 for alpha
+ // https://github.com/processing/processing/issues/2030
+ for (int i = 0; i < pixels.length; i++) {
+ pixels[i] = 0xff000000 | pixels[i];
+ }
+ }
+ //((BufferedImage) image).getRGB(0, 0, width, height, pixels, 0, width);
+// WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster();
+// WritableRaster raster = image.getRaster();
+ }
+
+
+// /**
+// * 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() {
+// //updatePixels(0, 0, width, height);
+//// WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster();
+//// WritableRaster raster = image.getRaster();
+// updatePixels(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)) {
+// System.err.format("%d %d %d %d .. w/h = %d %d .. pw/ph = %d %d %n", x, y, c, d, width, height, pixelWidth, pixelHeight);
+ if ((x != 0) || (y != 0) || (c != pixelWidth) || (d != pixelHeight)) {
+ // Show a warning message, but continue anyway.
+ showVariationWarning("updatePixels(x, y, w, h)");
+// new Exception().printStackTrace(System.out);
+ }
+// updatePixels();
+ if (pixels != null) {
+ getRaster().setDataElements(0, 0, pixelWidth, pixelHeight, pixels);
+ }
+ modified = true;
+ }
+
+
+// @Override
+// protected void updatePixelsImpl(int x, int y, int w, int h) {
+// super.updatePixelsImpl(x, y, w, h);
+//
+// if ((x != 0) || (y != 0) || (w != width) || (h != height)) {
+// // Show a warning message, but continue anyway.
+// showVariationWarning("updatePixels(x, y, w, h)");
+// }
+// getRaster().setDataElements(0, 0, width, height, pixels);
+// }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // GET/SET
+
+
+ static int getset[] = new int[1];
+
+
+ @Override
+ public int get(int x, int y) {
+ if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0;
+ //return ((BufferedImage) image).getRGB(x, y);
+// WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster();
+ WritableRaster raster = getRaster();
+ raster.getDataElements(x, y, getset);
+ if (raster.getNumBands() == 3) {
+ // https://github.com/processing/processing/issues/2030
+ return getset[0] | 0xff000000;
+ }
+ return getset[0];
+ }
+
+
+ //public PImage get(int x, int y, int w, int h)
+
+
+ @Override
+ protected void getImpl(int sourceX, int sourceY,
+ int sourceWidth, int sourceHeight,
+ PImage target, int targetX, int targetY) {
+ // last parameter to getRGB() is the scan size of the *target* buffer
+ //((BufferedImage) image).getRGB(x, y, w, h, output.pixels, 0, w);
+// WritableRaster raster =
+// ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster();
+ WritableRaster raster = getRaster();
+
+ if (sourceWidth == target.pixelWidth && sourceHeight == target.pixelHeight) {
+ raster.getDataElements(sourceX, sourceY, sourceWidth, sourceHeight, target.pixels);
+ // https://github.com/processing/processing/issues/2030
+ if (raster.getNumBands() == 3) {
+ target.filter(OPAQUE);
+ }
+
+ } else {
+ // TODO optimize, incredibly inefficient to reallocate this much memory
+ int[] temp = new int[sourceWidth * sourceHeight];
+ raster.getDataElements(sourceX, sourceY, sourceWidth, sourceHeight, temp);
+
+ // Copy the temporary output pixels over to the outgoing image
+ int sourceOffset = 0;
+ int targetOffset = targetY*target.pixelWidth + targetX;
+ for (int y = 0; y < sourceHeight; y++) {
+ if (raster.getNumBands() == 3) {
+ for (int i = 0; i < sourceWidth; i++) {
+ // Need to set the high bits for this feller
+ // https://github.com/processing/processing/issues/2030
+ target.pixels[targetOffset + i] = 0xFF000000 | temp[sourceOffset + i];
+ }
+ } else {
+ System.arraycopy(temp, sourceOffset, target.pixels, targetOffset, sourceWidth);
+ }
+ sourceOffset += sourceWidth;
+ targetOffset += target.pixelWidth;
+ }
+ }
+ }
+
+
+ @Override
+ public void set(int x, int y, int argb) {
+ if ((x < 0) || (y < 0) || (x >= pixelWidth) || (y >= pixelHeight)) return;
+// ((BufferedImage) image).setRGB(x, y, argb);
+ getset[0] = argb;
+// WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster();
+// WritableRaster raster = image.getRaster();
+ getRaster().setDataElements(x, y, getset);
+ }
+
+
+ //public void set(int x, int y, PImage img)
+
+
+ @Override
+ protected void setImpl(PImage sourceImage,
+ int sourceX, int sourceY,
+ int sourceWidth, int sourceHeight,
+ int targetX, int targetY) {
+ WritableRaster raster = getRaster();
+// ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster();
+
+ if ((sourceX == 0) && (sourceY == 0) &&
+ (sourceWidth == sourceImage.pixelWidth) &&
+ (sourceHeight == sourceImage.pixelHeight)) {
+// System.out.format("%d %d %dx%d %d%n", targetX, targetY,
+// sourceImage.width, sourceImage.height,
+// sourceImage.pixels.length);
+ raster.setDataElements(targetX, targetY,
+ sourceImage.pixelWidth, sourceImage.pixelHeight,
+ sourceImage.pixels);
+ } else {
+ // TODO optimize, incredibly inefficient to reallocate this much memory
+ PImage temp = sourceImage.get(sourceX, sourceY, sourceWidth, sourceHeight);
+ raster.setDataElements(targetX, targetY, temp.pixelWidth, temp.pixelHeight, temp.pixels);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MASK
+
+
+ static final String MASK_WARNING =
+ "mask() cannot be used on the main drawing surface";
+
+
+ @Override
+ public void mask(int[] alpha) {
+ if (primaryGraphics) {
+ showWarning(MASK_WARNING);
+
+ } else {
+ super.mask(alpha);
+ }
+ }
+
+
+ @Override
+ public void mask(PImage alpha) {
+ if (primaryGraphics) {
+ showWarning(MASK_WARNING);
+
+ } else {
+ super.mask(alpha);
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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 ((sw != dw) || (sh != dh)) {
+ g2.drawImage(image, dx, dy, dx + dw, dy + dh, sx, sy, sx + sw, sy + sh, null);
+
+ } else {
+ dx = dx - sx; // java2d's "dx" is the delta, not dest
+ dy = dy - sy;
+ g2.copyArea(sx, sy, sw, sh, dx, dy);
+ }
+ }
+
+
+ @Override
+ public void copy(PImage src,
+ int sx, int sy, int sw, int sh,
+ int dx, int dy, int dw, int dh) {
+ g2.drawImage((Image) src.getNative(),
+ dx, dy, dx + dw, dy + dh,
+ sx, sy, sx + sw, sy + sh, null);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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);
+// }
+}
diff --git a/src/main/java/processing/awt/PShapeJava2D.java b/src/main/java/processing/awt/PShapeJava2D.java
new file mode 100644
index 0000000..2b9b968
--- /dev/null
+++ b/src/main/java/processing/awt/PShapeJava2D.java
@@ -0,0 +1,377 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2015 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.awt;
+
+import java.awt.Paint;
+import java.awt.PaintContext;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.ColorModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+
+import processing.core.PApplet;
+import processing.core.PGraphics;
+import processing.core.PShapeSVG;
+import processing.data.*;
+
+
+/**
+ * Implements features for PShape that are specific to AWT and Java2D.
+ * At the moment, this is gradients and java.awt.Paint handling.
+ */
+public class PShapeJava2D extends PShapeSVG {
+ Paint strokeGradientPaint;
+ Paint fillGradientPaint;
+
+
+ public PShapeJava2D(XML svg) {
+ super(svg);
+ }
+
+
+ public PShapeJava2D(PShapeSVG parent, XML properties, boolean parseKids) {
+ super(parent, properties, parseKids);
+ }
+
+
+ @Override
+ protected void setParent(PShapeSVG parent) {
+ super.setParent(parent);
+
+ if (parent instanceof PShapeJava2D) {
+ PShapeJava2D pj = (PShapeJava2D) parent;
+ fillGradientPaint = pj.fillGradientPaint;
+ strokeGradientPaint = pj.strokeGradientPaint;
+
+ } else { // parent is null or not Java2D
+ fillGradientPaint = null;
+ strokeGradientPaint = null;
+ }
+ }
+
+
+ /** Factory method for subclasses. */
+ @Override
+ protected PShapeSVG createShape(PShapeSVG parent, XML properties, boolean parseKids) {
+ return new PShapeJava2D(parent, properties, parseKids);
+ }
+
+
+ /*
+ @Override
+ public void setColor(String colorText, boolean isFill) {
+ super.setColor(colorText, isFill);
+
+ if (fillGradient != null) {
+ fillGradientPaint = calcGradientPaint(fillGradient);
+ }
+ if (strokeGradient != null) {
+ strokeGradientPaint = calcGradientPaint(strokeGradient);
+ }
+ }
+ */
+
+
+ static class LinearGradientPaint implements Paint {
+ float x1, y1, x2, y2;
+ float[] offset;
+ int[] color;
+ int count;
+ float opacity;
+
+ public LinearGradientPaint(float x1, float y1, float x2, float y2,
+ float[] offset, int[] color, int count,
+ float opacity) {
+ this.x1 = x1;
+ this.y1 = y1;
+ this.x2 = x2;
+ this.y2 = y2;
+ this.offset = offset;
+ this.color = color;
+ this.count = count;
+ this.opacity = opacity;
+ }
+
+ public PaintContext createContext(ColorModel cm,
+ Rectangle deviceBounds, Rectangle2D userBounds,
+ AffineTransform xform, RenderingHints hints) {
+ Point2D t1 = xform.transform(new Point2D.Float(x1, y1), null);
+ Point2D t2 = xform.transform(new Point2D.Float(x2, y2), null);
+ return new LinearGradientContext((float) t1.getX(), (float) t1.getY(),
+ (float) t2.getX(), (float) t2.getY());
+ }
+
+ public int getTransparency() {
+ return TRANSLUCENT; // why not.. rather than checking each color
+ }
+
+ public class LinearGradientContext implements PaintContext {
+ int ACCURACY = 2;
+ float tx1, ty1, tx2, ty2;
+
+ public LinearGradientContext(float tx1, float ty1, float tx2, float ty2) {
+ this.tx1 = tx1;
+ this.ty1 = ty1;
+ this.tx2 = tx2;
+ this.ty2 = ty2;
+ }
+
+ public void dispose() { }
+
+ public ColorModel getColorModel() { return ColorModel.getRGBdefault(); }
+
+ public Raster getRaster(int x, int y, int w, int h) {
+ WritableRaster raster =
+ getColorModel().createCompatibleWritableRaster(w, h);
+
+ int[] data = new int[w * h * 4];
+
+ // make normalized version of base vector
+ float nx = tx2 - tx1;
+ float ny = ty2 - ty1;
+ float len = (float) Math.sqrt(nx*nx + ny*ny);
+ if (len != 0) {
+ nx /= len;
+ ny /= len;
+ }
+
+ int span = (int) PApplet.dist(tx1, ty1, tx2, ty2) * ACCURACY;
+ if (span <= 0) {
+ //System.err.println("span is too small");
+ // annoying edge case where the gradient isn't legit
+ int index = 0;
+ for (int j = 0; j < h; j++) {
+ for (int i = 0; i < w; i++) {
+ data[index++] = 0;
+ data[index++] = 0;
+ data[index++] = 0;
+ data[index++] = 255;
+ }
+ }
+
+ } else {
+ int[][] interp = new int[span][4];
+ int prev = 0;
+ for (int i = 1; i < count; i++) {
+ int c0 = color[i-1];
+ int c1 = color[i];
+ int last = (int) (offset[i] * (span-1));
+ //System.out.println("last is " + last);
+ for (int j = prev; j <= last; j++) {
+ float btwn = PApplet.norm(j, prev, last);
+ interp[j][0] = (int) PApplet.lerp((c0 >> 16) & 0xff, (c1 >> 16) & 0xff, btwn);
+ interp[j][1] = (int) PApplet.lerp((c0 >> 8) & 0xff, (c1 >> 8) & 0xff, btwn);
+ interp[j][2] = (int) PApplet.lerp(c0 & 0xff, c1 & 0xff, btwn);
+ interp[j][3] = (int) (PApplet.lerp((c0 >> 24) & 0xff, (c1 >> 24) & 0xff, btwn) * opacity);
+ //System.out.println(j + " " + interp[j][0] + " " + interp[j][1] + " " + interp[j][2]);
+ }
+ prev = last;
+ }
+
+ int index = 0;
+ for (int j = 0; j < h; j++) {
+ for (int i = 0; i < w; i++) {
+ //float distance = 0; //PApplet.dist(cx, cy, x + i, y + j);
+ //int which = PApplet.min((int) (distance * ACCURACY), interp.length-1);
+ float px = (x + i) - tx1;
+ float py = (y + j) - ty1;
+ // distance up the line is the dot product of the normalized
+ // vector of the gradient start/stop by the point being tested
+ int which = (int) ((px*nx + py*ny) * ACCURACY);
+ if (which < 0) which = 0;
+ if (which > interp.length-1) which = interp.length-1;
+ //if (which > 138) System.out.println("grabbing " + which);
+
+ data[index++] = interp[which][0];
+ data[index++] = interp[which][1];
+ data[index++] = interp[which][2];
+ data[index++] = interp[which][3];
+ }
+ }
+ }
+ raster.setPixels(0, 0, w, h, data);
+
+ return raster;
+ }
+ }
+ }
+
+
+ static class RadialGradientPaint implements Paint {
+ float cx, cy, radius;
+ float[] offset;
+ int[] color;
+ int count;
+ float opacity;
+
+ public RadialGradientPaint(float cx, float cy, float radius,
+ float[] offset, int[] color, int count,
+ float opacity) {
+ this.cx = cx;
+ this.cy = cy;
+ this.radius = radius;
+ this.offset = offset;
+ this.color = color;
+ this.count = count;
+ this.opacity = opacity;
+ }
+
+ public PaintContext createContext(ColorModel cm,
+ Rectangle deviceBounds, Rectangle2D userBounds,
+ AffineTransform xform, RenderingHints hints) {
+ return new RadialGradientContext();
+ }
+
+ public int getTransparency() {
+ return TRANSLUCENT;
+ }
+
+ public class RadialGradientContext implements PaintContext {
+ int ACCURACY = 5;
+
+ public void dispose() {}
+
+ public ColorModel getColorModel() { return ColorModel.getRGBdefault(); }
+
+ public Raster getRaster(int x, int y, int w, int h) {
+ WritableRaster raster =
+ getColorModel().createCompatibleWritableRaster(w, h);
+
+ int span = (int) radius * ACCURACY;
+ int[][] interp = new int[span][4];
+ int prev = 0;
+ for (int i = 1; i < count; i++) {
+ int c0 = color[i-1];
+ int c1 = color[i];
+ int last = (int) (offset[i] * (span - 1));
+ for (int j = prev; j <= last; j++) {
+ float btwn = PApplet.norm(j, prev, last);
+ interp[j][0] = (int) PApplet.lerp((c0 >> 16) & 0xff, (c1 >> 16) & 0xff, btwn);
+ interp[j][1] = (int) PApplet.lerp((c0 >> 8) & 0xff, (c1 >> 8) & 0xff, btwn);
+ interp[j][2] = (int) PApplet.lerp(c0 & 0xff, c1 & 0xff, btwn);
+ interp[j][3] = (int) (PApplet.lerp((c0 >> 24) & 0xff, (c1 >> 24) & 0xff, btwn) * opacity);
+ }
+ prev = last;
+ }
+
+ int[] data = new int[w * h * 4];
+ int index = 0;
+ for (int j = 0; j < h; j++) {
+ for (int i = 0; i < w; i++) {
+ float distance = PApplet.dist(cx, cy, x + i, y + j);
+ int which = PApplet.min((int) (distance * ACCURACY), interp.length-1);
+
+ data[index++] = interp[which][0];
+ data[index++] = interp[which][1];
+ data[index++] = interp[which][2];
+ data[index++] = interp[which][3];
+ }
+ }
+ raster.setPixels(0, 0, w, h, data);
+
+ return raster;
+ }
+ }
+ }
+
+
+ protected Paint calcGradientPaint(Gradient gradient) {
+ if (gradient instanceof LinearGradient) {
+// System.out.println("creating linear gradient");
+ LinearGradient grad = (LinearGradient) gradient;
+ return new LinearGradientPaint(grad.x1, grad.y1, grad.x2, grad.y2,
+ grad.offset, grad.color, grad.count,
+ opacity);
+
+ } else if (gradient instanceof RadialGradient) {
+// System.out.println("creating radial gradient");
+ RadialGradient grad = (RadialGradient) gradient;
+ return new RadialGradientPaint(grad.cx, grad.cy, grad.r,
+ grad.offset, grad.color, grad.count,
+ opacity);
+ }
+ return null;
+ }
+
+
+// protected Paint calcGradientPaint(Gradient gradient,
+// float x1, float y1, float x2, float y2) {
+// if (gradient instanceof LinearGradient) {
+// LinearGradient grad = (LinearGradient) gradient;
+// return new LinearGradientPaint(x1, y1, x2, y2,
+// grad.offset, grad.color, grad.count,
+// opacity);
+// }
+// throw new RuntimeException("Not a linear gradient.");
+// }
+
+
+// protected Paint calcGradientPaint(Gradient gradient,
+// float cx, float cy, float r) {
+// if (gradient instanceof RadialGradient) {
+// RadialGradient grad = (RadialGradient) gradient;
+// return new RadialGradientPaint(cx, cy, r,
+// grad.offset, grad.color, grad.count,
+// opacity);
+// }
+// throw new RuntimeException("Not a radial gradient.");
+// }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ @Override
+ protected void styles(PGraphics g) {
+ super.styles(g);
+
+ //if (g instanceof PGraphicsJava2D) {
+ PGraphicsJava2D p2d = (PGraphicsJava2D) g;
+
+ if (strokeGradient != null) {
+ p2d.strokeGradient = true;
+ if (strokeGradientPaint == null) {
+ strokeGradientPaint = calcGradientPaint(strokeGradient);
+ }
+ p2d.strokeGradientObject = strokeGradientPaint;
+ } else {
+ // need to shut off, in case parent object has a gradient applied
+ //p2d.strokeGradient = false;
+ }
+ if (fillGradient != null) {
+ p2d.fillGradient = true;
+ if (fillGradientPaint == null) {
+ fillGradientPaint = calcGradientPaint(fillGradient);
+ }
+ p2d.fillGradientObject = fillGradientPaint;
+ } else {
+ // need to shut off, in case parent object has a gradient applied
+ //p2d.fillGradient = false;
+ }
+ //}
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/processing/awt/PSurfaceAWT.java b/src/main/java/processing/awt/PSurfaceAWT.java
new file mode 100644
index 0000000..4cf50e8
--- /dev/null
+++ b/src/main/java/processing/awt/PSurfaceAWT.java
@@ -0,0 +1,1567 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2014-15 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 as published by the Free Software Foundation, version 2.1.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.awt;
+
+import java.awt.Canvas;
+import java.awt.Color;
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.Label;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.event.*;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.*;
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.JFrame;
+
+import processing.core.PApplet;
+import processing.core.PConstants;
+import processing.core.PGraphics;
+import processing.core.PImage;
+import processing.core.PSurfaceNone;
+import processing.event.KeyEvent;
+import processing.event.MouseEvent;
+
+
+public class PSurfaceAWT extends PSurfaceNone {
+ GraphicsDevice displayDevice;
+
+ // used for canvas to determine whether resizable or not
+// boolean resizable; // default is false
+
+ // Internally, we know it's always a JFrame (not just a Frame)
+// JFrame frame;
+ // Trying Frame again with a11 to see if this avoids some Swing nastiness.
+ // In the past, AWT Frames caused some problems on Windows and Linux,
+ // but those may not be a problem for our reworked PSurfaceAWT class.
+ Frame frame;
+
+ // Note that x and y may not be zero, depending on the display configuration
+ Rectangle screenRect;
+
+ // Used for resizing, at least on Windows insets size changes when
+ // frame.setResizable() is called, and in resize listener we need
+ // to know what size the window was before.
+ Insets currentInsets = new Insets(0, 0, 0, 0);
+
+ // 3.0a5 didn't use strategy, and active was shut off during init() w/ retina
+// boolean useStrategy = true;
+
+ Canvas canvas;
+// Component canvas;
+
+// PGraphics graphics; // moved to PSurfaceNone
+
+ int sketchWidth;
+ int sketchHeight;
+
+ int windowScaleFactor;
+
+
+ public PSurfaceAWT(PGraphics graphics) {
+ //this.graphics = graphics;
+ super(graphics);
+
+ /*
+ if (checkRetina()) {
+// System.out.println("retina in use");
+
+ // The active-mode rendering seems to be 2x slower, so disable it
+ // with retina. On a non-retina machine, however, useActive seems
+ // the only (or best) way to handle the rendering.
+// useActive = false;
+// canvas = new JPanel(true) {
+// @Override
+// public void paint(Graphics screen) {
+//// if (!sketch.insideDraw) {
+// screen.drawImage(PSurfaceAWT.this.graphics.image, 0, 0, sketchWidth, sketchHeight, null);
+//// }
+// }
+// };
+ // Under 1.8 and the current 3.0a6 threading regime, active mode w/o
+ // strategy is far faster, but perhaps only because it's blitting with
+ // flicker--pushing pixels out before the screen has finished rendering.
+// useStrategy = false;
+ }
+ */
+ canvas = new SmoothCanvas();
+// if (useStrategy) {
+ //canvas.setIgnoreRepaint(true);
+// }
+
+ // Pass tab key to the sketch, rather than moving between components
+ canvas.setFocusTraversalKeysEnabled(false);
+
+ canvas.addComponentListener(new ComponentAdapter() {
+ @Override
+ public void componentResized(ComponentEvent e) {
+ if (!sketch.isLooping()) {
+ // make sure this is a real resize event, not just initial setup
+ // https://github.com/processing/processing/issues/3310
+ Dimension canvasSize = canvas.getSize();
+ if (canvasSize.width != sketch.sketchWidth() ||
+ canvasSize.height != sketch.sketchHeight()) {
+ sketch.redraw();
+ }
+ }
+ }
+ });
+ addListeners();
+ }
+
+
+// /**
+// * Handle grabbing the focus on startup. Other renderers can override this
+// * if handling needs to be different. For the AWT, the request is invoked
+// * later on the EDT. Other implementations may not require that, so the
+// * invokeLater() happens in here rather than requiring the caller to wrap it.
+// */
+// @Override
+// void requestFocus() {
+//// System.out.println("requesFocus() outer " + EventQueue.isDispatchThread());
+// // for 2.0a6, moving this request to the EDT
+// EventQueue.invokeLater(new Runnable() {
+// public void run() {
+// // Call the request focus event once the image is sure to be on
+// // screen and the component is valid. The OpenGL renderer will
+// // request focus for its canvas inside beginDraw().
+// // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
+// // Disabling for 0185, because it causes an assertion failure on OS X
+// // http://code.google.com/p/processing/issues/detail?id=258
+// // requestFocus();
+//
+// // Changing to this version for 0187
+// // http://code.google.com/p/processing/issues/detail?id=279
+// //requestFocusInWindow();
+//
+// // For 3.0, just call this directly on the Canvas object
+// if (canvas != null) {
+// //System.out.println("requesting focus " + EventQueue.isDispatchThread());
+// //System.out.println("requesting focus " + frame.isVisible());
+// //canvas.requestFocusInWindow();
+// canvas.requestFocus();
+// }
+// }
+// });
+// }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public class SmoothCanvas extends Canvas {
+ private Dimension oldSize = new Dimension(0, 0);
+ private Dimension newSize = new Dimension(0, 0);
+
+
+ // Turns out getParent() returns a JPanel on a JFrame. Yech.
+ public Frame getFrame() {
+ return frame;
+ }
+
+
+ @Override
+ public Dimension getPreferredSize() {
+ return new Dimension(sketchWidth, sketchHeight);
+ }
+
+
+ @Override
+ public Dimension getMinimumSize() {
+ return getPreferredSize();
+ }
+
+
+ @Override
+ public Dimension getMaximumSize() {
+ //return resizable ? super.getMaximumSize() : getPreferredSize();
+ return frame.isResizable() ? super.getMaximumSize() : getPreferredSize();
+ }
+
+
+ @Override
+ public void validate() {
+ super.validate();
+ newSize.width = getWidth();
+ newSize.height = getHeight();
+// if (oldSize.equals(newSize)) {
+//// System.out.println("validate() return " + oldSize);
+// return;
+// } else {
+ if (!oldSize.equals(newSize)) {
+// System.out.println("validate() render old=" + oldSize + " -> new=" + newSize);
+ oldSize = newSize;
+ sketch.setSize(newSize.width / windowScaleFactor, newSize.height / windowScaleFactor);
+// try {
+ render();
+// } catch (IllegalStateException ise) {
+// System.out.println(ise.getMessage());
+// }
+ }
+ }
+
+
+ @Override
+ public void update(Graphics g) {
+// System.out.println("updating");
+ paint(g);
+ }
+
+
+ @Override
+ public void paint(Graphics screen) {
+// System.out.println("painting");
+// if (useStrategy) {
+ render();
+ /*
+ if (graphics != null) {
+ System.out.println("drawing to screen " + canvas);
+ screen.drawImage(graphics.image, 0, 0, sketchWidth, sketchHeight, null);
+ }
+ */
+
+// } else {
+//// new Exception("painting").printStackTrace(System.out);
+//// if (graphics.image != null) { // && !sketch.insideDraw) {
+// if (onscreen != null) {
+//// synchronized (graphics.image) {
+// // Needs the width/height to be set so that retina images are properly scaled down
+//// screen.drawImage(graphics.image, 0, 0, sketchWidth, sketchHeight, null);
+// synchronized (offscreenLock) {
+// screen.drawImage(onscreen, 0, 0, sketchWidth, sketchHeight, null);
+// }
+// }
+// }
+ }
+ }
+
+ /*
+ @Override
+ public void addNotify() {
+// System.out.println("adding notify");
+ super.addNotify();
+ // prior to Java 7 on OS X, this no longer works [121222]
+// createBufferStrategy(2);
+ }
+ */
+
+
+ synchronized protected void render() {
+ if (canvas.isDisplayable() &&
+ graphics.image != null) {
+ if (canvas.getBufferStrategy() == null) {
+ canvas.createBufferStrategy(2);
+ }
+ BufferStrategy strategy = canvas.getBufferStrategy();
+ if (strategy != null) {
+ // Render single frame
+// try {
+ do {
+ // The following loop ensures that the contents of the drawing buffer
+ // are consistent in case the underlying surface was recreated
+ do {
+ Graphics2D draw = (Graphics2D) strategy.getDrawGraphics();
+ // draw to width/height, since this may be a 2x image
+ draw.drawImage(graphics.image, 0, 0, sketchWidth, sketchHeight, null);
+ draw.dispose();
+ } while (strategy.contentsRestored());
+
+ // Display the buffer
+ strategy.show();
+
+ // Repeat the rendering if the drawing buffer was lost
+ } while (strategy.contentsLost());
+ }
+ }
+ }
+
+
+ /*
+ protected void blit() {
+ // Other folks that call render() (i.e. paint()) are already on the EDT.
+ // We need to be using the EDT since we're messing with the Canvas
+ // object and BufferStrategy and friends.
+ //EventQueue.invokeLater(new Runnable() {
+ //public void run() {
+ //((SmoothCanvas) canvas).render();
+ //}
+ //});
+
+ if (useStrategy) {
+ // Not necessary to be on the EDT to update BufferStrategy
+ //((SmoothCanvas) canvas).render();
+ render();
+ } else {
+ if (graphics.image != null) {
+ BufferedImage graphicsImage = (BufferedImage) graphics.image;
+ if (offscreen == null ||
+ offscreen.getWidth() != graphicsImage.getWidth() ||
+ offscreen.getHeight() != graphicsImage.getHeight()) {
+ System.out.println("creating new image");
+ offscreen = (BufferedImage)
+ canvas.createImage(graphicsImage.getWidth(),
+ graphicsImage.getHeight());
+// off = offscreen.getGraphics();
+ }
+// synchronized (offscreen) {
+ Graphics2D off = (Graphics2D) offscreen.getGraphics();
+// off.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1));
+ off.drawImage(graphicsImage, 0, 0, null);
+// }
+ off.dispose();
+ synchronized (offscreenLock) {
+ BufferedImage temp = onscreen;
+ onscreen = offscreen;
+ offscreen = temp;
+ }
+ canvas.repaint();
+ }
+ }
+ }
+ */
+
+
+ // what needs to happen here?
+ @Override
+ public void initOffscreen(PApplet sketch) {
+ this.sketch = sketch;
+ }
+
+ /*
+ public Frame initOffscreen() {
+ Frame dummy = new Frame();
+ dummy.pack(); // get legit AWT graphics
+ // but don't show it
+ return dummy;
+ }
+ */
+
+ /*
+ @Override
+ public Component initComponent(PApplet sketch) {
+ this.sketch = sketch;
+
+ // needed for getPreferredSize() et al
+ sketchWidth = sketch.sketchWidth();
+ sketchHeight = sketch.sketchHeight();
+
+ return canvas;
+ }
+ */
+
+
+ @Override
+ public void initFrame(final PApplet sketch) {/*, int backgroundColor,
+ int deviceIndex, boolean fullScreen, boolean spanDisplays) {*/
+ this.sketch = sketch;
+
+ GraphicsEnvironment environment =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+
+ int displayNum = sketch.sketchDisplay();
+// System.out.println("display from sketch is " + displayNum);
+ if (displayNum > 0) { // if -1, use the default device
+ GraphicsDevice[] devices = environment.getScreenDevices();
+ if (displayNum <= devices.length) {
+ displayDevice = devices[displayNum - 1];
+ } else {
+ System.err.format("Display %d does not exist, " +
+ "using the default display instead.%n", displayNum);
+ for (int i = 0; i < devices.length; i++) {
+ System.err.format("Display %d is %s%n", (i+1), devices[i]);
+ }
+ }
+ }
+ if (displayDevice == null) {
+ displayDevice = environment.getDefaultScreenDevice();
+ }
+
+ // 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
+ boolean spanDisplays = sketch.sketchDisplay() == PConstants.SPAN;
+ screenRect = spanDisplays ? getDisplaySpan() :
+ displayDevice.getDefaultConfiguration().getBounds();
+ // DisplayMode doesn't work here, because we can't get the upper-left
+ // corner of the display, which is important for multi-display setups.
+
+ // Set the displayWidth/Height variables inside PApplet, so that they're
+ // usable and can even be returned by the sketchWidth()/Height() methods.
+ sketch.displayWidth = screenRect.width;
+ sketch.displayHeight = screenRect.height;
+
+ windowScaleFactor = PApplet.platform == PConstants.MACOSX ?
+ 1 : sketch.pixelDensity;
+
+ sketchWidth = sketch.sketchWidth() * windowScaleFactor;
+ sketchHeight = sketch.sketchHeight() * windowScaleFactor;
+
+ boolean fullScreen = sketch.sketchFullScreen();
+ // Removing the section below because sometimes people want to do the
+ // full screen size in a window, and it also breaks insideSettings().
+ // With 3.x, fullScreen() is so easy, that it's just better that way.
+ // https://github.com/processing/processing/issues/3545
+ /*
+ // Sketch has already requested to be the same as the screen's
+ // width and height, so let's roll with full screen mode.
+ if (screenRect.width == sketchWidth &&
+ screenRect.height == sketchHeight) {
+ fullScreen = true;
+ sketch.fullScreen(); // won't change the renderer
+ }
+ */
+
+ if (fullScreen || spanDisplays) {
+ sketchWidth = screenRect.width;
+ sketchHeight = screenRect.height;
+ }
+
+ // Using a JFrame fixes a Windows problem with Present mode. This might
+ // be our error, but usually this is the sort of crap we usually get from
+ // OS X. It's time for a turnaround: Redmond is thinking different too!
+ // https://github.com/processing/processing/issues/1955
+ frame = new JFrame(displayDevice.getDefaultConfiguration());
+// frame = new Frame(displayDevice.getDefaultConfiguration());
+// // Default Processing gray, which will be replaced below if another
+// // color is specified on the command line (i.e. in the prefs).
+// ((JFrame) frame).getContentPane().setBackground(WINDOW_BGCOLOR);
+// // Cannot call setResizable(false) until later due to OS X (issue #467)
+
+// // Removed code above, also removed from what's now in the placeXxxx()
+// // methods. Not sure why it was being double-set; hopefully anachronistic.
+// if (backgroundColor == 0) {
+// backgroundColor = WINDOW_BGCOLOR;
+// }
+ final Color windowColor = new Color(sketch.sketchWindowColor(), false);
+ if (frame instanceof JFrame) {
+ ((JFrame) frame).getContentPane().setBackground(windowColor);
+ } else {
+ frame.setBackground(windowColor);
+ }
+
+ // Put the p5 logo in the Frame's corner to override the Java coffee cup.
+ setProcessingIcon(frame);
+
+ // 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
+
+ frame.add(canvas);
+ setSize(sketchWidth / windowScaleFactor, sketchHeight / windowScaleFactor);
+
+ /*
+ if (fullScreen) {
+ // Called here because the graphics device is needed before we can
+ // determine whether the sketch wants size(displayWidth, displayHeight),
+ // and getting the graphics device will be PSurface-specific.
+ PApplet.hideMenuBar();
+
+ // Tried to use this to fix the 'present' mode issue.
+ // Did not help, and the screenRect setup seems to work fine.
+ //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
+
+ // https://github.com/processing/processing/pull/3162
+ frame.dispose(); // release native resources, allows setUndecorated()
+ frame.setUndecorated(true);
+ // another duplicate?
+// if (backgroundColor != null) {
+// frame.getContentPane().setBackground(backgroundColor);
+// }
+ // this may be the bounds of all screens
+ frame.setBounds(screenRect);
+ // will be set visible in placeWindow() [3.0a10]
+ //frame.setVisible(true); // re-add native resources
+ }
+ */
+ frame.setLayout(null);
+ //frame.add(applet);
+
+ // Need to pass back our new sketchWidth/Height here, because it may have
+ // been overridden by numbers we calculated above if fullScreen and/or
+ // spanScreens was in use.
+// pg = sketch.makePrimaryGraphics(sketchWidth, sketchHeight);
+// pg = sketch.makePrimaryGraphics();
+
+ // resize sketch to sketchWidth/sketchHeight here
+
+ if (fullScreen) {
+ frame.invalidate();
+ } else {
+// frame.pack();
+ }
+
+ // insufficient, places the 100x100 sketches offset strangely
+ //frame.validate();
+
+ // disabling resize has to happen after pack() to avoid apparent Apple bug
+ // http://code.google.com/p/processing/issues/detail?id=467
+ frame.setResizable(false);
+
+ frame.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent e) {
+ sketch.exit(); // don't quit, need to just shut everything down (0133)
+ }
+ });
+
+// sketch.setFrame(frame);
+ }
+
+
+ @Override
+ public Object getNative() {
+ return canvas;
+ }
+
+
+// public Toolkit getToolkit() {
+// return canvas.getToolkit();
+// }
+
+
+ /** Set the window (and dock, or whatever necessary) title. */
+ @Override
+ public void setTitle(String title) {
+ frame.setTitle(title);
+ // Workaround for apparent Java bug on OS X?
+ // https://github.com/processing/processing/issues/3472
+ if (cursorVisible &&
+ (PApplet.platform == PConstants.MACOSX) &&
+ (cursorType != PConstants.ARROW)) {
+ hideCursor();
+ showCursor();
+ }
+ }
+
+
+ /** Set true if we want to resize things (default is not resizable) */
+ @Override
+ public void setResizable(boolean resizable) {
+ //this.resizable = resizable; // really only used for canvas
+
+ if (frame != null) {
+ frame.setResizable(resizable);
+ }
+ }
+
+
+ @Override
+ public void setIcon(PImage image) {
+ Image awtImage = (Image) image.getNative();
+
+ if (PApplet.platform != PConstants.MACOSX) {
+ frame.setIconImage(awtImage);
+
+ } else {
+ try {
+ final String td = "processing.core.ThinkDifferent";
+ Class> thinkDifferent =
+ Thread.currentThread().getContextClassLoader().loadClass(td);
+ Method method =
+ thinkDifferent.getMethod("setIconImage", new Class[] { java.awt.Image.class });
+ method.invoke(null, new Object[] { awtImage });
+ } catch (Exception e) {
+ e.printStackTrace(); // That's unfortunate
+ }
+ }
+ }
+
+
+ @Override
+ public void setAlwaysOnTop(boolean always) {
+ frame.setAlwaysOnTop(always);
+ }
+
+
+ @Override
+ public void setLocation(int x, int y) {
+ frame.setLocation(x, y);
+ }
+
+
+ List iconImages;
+
+ protected void setProcessingIcon(Frame frame) {
+ // On OS X, this only affects what shows up in the dock when minimized.
+ // So replacing it is actually a step backwards. Brilliant.
+ if (PApplet.platform != PConstants.MACOSX) {
+ //Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
+ //frame.setIconImage(image);
+ try {
+ if (iconImages == null) {
+ iconImages = new ArrayList();
+ final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 };
+
+ for (int sz : sizes) {
+ //URL url = getClass().getResource("/icon/icon-" + sz + ".png");
+ URL url = PApplet.class.getResource("/icon/icon-" + sz + ".png");
+ Image image = Toolkit.getDefaultToolkit().getImage(url);
+ iconImages.add(image);
+ //iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame));
+ }
+ }
+ frame.setIconImages(iconImages);
+
+ } catch (Exception e) { } // harmless; keep this to ourselves
+
+ } else { // handle OS X differently
+ if (!dockIconSpecified()) { // don't override existing -Xdock param
+ // On OS X, set this for AWT surfaces, which handles the dock image
+ // as well as the cmd-tab image that's shown. Just one size, I guess.
+ URL url = PApplet.class.getResource("/icon/icon-512.png");
+ // Seems dangerous to have this in code instead of using reflection, no?
+ //ThinkDifferent.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
+ try {
+ final String td = "processing.core.ThinkDifferent";
+ Class> thinkDifferent =
+ Thread.currentThread().getContextClassLoader().loadClass(td);
+ Method method =
+ thinkDifferent.getMethod("setIconImage", new Class[] { java.awt.Image.class });
+ method.invoke(null, new Object[] { Toolkit.getDefaultToolkit().getImage(url) });
+ } catch (Exception e) {
+ e.printStackTrace(); // That's unfortunate
+ }
+ }
+ }
+ }
+
+
+ /**
+ * @return true if -Xdock:icon was specified on the command line
+ */
+ private boolean dockIconSpecified() {
+ // TODO This is incomplete... Haven't yet found a way to figure out if
+ // the app has an icns file specified already. Help?
+ List jvmArgs =
+ ManagementFactory.getRuntimeMXBean().getInputArguments();
+ for (String arg : jvmArgs) {
+ if (arg.startsWith("-Xdock:icon")) {
+ return true; // dock image already set
+ }
+ }
+ return false;
+ }
+
+
+ @Override
+ public void setVisible(boolean visible) {
+ frame.setVisible(visible);
+
+ // Generally useful whenever setting the frame visible
+ if (canvas != null) {
+ //canvas.requestFocusInWindow();
+ canvas.requestFocus();
+ }
+
+ // removing per https://github.com/processing/processing/pull/3162
+ // can remove the code below once 3.0a6 is tested and behaving
+/*
+ if (visible && PApplet.platform == PConstants.LINUX) {
+ // Linux doesn't deal with insets the same way. We get fake insets
+ // earlier, and then the window manager will slap its own insets
+ // onto things once the frame is realized on the screen. Awzm.
+ if (PApplet.platform == PConstants.LINUX) {
+ Insets insets = frame.getInsets();
+ frame.setSize(Math.max(sketchWidth, MIN_WINDOW_WIDTH) +
+ insets.left + insets.right,
+ Math.max(sketchHeight, MIN_WINDOW_HEIGHT) +
+ insets.top + insets.bottom);
+ }
+ }
+*/
+ }
+
+
+ //public void placeFullScreen(boolean hideStop) {
+ @Override
+ public void placePresent(int stopColor) {
+ setFullFrame();
+
+ // After the pack(), the screen bounds are gonna be 0s
+// frame.setBounds(screenRect); // already called in setFullFrame()
+ canvas.setBounds((screenRect.width - sketchWidth) / 2,
+ (screenRect.height - sketchHeight) / 2,
+ sketchWidth, sketchHeight);
+
+// if (PApplet.platform == PConstants.MACOSX) {
+// macosxFullScreenEnable(frame);
+// macosxFullScreenToggle(frame);
+// }
+
+ if (stopColor != 0) {
+ Label label = new Label("stop");
+ label.setForeground(new Color(stopColor, false));
+ label.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mousePressed(java.awt.event.MouseEvent e) {
+ sketch.exit();
+ }
+ });
+ 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, screenRect.height - labelSize.height - 20);
+ }
+
+// if (sketch.getGraphics().displayable()) {
+// setVisible(true);
+// }
+ }
+
+
+ /*
+ @Override
+ public void placeWindow(int[] location) {
+ setFrameSize(); //sketchWidth, sketchHeight);
+
+ if (location != null) {
+ // a specific location was received from the Runner
+ // (applet has been run more than once, user placed window)
+ frame.setLocation(location[0], location[1]);
+
+ } else { // just center on screen
+ // Can't use frame.setLocationRelativeTo(null) because it sends the
+ // frame to the main display, which undermines the --display setting.
+ frame.setLocation(screenRect.x + (screenRect.width - sketchWidth) / 2,
+ screenRect.y + (screenRect.height - sketchHeight) / 2);
+ }
+ Point frameLoc = frame.getLocation();
+ if (frameLoc.y < 0) {
+ // Windows actually allows you to place frames where they can't be
+ // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
+ frame.setLocation(frameLoc.x, 30);
+ }
+
+// if (backgroundColor != null) {
+// ((JFrame) frame).getContentPane().setBackground(backgroundColor);
+// }
+
+ setCanvasSize(); //sketchWidth, sketchHeight);
+
+ frame.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ });
+
+ // handle frame resizing events
+ setupFrameResizeListener();
+
+ // all set for rockin
+ if (sketch.getGraphics().displayable()) {
+ frame.setVisible(true);
+ }
+ }
+ */
+
+
+ private void setCanvasSize() {
+// System.out.format("setting canvas size %d %d%n", sketchWidth, sketchHeight);
+// new Exception().printStackTrace(System.out);
+ int contentW = Math.max(sketchWidth, MIN_WINDOW_WIDTH);
+ int contentH = Math.max(sketchHeight, MIN_WINDOW_HEIGHT);
+
+ canvas.setBounds((contentW - sketchWidth)/2,
+ (contentH - sketchHeight)/2,
+ sketchWidth, sketchHeight);
+ }
+
+
+ /** Resize frame for these sketch (canvas) dimensions. */
+ private Dimension setFrameSize() { //int sketchWidth, int sketchHeight) {
+ // https://github.com/processing/processing/pull/3162
+ frame.addNotify(); // using instead of show() to add the peer [fry]
+
+// System.out.format("setting frame size %d %d %n", sketchWidth, sketchHeight);
+// new Exception().printStackTrace(System.out);
+ currentInsets = frame.getInsets();
+ int windowW = Math.max(sketchWidth, MIN_WINDOW_WIDTH) +
+ currentInsets.left + currentInsets.right;
+ int windowH = Math.max(sketchHeight, MIN_WINDOW_HEIGHT) +
+ currentInsets.top + currentInsets.bottom;
+ frame.setSize(windowW, windowH);
+ return new Dimension(windowW, windowH);
+ }
+
+
+ private void setFrameCentered() {
+ // Can't use frame.setLocationRelativeTo(null) because it sends the
+ // frame to the main display, which undermines the --display setting.
+ frame.setLocation(screenRect.x + (screenRect.width - sketchWidth) / 2,
+ screenRect.y + (screenRect.height - sketchHeight) / 2);
+ }
+
+
+ /** Hide the menu bar, make the Frame undecorated, set it to screenRect. */
+ private void setFullFrame() {
+ // Called here because the graphics device is needed before we can
+ // determine whether the sketch wants size(displayWidth, displayHeight),
+ // and getting the graphics device will be PSurface-specific.
+ PApplet.hideMenuBar();
+
+ // Tried to use this to fix the 'present' mode issue.
+ // Did not help, and the screenRect setup seems to work fine.
+ //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
+
+ // https://github.com/processing/processing/pull/3162
+ //frame.dispose(); // release native resources, allows setUndecorated()
+ frame.removeNotify();
+ frame.setUndecorated(true);
+ frame.addNotify();
+
+ // this may be the bounds of all screens
+ frame.setBounds(screenRect);
+ // will be set visible in placeWindow() [3.0a10]
+ //frame.setVisible(true); // re-add native resources
+ }
+
+
+ @Override
+ public void placeWindow(int[] location, int[] editorLocation) {
+ //Dimension window = setFrameSize(sketchWidth, sketchHeight);
+ Dimension window = setFrameSize(); //sketchWidth, sketchHeight);
+
+ int contentW = Math.max(sketchWidth, MIN_WINDOW_WIDTH);
+ int contentH = Math.max(sketchHeight, MIN_WINDOW_HEIGHT);
+
+ if (sketch.sketchFullScreen()) {
+ setFullFrame();
+ }
+
+ // Ignore placement of previous window and editor when full screen
+ if (!sketch.sketchFullScreen()) {
+ if (location != null) {
+ // a specific location was received from the Runner
+ // (applet has been run more than once, user placed window)
+ frame.setLocation(location[0], location[1]);
+
+ } else if (editorLocation != null) {
+ int locationX = editorLocation[0] - 20;
+ int locationY = editorLocation[1];
+
+ if (locationX - window.width > 10) {
+ // if it fits to the left of the window
+ frame.setLocation(locationX - window.width, 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;
+ locationX = (sketch.displayWidth - window.width) / 2;
+ locationY = (sketch.displayHeight - window.height) / 2;
+
+ /*
+ if ((locationX + window.width > sketch.displayWidth - 33) ||
+ (locationY + window.height > sketch.displayHeight - 33)) {
+ // otherwise center on screen
+ locationX = (sketch.displayWidth - window.width) / 2;
+ locationY = (sketch.displayHeight - window.height) / 2;
+ }
+ */
+ frame.setLocation(locationX, locationY);
+ }
+ } else { // just center on screen
+ setFrameCentered();
+ }
+ Point frameLoc = frame.getLocation();
+ if (frameLoc.y < 0) {
+ // Windows actually allows you to place frames where they can't be
+ // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
+ frame.setLocation(frameLoc.x, 30);
+ }
+ }
+
+ canvas.setBounds((contentW - sketchWidth)/2,
+ (contentH - sketchHeight)/2,
+ sketchWidth, sketchHeight);
+
+ // handle frame resizing events
+ setupFrameResizeListener();
+
+ /*
+ // If displayable() is false, then PSurfaceNone should be used, but...
+ if (sketch.getGraphics().displayable()) {
+ frame.setVisible(true);
+// System.out.println("setting visible on EDT? " + EventQueue.isDispatchThread());
+ //requestFocus();
+// if (canvas != null) {
+// //canvas.requestFocusInWindow();
+// canvas.requestFocus();
+// }
+ }
+ */
+// if (sketch.getGraphics().displayable()) {
+// setVisible(true);
+// }
+ }
+
+
+ // needs to resize the frame, which will resize the canvas, and so on...
+ @Override
+ public void setSize(int wide, int high) {
+ // When the surface is set to resizable via surface.setResizable(true),
+ // a crash may occur if the user sets the window to size zero.
+ // https://github.com/processing/processing/issues/5052
+ if (high <= 0) {
+ high = 1;
+ }
+ if (wide <= 0) {
+ wide = 1;
+ }
+
+// if (PApplet.DEBUG) {
+// //System.out.format("frame visible %b, setSize(%d, %d) %n", frame.isVisible(), wide, high);
+// new Exception(String.format("setSize(%d, %d)", wide, high)).printStackTrace(System.out);
+// }
+
+ //if (wide == sketchWidth && high == sketchHeight) { // doesn't work on launch
+ if (wide == sketch.width && high == sketch.height &&
+ (frame == null || currentInsets.equals(frame.getInsets()))) {
+// if (PApplet.DEBUG) {
+// new Exception("w/h unchanged " + wide + " " + high).printStackTrace(System.out);
+// }
+ return; // unchanged, don't rebuild everything
+ }
+
+ sketchWidth = wide * windowScaleFactor;
+ sketchHeight = high * windowScaleFactor;
+
+// canvas.setSize(wide, high);
+// frame.setSize(wide, high);
+ if (frame != null) { // skip if just a canvas
+ setFrameSize(); //wide, high);
+ }
+ setCanvasSize();
+// if (frame != null) {
+// frame.setLocationRelativeTo(null);
+// }
+
+ //initImage(graphics, wide, high);
+
+ //throw new RuntimeException("implement me, see readme.md");
+ sketch.setSize(wide, high);
+// sketch.width = wide;
+// sketch.height = high;
+
+ // set PGraphics variables for width/height/pixelWidth/pixelHeight
+ graphics.setSize(wide, high);
+// System.out.println("out of setSize()");
+ }
+
+
+ //public void initImage(PGraphics gr, int wide, int high) {
+ /*
+ @Override
+ public void initImage(PGraphics graphics) {
+ GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
+ // If not realized (off-screen, i.e the Color Selector Tool), gc will be null.
+ if (gc == null) {
+ System.err.println("GraphicsConfiguration null in initImage()");
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
+ }
+
+ // Formerly this was broken into separate versions based on offscreen or
+ // not, but we may as well create a compatible image; it won't hurt, right?
+ int wide = graphics.width * graphics.pixelFactor;
+ int high = graphics.height * graphics.pixelFactor;
+ graphics.image = gc.createCompatibleImage(wide, high);
+ }
+ */
+
+
+// @Override
+// public Component getComponent() {
+// return canvas;
+// }
+
+
+// @Override
+// public void setSmooth(int level) {
+// }
+
+
+ /*
+ private boolean checkRetina() {
+ if (PApplet.platform == PConstants.MACOSX) {
+ // This should probably be reset each time there's a display change.
+ // A 5-minute search didn't turn up any such event in the Java 7 API.
+ // Also, should we use the Toolkit associated with the editor window?
+ final String javaVendor = System.getProperty("java.vendor");
+ if (javaVendor.contains("Oracle")) {
+ GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ GraphicsDevice device = env.getDefaultScreenDevice();
+
+ try {
+ Field field = device.getClass().getDeclaredField("scale");
+ if (field != null) {
+ field.setAccessible(true);
+ Object scale = field.get(device);
+
+ if (scale instanceof Integer && ((Integer)scale).intValue() == 2) {
+ return true;
+ }
+ }
+ } catch (Exception ignore) { }
+ }
+ }
+ return false;
+ }
+ */
+
+
+ /** Get the bounds rectangle for all displays. */
+ static Rectangle getDisplaySpan() {
+ Rectangle bounds = new Rectangle();
+ GraphicsEnvironment environment =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+ for (GraphicsDevice device : environment.getScreenDevices()) {
+ for (GraphicsConfiguration config : device.getConfigurations()) {
+ Rectangle2D.union(bounds, config.getBounds(), bounds);
+ }
+ }
+ return bounds;
+ }
+
+
+ /*
+ private void checkDisplaySize() {
+ if (canvas.getGraphicsConfiguration() != null) {
+ GraphicsDevice displayDevice = getGraphicsConfiguration().getDevice();
+
+ if (displayDevice != null) {
+ Rectangle screenRect =
+ displayDevice.getDefaultConfiguration().getBounds();
+
+ displayWidth = screenRect.width;
+ displayHeight = screenRect.height;
+ }
+ }
+ }
+ */
+
+
+ /**
+ * 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.
+ */
+ @Override
+ public void setupExternalMessages() {
+ frame.addComponentListener(new ComponentAdapter() {
+ @Override
+ public void componentMoved(ComponentEvent e) {
+ Point where = ((Frame) e.getSource()).getLocation();
+ sketch.frameMoved(where.x, where.y);
+ }
+ });
+ }
+
+
+ /**
+ * Set up a listener that will fire proper component resize events
+ * in cases where frame.setResizable(true) is called.
+ */
+ private void setupFrameResizeListener() {
+ frame.addWindowStateListener(new WindowStateListener() {
+ @Override
+ // Detecting when the frame is resized in order to handle the frame
+ // maximization bug in OSX:
+ // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8036935
+ public void windowStateChanged(WindowEvent e) {
+ // This seems to be firing when dragging the window on OS X
+ // https://github.com/processing/processing/issues/3092
+ if (Frame.MAXIMIZED_BOTH == e.getNewState()) {
+ // Supposedly, sending the frame to back and then front is a
+ // workaround for this bug:
+ // http://stackoverflow.com/a/23897602
+ // but is not working for me...
+ //frame.toBack();
+ //frame.toFront();
+ // Packing the frame works, but that causes the window to collapse
+ // on OS X when the window is dragged. Changing to addNotify() for
+ // https://github.com/processing/processing/issues/3092
+ //frame.pack();
+ frame.addNotify();
+ }
+ }
+ });
+
+ frame.addComponentListener(new ComponentAdapter() {
+ @Override
+ 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()) {
+ Dimension windowSize = farm.getSize();
+ int x = farm.getX() + currentInsets.left;
+ int y = farm.getY() + currentInsets.top;
+
+ // JFrame (unlike java.awt.Frame) doesn't include the left/top
+ // insets for placement (though it does seem to need them for
+ // overall size of the window. Perhaps JFrame sets its coord
+ // system so that (0, 0) is always the upper-left of the content
+ // area. Which seems nice, but breaks any f*ing AWT-based code.
+ int w = windowSize.width - currentInsets.left - currentInsets.right;
+ int h = windowSize.height - currentInsets.top - currentInsets.bottom;
+ setSize(w / windowScaleFactor, h / windowScaleFactor);
+
+ // correct the location when inset size changes
+ setLocation(x - currentInsets.left, y - currentInsets.top);
+ }
+ }
+ }
+ });
+ }
+
+
+// /**
+// * (No longer in use) Use reflection to call
+// * com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(window, true);
+// */
+// static void macosxFullScreenEnable(Window window) {
+// try {
+// Class> util = Class.forName("com.apple.eawt.FullScreenUtilities");
+// Class params[] = new Class[] { Window.class, Boolean.TYPE };
+// Method method = util.getMethod("setWindowCanFullScreen", params);
+// method.invoke(util, window, true);
+//
+// } catch (ClassNotFoundException cnfe) {
+// // ignored
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+// }
+//
+//
+// /**
+// * (No longer in use) Use reflection to call
+// * com.apple.eawt.Application.getApplication().requestToggleFullScreen(window);
+// */
+// static void macosxFullScreenToggle(Window window) {
+// try {
+// Class> appClass = Class.forName("com.apple.eawt.Application");
+//
+// Method getAppMethod = appClass.getMethod("getApplication");
+// Object app = getAppMethod.invoke(null, new Object[0]);
+//
+// Method requestMethod =
+// appClass.getMethod("requestToggleFullScreen", Window.class);
+// requestMethod.invoke(app, window);
+//
+// } catch (ClassNotFoundException cnfe) {
+// // ignored
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /*
+ // disabling for now; requires Java 1.7 and "precise" semantics are odd...
+ // returns 0.1 for tick-by-tick scrolling on OS X, but it's not a matter of
+ // calling ceil() on the value: 1.5 goes to 1, but 2.3 goes to 2.
+ // "precise" is a whole different animal, so add later API to shore that up.
+ static protected Method preciseWheelMethod;
+ static {
+ try {
+ preciseWheelMethod = MouseWheelEvent.class.getMethod("getPreciseWheelRotation", new Class[] { });
+ } catch (Exception e) {
+ // ignored, the method will just be set to null
+ }
+ }
+ */
+
+
+ /**
+ * 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 nativeMouseEvent(java.awt.event.MouseEvent nativeEvent) {
+ // the 'amount' is the number of button clicks for a click event,
+ // or the number of steps/clicks on the wheel for a mouse wheel event.
+ int peCount = nativeEvent.getClickCount();
+
+ int peAction = 0;
+ switch (nativeEvent.getID()) {
+ case java.awt.event.MouseEvent.MOUSE_PRESSED:
+ peAction = MouseEvent.PRESS;
+ break;
+ case java.awt.event.MouseEvent.MOUSE_RELEASED:
+ peAction = MouseEvent.RELEASE;
+ break;
+ case java.awt.event.MouseEvent.MOUSE_CLICKED:
+ peAction = MouseEvent.CLICK;
+ break;
+ case java.awt.event.MouseEvent.MOUSE_DRAGGED:
+ peAction = MouseEvent.DRAG;
+ break;
+ case java.awt.event.MouseEvent.MOUSE_MOVED:
+ peAction = MouseEvent.MOVE;
+ break;
+ case java.awt.event.MouseEvent.MOUSE_ENTERED:
+ peAction = MouseEvent.ENTER;
+ break;
+ case java.awt.event.MouseEvent.MOUSE_EXITED:
+ peAction = MouseEvent.EXIT;
+ break;
+ //case java.awt.event.MouseWheelEvent.WHEEL_UNIT_SCROLL:
+ case java.awt.event.MouseEvent.MOUSE_WHEEL:
+ peAction = MouseEvent.WHEEL;
+ /*
+ if (preciseWheelMethod != null) {
+ try {
+ peAmount = ((Double) preciseWheelMethod.invoke(nativeEvent, (Object[]) null)).floatValue();
+ } catch (Exception e) {
+ preciseWheelMethod = null;
+ }
+ }
+ */
+ peCount = ((MouseWheelEvent) nativeEvent).getWheelRotation();
+ break;
+ }
+
+ //System.out.println(nativeEvent);
+ //int modifiers = nativeEvent.getModifiersEx();
+ // If using getModifiersEx(), the regular modifiers don't set properly.
+ int modifiers = nativeEvent.getModifiers();
+
+ int peModifiers = modifiers &
+ (InputEvent.SHIFT_MASK |
+ InputEvent.CTRL_MASK |
+ InputEvent.META_MASK |
+ InputEvent.ALT_MASK);
+
+ // Windows and OS X seem to disagree on how to handle this. Windows only
+ // sets BUTTON1_DOWN_MASK, while OS X seems to set BUTTON1_MASK.
+ // This is an issue in particular with mouse release events:
+ // http://code.google.com/p/processing/issues/detail?id=1294
+ // The fix for which led to a regression (fixed here by checking both):
+ // http://code.google.com/p/processing/issues/detail?id=1332
+ int peButton = 0;
+// if ((modifiers & InputEvent.BUTTON1_MASK) != 0 ||
+// (modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) {
+// peButton = LEFT;
+// } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0 ||
+// (modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) {
+// peButton = CENTER;
+// } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0 ||
+// (modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) {
+// peButton = RIGHT;
+// }
+ if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
+ peButton = PConstants.LEFT;
+ } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
+ peButton = PConstants.CENTER;
+ } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
+ peButton = PConstants.RIGHT;
+ }
+
+ // If running on Mac OS, allow ctrl-click as right mouse. Prior to 0215,
+ // this used isPopupTrigger() on the native event, but that doesn't work
+ // for mouseClicked and mouseReleased (or others).
+ if (PApplet.platform == PConstants.MACOSX) {
+ //if (nativeEvent.isPopupTrigger()) {
+ if ((modifiers & InputEvent.CTRL_MASK) != 0) {
+ peButton = PConstants.RIGHT;
+ }
+ }
+
+ sketch.postEvent(new MouseEvent(nativeEvent, nativeEvent.getWhen(),
+ peAction, peModifiers,
+ nativeEvent.getX() / windowScaleFactor,
+ nativeEvent.getY() / windowScaleFactor,
+ peButton,
+ peCount));
+ }
+
+
+ protected void nativeKeyEvent(java.awt.event.KeyEvent event) {
+ int peAction = 0;
+ switch (event.getID()) {
+ case java.awt.event.KeyEvent.KEY_PRESSED:
+ peAction = KeyEvent.PRESS;
+ break;
+ case java.awt.event.KeyEvent.KEY_RELEASED:
+ peAction = KeyEvent.RELEASE;
+ break;
+ case java.awt.event.KeyEvent.KEY_TYPED:
+ peAction = KeyEvent.TYPE;
+ break;
+ }
+
+// int peModifiers = event.getModifiersEx() &
+// (InputEvent.SHIFT_DOWN_MASK |
+// InputEvent.CTRL_DOWN_MASK |
+// InputEvent.META_DOWN_MASK |
+// InputEvent.ALT_DOWN_MASK);
+ int peModifiers = event.getModifiers() &
+ (InputEvent.SHIFT_MASK |
+ InputEvent.CTRL_MASK |
+ InputEvent.META_MASK |
+ InputEvent.ALT_MASK);
+
+ sketch.postEvent(new KeyEvent(event, event.getWhen(),
+ peAction, peModifiers,
+ event.getKeyChar(), event.getKeyCode()));
+ }
+
+
+ // listeners, for all my men!
+ protected void addListeners() {
+
+ canvas.addMouseListener(new MouseListener() {
+
+ public void mousePressed(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+
+ public void mouseReleased(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+
+ public void mouseClicked(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+
+ public void mouseEntered(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+
+ public void mouseExited(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+ });
+
+ canvas.addMouseMotionListener(new MouseMotionListener() {
+
+ public void mouseDragged(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+
+ public void mouseMoved(java.awt.event.MouseEvent e) {
+ nativeMouseEvent(e);
+ }
+ });
+
+ canvas.addMouseWheelListener(new MouseWheelListener() {
+
+ public void mouseWheelMoved(MouseWheelEvent e) {
+ nativeMouseEvent(e);
+ }
+ });
+
+ canvas.addKeyListener(new KeyListener() {
+
+ public void keyPressed(java.awt.event.KeyEvent e) {
+ nativeKeyEvent(e);
+ }
+
+
+ public void keyReleased(java.awt.event.KeyEvent e) {
+ nativeKeyEvent(e);
+ }
+
+
+ public void keyTyped(java.awt.event.KeyEvent e) {
+ nativeKeyEvent(e);
+ }
+ });
+
+ canvas.addFocusListener(new FocusListener() {
+
+ public void focusGained(FocusEvent e) {
+ sketch.focused = true;
+ sketch.focusGained();
+ }
+
+ public void focusLost(FocusEvent e) {
+ sketch.focused = false;
+ sketch.focusLost();
+ }
+ });
+ }
+
+
+ /*
+ public void addListeners(Component comp) {
+ comp.addMouseListener(this);
+ comp.addMouseWheelListener(this);
+ comp.addMouseMotionListener(this);
+ comp.addKeyListener(this);
+ comp.addFocusListener(this);
+ }
+
+
+ public void removeListeners(Component comp) {
+ comp.removeMouseListener(this);
+ comp.removeMouseWheelListener(this);
+ comp.removeMouseMotionListener(this);
+ comp.removeKeyListener(this);
+ comp.removeFocusListener(this);
+ }
+ */
+
+
+// /**
+// * Call to remove, then add, listeners to a component.
+// * Avoids issues with double-adding.
+// */
+// public void updateListeners(Component comp) {
+// removeListeners(comp);
+// addListeners(comp);
+// }
+
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ int cursorType = PConstants.ARROW;
+ boolean cursorVisible = true;
+ Cursor invisibleCursor;
+
+
+ @Override
+ public void setCursor(int kind) {
+ // Swap the HAND cursor because MOVE doesn't seem to be available on OS X
+ // https://github.com/processing/processing/issues/2358
+ if (PApplet.platform == PConstants.MACOSX && kind == PConstants.MOVE) {
+ kind = PConstants.HAND;
+ }
+ canvas.setCursor(Cursor.getPredefinedCursor(kind));
+ cursorVisible = true;
+ this.cursorType = kind;
+ }
+
+
+ @Override
+ public void setCursor(PImage img, int x, int y) {
+ // Don't set cursorType, instead use cursorType to save the last
+ // regular cursor type used for when cursor() is called.
+ //cursor_type = Cursor.CUSTOM_CURSOR;
+
+ // this is a temporary workaround for the CHIP, will be removed
+ Dimension cursorSize = Toolkit.getDefaultToolkit().getBestCursorSize(img.width, img.height);
+ if (cursorSize.width == 0 || cursorSize.height == 0) {
+ return;
+ }
+
+ Cursor cursor =
+ canvas.getToolkit().createCustomCursor((Image) img.getNative(),
+ new Point(x, y),
+ "custom");
+ canvas.setCursor(cursor);
+ cursorVisible = true;
+ }
+
+
+ @Override
+ public void showCursor() {
+ // 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 sketch
+ // will be stuck b/c p5 thinks the cursor is set to one particular thing.
+ if (!cursorVisible) {
+ cursorVisible = true;
+ canvas.setCursor(Cursor.getPredefinedCursor(cursorType));
+ }
+ }
+
+
+ @Override
+ public void hideCursor() {
+ // Because the OS may have shown the cursor on its own,
+ // don't return if 'cursorVisible' is set to true. [rev 0216]
+
+ if (invisibleCursor == null) {
+ BufferedImage cursorImg =
+ new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
+ // this is a temporary workaround for the CHIP, will be removed
+ Dimension cursorSize = Toolkit.getDefaultToolkit().getBestCursorSize(16, 16);
+ if (cursorSize.width == 0 || cursorSize.height == 0) {
+ invisibleCursor = Cursor.getDefaultCursor();
+ } else {
+ invisibleCursor =
+ canvas.getToolkit().createCustomCursor(cursorImg, new Point(8, 8), "blank");
+ }
+ }
+ canvas.setCursor(invisibleCursor);
+ cursorVisible = false;
+ }
+
+
+ @Override
+ public Thread createThread() {
+ return new AnimationThread() {
+ @Override
+ public void callDraw() {
+ sketch.handleDraw();
+ render();
+ }
+ };
+ }
+
+
+ void debug(String format, Object ... args) {
+ System.out.format(format + "%n", args);
+ }
+}
diff --git a/src/main/java/processing/core/PApplet.java b/src/main/java/processing/core/PApplet.java
new file mode 100644
index 0000000..ea45f20
--- /dev/null
+++ b/src/main/java/processing/core/PApplet.java
@@ -0,0 +1,15708 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-15 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
+*/
+
+package processing.core;
+
+// used by link()
+import java.awt.Desktop;
+import java.awt.DisplayMode;
+import java.awt.EventQueue;
+import java.awt.FileDialog;
+import java.awt.Frame;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.HeadlessException;
+import java.awt.Image;
+import java.awt.Toolkit;
+import java.awt.color.ColorSpace;
+import java.awt.image.BufferedImage;
+
+// used by loadImage() functions
+import javax.imageio.ImageIO;
+// allows us to remove our own MediaTracker code
+import javax.swing.ImageIcon;
+// used by selectInput(), selectOutput(), selectFolder()
+import javax.swing.JFileChooser;
+import javax.swing.UIManager;
+// used to present the fullScreen() warning about Spaces on OS X
+import javax.swing.JOptionPane;
+// used by desktopFile() method
+import javax.swing.filechooser.FileSystemView;
+
+// loadXML() error handling
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.xml.sax.SAXException;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.net.*;
+import java.nio.charset.StandardCharsets;
+import java.text.*;
+import java.util.*;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.regex.*;
+import java.util.zip.*;
+
+import processing.data.*;
+import processing.event.*;
+import processing.opengl.*;
+
+
+/**
+ * Base class for all sketches that use processing.core.
+ *
+ * The
+ * Window Size and Full Screen page on the Wiki has useful information
+ * about sizing, multiple displays, full screen, etc.
+ *
+ * Processing uses active mode rendering. All animation tasks happen on the
+ * "Processing Animation Thread". The setup() and draw() methods are handled
+ * by that thread, and events (like mouse movement and key presses, which are
+ * fired by the event dispatch thread or EDT) are queued to be safely handled
+ * at the end of draw().
+ *
+ * Starting with 3.0a6, blit operations are on the EDT, so as not to cause
+ * GUI problems with Swing and AWT. In the case of the default renderer, the
+ * sketch renders to an offscreen image, then the EDT is asked to bring that
+ * image to the screen.
+ *
+ * For code that needs to run on the EDT, use EventQueue.invokeLater(). When
+ * doing so, be careful to synchronize between that code and the Processing
+ * animation thread. That is, you can't call Processing methods from the EDT
+ * or at any random time from another thread. Use of a callback function or
+ * the registerXxx() methods in PApplet can help ensure that your code doesn't
+ * do something naughty.
+ *
+ * As of Processing 3.0, we have removed Applet as the base class for PApplet.
+ * This means that we can remove lots of legacy code, however one downside is
+ * that it's no longer possible (without extra code) to embed a PApplet into
+ * another Java application.
+ *
+ * As of Processing 3.0, we have discontinued support for versions of Java
+ * prior to 1.8. We don't have enough people to support it, and for a
+ * project of our (tiny) size, we should be focusing on the future, rather
+ * than working around legacy Java code.
+ */
+public class PApplet implements PConstants {
+ /** Full name of the Java version (i.e. 1.5.0_11). */
+ static public final String javaVersionName =
+ System.getProperty("java.version");
+
+ static public final int javaPlatform;
+ static {
+ String version = javaVersionName;
+ if (javaVersionName.startsWith("1.")) {
+ version = version.substring(2);
+ }
+ javaPlatform = parseInt(version.substring(0, version.indexOf('.')));
+ }
+
+ /**
+ * Do not use; javaPlatform or javaVersionName are better options.
+ * For instance, javaPlatform is useful when you need a number for
+ * comparison, i.e. "if (javaPlatform >= 9)".
+ * @deprecated
+ */
+ @Deprecated
+ public static final float javaVersion = 1 + javaPlatform / 10f;
+
+ /**
+ * Current platform in use, one of the
+ * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER.
+ */
+ static public int platform;
+
+ static {
+ String osname = System.getProperty("os.name");
+
+ if (osname.indexOf("Mac") != -1) {
+ platform = MACOSX;
+
+ } else if (osname.indexOf("Windows") != -1) {
+ platform = WINDOWS;
+
+ } else if (osname.equals("Linux")) { // true for the ibm vm
+ platform = LINUX;
+
+ } else {
+ platform = OTHER;
+ }
+ }
+
+ /**
+ * Whether to use native (AWT) dialogs for selectInput and selectOutput.
+ * The native dialogs on some platforms can be ugly, buggy, or missing
+ * features. For 3.3.5, this defaults to true on all platforms.
+ */
+ static public boolean useNativeSelect = true;
+
+ /** The PGraphics renderer associated with this PApplet */
+ public PGraphics g;
+
+ /**
+ * ( begin auto-generated from displayWidth.xml )
+ *
+ * System variable which stores the width of the computer screen. For
+ * example, if the current screen resolution is 1024x768,
+ * displayWidth is 1024 and displayHeight is 768. These
+ * dimensions are useful when exporting full-screen applications.
+ *
+ * To ensure that the sketch takes over the entire screen, use "Present"
+ * instead of "Run". Otherwise the window will still have a frame border
+ * around it and not be placed in the upper corner of the screen. On Mac OS
+ * X, the menu bar will remain present unless "Present" mode is used.
+ *
+ * ( end auto-generated )
+ */
+ public int displayWidth;
+
+ /**
+ * ( begin auto-generated from displayHeight.xml )
+ *
+ * System variable that stores the height of the computer screen. For
+ * example, if the current screen resolution is 1024x768,
+ * displayWidth is 1024 and displayHeight is 768. These
+ * dimensions are useful when exporting full-screen applications.
+ *
+ * To ensure that the sketch takes over the entire screen, use "Present"
+ * instead of "Run". Otherwise the window will still have a frame border
+ * around it and not be placed in the upper corner of the screen. On Mac OS
+ * X, the menu bar will remain present unless "Present" mode is used.
+ *
+ * ( end auto-generated )
+ */
+ public int displayHeight;
+
+ /** A leech graphics object that is echoing all events. */
+ public PGraphics recorder;
+
+ /**
+ * Command line options passed in from main().
+ * This does not include the arguments passed in to PApplet itself.
+ * @see PApplet#main
+ */
+ public String[] args;
+
+ /**
+ * Path to sketch folder. Previously undocumented, made private in 3.0a5
+ * so that people use the sketchPath() method and it's inited properly.
+ * Call sketchPath() once to set the default.
+ */
+ private String sketchPath;
+// public String sketchPath;
+
+ static final boolean DEBUG = false;
+// static final boolean DEBUG = true;
+
+ /** Default width and height for sketch when not specified */
+ static public final int DEFAULT_WIDTH = 100;
+ static public final int DEFAULT_HEIGHT = 100;
+
+// /**
+// * Exception thrown when size() is called the first time.
+// *
+// * This is used internally so that setup() is forced to run twice
+// * when the renderer is changed. This is the only way for us to handle
+// * invoking the new renderer while also in the midst of rendering.
+// */
+// static public class RendererChangeException extends RuntimeException { }
+
+ /**
+ * true if no size() command has been executed. This is used to wait until
+ * a size has been set before placing in the window and showing it.
+ */
+// public boolean defaultSize;
+
+// /** Storage for the current renderer size to avoid re-allocation. */
+// Dimension currentSize = new Dimension();
+
+ /**
+ * ( begin auto-generated from pixels.xml )
+ *
+ * Array containing the values for all the pixels in the display window.
+ * These values are of the color datatype. This array is the size of the
+ * display window. For example, if the image is 100x100 pixels, there will
+ * be 10000 values and if the window is 200x300 pixels, there will be 60000
+ * values. The index value defines the position of a value within
+ * the array. For example, the statement color b = pixels[230] will
+ * set the variable b to be equal to the value at that location in
+ * the array.
+ *
+ * Before accessing this array, the data must loaded with the
+ * loadPixels() function. After the array data has been modified,
+ * the updatePixels() function must be run to update the changes.
+ * Without loadPixels(), running the code may (or will in future
+ * releases) result in a NullPointerException.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:pixels
+ * @see PApplet#loadPixels()
+ * @see PApplet#updatePixels()
+ * @see PApplet#get(int, int, int, int)
+ * @see PApplet#set(int, int, int)
+ * @see PImage
+ */
+ public int[] pixels;
+
+ /**
+ * ( begin auto-generated from width.xml )
+ *
+ * System variable which stores the width of the display window. This value
+ * is set by the first parameter of the size() function. For
+ * example, the function call size(320, 240) sets the width
+ * variable to the value 320. The value of width is zero until
+ * size() is called.
+ *
+ * ( end auto-generated )
+ * @webref environment
+ * @see PApplet#height
+ * @see PApplet#size(int, int)
+ */
+ public int width = DEFAULT_WIDTH;
+
+ /**
+ * ( begin auto-generated from height.xml )
+ *
+ * System variable which stores the height of the display window. This
+ * value is set by the second parameter of the size() function. For
+ * example, the function call size(320, 240) sets the height
+ * variable to the value 240. The value of height is zero until
+ * size() is called.
+ *
+ * ( end auto-generated )
+ *
+ * @webref environment
+ * @see PApplet#width
+ * @see PApplet#size(int, int)
+ */
+ public int height = DEFAULT_HEIGHT;
+
+ /**
+ * ( begin auto-generated from pixelWidth.xml )
+ *
+ * When pixelDensity(2) is used to make use of a high resolution
+ * display (called a Retina display on OS X or high-dpi on Windows and
+ * Linux), the width and height of the sketch do not change, but the
+ * number of pixels is doubled. As a result, all operations that use pixels
+ * (like loadPixels(), get(), set(), etc.) happen
+ * in this doubled space. As a convenience, the variables pixelWidth
+ * and pixelHeight hold the actual width and height of the sketch
+ * in pixels. This is useful for any sketch that uses the pixels[]
+ * array, for instance, because the number of elements in the array will
+ * be pixelWidth*pixelHeight, not width*height.
+ *
+ * ( end auto-generated )
+ *
+ * @webref environment
+ * @see PApplet#pixelHeight
+ * @see #pixelDensity(int)
+ * @see #displayDensity()
+ */
+ public int pixelWidth;
+
+
+ /**
+ * ( begin auto-generated from pixelHeight.xml )
+ *
+ * When pixelDensity(2) is used to make use of a high resolution
+ * display (called a Retina display on OS X or high-dpi on Windows and
+ * Linux), the width and height of the sketch do not change, but the
+ * number of pixels is doubled. As a result, all operations that use pixels
+ * (like loadPixels(), get(), set(), etc.) happen
+ * in this doubled space. As a convenience, the variables pixelWidth
+ * and pixelHeight hold the actual width and height of the sketch
+ * in pixels. This is useful for any sketch that uses the pixels[]
+ * array, for instance, because the number of elements in the array will
+ * be pixelWidth*pixelHeight, not width*height.
+ *
+ * ( end auto-generated )
+ *
+ * @webref environment
+ * @see PApplet#pixelWidth
+ * @see #pixelDensity(int)
+ * @see #displayDensity()
+ */
+ public int pixelHeight;
+
+ /**
+ * Keeps track of ENABLE_KEY_REPEAT hint
+ */
+ protected boolean keyRepeatEnabled = false;
+
+ /**
+ * ( begin auto-generated from mouseX.xml )
+ *
+ * The system variable mouseX always contains the current horizontal
+ * coordinate of the mouse.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ *
+ *
+ */
+ public int mouseX;
+
+ /**
+ * ( begin auto-generated from mouseY.xml )
+ *
+ * The system variable mouseY always contains the current vertical
+ * coordinate of the mouse.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ *
+ */
+ public int mouseY;
+
+ /**
+ * ( begin auto-generated from pmouseX.xml )
+ *
+ * The system variable pmouseX always contains the horizontal
+ * position of the mouse in the frame previous to the current frame.
+ *
+ * You may find that pmouseX and pmouseY have different
+ * values inside draw() and inside events like mousePressed()
+ * and mouseMoved(). This is because they're used for different
+ * roles, so don't mix them. Inside draw(), pmouseX and
+ * pmouseY update only once per frame (once per trip through your
+ * draw()). But, inside mouse events, they update each time the
+ * event is called. If they weren't separated, then the mouse would be read
+ * only once per frame, making response choppy. If the mouse variables were
+ * always updated multiple times per frame, using line(pmouseX,
+ * pmouseY, mouseX, mouseY) inside draw() would have lots
+ * of gaps, because pmouseX may have changed several times in
+ * between the calls to line(). Use pmouseX and
+ * pmouseY inside draw() if you want values relative to the
+ * previous frame. Use pmouseX and pmouseY inside the mouse
+ * functions if you want continuous response.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public int pmouseX;
+
+ /**
+ * ( begin auto-generated from pmouseY.xml )
+ *
+ * The system variable pmouseY always contains the vertical position
+ * of the mouse in the frame previous to the current frame. More detailed
+ * information about how pmouseY is updated inside of draw()
+ * and mouse events is explained in the reference for pmouseX.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public int pmouseY;
+
+ /**
+ * Previous mouseX/Y for the draw loop, separated out because this is
+ * separate from the pmouseX/Y when inside the mouse event handlers.
+ * See emouseX/Y for an explanation.
+ */
+ protected int dmouseX, dmouseY;
+
+ /**
+ * The pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc)
+ * these are different because mouse events are queued to the end of
+ * draw, so the previous position has to be updated on each event,
+ * as opposed to the pmouseX/Y that's used inside draw, which is expected
+ * to be updated once per trip through draw().
+ */
+ protected int emouseX, emouseY;
+
+ /**
+ * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used,
+ * otherwise pmouseX/Y are always zero, causing a nasty jump.
+ *
+ * Just using (frameCount == 0) won't work since mouseXxxxx()
+ * may not be called until a couple frames into things.
+ *
+ * @deprecated Please refrain from using this variable, it will be removed
+ * from future releases of Processing because it cannot be used consistently
+ * across platforms and input methods.
+ */
+ @Deprecated
+ public boolean firstMouse = true;
+
+ /**
+ * ( begin auto-generated from mouseButton.xml )
+ *
+ * Processing automatically tracks if the mouse button is pressed and which
+ * button is pressed. The value of the system variable mouseButton
+ * is either LEFT, RIGHT, or CENTER depending on which
+ * button is pressed.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced:
+ *
+ * If running on Mac OS, a ctrl-click will be interpreted as the right-hand
+ * mouse button (unlike Java, which reports it as the left mouse).
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public int mouseButton;
+
+ /**
+ * ( begin auto-generated from mousePressed_var.xml )
+ *
+ * Variable storing if a mouse button is pressed. The value of the system
+ * variable mousePressed is true if a mouse button is pressed and
+ * false if a button is not pressed.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public boolean mousePressed;
+
+
+ /** @deprecated Use a mouse event handler that passes an event instead. */
+ @Deprecated
+ public MouseEvent mouseEvent;
+
+ /**
+ * ( begin auto-generated from key.xml )
+ *
+ * The system variable key always contains the value of the most
+ * recent key on the keyboard that was used (either pressed or released).
+ *
+ * For non-ASCII keys, use the keyCode variable. The keys included
+ * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and
+ * DELETE) do not require checking to see if they key is coded, and you
+ * should simply use the key variable instead of keyCode If
+ * you're making cross-platform projects, note that the ENTER key is
+ * commonly used on PCs and Unix and the RETURN key is used instead on
+ * Macintosh. Check for both ENTER and RETURN to make sure your program
+ * will work for all platforms.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ *
+ * Last key pressed.
+ *
+ * If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT,
+ * this will be set to CODED (0xffff or 65535).
+ *
+ * @webref input:keyboard
+ * @see PApplet#keyCode
+ * @see PApplet#keyPressed
+ * @see PApplet#keyPressed()
+ * @see PApplet#keyReleased()
+ */
+ public char key;
+
+ /**
+ * ( begin auto-generated from keyCode.xml )
+ *
+ * The variable keyCode is used to detect special keys such as the
+ * UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking
+ * for these keys, it's first necessary to check and see if the key is
+ * coded. This is done with the conditional "if (key == CODED)" as shown in
+ * the example.
+ *
+ * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER,
+ * RETURN, ESC, and DELETE) do not require checking to see if they key is
+ * coded, and you should simply use the key variable instead of
+ * keyCode If you're making cross-platform projects, note that the
+ * ENTER key is commonly used on PCs and Unix and the RETURN key is used
+ * instead on Macintosh. Check for both ENTER and RETURN to make sure your
+ * program will work for all platforms.
+ *
+ * For users familiar with Java, the values for UP and DOWN are simply
+ * shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other
+ * keyCode values can be found in the Java KeyEvent reference.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * When "key" is set to CODED, this will contain a Java key code.
+ *
+ * For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT.
+ * Also available are ALT, CONTROL and SHIFT. A full set of constants
+ * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables.
+ *
+ * @webref input:keyboard
+ * @see PApplet#key
+ * @see PApplet#keyPressed
+ * @see PApplet#keyPressed()
+ * @see PApplet#keyReleased()
+ */
+ public int keyCode;
+
+ /**
+ * ( begin auto-generated from keyPressed_var.xml )
+ *
+ * The boolean system variable keyPressed is true if any key
+ * is pressed and false if no keys are pressed.
+ *
+ * ( end auto-generated )
+ * @webref input:keyboard
+ * @see PApplet#key
+ * @see PApplet#keyCode
+ * @see PApplet#keyPressed()
+ * @see PApplet#keyReleased()
+ */
+ public boolean keyPressed;
+ List pressedKeys = new ArrayList<>(6);
+
+ /**
+ * The last KeyEvent object passed into a mouse function.
+ * @deprecated Use a key event handler that passes an event instead.
+ */
+ @Deprecated
+ public KeyEvent keyEvent;
+
+ /**
+ * ( begin auto-generated from focused.xml )
+ *
+ * Confirms if a Processing program is "focused", meaning that it is active
+ * and will accept input from mouse or keyboard. This variable is "true" if
+ * it is focused and "false" if not. This variable is often used when you
+ * want to warn people they need to click on or roll over an applet before
+ * it will work.
+ *
+ * ( end auto-generated )
+ * @webref environment
+ */
+ public boolean focused = false;
+
+// /**
+// * Confirms if a Processing program is running inside a web browser. This
+// * variable is "true" if the program is online and "false" if not.
+// */
+// @Deprecated
+// public boolean online = false;
+// // This is deprecated because it's poorly named (and even more poorly
+// // understood). Further, we'll probably be removing applets soon, in which
+// // case this won't work at all. If you want this feature, you can check
+// // whether getAppletContext() returns null.
+
+ /**
+ * Time in milliseconds when the applet was started.
+ *
+ * Used by the millis() function.
+ */
+ long millisOffset = System.currentTimeMillis();
+
+ /**
+ * ( begin auto-generated from frameRate_var.xml )
+ *
+ * The system variable frameRate contains the approximate frame rate
+ * of the software as it executes. The initial value is 10 fps and is
+ * updated with each frame. The value is averaged (integrated) over several
+ * frames. As such, this value won't be valid until after 5-10 frames.
+ *
+ * ( end auto-generated )
+ * @webref environment
+ * @see PApplet#frameRate(float)
+ * @see PApplet#frameCount
+ */
+ public float frameRate = 10;
+
+ protected boolean looping = true;
+
+ /** flag set to true when a redraw is asked for by the user */
+ protected boolean redraw = true;
+
+ /**
+ * ( begin auto-generated from frameCount.xml )
+ *
+ * The system variable frameCount contains the number of frames
+ * displayed since the program started. Inside setup() the value is
+ * 0 and and after the first iteration of draw it is 1, etc.
+ *
+ * ( end auto-generated )
+ * @webref environment
+ * @see PApplet#frameRate(float)
+ * @see PApplet#frameRate
+ */
+ public int frameCount;
+
+ /** true if the sketch has stopped permanently. */
+ public volatile boolean finished;
+
+ /** used by the UncaughtExceptionHandler, so has to be static */
+ static Throwable uncaughtThrowable;
+
+ // public, but undocumented.. removing for 3.0a5
+// /**
+// * true if the animation thread is paused.
+// */
+// public volatile boolean paused;
+
+ /**
+ * true if exit() has been called so that things shut down
+ * once the main thread kicks off.
+ */
+ protected boolean exitCalled;
+
+ // messages to send if attached as an external vm
+
+ /**
+ * Position of the upper-lefthand corner of the editor window
+ * that launched this applet.
+ */
+ static public final String ARGS_EDITOR_LOCATION = "--editor-location";
+
+ static public final String ARGS_EXTERNAL = "--external";
+
+ /**
+ * 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_LOCATION = "--location";
+
+ /** Used by the PDE to suggest a display (set in prefs, passed on Run) */
+ static public final String ARGS_DISPLAY = "--display";
+
+// static public final String ARGS_SPAN_DISPLAYS = "--span";
+
+ static public final String ARGS_WINDOW_COLOR = "--window-color";
+
+ static public final String ARGS_PRESENT = "--present";
+
+ 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";
+
+ static public final String ARGS_DENSITY = "--density";
+
+ /**
+ * When run externally to a PdeEditor,
+ * this is sent by the sketch when it quits.
+ */
+ static public final String EXTERNAL_STOP = "__STOP__";
+
+ /**
+ * When run externally to a PDE Editor, this is sent by the applet
+ * whenever the window is moved.
+ *
+ * This is used so that the editor can re-open the sketch window
+ * in the same position as the user last left it.
+ */
+ static public final String EXTERNAL_MOVE = "__MOVE__";
+
+ /** true if this sketch is being run by the PDE */
+ boolean external = false;
+
+ static final String ERROR_MIN_MAX =
+ "Cannot use min() or max() on an empty array.";
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ protected PSurface surface;
+
+
+ public PSurface getSurface() {
+ return surface;
+ }
+
+
+ /**
+ * A dummy frame to keep compatibility with 2.x code
+ * and encourage users to update.
+ */
+ public Frame frame;
+
+
+// public Frame getFrame() {
+// return frame;
+// }
+//
+//
+// public void setFrame(Frame frame) {
+// this.frame = frame;
+// }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+// /**
+// * Applet initialization. This can do GUI work because the components have
+// * not been 'realized' yet: things aren't visible, displayed, etc.
+// */
+// public void init() {
+//// println("init() called " + Integer.toHexString(hashCode()));
+// // using a local version here since the class variable is deprecated
+//// Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
+//// screenWidth = screen.width;
+//// screenHeight = screen.height;
+//
+// defaultSize = true;
+// finished = false; // just for clarity
+//
+// // this will be cleared by draw() if it is not overridden
+// looping = true;
+// redraw = true; // draw this guy at least once
+// firstMouse = true;
+//
+// // calculated dynamically on first call
+//// // Removed in 2.1.2, brought back for 2.1.3. Usually sketchPath is set
+//// // inside runSketch(), but if this sketch takes care of calls to init()
+//// // when PApplet.main() is not used (i.e. it's in a Java application).
+//// // THe path needs to be set here so that loadXxxx() functions work.
+//// if (sketchPath == null) {
+//// sketchPath = calcSketchPath();
+//// }
+//
+// // set during Surface.initFrame()
+//// // Figure out the available display width and height.
+//// // No major problem if this fails, we have to try again anyway in
+//// // handleDraw() on the first (== 0) frame.
+//// checkDisplaySize();
+//
+//// // Set the default size, until the user specifies otherwise
+//// int w = sketchWidth();
+//// int h = sketchHeight();
+//// defaultSize = (w == DEFAULT_WIDTH) && (h == DEFAULT_HEIGHT);
+////
+//// g = makeGraphics(w, h, sketchRenderer(), null, true);
+//// // Fire component resize event
+//// setSize(w, h);
+//// setPreferredSize(new Dimension(w, h));
+////
+//// width = g.width;
+//// height = g.height;
+//
+// surface.startThread();
+// }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ boolean insideSettings;
+
+ String renderer = JAVA2D;
+// int quality = 2;
+ int smooth = 1; // default smoothing (whatever that means for the renderer)
+
+ boolean fullScreen;
+ int display = -1; // use default
+ GraphicsDevice[] displayDevices;
+ // Unlike the others above, needs to be public to support
+ // the pixelWidth and pixelHeight fields.
+ public int pixelDensity = 1;
+ int suggestedDensity = -1;
+
+ boolean present;
+
+ String outputPath;
+ OutputStream outputStream;
+
+ // 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;
+
+
+ /**
+ * @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;
+
+ // Need the list of display devices to be queried already for usage below.
+ // https://github.com/processing/processing/issues/3295
+ // https://github.com/processing/processing/issues/3296
+ // Not doing this from a static initializer because it may cause
+ // PApplet to cache and the values to stick through subsequent runs.
+ // Instead make it a runtime thing and a local variable.
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ GraphicsDevice device = ge.getDefaultScreenDevice();
+ displayDevices = ge.getScreenDevices();
+
+ // Default or unparsed will be -1, spanning will be 0, actual displays will
+ // be numbered from 1 because it's too weird to say "display 0" in prefs.
+ if (display > 0 && display <= displayDevices.length) {
+ device = displayDevices[display-1];
+ }
+ // Set displayWidth and displayHeight for people still using those.
+ DisplayMode displayMode = device.getDisplayMode();
+ displayWidth = displayMode.getWidth();
+ displayHeight = displayMode.getHeight();
+
+ // Here's where size(), fullScreen(), smooth(N) and noSmooth() might
+ // be called, conjuring up the demons of various rendering configurations.
+ settings();
+
+ if (display == SPAN && platform == MACOSX) {
+ // Make sure "Displays have separate Spaces" is unchecked
+ // in System Preferences > Mission Control
+ Process p = exec("defaults", "read", "com.apple.spaces", "spans-displays");
+ BufferedReader outReader = createReader(p.getInputStream());
+ BufferedReader errReader = createReader(p.getErrorStream());
+ StringBuilder stdout = new StringBuilder();
+ StringBuilder stderr = new StringBuilder();
+ String line = null;
+ try {
+ while ((line = outReader.readLine()) != null) {
+ stdout.append(line);
+ }
+ while ((line = errReader.readLine()) != null) {
+ stderr.append(line);
+ }
+ } catch (IOException e) {
+ printStackTrace(e);
+ }
+
+ int resultCode = -1;
+ try {
+ resultCode = p.waitFor();
+ } catch (InterruptedException e) { }
+
+ String result = trim(stdout.toString());
+ if ("0".equals(result)) {
+ EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ checkLookAndFeel();
+ final String msg =
+ "To use fullScreen(SPAN), first turn off “Displays have separate spaces”\n" +
+ "in System Preferences \u2192 Mission Control. Then log out and log back in.";
+ JOptionPane.showMessageDialog(null, msg, "Apple's Defaults Stink",
+ JOptionPane.WARNING_MESSAGE);
+ }
+ });
+ } else if (!"1".equals(result)) {
+ System.err.println("Could not check the status of “Displays have separate spaces.”");
+ System.err.format("Received message '%s' and result code %d.%n", trim(stderr.toString()), resultCode);
+ }
+ }
+
+ insideSettings = false;
+ }
+
+
+ /**
+ * ( begin auto-generated from settings.xml )
+ *
+ * Description to come...
+ *
+ * ( end auto-generated )
+ *
+ * Override this method to call size() when not using the PDE.
+ *
+ * @webref environment
+ * @see PApplet#fullScreen()
+ * @see PApplet#setup()
+ * @see PApplet#size(int,int)
+ * @see PApplet#smooth()
+ */
+ public void settings() {
+ // is this necessary? (doesn't appear to be, so removing)
+ //size(DEFAULT_WIDTH, DEFAULT_HEIGHT, JAVA2D);
+ }
+
+
+ final public int sketchWidth() {
+ return width;
+ }
+
+
+ final public int sketchHeight() {
+ return height;
+ }
+
+
+ final public String sketchRenderer() {
+ return renderer;
+ }
+
+
+ // Named quality instead of smooth to avoid people trying to set (or get)
+ // the current smooth level this way. Also that smooth(number) isn't really
+ // public or well-known API. It's specific to the capabilities of the
+ // rendering surface, and somewhat independent of whether the sketch is
+ // smoothing at any given time. It's also a bit like getFill() would return
+ // true/false for whether fill was enabled, getFillColor() would return the
+ // color itself. Or at least that's what I can recall at the moment. [fry]
+// public int sketchQuality() {
+// //return 2;
+// return quality;
+// }
+ // smoothing 1 is default.. 0 is none.. 2,4,8 depend on renderer
+ final public int sketchSmooth() {
+ return smooth;
+ }
+
+
+ final public boolean sketchFullScreen() {
+ //return false;
+ return fullScreen;
+ }
+
+
+// // Could be named 'screen' instead of display since it's the people using
+// // full screen who will be looking for it. On the other hand, screenX/Y/Z
+// // makes things confusing, and if 'displayIndex' exists...
+// public boolean sketchSpanDisplays() {
+// //return false;
+// return spanDisplays;
+// }
+
+
+ // Numbered from 1, SPAN (0) means all displays, -1 means the default display
+ final public int sketchDisplay() {
+ return display;
+ }
+
+
+ final public String sketchOutputPath() {
+ //return null;
+ return outputPath;
+ }
+
+
+ final public OutputStream sketchOutputStream() {
+ //return null;
+ return outputStream;
+ }
+
+
+ final public int sketchWindowColor() {
+ return windowColor;
+ }
+
+
+ final public int sketchPixelDensity() {
+ return pixelDensity;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /**
+ * ( begin auto-generated from displayDensity.xml )
+ *
+ * This function returns the number "2" if the screen is a high-density
+ * screen (called a Retina display on OS X or high-dpi on Windows and Linux)
+ * and a "1" if not. This information is useful for a program to adapt to
+ * run at double the pixel density on a screen that supports it.
+ *
+ * ( end auto-generated )
+ *
+ * @webref environment
+ * @see PApplet#pixelDensity(int)
+ * @see PApplet#size(int,int)
+ */
+ public int displayDensity() {
+ if (display != SPAN && (fullScreen || present)) {
+ return displayDensity(display);
+ }
+ // walk through all displays, use 2 if any display is 2
+ for (int i = 0; i < displayDevices.length; i++) {
+ if (displayDensity(i+1) == 2) {
+ return 2;
+ }
+ }
+ // If nobody's density is 2 then everyone is 1
+ return 1;
+ }
+
+ /**
+ * @param display the display number to check
+ */
+ public int displayDensity(int display) {
+ if (PApplet.platform == PConstants.MACOSX) {
+ // This should probably be reset each time there's a display change.
+ // A 5-minute search didn't turn up any such event in the Java 7 API.
+ // Also, should we use the Toolkit associated with the editor window?
+ final String javaVendor = System.getProperty("java.vendor");
+ if (javaVendor.contains("Oracle")) {
+ GraphicsDevice device;
+ GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
+
+ if (display == -1) {
+ device = env.getDefaultScreenDevice();
+
+ } else if (display == SPAN) {
+ throw new RuntimeException("displayDensity() only works with specific display numbers");
+
+ } else {
+ GraphicsDevice[] devices = env.getScreenDevices();
+ if (display > 0 && display <= devices.length) {
+ device = devices[display - 1];
+ } else {
+ if (devices.length == 1) {
+ System.err.println("Only one display is currently known, use displayDensity(1).");
+ } else {
+ System.err.format("Your displays are numbered %d through %d, " +
+ "pass one of those numbers to displayDensity()%n", 1, devices.length);
+ }
+ throw new RuntimeException("Display " + display + " does not exist.");
+ }
+ }
+
+ try {
+ Field field = device.getClass().getDeclaredField("scale");
+ if (field != null) {
+ field.setAccessible(true);
+ Object scale = field.get(device);
+
+ if (scale instanceof Integer && ((Integer)scale).intValue() == 2) {
+ return 2;
+ }
+ }
+ } catch (Exception ignore) { }
+ }
+ } else if (PApplet.platform == PConstants.WINDOWS ||
+ PApplet.platform == PConstants.LINUX) {
+ if (suggestedDensity == -1) {
+ // TODO: detect and return DPI scaling using JNA; Windows has
+ // a system-wide value, not sure how it works on Linux
+ return 1;
+ } else if (suggestedDensity == 1 || suggestedDensity == 2) {
+ return suggestedDensity;
+ }
+ }
+ return 1;
+ }
+
+
+ /**
+ * @webref environment
+ * @param density 1 or 2
+ *
+ */
+ public void pixelDensity(int density) {
+ //println(density + " " + this.pixelDensity);
+ if (density != this.pixelDensity) {
+ if (insideSettings("pixelDensity", density)) {
+ if (density != 1 && density != 2) {
+ throw new RuntimeException("pixelDensity() can only be 1 or 2");
+ }
+ if (!FX2D.equals(renderer) && density == 2 && displayDensity() == 1) {
+ // FX has its own check in PSurfaceFX
+ // Don't throw exception because the sketch should still work
+ System.err.println("pixelDensity(2) is not available for this display");
+ this.pixelDensity = 1;
+ } else {
+ this.pixelDensity = density;
+ }
+ } else {
+ System.err.println("not inside settings");
+ // this should only be reachable when not running in the PDE,
+ // so saying it's a settings()--not just setup()--issue should be ok
+ throw new RuntimeException("pixelDensity() can only be used inside settings()");
+ }
+ }
+ }
+
+
+ /**
+ * Called by PSurface objects to set the width and height variables,
+ * and update the pixelWidth and pixelHeight variables.
+ */
+ public void setSize(int width, int height) {
+ this.width = width;
+ this.height = height;
+ pixelWidth = width * pixelDensity;
+ pixelHeight = height * pixelDensity;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /**
+ * @nowebref
+ */
+ public void smooth() {
+ smooth(1);
+ }
+
+ /**
+ * @webref environment
+ * @param level either 2, 3, 4, or 8 depending on the renderer
+ */
+ public void smooth(int level) {
+ if (insideSettings) {
+ this.smooth = level;
+
+ } else if (this.smooth != level) {
+ smoothWarning("smooth");
+ }
+ }
+
+ /**
+ * @webref environment
+ */
+ 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);
+ if (external) {
+ PGraphics.showWarning("When run from the PDE, %s() is automatically moved from setup() to settings()", method);
+ }
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public PGraphics getGraphics() {
+ return g;
+ }
+
+
+ // TODO should this join the sketchXxxx() functions specific to settings()?
+ public void orientation(int which) {
+ // ignore calls to the orientation command
+ }
+
+
+ /**
+ * 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() {
+// paused = false; // unpause the thread // removing for 3.0a5, don't think we want this here
+
+ resume();
+ handleMethods("resume");
+ surface.resumeThread();
+ }
+
+
+ /**
+ * Called by the browser or applet viewer to inform
+ * this applet that it should stop its execution.
+ *
+ * Unfortunately, there are no guarantees from the Java spec
+ * when or if stop() will be called (i.e. on browser quit,
+ * or when moving between web pages), and it's not always called.
+ */
+ public void stop() {
+ // this used to shut down the sketch, but that code has
+ // been moved to destroy/dispose()
+
+// if (paused) {
+// synchronized (pauseObject) {
+// try {
+// pauseObject.wait();
+// } catch (InterruptedException e) {
+// // waiting for this interrupt on a start() (resume) call
+// }
+// }
+// }
+
+ //paused = true; // causes animation thread to sleep // 3.0a5
+ pause();
+ handleMethods("pause");
+ // calling this down here, since it's another thread it's safer to call
+ // pause() and the registered pause methods first.
+ surface.pauseThread();
+
+ // actual pause will happen in the run() method
+
+// synchronized (pauseObject) {
+// debug("stop() calling pauseObject.wait()");
+// try {
+// pauseObject.wait();
+// } catch (InterruptedException e) {
+// // waiting for this interrupt on a start() (resume) call
+// }
+// }
+ }
+
+
+ /**
+ * Sketch has been paused. Called when switching tabs in a browser or
+ * swapping to a different application on Android. Also called just before
+ * quitting. Use to safely disable things like serial, sound, or sensors.
+ */
+ public void pause() { }
+
+
+ /**
+ * Sketch has resumed. Called when switching tabs in a browser or
+ * swapping to this application on Android. Also called on startup.
+ * Use this to safely disable things like serial, sound, or sensors.
+ */
+ public void resume() { }
+
+
+// /**
+// * Called by the browser or applet viewer to inform this applet
+// * that it is being reclaimed and that it should destroy
+// * any resources that it has allocated.
+// *
+// * destroy() supposedly gets called as the applet viewer
+// * is shutting down the applet. stop() is called
+// * first, and then destroy() to really get rid of things.
+// * no guarantees on when they're run (on browser quit, or
+// * when moving between pages), though.
+// */
+// @Override
+// public void destroy() {
+// this.dispose();
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /** Map of registered methods, stored by name. */
+ HashMap registerMap =
+ new HashMap<>();
+
+ /** Lock when un/registering from multiple threads */
+ private final Object registerLock = new Object[0];
+
+
+ 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
+ printStackTrace(t);
+ }
+ }
+ }
+ }
+
+
+ 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 });
+
+ } else {
+ registerNoArgs(methodName, target);
+ }
+ }
+
+
+ private void registerNoArgs(String name, Object o) {
+ Class> c = o.getClass();
+ try {
+ Method method = c.getMethod(name);
+ synchronized (registerLock) {
+ RegisteredMethods meth = registerMap.get(name);
+ if (meth == null) {
+ meth = new RegisteredMethods();
+ registerMap.put(name, meth);
+ }
+ 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[]) {
+ Class> c = o.getClass();
+ try {
+ Method method = c.getMethod(name, cargs);
+ synchronized (registerLock) {
+ RegisteredMethods meth = registerMap.get(name);
+ if (meth == null) {
+ meth = new RegisteredMethods();
+ registerMap.put(name, meth);
+ }
+ 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) {
+ synchronized (registerLock) {
+ 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) {
+ synchronized (registerLock) {
+ RegisteredMethods meth = registerMap.get(methodName);
+ if (meth != null) {
+ meth.handle();
+ }
+ }
+ }
+
+
+ protected void handleMethods(String methodName, Object[] args) {
+ synchronized (registerLock) {
+ RegisteredMethods meth = registerMap.get(methodName);
+ if (meth != null) {
+ 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);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ // Old methods with AWT API that should not be used.
+ // These were never implemented on Android so they're stored separately.
+
+ RegisteredMethods mouseEventMethods, keyEventMethods;
+
+
+ protected void reportDeprecation(Class> c, boolean mouse) {
+ if (g != null) {
+ PGraphics.showWarning("The class " + c.getName() +
+ " is incompatible with Processing 2.0.");
+ PGraphics.showWarning("A library (or other code) is using register" +
+ (mouse ? "Mouse" : "Key") + "Event() " +
+ "which is no longer available.");
+ // This will crash with OpenGL, so quit anyway
+ if (g instanceof PGraphicsOpenGL) {
+ PGraphics.showWarning("Stopping the sketch because this code will " +
+ "not work correctly with OpenGL.");
+ throw new RuntimeException("This sketch uses a library that " +
+ "needs to be updated for Processing 2.0.");
+ }
+ }
+ }
+
+
+ @Deprecated
+ public void registerMouseEvent(Object o) {
+ Class> c = o.getClass();
+ reportDeprecation(c, true);
+ try {
+ Method method = c.getMethod("mouseEvent", new Class[] { java.awt.event.MouseEvent.class });
+ if (mouseEventMethods == null) {
+ mouseEventMethods = new RegisteredMethods();
+ }
+ mouseEventMethods.add(o, method);
+ } catch (Exception e) {
+ die("Could not register mouseEvent() for " + o, e);
+ }
+ }
+
+
+ @Deprecated
+ public void unregisterMouseEvent(Object o) {
+ try {
+// Method method = o.getClass().getMethod("mouseEvent", new Class[] { MouseEvent.class });
+// mouseEventMethods.remove(o, method);
+ mouseEventMethods.remove(o);
+ } catch (Exception e) {
+ die("Could not unregister mouseEvent() for " + o, e);
+ }
+ }
+
+
+ @Deprecated
+ public void registerKeyEvent(Object o) {
+ Class> c = o.getClass();
+ reportDeprecation(c, false);
+ try {
+ Method method = c.getMethod("keyEvent", new Class[] { java.awt.event.KeyEvent.class });
+ if (keyEventMethods == null) {
+ keyEventMethods = new RegisteredMethods();
+ }
+ keyEventMethods.add(o, method);
+ } catch (Exception e) {
+ die("Could not register keyEvent() for " + o, e);
+ }
+ }
+
+
+ @Deprecated
+ public void unregisterKeyEvent(Object o) {
+ try {
+// Method method = o.getClass().getMethod("keyEvent", new Class[] { KeyEvent.class });
+// keyEventMethods.remove(o, method);
+ keyEventMethods.remove(o);
+ } catch (Exception e) {
+ die("Could not unregister keyEvent() for " + o, e);
+ }
+ }
+ */
+
+
+
+ //////////////////////////////////////////////////////////////
+
+/**
+ * ( begin auto-generated from setup.xml )
+ *
+ * The setup() function is called once when the program starts. It's
+ * used to define initial
+ * enviroment properties such as screen size and background color and to
+ * load media such as images
+ * and fonts as the program starts. There can only be one setup()
+ * function for each program and
+ * it shouldn't be called again after its initial execution. Note:
+ * Variables declared within
+ * setup() are not accessible within other functions, including
+ * draw().
+ *
+ * ( end auto-generated )
+ * @webref structure
+ * @usage web_application
+ * @see PApplet#size(int, int)
+ * @see PApplet#loop()
+ * @see PApplet#noLoop()
+ * @see PApplet#draw()
+ */
+ public void setup() {
+ }
+
+/**
+ * ( begin auto-generated from draw.xml )
+ *
+ * Called directly after setup() and continuously executes the lines
+ * of code contained inside its block until the program is stopped or
+ * noLoop() is called. The draw() function is called
+ * automatically and should never be called explicitly. It should always be
+ * controlled with noLoop(), redraw() and loop().
+ * After noLoop() stops the code in draw() from executing,
+ * redraw() causes the code inside draw() to execute once and
+ * loop() will causes the code inside draw() to execute
+ * continuously again. The number of times draw() executes in each
+ * second may be controlled with frameRate() function.
+ * There can only be one draw() function for each sketch
+ * and draw() must exist if you want the code to run continuously or
+ * to process events such as mousePressed(). Sometimes, you might
+ * have an empty call to draw() in your program as shown in the
+ * above example.
+ *
+ * ( end auto-generated )
+ * @webref structure
+ * @usage web_application
+ * @see PApplet#setup()
+ * @see PApplet#loop()
+ * @see PApplet#noLoop()
+ * @see PApplet#redraw()
+ * @see PApplet#frameRate(float)
+ * @see PGraphics#background(float, float, float, float)
+ */
+ public void draw() {
+ // if no draw method, then shut things down
+ //System.out.println("no draw method, goodbye");
+ finished = true;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /*
+ protected void resizeRenderer(int newWidth, int newHeight) {
+ debug("resizeRenderer request for " + newWidth + " " + newHeight);
+ if (width != newWidth || height != newHeight) {
+ debug(" former size was " + width + " " + height);
+ g.setSize(newWidth, newHeight);
+ width = newWidth;
+ height = newHeight;
+ }
+ }
+ */
+
+
+ /**
+ * 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) {
+ if (!fullScreen || display != this.display) {
+ if (insideSettings("fullScreen", display)) {
+ this.fullScreen = true;
+ this.display = display;
+ }
+ }
+ }
+
+
+/**
+ * ( begin auto-generated from fullScreen.xml )
+ *
+ * Description to come...
+ *
+ * ( end auto-generated )
+ * @webref environment
+ * @param renderer the renderer to use, e.g. P2D, P3D, JAVA2D (default)
+ * @see PApplet#settings()
+ * @see PApplet#setup()
+ * @see PApplet#size(int,int)
+ * @see PApplet#smooth()
+ */
+ public void fullScreen(String renderer) {
+ if (!fullScreen ||
+ !renderer.equals(this.renderer)) {
+ if (insideSettings("fullScreen", renderer)) {
+ this.fullScreen = true;
+ this.renderer = renderer;
+ }
+ }
+ }
+
+
+ /**
+ * @param display the screen to run the sketch on (1, 2, 3, etc. or on multiple screens using SPAN)
+ */
+
+ 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;
+ }
+ }
+ }
+
+
+ /**
+ * ( begin auto-generated from size.xml )
+ *
+ * Defines the dimension of the display window in units of pixels. The
+ * size() function must be the first line in setup(). If
+ * size() is not used, the default size of the window is 100x100
+ * pixels. The system variables width and height are set by
+ * the parameters passed to this function.
+ *
+ * Do not use variables as the parameters to size() function,
+ * because it will cause problems when exporting your sketch. When
+ * variables are used, the dimensions of your sketch cannot be determined
+ * during export. Instead, employ numeric values in the size()
+ * statement, and then use the built-in width and height
+ * variables inside your program when the dimensions of the display window
+ * are needed.
+ *
+ * The size() function can only be used once inside a sketch, and
+ * cannot be used for resizing.
+ * renderer parameter selects which rendering engine to use.
+ * For example, if you will be drawing 3D shapes, use P3D, if you
+ * want to export images from a program as a PDF file use PDF. A
+ * brief description of the three primary renderers follows:
+ *
+ * P2D (Processing 2D) - The default renderer that supports two
+ * dimensional drawing.
+ *
+ * P3D (Processing 3D) - 3D graphics renderer that makes use of
+ * OpenGL-compatible graphics hardware.
+ *
+ * PDF - The PDF renderer draws 2D graphics directly to an Acrobat
+ * PDF file. This produces excellent results when you need vector shapes
+ * for high resolution output or printing. You must first use Import
+ * Library → PDF to make use of the library. More information can be
+ * found in the PDF library reference.
+ *
+ * The P3D renderer doesn't support strokeCap() or
+ * strokeJoin(), which can lead to ugly results when using
+ * strokeWeight(). (Issue
+ * 123)
+ *
+ * The maximum width and height is limited by your operating system, and is
+ * usually the width and height of your actual screen. On some machines it
+ * may simply be the number of pixels on your current screen, meaning that
+ * a screen of 800x600 could support size(1600, 300), since it's the
+ * same number of pixels. This varies widely so you'll have to try
+ * different rendering modes and sizes until you get what you're looking
+ * for. If you need something larger, use createGraphics to create a
+ * non-visible drawing surface.
+ *
+ * Again, the size() function must be the first line of the code (or
+ * first item inside setup). Any code that appears before the size()
+ * command may run more than once, which can lead to confusing results.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * If using Java 1.3 or later, this will default to using
+ * PGraphics2, the Java2D-based renderer. If using Java 1.1,
+ * or if PGraphics2 is not available, then PGraphics will be used.
+ * To set your own renderer, use the other version of the size()
+ * method that takes a renderer as its last parameter.
+ *
+ * If called once a renderer has already been set, this will
+ * use the previous renderer and simply resize it.
+ *
+ * @webref environment
+ * @param width width of the display window in units of pixels
+ * @param height height of the display window in units of pixels
+ * @see PApplet#width
+ * @see PApplet#height
+ */
+ public void size(int width, int height) {
+ // Check to make sure the width/height have actually changed. It's ok to
+ // have size() duplicated (and may be better to not remove it from where
+ // it sits in the code anyway when adding it to settings()). Only take
+ // action if things have changed.
+ if (width != this.width ||
+ height != this.height) {
+ if (insideSettings("size", width, height)) {
+ this.width = width;
+ this.height = height;
+ }
+ }
+ }
+
+
+ public void size(int width, int height, String renderer) {
+ if (width != this.width ||
+ height != this.height ||
+ !renderer.equals(this.renderer)) {
+ //println(width, height, renderer, this.width, this.height, this.renderer);
+ if (insideSettings("size", width, height, "\"" + renderer + "\"")) {
+ this.width = width;
+ this.height = height;
+ this.renderer = renderer;
+ }
+ }
+ }
+
+
+ /**
+ * @nowebref
+ */
+ public void size(int width, int height, String renderer, String path) {
+ // Don't bother checking path, it's probably been modified to absolute,
+ // so it would always trigger. But the alternative is comparing the
+ // canonical file, which seems overboard.
+ if (width != this.width ||
+ height != this.height ||
+ !renderer.equals(this.renderer)) {
+ if (insideSettings("size", width, height, "\"" + renderer + "\"",
+ "\"" + path + "\"")) {
+ this.width = width;
+ this.height = height;
+ this.renderer = renderer;
+ this.outputPath = path;
+ }
+ }
+
+ /*
+ if (!renderer.equals(sketchRenderer())) {
+ if (external) {
+ // The PDE should have parsed it, but something still went wrong
+ final String msg =
+ String.format("Something bad happened when calling " +
+ "size(%d, %d, %s, %s)", w, h, renderer, path);
+ throw new RuntimeException(msg);
+
+ } else {
+ System.err.println("Because you're not running from the PDE, add this to your code:");
+ System.err.println("public String sketchRenderer() {");
+ System.err.println(" return \"" + renderer + "\";");
+ System.err.println("}");
+ throw new RuntimeException("The sketchRenderer() method is not implemented.");
+ }
+ }
+ */
+
+ // size() shouldn't actually do anything here [3.0a8]
+// surface.setSize(w, h);
+ // this won't be absolute, which will piss off PDF [3.0a8]
+// g.setPath(path); // finally, a path
+
+// // Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing)
+// EventQueue.invokeLater(new Runnable() {
+// public void run() {
+// // Set the preferred size so that the layout managers can handle it
+// setPreferredSize(new Dimension(w, h));
+// setSize(w, h);
+// }
+// });
+//
+// // ensure that this is an absolute path
+// if (path != null) path = savePath(path);
+//
+// String currentRenderer = g.getClass().getName();
+// if (currentRenderer.equals(renderer)) {
+//// // Avoid infinite loop of throwing exception to reset renderer
+//// resizeRenderer(w, h);
+// surface.setSize(w, h);
+//
+// } else { // renderer change attempted
+// // no longer kosher with 3.0a5
+// throw new RuntimeException("Y'all need to implement sketchRenderer()");
+// /*
+// // otherwise ok to fall through and create renderer below
+// // the renderer is changing, so need to create a new object
+// g = makeGraphics(w, h, renderer, path, true);
+// this.width = w;
+// this.height = h;
+//
+// // fire resize event to make sure the applet is the proper size
+//// setSize(iwidth, iheight);
+// // this is the function that will run if the user does their own
+// // size() command inside setup, so set defaultSize to false.
+// defaultSize = false;
+//
+// // throw an exception so that setup() is called again
+// // but with a properly sized render
+// // this is for opengl, which needs a valid, properly sized
+// // display before calling anything inside setup().
+// throw new RendererChangeException();
+// */
+// }
+ }
+
+
+ public PGraphics createGraphics(int w, int h) {
+ return createGraphics(w, h, JAVA2D);
+ }
+
+
+ /**
+ * ( begin auto-generated from createGraphics.xml )
+ *
+ * Creates and returns a new PGraphics object of the types P2D or
+ * P3D. Use this class if you need to draw into an off-screen graphics
+ * buffer. The PDF renderer requires the filename parameter. The DXF
+ * renderer should not be used with createGraphics(), it's only
+ * built for use with beginRaw() and endRaw().
+ *
+ * It's important to call any drawing functions between beginDraw()
+ * and endDraw() statements. This is also true for any functions
+ * that affect drawing, such as smooth() or colorMode().
+ * the main drawing surface which is completely opaque, surfaces
+ * created with createGraphics() can have transparency. This makes
+ * it possible to draw into a graphics and maintain the alpha channel. By
+ * using save() to write a PNG or TGA file, the transparency of the
+ * graphics object will be honored. Note that transparency levels are
+ * binary: pixels are either complete opaque or transparent. For the time
+ * being, this means that text characters will be opaque blocks. This will
+ * be fixed in a future release (Issue 80).
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Create an offscreen PGraphics object for drawing. This can be used
+ * for bitmap or vector images drawing or rendering.
+ *
+ *
Do not use "new PGraphicsXxxx()", use this method. This method
+ * ensures that internal variables are set up properly that tie the
+ * new graphics context back to its parent PApplet.
+ *
The basic way to create bitmap images is to use the saveFrame()
+ * function.
+ *
If you want to create a really large scene and write that,
+ * first make sure that you've allocated a lot of memory in the Preferences.
+ *
If you want to create images that are larger than the screen,
+ * you should create your own PGraphics object, draw to that, and use
+ * save().
+ *
+ *
+ * PGraphics big;
+ *
+ * void setup() {
+ * big = createGraphics(3000, 3000);
+ *
+ * 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.
+ *
With Processing 0115 and later, it's possible to write images in
+ * formats other than the default .tga and .tiff. The exact formats and
+ * background information can be found in the developer's reference for
+ * PImage.save().
+ *
+ *
+ * @webref rendering
+ * @param w width in pixels
+ * @param h height in pixels
+ * @param renderer Either P2D, P3D, or PDF
+ * @see PGraphics#PGraphics
+ *
+ */
+ public PGraphics createGraphics(int w, int h, String renderer) {
+ return createGraphics(w, h, renderer, null);
+ }
+
+
+ /**
+ * Create an offscreen graphics surface for drawing, in this case
+ * for a renderer that writes to a file (such as PDF or DXF).
+ * @param path the name of the file (can be an absolute or relative path)
+ */
+ public PGraphics createGraphics(int w, int h,
+ String renderer, String path) {
+ return makeGraphics(w, h, renderer, path, false);
+ /*
+ if (path != null) {
+ path = savePath(path);
+ }
+ PGraphics pg = makeGraphics(w, h, renderer, path, false);
+ //pg.parent = this; // why wasn't setParent() used before 3.0a6?
+ //pg.setParent(this); // make save() work
+ // Nevermind, parent is set in makeGraphics()
+ return pg;
+ */
+ }
+
+
+// public PGraphics makePrimaryGraphics(int wide, int high) {
+// return makeGraphics(wide, high, sketchRenderer(), null, true);
+// }
+
+
+ /**
+ * Version of createGraphics() used internally.
+ * @param path A path (or null if none), can be absolute or relative ({@link PApplet#savePath} will be called)
+ */
+ protected PGraphics makeGraphics(int w, int h,
+ String renderer, String path,
+ boolean primary) {
+// String openglError = external ?
+// // This first one should no longer be possible
+// "Before using OpenGL, first select " +
+// "Import Library > OpenGL from the Sketch menu." :
+// // Welcome to Java programming! The training wheels are off.
+// "The Java classpath and native library path is not " +
+// "properly set for using the OpenGL library.";
+
+ if (!primary && !g.isGL()) {
+ if (renderer.equals(P2D)) {
+ throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D");
+ } else if (renderer.equals(P3D)) {
+ throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D");
+ }
+ }
+
+ try {
+ Class> rendererClass =
+ Thread.currentThread().getContextClassLoader().loadClass(renderer);
+
+ Constructor> constructor = rendererClass.getConstructor(new Class[] { });
+ PGraphics pg = (PGraphics) constructor.newInstance();
+
+ pg.setParent(this);
+ pg.setPrimary(primary);
+ if (path != null) {
+ pg.setPath(savePath(path));
+ }
+// pg.setQuality(sketchQuality());
+// if (!primary) {
+// surface.initImage(pg, w, h);
+// }
+ pg.setSize(w, h);
+
+ // everything worked, return it
+ return pg;
+
+ } catch (InvocationTargetException ite) {
+ String msg = ite.getTargetException().getMessage();
+ if ((msg != null) &&
+ (msg.indexOf("no jogl in java.library.path") != -1)) {
+ // Is this true anymore, since the JARs contain the native libs?
+ throw new RuntimeException("The jogl library folder needs to be " +
+ "specified with -Djava.library.path=/path/to/jogl");
+
+ } else {
+ printStackTrace(ite.getTargetException());
+ Throwable target = ite.getTargetException();
+ /*
+ // removing for 3.2, we'll see
+ if (platform == MACOSX) {
+ target.printStackTrace(System.out); // OS X bug (still true?)
+ }
+ */
+ throw new RuntimeException(target.getMessage());
+ }
+
+ } catch (ClassNotFoundException cnfe) {
+// if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) {
+// throw new RuntimeException(openglError +
+// " (The library .jar file is missing.)");
+// } else {
+ if (external) {
+ throw new RuntimeException("You need to use \"Import Library\" " +
+ "to add " + renderer + " to your sketch.");
+ } else {
+ throw new RuntimeException("The " + renderer +
+ " renderer is not in the class path.");
+ }
+
+ } catch (Exception e) {
+ if ((e instanceof IllegalArgumentException) ||
+ (e instanceof NoSuchMethodException) ||
+ (e instanceof IllegalAccessException)) {
+ if (e.getMessage().contains("cannot be <= 0")) {
+ // IllegalArgumentException will be thrown if w/h is <= 0
+ // http://code.google.com/p/processing/issues/detail?id=983
+ throw new RuntimeException(e);
+
+ } else {
+ printStackTrace(e);
+ String msg = renderer + " needs to be updated " +
+ "for the current release of Processing.";
+ throw new RuntimeException(msg);
+ }
+ } else {
+ /*
+ if (platform == MACOSX) {
+ e.printStackTrace(System.out); // OS X bug (still true?)
+ }
+ */
+ printStackTrace(e);
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+ }
+
+
+ /** Create default renderer, likely to be resized, but needed for surface init. */
+ protected PGraphics createPrimaryGraphics() {
+ return makeGraphics(sketchWidth(), sketchHeight(),
+ sketchRenderer(), sketchOutputPath(), true);
+ }
+
+
+ /**
+ * ( begin auto-generated from createImage.xml )
+ *
+ * Creates a new PImage (the datatype for storing images). This provides a
+ * fresh buffer of pixels to play with. Set the size of the buffer with the
+ * width and height parameters. The format parameter
+ * defines how the pixels are stored. See the PImage reference for more information.
+ *
+ * Be sure to include all three parameters, specifying only the width and
+ * height (but no format) will produce a strange error.
+ *
+ * Advanced users please note that createImage() should be used instead of
+ * the syntax new PImage().
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Preferred method of creating new PImage objects, ensures that a
+ * reference to the parent PApplet is included, which makes save() work
+ * without needing an absolute path.
+ *
+ * @webref image
+ * @param w width in pixels
+ * @param h height in pixels
+ * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel)
+ * @see PImage
+ * @see PGraphics
+ */
+ public PImage createImage(int w, int h, int format) {
+ PImage image = new PImage(w, h, format);
+ image.parent = this; // make save() work
+ return image;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ protected boolean insideDraw;
+
+ /** Last time in nanoseconds that frameRate was checked */
+ protected long frameRateLastNanos = 0;
+
+
+ public void handleDraw() {
+ //debug("handleDraw() " + g + " " + looping + " " + redraw + " valid:" + this.isValid() + " visible:" + this.isVisible());
+
+ // canDraw = g != null && (looping || redraw);
+ if (g == null) return;
+ if (!looping && !redraw) return;
+// System.out.println("looping/redraw = " + looping + " " + redraw);
+
+ // no longer in use by any of our renderers
+// if (!g.canDraw()) {
+// debug("g.canDraw() is false");
+// // Don't draw if the renderer is not yet ready.
+// // (e.g. OpenGL has to wait for a peer to be on screen)
+// return;
+// }
+
+ // Store the quality setting in case it's changed during draw and the
+ // drawing context needs to be re-built before the next frame.
+// int pquality = g.smooth;
+
+ if (insideDraw) {
+ System.err.println("handleDraw() called before finishing");
+ System.exit(1);
+ }
+
+ insideDraw = true;
+ g.beginDraw();
+ if (recorder != null) {
+ recorder.beginDraw();
+ }
+
+ long now = System.nanoTime();
+
+ if (frameCount == 0) {
+ // 3.0a5 should be no longer needed; handled by PSurface
+ //surface.checkDisplaySize();
+
+// try {
+ //println("Calling setup()");
+ setup();
+ //println("Done with setup()");
+
+// } catch (RendererChangeException e) {
+// // Give up, instead set the new renderer and re-attempt setup()
+// return;
+// }
+// defaultSize = false;
+
+ } else { // frameCount > 0, meaning an actual draw()
+ // update the current frameRate
+ double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0);
+ float instantaneousRate = (float) (rate / 1000.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;
+
+ //println("Calling draw()");
+ draw();
+ //println("Done calling draw()");
+
+ // dmouseX/Y is updated only once per frame (unlike emouseX/Y)
+ dmouseX = mouseX;
+ dmouseY = mouseY;
+
+ // these are called *after* loop so that valid
+ // drawing commands can be run inside them. it can't
+ // be before, since a call to background() would wipe
+ // out anything that had been drawn so far.
+ dequeueEvents();
+
+ handleMethods("draw");
+
+ redraw = false; // unset 'redraw' flag in case it was set
+ // (only do this once draw() has run, not just setup())
+ }
+ g.endDraw();
+
+// if (pquality != g.smooth) {
+// surface.setSmooth(g.smooth);
+// }
+
+ if (recorder != null) {
+ recorder.endDraw();
+ }
+ insideDraw = false;
+
+ if (frameCount != 0) {
+ handleMethods("post");
+ }
+
+ frameRateLastNanos = now;
+ frameCount++;
+ }
+
+
+// /** Not official API, not guaranteed to work in the future. */
+// public boolean canDraw() {
+// return g != null && (looping || redraw);
+// }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+/**
+ * ( begin auto-generated from redraw.xml )
+ *
+ * Executes the code within draw() one time. This functions allows
+ * the program to update the display window only when necessary, for
+ * example when an event registered by mousePressed() or
+ * keyPressed() occurs.
+ *
structuring a program, it only makes sense to call redraw()
+ * within events such as mousePressed(). This is because
+ * redraw() does not run draw() immediately (it only sets a
+ * flag that indicates an update is needed).
+ *
redraw() within draw() has no effect because
+ * draw() is continuously called anyway.
+ *
+ * ( end auto-generated )
+ * @webref structure
+ * @usage web_application
+ * @see PApplet#draw()
+ * @see PApplet#loop()
+ * @see PApplet#noLoop()
+ * @see PApplet#frameRate(float)
+ */
+ 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();
+// }
+// }
+// }
+ }
+ }
+
+/**
+ * ( begin auto-generated from loop.xml )
+ *
+ * Causes Processing to continuously execute the code within draw().
+ * If noLoop() is called, the code in draw() stops executing.
+ *
+ * ( end auto-generated )
+ * @webref structure
+ * @usage web_application
+ * @see PApplet#noLoop()
+ * @see PApplet#redraw()
+ * @see PApplet#draw()
+ */
+ synchronized public void loop() {
+ if (!looping) {
+ looping = true;
+ }
+ }
+
+/**
+ * ( begin auto-generated from noLoop.xml )
+ *
+ * Stops Processing from continuously executing the code within
+ * draw(). If loop() is called, the code in draw()
+ * begin to run continuously again. If using noLoop() in
+ * setup(), it should be the last line inside the block.
+ *
+ * When noLoop() is used, it's not possible to manipulate or access
+ * the screen inside event handling functions such as mousePressed()
+ * or keyPressed(). Instead, use those functions to call
+ * redraw() or loop(), which will run draw(), which
+ * can update the screen properly. This means that when noLoop() has been
+ * called, no drawing can happen, and functions like saveFrame() or
+ * loadPixels() may not be used.
+ *
+ * Note that if the sketch is resized, redraw() will be called to
+ * update the sketch, even after noLoop() has been specified.
+ * Otherwise, the sketch would enter an odd state until loop() was called.
+ *
+ * ( end auto-generated )
+ * @webref structure
+ * @usage web_application
+ * @see PApplet#loop()
+ * @see PApplet#redraw()
+ * @see PApplet#draw()
+ */
+ synchronized public void noLoop() {
+ if (looping) {
+ looping = false;
+ }
+ }
+
+
+ public boolean isLooping() {
+ return looping;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ BlockingQueue eventQueue = new LinkedBlockingQueue<>();
+ private final Object eventQueueDequeueLock = new Object[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() {
+ synchronized (eventQueueDequeueLock) {
+ while (!eventQueue.isEmpty()) {
+ Event e = eventQueue.remove();
+ switch (e.getFlavor()) {
+ case Event.MOUSE:
+ handleMouseEvent((MouseEvent) e);
+ break;
+ case Event.KEY:
+ handleKeyEvent((KeyEvent) e);
+ break;
+ }
+ }
+ }
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Actually take action based on a mouse event.
+ * Internally updates mouseX, mouseY, mousePressed, and mouseEvent.
+ * Then it calls the event type with no params,
+ * i.e. mousePressed() or mouseReleased() that the user may have
+ * overloaded to do something more useful.
+ */
+ protected void handleMouseEvent(MouseEvent event) {
+ // 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.
+ // Not necessary to set mouseX/Y on RELEASE events because the
+ // actual position will have been set by a PRESS or DRAG event.
+ // However, PRESS events might come without a preceeding move,
+ // if the sketch window gains focus on that PRESS.
+ final int action = event.getAction();
+ if (action == MouseEvent.DRAG ||
+ action == MouseEvent.MOVE ||
+ action == MouseEvent.PRESS) {
+ pmouseX = emouseX;
+ pmouseY = emouseY;
+ mouseX = event.getX();
+ mouseY = event.getY();
+ }
+
+ // Get the (already processed) button code
+ mouseButton = event.getButton();
+
+ /*
+ // Compatibility for older code (these have AWT object params, not P5)
+ if (mouseEventMethods != null) {
+ // Probably also good to check this, in case anyone tries to call
+ // postEvent() with an artificial event they've created.
+ if (event.getNative() != null) {
+ mouseEventMethods.handle(new Object[] { event.getNative() });
+ }
+ }
+ */
+
+ // this used to only be called on mouseMoved and mouseDragged
+ // change it back if people run into trouble
+ if (firstMouse) {
+ pmouseX = mouseX;
+ pmouseY = mouseY;
+ dmouseX = mouseX;
+ dmouseY = mouseY;
+ firstMouse = false;
+ }
+
+ mouseEvent = event;
+
+ // Do this up here in case a registered method relies on the
+ // boolean for mousePressed.
+
+ switch (action) {
+ case MouseEvent.PRESS:
+ mousePressed = true;
+ break;
+ case MouseEvent.RELEASE:
+ mousePressed = false;
+ break;
+ }
+
+ handleMethods("mouseEvent", new Object[] { event });
+
+ switch (action) {
+ case MouseEvent.PRESS:
+// mousePressed = true;
+ mousePressed(event);
+ break;
+ case MouseEvent.RELEASE:
+// mousePressed = false;
+ 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;
+ case MouseEvent.WHEEL:
+ mouseWheel(event);
+ break;
+ }
+
+ if ((action == MouseEvent.DRAG) ||
+ (action == MouseEvent.MOVE)) {
+ emouseX = mouseX;
+ emouseY = mouseY;
+ }
+ }
+
+
+ /**
+ * ( begin auto-generated from mousePressed.xml )
+ *
+ * The mousePressed() function is called once after every time a
+ * mouse button is pressed. The mouseButton variable (see the
+ * related reference entry) can be used to determine which button has been pressed.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ *
+ * If you must, use
+ * int button = mouseEvent.getButton();
+ * to figure out which button was clicked. It will be one of:
+ * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3
+ * Note, however, that this is completely inconsistent across
+ * platforms.
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public void mousePressed() { }
+
+
+ public void mousePressed(MouseEvent event) {
+ mousePressed();
+ }
+
+
+ /**
+ * ( begin auto-generated from mouseReleased.xml )
+ *
+ * The mouseReleased() function is called every time a mouse button
+ * is released.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public void mouseReleased() { }
+
+
+ public void mouseReleased(MouseEvent event) {
+ mouseReleased();
+ }
+
+
+ /**
+ * ( begin auto-generated from mouseClicked.xml )
+ *
+ * The mouseClicked() function is called once after a mouse button
+ * has been pressed and then released.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * When the mouse is clicked, mousePressed() will be called,
+ * then mouseReleased(), then mouseClicked(). Note that
+ * mousePressed is already false inside of mouseClicked().
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public void mouseClicked() { }
+
+
+ public void mouseClicked(MouseEvent event) {
+ mouseClicked();
+ }
+
+
+ /**
+ * ( begin auto-generated from mouseDragged.xml )
+ *
+ * The mouseDragged() function is called once every time the mouse
+ * moves and a mouse button is pressed.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ public void mouseDragged() { }
+
+
+ public void mouseDragged(MouseEvent event) {
+ mouseDragged();
+ }
+
+
+ /**
+ * ( begin auto-generated from mouseMoved.xml )
+ *
+ * The mouseMoved() function is called every time the mouse moves
+ * and a mouse button is not pressed.
+ *
+ * ( end auto-generated )
+ * @webref input:mouse
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ * @see PApplet#mouseWheel(MouseEvent)
+ */
+ 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();
+ }
+
+ /**
+ * @nowebref
+ */
+ public void mouseWheel() { }
+
+ /**
+ * The event.getAmount() method returns negative values if the mouse wheel
+ * if rotated up or away from the user and positive in the other direction.
+ * On OS X with "natural" scrolling enabled, the values are opposite.
+ *
+ * @webref input:mouse
+ * @param event the MouseEvent
+ * @see PApplet#mouseX
+ * @see PApplet#mouseY
+ * @see PApplet#pmouseX
+ * @see PApplet#pmouseY
+ * @see PApplet#mousePressed
+ * @see PApplet#mousePressed()
+ * @see PApplet#mouseReleased()
+ * @see PApplet#mouseClicked()
+ * @see PApplet#mouseMoved()
+ * @see PApplet#mouseDragged()
+ * @see PApplet#mouseButton
+ */
+ public void mouseWheel(MouseEvent event) {
+ mouseWheel();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ 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:
+ Long hash = ((long) keyCode << Character.SIZE) | key;
+ if (!pressedKeys.contains(hash)) pressedKeys.add(hash);
+ keyPressed = true;
+ keyPressed(keyEvent);
+ break;
+ case KeyEvent.RELEASE:
+ pressedKeys.remove(((long) keyCode << Character.SIZE) | key);
+ keyPressed = !pressedKeys.isEmpty();
+ keyReleased(keyEvent);
+ break;
+ case KeyEvent.TYPE:
+ keyTyped(keyEvent);
+ break;
+ }
+
+ /*
+ if (keyEventMethods != null) {
+ keyEventMethods.handle(new Object[] { event.getNative() });
+ }
+ */
+
+ handleMethods("keyEvent", new Object[] { event });
+
+ // if someone else wants to intercept the key, they should
+ // set key to zero (or something besides the ESC).
+ if (event.getAction() == KeyEvent.PRESS) {
+ //if (key == java.awt.event.KeyEvent.VK_ESCAPE) {
+ if (key == ESC) {
+ exit();
+ }
+ // When running tethered to the Processing application, respond to
+ // Ctrl-W (or Cmd-W) events by closing the sketch. Not enabled when
+ // running independently, because this sketch may be one component
+ // embedded inside an application that has its own close behavior.
+ if (external &&
+ event.getKeyCode() == 'W' &&
+ ((event.isMetaDown() && platform == MACOSX) ||
+ (event.isControlDown() && platform != MACOSX))) {
+ // Can't use this native stuff b/c the native event might be NEWT
+// if (external && event.getNative() instanceof java.awt.event.KeyEvent &&
+// ((java.awt.event.KeyEvent) event.getNative()).getModifiers() ==
+// Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() &&
+// event.getKeyCode() == 'W') {
+ exit();
+ }
+ }
+ }
+
+
+ /**
+ *
+ * ( begin auto-generated from keyPressed.xml )
+ *
+ * The keyPressed() function is called once every time a key is
+ * pressed. The key that was pressed is stored in the key variable.
+ *
+ * For non-ASCII keys, use the keyCode variable. The keys included
+ * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and
+ * DELETE) do not require checking to see if they key is coded, and you
+ * should simply use the key variable instead of keyCode If
+ * you're making cross-platform projects, note that the ENTER key is
+ * commonly used on PCs and Unix and the RETURN key is used instead on
+ * Macintosh. Check for both ENTER and RETURN to make sure your program
+ * will work for all platforms.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * may cause multiple calls to keyPressed() (and keyReleased() as well).
+ * The rate of repeat is set by the operating system and how each computer
+ * is configured.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ *
+ * Called each time a single key on the keyboard is pressed.
+ * Because of how operating systems handle key repeats, holding
+ * down a key will cause multiple calls to keyPressed(), because
+ * the OS repeat takes over.
+ *
+ * Examples for key handling:
+ * (Tested on Windows XP, please notify if different on other
+ * platforms, I have a feeling Mac OS and Linux may do otherwise)
+ *
+ * 1. Pressing 'a' on the keyboard:
+ * keyPressed with key == 'a' and keyCode == 'A'
+ * keyTyped with key == 'a' and keyCode == 0
+ * keyReleased with key == 'a' and keyCode == 'A'
+ *
+ * 2. Pressing 'A' on the keyboard:
+ * keyPressed with key == 'A' and keyCode == 'A'
+ * keyTyped with key == 'A' and keyCode == 0
+ * keyReleased with key == 'A' and keyCode == 'A'
+ *
+ * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off):
+ * keyPressed with key == CODED and keyCode == SHIFT
+ * keyPressed with key == 'A' and keyCode == 'A'
+ * keyTyped with key == 'A' and keyCode == 0
+ * keyReleased with key == 'A' and keyCode == 'A'
+ * keyReleased with key == CODED and keyCode == SHIFT
+ *
+ * 4. Holding down the 'a' key.
+ * The following will happen several times,
+ * depending on your machine's "key repeat rate" settings:
+ * keyPressed with key == 'a' and keyCode == 'A'
+ * keyTyped with key == 'a' and keyCode == 0
+ * When you finally let go, you'll get:
+ * keyReleased with key == 'a' and keyCode == 'A'
+ *
+ * 5. Pressing and releasing the 'shift' key
+ * keyPressed with key == CODED and keyCode == SHIFT
+ * keyReleased with key == CODED and keyCode == SHIFT
+ * (note there is no keyTyped)
+ *
+ * 6. Pressing the tab key in an applet with Java 1.4 will
+ * normally do nothing, but PApplet dynamically shuts
+ * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows).
+ * Java 1.1 (Microsoft VM) passes the TAB key through normally.
+ * Not tested on other platforms or for 1.3.
+ *
+ * @webref input:keyboard
+ * @see PApplet#key
+ * @see PApplet#keyCode
+ * @see PApplet#keyPressed
+ * @see PApplet#keyReleased()
+ */
+ public void keyPressed() { }
+
+
+ public void keyPressed(KeyEvent event) {
+ keyPressed();
+ }
+
+
+ /**
+ * ( begin auto-generated from keyReleased.xml )
+ *
+ * The keyReleased() function is called once every time a key is
+ * released. The key that was released will be stored in the key
+ * variable. See key and keyReleased for more information.
+ *
+ * ( end auto-generated )
+ * @webref input:keyboard
+ * @see PApplet#key
+ * @see PApplet#keyCode
+ * @see PApplet#keyPressed
+ * @see PApplet#keyPressed()
+ */
+ public void keyReleased() { }
+
+
+ public void keyReleased(KeyEvent event) {
+ keyReleased();
+ }
+
+
+ /**
+ * ( begin auto-generated from keyTyped.xml )
+ *
+ * The keyTyped() function is called once every time a key is
+ * pressed, but action keys such as Ctrl, Shift, and Alt are ignored.
+ * Because of how operating systems handle key repeats, holding down a key
+ * will cause multiple calls to keyTyped(), the rate is set by the
+ * operating system and how each computer is configured.
+ *
+ * ( end auto-generated )
+ * @webref input:keyboard
+ * @see PApplet#keyPressed
+ * @see PApplet#key
+ * @see PApplet#keyCode
+ * @see PApplet#keyReleased()
+ */
+ public void keyTyped() { }
+
+
+ public void keyTyped(KeyEvent event) {
+ keyTyped();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // i am focused man, and i'm not afraid of death.
+ // and i'm going all out. i circle the vultures in a van
+ // and i run the block.
+
+
+ public void focusGained() { }
+
+
+ public void focusLost() {
+ // TODO: if user overrides this without calling super it's not gonna work
+ pressedKeys.clear();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // getting the time
+
+
+ /**
+ * ( begin auto-generated from millis.xml )
+ *
+ * Returns the number of milliseconds (thousandths of a second) since
+ * starting an applet. This information is often used for timing animation
+ * sequences.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ *
+ * This is a function, rather than a variable, because it may
+ * change multiple times per frame.
+ *
+ * @webref input:time_date
+ * @see PApplet#second()
+ * @see PApplet#minute()
+ * @see PApplet#hour()
+ * @see PApplet#day()
+ * @see PApplet#month()
+ * @see PApplet#year()
+ *
+ */
+ public int millis() {
+ return (int) (System.currentTimeMillis() - millisOffset);
+ }
+
+ /**
+ * ( begin auto-generated from second.xml )
+ *
+ * Processing communicates with the clock on your computer. The
+ * second() function returns the current second as a value from 0 - 59.
+ *
+ * ( end auto-generated )
+ * @webref input:time_date
+ * @see PApplet#millis()
+ * @see PApplet#minute()
+ * @see PApplet#hour()
+ * @see PApplet#day()
+ * @see PApplet#month()
+ * @see PApplet#year()
+ * */
+ static public int second() {
+ return Calendar.getInstance().get(Calendar.SECOND);
+ }
+
+ /**
+ * ( begin auto-generated from minute.xml )
+ *
+ * Processing communicates with the clock on your computer. The
+ * minute() function returns the current minute as a value from 0 - 59.
+ *
+ * ( end auto-generated )
+ *
+ * @webref input:time_date
+ * @see PApplet#millis()
+ * @see PApplet#second()
+ * @see PApplet#hour()
+ * @see PApplet#day()
+ * @see PApplet#month()
+ * @see PApplet#year()
+ *
+ * */
+ static public int minute() {
+ return Calendar.getInstance().get(Calendar.MINUTE);
+ }
+
+ /**
+ * ( begin auto-generated from hour.xml )
+ *
+ * Processing communicates with the clock on your computer. The
+ * hour() function returns the current hour as a value from 0 - 23.
+ *
+ * ( end auto-generated )
+ * @webref input:time_date
+ * @see PApplet#millis()
+ * @see PApplet#second()
+ * @see PApplet#minute()
+ * @see PApplet#day()
+ * @see PApplet#month()
+ * @see PApplet#year()
+ *
+ */
+ static public int hour() {
+ return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
+ }
+
+ /**
+ * ( begin auto-generated from day.xml )
+ *
+ * Processing communicates with the clock on your computer. The
+ * day() function returns the current day as a value from 1 - 31.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Get the current day of the month (1 through 31).
+ *
+ * If you're looking for the day of the week (M-F or whatever)
+ * or day of the year (1..365) then use java's Calendar.get()
+ *
+ * @webref input:time_date
+ * @see PApplet#millis()
+ * @see PApplet#second()
+ * @see PApplet#minute()
+ * @see PApplet#hour()
+ * @see PApplet#month()
+ * @see PApplet#year()
+ */
+ static public int day() {
+ return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
+ }
+
+ /**
+ * ( begin auto-generated from month.xml )
+ *
+ * Processing communicates with the clock on your computer. The
+ * month() function returns the current month as a value from 1 - 12.
+ *
+ * ( end auto-generated )
+ *
+ * @webref input:time_date
+ * @see PApplet#millis()
+ * @see PApplet#second()
+ * @see PApplet#minute()
+ * @see PApplet#hour()
+ * @see PApplet#day()
+ * @see PApplet#year()
+ */
+ static public int month() {
+ // months are number 0..11 so change to colloquial 1..12
+ return Calendar.getInstance().get(Calendar.MONTH) + 1;
+ }
+
+ /**
+ * ( begin auto-generated from year.xml )
+ *
+ * Processing communicates with the clock on your computer. The
+ * year() function returns the current year as an integer (2003,
+ * 2004, 2005, etc).
+ *
+ * ( end auto-generated )
+ * The year() function returns the current year as an integer (2003, 2004, 2005, etc).
+ *
+ * @webref input:time_date
+ * @see PApplet#millis()
+ * @see PApplet#second()
+ * @see PApplet#minute()
+ * @see PApplet#hour()
+ * @see PApplet#day()
+ * @see PApplet#month()
+ */
+ static public int year() {
+ return Calendar.getInstance().get(Calendar.YEAR);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // controlling time (playing god)
+
+
+ /**
+ * ( begin auto-generated from delay.xml )
+ *
+ * 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).
+ *
+ * ( end auto-generated )
+ * @webref environment
+ * @param napTime milliseconds to pause before running draw() again
+ * @see PApplet#frameRate
+ * @see PApplet#draw()
+ */
+ 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 )
+ * @webref environment
+ * @param fps number of desired frames per second
+ * @see PApplet#frameRate
+ * @see PApplet#frameCount
+ * @see PApplet#setup()
+ * @see PApplet#draw()
+ * @see PApplet#loop()
+ * @see PApplet#noLoop()
+ * @see PApplet#redraw()
+ */
+ public void frameRate(float fps) {
+ surface.setFrameRate(fps);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * Links to a webpage either in the same window or in a new window. The
+ * complete URL must be specified.
+ *
+ *
Advanced
+ * Link to an external page without all the muss.
+ *
+ * When run with an applet, uses the browser to open the url,
+ * for applications, attempts to launch a browser with the url.
+ *
+ * @param url the complete URL, as a String in quotes
+ */
+ public void link(String url) {
+ try {
+ if (Desktop.isDesktopSupported()) {
+ Desktop.getDesktop().browse(new URI(url));
+ } else {
+ // Just pass it off to open() and hope for the best
+ launch(url);
+ }
+ } catch (IOException e) {
+ printStackTrace(e);
+ } catch (URISyntaxException e) {
+ printStackTrace(e);
+ }
+ }
+
+
+ static String openLauncher;
+
+
+ /**
+ * ( begin auto-generated from launch.xml )
+ *
+ * Attempts to open an application or file using your platform's launcher.
+ * The file parameter is a String specifying the file name and
+ * location. The location parameter must be a full path name, or the name
+ * of an executable in the system's PATH. In most cases, using a full path
+ * is the best option, rather than relying on the system PATH. Be sure to
+ * make the file executable before attempting to open it (chmod +x).
+ *
+ * The args parameter is a String or String array which is passed to
+ * the command line. If you have multiple parameters, e.g. an application
+ * and a document, or a command with multiple switches, use the version
+ * that takes a String array, and place each individual item in a separate
+ * element.
+ *
+ * If args is a String (not an array), then it can only be a single file or
+ * application with no parameters. It's not the same as executing that
+ * String using a shell. For instance, launch("javac -help") will not work
+ * properly.
+ *
+ * This function behaves differently on each platform. On Windows, the
+ * parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the
+ * "open" command is used (type "man open" in Terminal.app for
+ * documentation). On Linux, it first tries gnome-open, then kde-open, but
+ * if neither are available, it sends the command to the shell without any
+ * alterations.
+ *
+ * For users familiar with Java, this is not quite the same as
+ * Runtime.exec(), because the launcher command is prepended. Instead, the
+ * exec(String[]) function is a shortcut for
+ * Runtime.getRuntime.exec(String[]).
+ *
+ * ( end auto-generated )
+ * @webref input:files
+ * @param args arguments to the launcher, eg. a filename.
+ * @usage Application
+ */
+ static public Process launch(String... args) {
+ String[] params = null;
+
+ if (platform == WINDOWS) {
+ // just launching the .html file via the shell works
+ // but make sure to chmod +x the .html files first
+ // also place quotes around it in case there's a space
+ // in the user.dir part of the url
+ params = new String[] { "cmd", "/c" };
+
+ } else if (platform == MACOSX) {
+ params = new String[] { "open" };
+
+ } else if (platform == LINUX) {
+ // xdg-open is in the Free Desktop Specification and really should just
+ // work on desktop Linux. Not risking it though.
+ final String[] launchers = { "xdg-open", "gnome-open", "kde-open" };
+ for (String launcher : launchers) {
+ if (openLauncher != null) break;
+ try {
+ Process p = Runtime.getRuntime().exec(new String[] { launcher });
+ /*int result =*/ p.waitFor();
+ // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
+ openLauncher = launcher;
+ } catch (Exception e) { }
+ }
+ if (openLauncher == null) {
+ System.err.println("Could not find xdg-open, gnome-open, or kde-open: " +
+ "the open() command may not work.");
+ }
+ if (openLauncher != null) {
+ params = new String[] { openLauncher };
+ }
+ //} else { // give up and just pass it to Runtime.exec()
+ //open(new String[] { filename });
+ //params = new String[] { filename };
+ }
+ if (params != null) {
+ // If the 'open', 'gnome-open' or 'cmd' are already included
+ if (params[0].equals(args[0])) {
+ // then don't prepend those params again
+ return exec(args);
+ } else {
+ params = concat(params, args);
+ return exec(params);
+ }
+ } else {
+ return exec(args);
+ }
+ }
+
+
+ /**
+ * Pass a set of arguments directly to the command line. Uses Java's
+ * Runtime.exec()
+ * method. This is different from the launch()
+ * method, which uses the operating system's launcher to open the files.
+ * It's always a good idea to use a full path to the executable here.
+ *
+ * exec("/usr/bin/say", "welcome to the command line");
+ *
+ * Or if you want to wait until it's completed, something like this:
+ *
+ * Process p = exec("/usr/bin/say", "waiting until done");
+ * try {
+ * int result = p.waitFor();
+ * println("the process returned " + result);
+ * } catch (InterruptedException e) { }
+ *
+ * You can also get the system output and error streams from the Process
+ * object, but that's more that we'd like to cover here.
+ * @return a Process object
+ */
+ static public Process exec(String... args) {
+ try {
+ return Runtime.getRuntime().exec(args);
+ } catch (Exception e) {
+ throw new RuntimeException("Could not open " + join(args, ' '), e);
+ }
+ }
+
+
+ /**
+ * Alternative version of exec() that retrieves stdout and stderr into the
+ * StringList objects provided. This is a convenience function that handles
+ * simple exec() calls. If the results will be more than a couple lines,
+ * you shouldn't use this function, you should use a more elaborate method
+ * that makes use of proper threading (to drain the shell output) and error
+ * handling to address the many things that can go wrong within this method.
+ *
+ * @param stdout a non-null StringList object to be filled with any output
+ * @param stderr a non-null StringList object to be filled with error lines
+ * @param args each argument to be passed as a series of String objects
+ * @return the result returned from the application, or -1 if an Exception
+ * occurs before the application is able to return a result.
+ */
+ static public int exec(StringList stdout, StringList stderr, String... args) {
+ Process p = exec(args);
+ int result = -1;
+ try {
+ BufferedReader out = createReader(p.getInputStream());
+ BufferedReader err = createReader(p.getErrorStream());
+ result = p.waitFor();
+ String line;
+ while ((line = out.readLine()) != null) {
+ stdout.append(line);
+ }
+ while ((line = err.readLine()) != null) {
+ stderr.append(line);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+
+ } catch (InterruptedException e) {
+ // can be safely ignored
+ }
+ return result;
+ }
+
+
+ /**
+ * Same as exec() above, but prefixes the call with a shell.
+ */
+ static public int shell(StringList stdout, StringList stderr, String... args) {
+ String shell;
+ String runCmd;
+ StringList argList = new StringList();
+ if (platform == WINDOWS) {
+ shell = System.getenv("COMSPEC");
+ runCmd = "/C";
+ } else {
+ shell = "/bin/sh";
+ runCmd = "-c";
+ // attempt emulate the behavior of an interactive shell
+ // can't use -i or -l since the version of bash shipped with macOS does not support this together with -c
+ // also we want to make sure no motd or similar gets returned as stdout
+ argList.append("if [ -f /etc/profile ]; then . /etc/profile >/dev/null 2>&1; fi;");
+ argList.append("if [ -f ~/.bash_profile ]; then . ~/.bash_profile >/dev/null 2>&1; elif [ -f ~/.bash_profile ]; then . ~/.bash_profile >/dev/null 2>&1; elif [ -f ~/.profile ]; then ~/.profile >/dev/null 2>&1; fi;");
+ }
+ for (String arg : args) {
+ argList.append(arg);
+ }
+ return exec(stdout, stderr, shell, runCmd, argList.join(" "));
+ }
+
+
+ /*
+ static private final String shellQuoted(String arg) {
+ if (arg.indexOf(' ') != -1) {
+ // check to see if already quoted
+ if ((arg.charAt(0) != '\"' || arg.charAt(arg.length()-1) != '\"') &&
+ (arg.charAt(0) != '\'' || arg.charAt(arg.length()-1) != '\'')) {
+
+ // see which quotes we can use
+ if (arg.indexOf('\"') == -1) {
+ // if no double quotes, try those first
+ return "\"" + arg + "\"";
+
+ } else if (arg.indexOf('\'') == -1) {
+ // if no single quotes, let's use those
+ return "'" + arg + "'";
+ }
+ }
+ }
+ return arg;
+ }
+ */
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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) {
+ dispose();
+ throw new RuntimeException(what);
+ }
+
+
+ /**
+ * Same as above but with an exception. Also needs work.
+ */
+ public void die(String what, Exception e) {
+ if (e != null) e.printStackTrace();
+ die(what);
+ }
+
+
+ /**
+ * ( begin auto-generated from exit.xml )
+ *
+ * Quits/stops/exits the program. Programs without a draw() function
+ * exit automatically after the last line has run, but programs with
+ * draw() run continuously until the program is manually stopped or
+ * exit() is run.
+ *
+ * Rather than terminating immediately, exit() will cause the sketch
+ * to exit after draw() has completed (or after setup()
+ * completes if called during the setup() function).
+ *
+ * For Java programmers, this is not the same as System.exit().
+ * Further, System.exit() should not be used because closing out an
+ * application while draw() is running may cause a crash
+ * (particularly with P3D).
+ *
+ * ( end auto-generated )
+ * @webref structure
+ */
+ public void exit() {
+ if (surface.isStopped()) {
+ // exit immediately, dispose() has already been called,
+ // meaning that the main thread has long since exited
+ exitActual();
+
+ } else if (looping) {
+ // dispose() will be called as the thread exits
+ finished = true;
+ // tell the code to call exitActual() to do a System.exit()
+ // once the next draw() has completed
+ exitCalled = true;
+
+ } else if (!looping) {
+ // if not looping, shut down things explicitly,
+ // because the main thread will be sleeping
+ dispose();
+
+ // now get out
+ exitActual();
+ }
+ }
+
+
+ public boolean exitCalled() {
+ return exitCalled;
+ }
+
+
+ /**
+ * Some subclasses (I'm looking at you, processing.py) might wish to do something
+ * other than actually terminate the JVM. This gives them a chance to do whatever
+ * they have in mind when cleaning up.
+ */
+ public void exitActual() {
+ try {
+ System.exit(0);
+ } catch (SecurityException e) {
+ // don't care about applet security exceptions
+ }
+ }
+
+
+ /**
+ * Called to dispose of resources and shut down the sketch.
+ * Destroys the thread, dispose the renderer,and notify listeners.
+ *
+ * Not to be called or overriden by users. If called multiple times,
+ * will only notify listeners once. Register a dispose listener instead.
+ */
+ public void dispose() {
+ // moved here from stop()
+ finished = true; // let the sketch know it is shut down time
+
+ // don't run the disposers twice
+ if (surface.stopThread()) {
+
+ // shut down renderer
+ if (g != null) {
+ g.dispose();
+ }
+ // run dispose() methods registered by libraries
+ handleMethods("dispose");
+ }
+
+ if (platform == MACOSX) {
+ try {
+ final String td = "processing.core.ThinkDifferent";
+ final Class> thinkDifferent = getClass().getClassLoader().loadClass(td);
+ thinkDifferent.getMethod("cleanup").invoke(null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ e.getTargetException().printStackTrace();
+ } catch (NoSuchMethodException nsme) {
+ System.err.println("There is no public " + name + "() method " +
+ "in the class " + getClass().getName());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ /**
+ * 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.
+ *
+ * @webref structure
+ * @usage Application
+ * @param name name of the function to be executed in a separate thread
+ * @see PApplet#setup()
+ * @see PApplet#draw()
+ * @see PApplet#loop()
+ * @see PApplet#noLoop()
+ */
+ public void thread(final String name) {
+ Thread later = new Thread() {
+ @Override
+ public void run() {
+ method(name);
+ }
+ };
+ later.start();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SCREEN GRABASS
+
+
+ /**
+ * ( begin auto-generated from save.xml )
+ *
+ * Saves an image from the display window. Images are saved in TIFF, TARGA,
+ * JPEG, and PNG format depending on the extension within the
+ * filename parameter. For example, "image.tif" will have a TIFF
+ * image and "image.png" will save a PNG image. If no extension is included
+ * in the filename, the image will save in TIFF format and .tif will
+ * be added to the name. These files are saved to the sketch's folder,
+ * which may be opened by selecting "Show sketch folder" from the "Sketch"
+ * menu. It is not possible to use save() while running the program
+ * in a web browser.
+ * images saved from the main drawing window will be opaque. To save
+ * images without a background, use createGraphics().
+ *
+ * ( end auto-generated )
+ * @webref output:image
+ * @param filename any sequence of letters and numbers
+ * @see PApplet#saveFrame()
+ * @see PApplet#createGraphics(int, int, String)
+ */
+ public void save(String filename) {
+ g.save(savePath(filename));
+ }
+
+
+ /**
+ */
+ 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.");
+ }
+ }
+
+
+ /**
+ * ( begin auto-generated from saveFrame.xml )
+ *
+ * Saves a numbered sequence of images, one image each time the function is
+ * run. To save an image that is identical to the display window, run the
+ * function at the end of draw() or within mouse and key events such
+ * as mousePressed() and keyPressed(). If saveFrame()
+ * is called without parameters, it will save the files as screen-0000.tif,
+ * screen-0001.tif, etc. It is possible to specify the name of the sequence
+ * with the filename parameter and make the choice of saving TIFF,
+ * TARGA, PNG, or JPEG files with the ext parameter. These image
+ * sequences can be loaded into programs such as Apple's QuickTime software
+ * and made into movies. These files are saved to the sketch's folder,
+ * which may be opened by selecting "Show sketch folder" from the "Sketch"
+ * menu.
+ *
+ * It is not possible to use saveXxxxx() functions inside a web browser
+ * unless the sketch is signed applet. To
+ * save a file back to a server, see the save to
+ * web code snippet on the Processing Wiki.
+ *
+ * All images saved from the main drawing window will be opaque. To save
+ * images without a background, use createGraphics().
+ *
+ * ( end auto-generated )
+ * @webref output:image
+ * @see PApplet#save(String)
+ * @see PApplet#createGraphics(int, int, String, String)
+ * @see PApplet#frameCount
+ * @param filename any sequence of letters or numbers that ends with either ".tif", ".tga", ".jpg", or ".png"
+ */
+ public void saveFrame(String filename) {
+ try {
+ g.save(savePath(insertFrame(filename)));
+ } 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.
+ */
+ public 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
+
+ //
+
+
+ /**
+ * Set the cursor type
+ * @param kind either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT
+ */
+ public void cursor(int kind) {
+ surface.setCursor(kind);
+ }
+
+
+ /**
+ * 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 img) {
+ cursor(img, img.width/2, img.height/2);
+ }
+
+
+ /**
+ * ( begin auto-generated from cursor.xml )
+ *
+ * Sets the cursor to a predefined symbol, an image, or makes it visible if
+ * already hidden. If you are trying to set an image as the cursor, it is
+ * recommended to make the size 16x16 or 32x32 pixels. It is not possible
+ * to load an image as the cursor if you are exporting your program for the
+ * Web and not all MODES work with all Web browsers. The values for
+ * parameters x and y must be less than the dimensions of the image.
+ *
+ * Setting or hiding the cursor generally does not work with "Present" mode
+ * (when running full-screen).
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Set a custom cursor to an image with a specific hotspot.
+ * Only works with JDK 1.2 and later.
+ * Currently seems to be broken on Java 1.4 for Mac OS X
+ *
+ * Based on code contributed by Amit Pitaru, plus additional
+ * code to handle Java versions via reflection by Jonathan Feinberg.
+ * Reflection removed for release 0128 and later.
+ * @webref environment
+ * @see PApplet#noCursor()
+ * @param img any variable of type PImage
+ * @param x the horizontal active spot of the cursor
+ * @param y the vertical active spot of the cursor
+ */
+ public void cursor(PImage img, int x, int y) {
+ surface.setCursor(img, x, y);
+ }
+
+
+ /**
+ * Show the cursor after noCursor() was called.
+ * Notice that the program remembers the last set cursor type
+ */
+ public void cursor() {
+ surface.showCursor();
+ }
+
+
+ /**
+ * ( begin auto-generated from noCursor.xml )
+ *
+ * Hides the cursor from view. Will not work when running the program in a
+ * web browser or when running in full screen (Present) mode.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Hide the cursor by creating a transparent image
+ * and using it as a custom cursor.
+ * @webref environment
+ * @see PApplet#cursor()
+ * @usage Application
+ */
+ public void noCursor() {
+ surface.hideCursor();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+/**
+ * ( begin auto-generated from print.xml )
+ *
+ * Writes to the console area of the Processing environment. This is often
+ * helpful for looking at the data a program is producing. The companion
+ * function println() works like print(), but creates a new
+ * line of text for each call to the function. Individual elements can be
+ * separated with quotes ("") and joined with the addition operator (+).
+ *
+ * Beginning with release 0125, to print the contents of an array, use
+ * println(). There's no sensible way to do a print() of an array,
+ * because there are too many possibilities for how to separate the data
+ * (spaces, commas, etc). If you want to print an array as a single line,
+ * use join(). With join(), you can choose any delimiter you
+ * like and print() the result.
+ *
+ * Using print() on an object will output null, a memory
+ * location that may look like "@10be08," or the result of the
+ * toString() method from the object that's being printed. Advanced
+ * users who want more useful output when calling print() on their
+ * own classes can add a toString() method to the class that returns
+ * a String.
+ *
+ * ( end auto-generated )
+ * @webref output:text_area
+ * @usage IDE
+ * @param what data to print to console
+ * @see PApplet#println()
+ * @see PApplet#printArray(Object)
+ * @see PApplet#join(String[], char)
+ */
+ 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(long 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(double 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());
+ }
+ }
+ */
+
+
+ /**
+ * ( begin auto-generated from println.xml )
+ *
+ * Writes to the text area of the Processing environment's console. This is
+ * often helpful for looking at the data a program is producing. Each call
+ * to this function creates a new line of output. Individual elements can
+ * be separated with quotes ("") and joined with the string concatenation
+ * operator (+). See print() for more about what to expect in the output.
+ *
println() on an array (by itself) will write the
+ * contents of the array to the console. This is often helpful for looking
+ * at the data a program is producing. A new line is put between each
+ * element of the array. This function can only print one dimensional
+ * arrays. For arrays with higher dimensions, the result will be closer to
+ * that of print().
+ *
+ * ( end auto-generated )
+ * @webref output:text_area
+ * @usage IDE
+ * @see PApplet#print(byte)
+ * @see PApplet#printArray(Object)
+ */
+ static public void println() {
+ System.out.println();
+ }
+
+
+/**
+ * @param what data to print to console
+ */
+ static public void println(byte what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(boolean what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(char what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(int what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(long what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(float what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(double what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ static public void println(String what) {
+ System.out.println(what);
+ System.out.flush();
+ }
+
+ /**
+ * @param variables list of data, separated by commas
+ */
+ static public void println(Object... variables) {
+// System.out.println("got " + variables.length + " variables");
+ print(variables);
+ println();
+ }
+
+
+ /*
+ // Breaking this out since the compiler doesn't know the difference between
+ // Object... and just Object (with an array passed in). This should take care
+ // of the confusion for at least the most common case (a String array).
+ // On second thought, we're going the printArray() route, since the other
+ // object types are also used frequently.
+ static public void println(String[] array) {
+ for (int i = 0; i < array.length; i++) {
+ System.out.println("[" + i + "] \"" + array[i] + "\"");
+ }
+ System.out.flush();
+ }
+ */
+
+
+ /**
+ * For arrays, use printArray() instead. This function causes a warning
+ * because the new print(Object...) and println(Object...) functions can't
+ * be reliably bound by the compiler.
+ */
+ static public void println(Object what) {
+ if (what == null) {
+ System.out.println("null");
+ } else if (what.getClass().isArray()) {
+ printArray(what);
+ } else {
+ System.out.println(what.toString());
+ System.out.flush();
+ }
+ }
+
+ /**
+ * ( begin auto-generated from printArray.xml )
+ *
+ * To come...
+ *
+ * ( end auto-generated )
+ * @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();
+ }
+
+
+ static public void debug(String msg) {
+ if (DEBUG) println(msg);
+ }
+ //
+
+ /*
+ // 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.
+
+/**
+ * ( begin auto-generated from abs.xml )
+ *
+ * Calculates the absolute value (magnitude) of a number. The absolute
+ * value of a number is always positive.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n number to compute
+ */
+ static public final float abs(float n) {
+ return (n < 0) ? -n : n;
+ }
+
+ static public final int abs(int n) {
+ return (n < 0) ? -n : n;
+ }
+
+/**
+ * ( begin auto-generated from sq.xml )
+ *
+ * Squares a number (multiplies a number by itself). The result is always a
+ * positive number, as multiplying two negative numbers always yields a
+ * positive result. For example, -1 * -1 = 1.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n number to square
+ * @see PApplet#sqrt(float)
+ */
+ static public final float sq(float n) {
+ return n*n;
+ }
+
+/**
+ * ( begin auto-generated from sqrt.xml )
+ *
+ * Calculates the square root of a number. The square root of a number is
+ * always positive, even though there may be a valid negative root. The
+ * square root s of number a is such that s*s = a. It
+ * is the opposite of squaring.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n non-negative number
+ * @see PApplet#pow(float, float)
+ * @see PApplet#sq(float)
+ */
+ static public final float sqrt(float n) {
+ return (float)Math.sqrt(n);
+ }
+
+/**
+ * ( begin auto-generated from log.xml )
+ *
+ * Calculates the natural logarithm (the base-e logarithm) of a
+ * number. This function expects the values greater than 0.0.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n number greater than 0.0
+ */
+ static public final float log(float n) {
+ return (float)Math.log(n);
+ }
+
+/**
+ * ( begin auto-generated from exp.xml )
+ *
+ * Returns Euler's number e (2.71828...) raised to the power of the
+ * value parameter.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n exponent to raise
+ */
+ static public final float exp(float n) {
+ return (float)Math.exp(n);
+ }
+
+/**
+ * ( begin auto-generated from pow.xml )
+ *
+ * Facilitates exponential expressions. The pow() function is an
+ * efficient way of multiplying numbers by themselves (or their reciprocal)
+ * in large quantities. For example, pow(3, 5) is equivalent to the
+ * expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n base of the exponential expression
+ * @param e power by which to raise the base
+ * @see PApplet#sqrt(float)
+ */
+ static public final float pow(float n, float e) {
+ return (float)Math.pow(n, e);
+ }
+
+/**
+ * ( begin auto-generated from max.xml )
+ *
+ * Determines the largest value in a sequence of numbers.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param a first number to compare
+ * @param b second number to compare
+ * @see PApplet#min(float, float, float)
+ */
+ static public final int max(int a, int b) {
+ return (a > b) ? a : b;
+ }
+
+ static public final float max(float a, float b) {
+ return (a > b) ? a : b;
+ }
+
+ /*
+ static public final double max(double a, double b) {
+ return (a > b) ? a : b;
+ }
+ */
+
+/**
+ * @param c third number to compare
+ */
+ 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);
+ }
+
+
+ /**
+ * @param list array of numbers to compare
+ */
+ 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;
+ }
+
+ static public final float max(float[] list) {
+ if (list.length == 0) {
+ throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
+ }
+ float max = list[0];
+ for (int i = 1; i < list.length; i++) {
+ if (list[i] > max) max = list[i];
+ }
+ return max;
+ }
+
+
+// /**
+// * Find the maximum value in an array.
+// * Throws an ArrayIndexOutOfBoundsException if the array is length 0.
+// * @param list the source array
+// * @return The maximum value
+// */
+ /*
+ static public final double max(double[] list) {
+ if (list.length == 0) {
+ throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
+ }
+ double max = list[0];
+ for (int i = 1; i < list.length; i++) {
+ if (list[i] > max) max = list[i];
+ }
+ return max;
+ }
+ */
+
+
+ static public final int min(int a, int b) {
+ return (a < b) ? a : b;
+ }
+
+ static public final float min(float a, float b) {
+ return (a < b) ? a : b;
+ }
+
+ /*
+ static public final double min(double a, double b) {
+ return (a < b) ? a : b;
+ }
+ */
+
+
+ static public final int min(int a, int b, int c) {
+ return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
+ }
+
+/**
+ * ( begin auto-generated from min.xml )
+ *
+ * Determines the smallest value in a sequence of numbers.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param a first number
+ * @param b second number
+ * @param c third number
+ * @see PApplet#max(float, float, float)
+ */
+ static public final float min(float a, float b, float c) {
+ return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
+ }
+
+ /*
+ static public final double min(double a, double b, double c) {
+ return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
+ }
+ */
+
+
+ /**
+ * @param list array of numbers to compare
+ */
+ 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;
+ }
+
+ static public final float min(float[] list) {
+ if (list.length == 0) {
+ throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
+ }
+ float min = list[0];
+ for (int i = 1; i < list.length; i++) {
+ if (list[i] < min) min = list[i];
+ }
+ return min;
+ }
+
+
+ /*
+ * Find the minimum value in an array.
+ * Throws an ArrayIndexOutOfBoundsException if the array is length 0.
+ * @param list the source array
+ * @return The minimum value
+ */
+ /*
+ static public final double min(double[] list) {
+ if (list.length == 0) {
+ throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
+ }
+ double min = list[0];
+ for (int i = 1; i < list.length; i++) {
+ if (list[i] < min) min = list[i];
+ }
+ return min;
+ }
+ */
+
+
+ static public final int constrain(int amt, int low, int high) {
+ return (amt < low) ? low : ((amt > high) ? high : amt);
+ }
+
+/**
+ * ( begin auto-generated from constrain.xml )
+ *
+ * Constrains a value to not exceed a maximum and minimum value.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param amt the value to constrain
+ * @param low minimum limit
+ * @param high maximum limit
+ * @see PApplet#max(float, float, float)
+ * @see PApplet#min(float, float, float)
+ */
+
+ static public final float constrain(float amt, float low, float high) {
+ return (amt < low) ? low : ((amt > high) ? high : amt);
+ }
+
+/**
+ * ( begin auto-generated from sin.xml )
+ *
+ * Calculates the sine of an angle. This function expects the values of the
+ * angle parameter to be provided in radians (values from 0 to
+ * 6.28). Values are returned in the range -1 to 1.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param angle an angle in radians
+ * @see PApplet#cos(float)
+ * @see PApplet#tan(float)
+ * @see PApplet#radians(float)
+ */
+ static public final float sin(float angle) {
+ return (float)Math.sin(angle);
+ }
+
+/**
+ * ( begin auto-generated from cos.xml )
+ *
+ * Calculates the cosine of an angle. This function expects the values of
+ * the angle parameter to be provided in radians (values from 0 to
+ * PI*2). Values are returned in the range -1 to 1.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param angle an angle in radians
+ * @see PApplet#sin(float)
+ * @see PApplet#tan(float)
+ * @see PApplet#radians(float)
+ */
+ static public final float cos(float angle) {
+ return (float)Math.cos(angle);
+ }
+
+/**
+ * ( begin auto-generated from tan.xml )
+ *
+ * Calculates the ratio of the sine and cosine of an angle. This function
+ * expects the values of the angle parameter to be provided in
+ * radians (values from 0 to PI*2). Values are returned in the range
+ * infinity to -infinity.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param angle an angle in radians
+ * @see PApplet#cos(float)
+ * @see PApplet#sin(float)
+ * @see PApplet#radians(float)
+ */
+ static public final float tan(float angle) {
+ return (float)Math.tan(angle);
+ }
+
+/**
+ * ( begin auto-generated from asin.xml )
+ *
+ * The inverse of sin(), returns the arc sine of a value. This
+ * function expects the values in the range of -1 to 1 and values are
+ * returned in the range -PI/2 to PI/2.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param value the value whose arc sine is to be returned
+ * @see PApplet#sin(float)
+ * @see PApplet#acos(float)
+ * @see PApplet#atan(float)
+ */
+ static public final float asin(float value) {
+ return (float)Math.asin(value);
+ }
+
+/**
+ * ( begin auto-generated from acos.xml )
+ *
+ * The inverse of cos(), returns the arc cosine of a value. This
+ * function expects the values in the range of -1 to 1 and values are
+ * returned in the range 0 to PI (3.1415927).
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param value the value whose arc cosine is to be returned
+ * @see PApplet#cos(float)
+ * @see PApplet#asin(float)
+ * @see PApplet#atan(float)
+ */
+ static public final float acos(float value) {
+ return (float)Math.acos(value);
+ }
+
+/**
+ * ( begin auto-generated from atan.xml )
+ *
+ * The inverse of tan(), returns the arc tangent of a value. This
+ * function expects the values in the range of -Infinity to Infinity
+ * (exclusive) and values are returned in the range -PI/2 to PI/2 .
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param value -Infinity to Infinity (exclusive)
+ * @see PApplet#tan(float)
+ * @see PApplet#asin(float)
+ * @see PApplet#acos(float)
+ */
+ static public final float atan(float value) {
+ return (float)Math.atan(value);
+ }
+
+/**
+ * ( begin auto-generated from atan2.xml )
+ *
+ * Calculates the angle (in radians) from a specified point to the
+ * coordinate origin as measured from the positive x-axis. Values are
+ * returned as a float in the range from PI to -PI.
+ * The atan2() function is most often used for orienting geometry to
+ * the position of the cursor. Note: The y-coordinate of the point is the
+ * first parameter and the x-coordinate is the second due the the structure
+ * of calculating the tangent.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param y y-coordinate of the point
+ * @param x x-coordinate of the point
+ * @see PApplet#tan(float)
+ */
+ static public final float atan2(float y, float x) {
+ return (float)Math.atan2(y, x);
+ }
+
+/**
+ * ( begin auto-generated from degrees.xml )
+ *
+ * Converts a radian measurement to its corresponding value in degrees.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. All trigonometric functions in Processing
+ * require their parameters to be specified in radians.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param radians radian value to convert to degrees
+ * @see PApplet#radians(float)
+ */
+ static public final float degrees(float radians) {
+ return radians * RAD_TO_DEG;
+ }
+
+/**
+ * ( begin auto-generated from radians.xml )
+ *
+ * Converts a degree measurement to its corresponding value in radians.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. All trigonometric functions in Processing
+ * require their parameters to be specified in radians.
+ *
+ * ( end auto-generated )
+ * @webref math:trigonometry
+ * @param degrees degree value to convert to radians
+ * @see PApplet#degrees(float)
+ */
+ static public final float radians(float degrees) {
+ return degrees * DEG_TO_RAD;
+ }
+
+/**
+ * ( begin auto-generated from ceil.xml )
+ *
+ * Calculates the closest int value that is greater than or equal to the
+ * value of the parameter. For example, ceil(9.03) returns the value 10.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n number to round up
+ * @see PApplet#floor(float)
+ * @see PApplet#round(float)
+ */
+ static public final int ceil(float n) {
+ return (int) Math.ceil(n);
+ }
+
+/**
+ * ( begin auto-generated from floor.xml )
+ *
+ * Calculates the closest int value that is less than or equal to the value
+ * of the parameter.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n number to round down
+ * @see PApplet#ceil(float)
+ * @see PApplet#round(float)
+ */
+ static public final int floor(float n) {
+ return (int) Math.floor(n);
+ }
+
+/**
+ * ( begin auto-generated from round.xml )
+ *
+ * Calculates the integer closest to the value parameter. For
+ * example, round(9.2) returns the value 9.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param n number to round
+ * @see PApplet#floor(float)
+ * @see PApplet#ceil(float)
+ */
+ static public final int round(float n) {
+ return Math.round(n);
+ }
+
+
+ static public final float mag(float a, float b) {
+ return (float)Math.sqrt(a*a + b*b);
+ }
+
+/**
+ * ( begin auto-generated from mag.xml )
+ *
+ * Calculates the magnitude (or length) of a vector. A vector is a
+ * direction in space commonly used in computer graphics and linear
+ * algebra. Because it has no "start" position, the magnitude of a vector
+ * can be thought of as the distance from coordinate (0,0) to its (x,y)
+ * value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)".
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param a first value
+ * @param b second value
+ * @param c third value
+ * @see PApplet#dist(float, float, float, float)
+ */
+ 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));
+ }
+
+/**
+ * ( begin auto-generated from dist.xml )
+ *
+ * Calculates the distance between two points.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param x1 x-coordinate of the first point
+ * @param y1 y-coordinate of the first point
+ * @param z1 z-coordinate of the first point
+ * @param x2 x-coordinate of the second point
+ * @param y2 y-coordinate of the second point
+ * @param z2 z-coordinate of the second point
+ */
+ 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));
+ }
+
+/**
+ * ( begin auto-generated from lerp.xml )
+ *
+ * Calculates a number between two numbers at a specific increment. The
+ * amt parameter is the amount to interpolate between the two values
+ * where 0.0 equal to the first point, 0.1 is very near the first point,
+ * 0.5 is half-way in between, etc. The lerp function is convenient for
+ * creating motion along a straight path and for drawing dotted lines.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param start first value
+ * @param stop second value
+ * @param amt float between 0.0 and 1.0
+ * @see PGraphics#curvePoint(float, float, float, float, float)
+ * @see PGraphics#bezierPoint(float, float, float, float, float)
+ * @see PVector#lerp(PVector, float)
+ * @see PGraphics#lerpColor(int, int, float)
+ */
+ static public final float lerp(float start, float stop, float amt) {
+ return start + (stop-start) * amt;
+ }
+
+ /**
+ * ( begin auto-generated from norm.xml )
+ *
+ * Normalizes a number from another range into a value between 0 and 1.
+ *
+ * Identical to map(value, low, high, 0, 1);
+ *
+ * Numbers outside the range are not clamped to 0 and 1, because
+ * out-of-range values are often intentional and useful.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param value the incoming value to be converted
+ * @param start lower bound of the value's current range
+ * @param stop upper bound of the value's current range
+ * @see PApplet#map(float, float, float, float, float)
+ * @see PApplet#lerp(float, float, float)
+ */
+ static public final float norm(float value, float start, float stop) {
+ return (value - start) / (stop - start);
+ }
+
+ /**
+ * ( begin auto-generated from map.xml )
+ *
+ * Re-maps a number from one range to another. In the example above,
+ * the number '25' is converted from a value in the range 0..100 into
+ * a value that ranges from the left edge (0) to the right edge (width)
+ * of the screen.
+ *
+ * Numbers outside the range are not clamped to 0 and 1, because
+ * out-of-range values are often intentional and useful.
+ *
+ * ( end auto-generated )
+ * @webref math:calculation
+ * @param value the incoming value to be converted
+ * @param start1 lower bound of the value's current range
+ * @param stop1 upper bound of the value's current range
+ * @param start2 lower bound of the value's target range
+ * @param stop2 upper bound of the value's target range
+ * @see PApplet#norm(float, float, float)
+ * @see PApplet#lerp(float, float, float)
+ */
+ static public final float map(float value,
+ float start1, float stop1,
+ float start2, float stop2) {
+ float outgoing =
+ start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
+ String badness = null;
+ if (outgoing != outgoing) {
+ badness = "NaN (not a number)";
+
+ } else if (outgoing == Float.NEGATIVE_INFINITY ||
+ outgoing == Float.POSITIVE_INFINITY) {
+ badness = "infinity";
+ }
+ if (badness != null) {
+ final String msg =
+ String.format("map(%s, %s, %s, %s, %s) called, which returns %s",
+ nf(value), nf(start1), nf(stop1),
+ nf(start2), nf(stop2), badness);
+ PGraphics.showWarning(msg);
+ }
+ return outgoing;
+ }
+
+
+ /*
+ static public final double map(double value,
+ double istart, double istop,
+ double ostart, double ostop) {
+ return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
+ }
+ */
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RANDOM NUMBERS
+
+
+ Random internalRandom;
+
+ /**
+ *
+ */
+ 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;
+ }
+
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ protected String[] loadImageFormats;
+
+ /**
+ * ( begin auto-generated from loadImage.xml )
+ *
+ * Loads an image into a variable of type PImage. Four types of
+ * images ( .gif, .jpg, .tga, .png) images may
+ * be loaded. To load correctly, images must be located in the data
+ * directory of the current sketch. In most cases, load all images in
+ * setup() to preload them at the start of the program. Loading
+ * images inside draw() will reduce the speed of a program.
+ * filename parameter can also be a URL to a file found
+ * online. For security reasons, a Processing sketch found online can only
+ * download files from the same server from which it came. Getting around
+ * this restriction requires a signed
+ * applet.
+ * extension parameter is used to determine the image type in
+ * cases where the image filename does not end with a proper extension.
+ * Specify the extension as the second parameter to loadImage(), as
+ * shown in the third example on this page.
+ * an image is not loaded successfully, the null value is
+ * returned and an error message will be printed to the console. The error
+ * message does not halt the program, however the null value may cause a
+ * NullPointerException if your code does not check whether the value
+ * returned from loadImage() is null.
+ * on the type of error, a PImage object may still be
+ * returned, but the width and height of the image will be set to -1. This
+ * happens if bad image data is returned or cannot be decoded properly.
+ * Sometimes this happens with image URLs that produce a 403 error or that
+ * redirect to a password prompt, because loadImage() will attempt
+ * to interpret the HTML as image data.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:loading_displaying
+ * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
+ * @see PImage
+ * @see PGraphics#image(PImage, float, float, float, float)
+ * @see PGraphics#imageMode(int)
+ * @see PGraphics#background(float, float, float, float)
+ */
+ public PImage loadImage(String filename) {
+// return loadImage(filename, null, null);
+ return loadImage(filename, null);
+ }
+
+// /**
+// * @param extension the type of image to load, for example "png", "gif", "jpg"
+// */
+// public PImage loadImage(String filename, String extension) {
+// return loadImage(filename, extension, null);
+// }
+
+// /**
+// * @nowebref
+// */
+// public PImage loadImage(String filename, Object params) {
+// return loadImage(filename, null, params);
+// }
+
+ /**
+ * @param extension type of image to load, for example "png", "gif", "jpg"
+ */
+ public PImage loadImage(String filename, String extension) { //, Object params) {
+
+ // await... has to run on the main thread, because P2D and P3D call GL functions
+ // If this runs on background, requestImage() already called await... on the main thread
+ if (g != null && !Thread.currentThread().getName().startsWith(ASYNC_IMAGE_LOADER_THREAD_PREFIX)) {
+ g.awaitAsyncSaveCompletion(filename);
+ }
+
+ if (extension == null) {
+ String lower = filename.toLowerCase();
+ int dot = filename.lastIndexOf('.');
+ if (dot == -1) {
+ extension = "unknown"; // no extension found
+
+ } else {
+ extension = lower.substring(dot + 1);
+
+ // check for, and strip any parameters on the url, i.e.
+ // filename.jpg?blah=blah&something=that
+ int question = extension.indexOf('?');
+ if (question != -1) {
+ extension = extension.substring(0, question);
+ }
+ }
+ }
+
+ // just in case. them users will try anything!
+ extension = extension.toLowerCase();
+
+ if (extension.equals("tga")) {
+ try {
+ PImage image = loadImageTGA(filename);
+// if (params != null) {
+// image.setParams(g, params);
+// }
+ return image;
+ } catch (IOException e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+ if (extension.equals("tif") || extension.equals("tiff")) {
+ byte bytes[] = loadBytes(filename);
+ PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes);
+// if (params != null) {
+// image.setParams(g, params);
+// }
+ return image;
+ }
+
+ // For jpeg, gif, and png, load them using createImage(),
+ // because the javax.imageio code was found to be much slower.
+ // http://dev.processing.org/bugs/show_bug.cgi?id=392
+ try {
+ if (extension.equals("jpg") || extension.equals("jpeg") ||
+ extension.equals("gif") || extension.equals("png") ||
+ extension.equals("unknown")) {
+ byte bytes[] = loadBytes(filename);
+ if (bytes == null) {
+ return null;
+ } else {
+ //Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
+ Image awtImage = new ImageIcon(bytes).getImage();
+
+ if (awtImage instanceof BufferedImage) {
+ BufferedImage buffImage = (BufferedImage) awtImage;
+ int space = buffImage.getColorModel().getColorSpace().getType();
+ if (space == ColorSpace.TYPE_CMYK) {
+ System.err.println(filename + " is a CMYK image, " +
+ "only RGB images are supported.");
+ return null;
+ /*
+ // wishful thinking, appears to not be supported
+ // https://community.oracle.com/thread/1272045?start=0&tstart=0
+ BufferedImage destImage =
+ new BufferedImage(buffImage.getWidth(),
+ buffImage.getHeight(),
+ BufferedImage.TYPE_3BYTE_BGR);
+ ColorConvertOp op = new ColorConvertOp(null);
+ op.filter(buffImage, destImage);
+ image = new PImage(destImage);
+ */
+ }
+ }
+
+ PImage image = new PImage(awtImage);
+ if (image.width == -1) {
+ System.err.println("The file " + filename +
+ " contains bad image data, or may not be an image.");
+ }
+
+ // if it's a .gif image, test to see if it has transparency
+ if (extension.equals("gif") || extension.equals("png") ||
+ extension.equals("unknown")) {
+ image.checkAlpha();
+ }
+
+// if (params != null) {
+// image.setParams(g, params);
+// }
+ image.parent = this;
+ return image;
+ }
+ }
+ } catch (Exception e) {
+ // show error, but move on to the stuff below, see if it'll work
+ printStackTrace(e);
+ }
+
+ if (loadImageFormats == null) {
+ loadImageFormats = ImageIO.getReaderFormatNames();
+ }
+ if (loadImageFormats != null) {
+ for (int i = 0; i < loadImageFormats.length; i++) {
+ if (extension.equals(loadImageFormats[i])) {
+ return loadImageIO(filename);
+// PImage image = loadImageIO(filename);
+// if (params != null) {
+// image.setParams(g, params);
+// }
+// return image;
+ }
+ }
+ }
+
+ // failed, could not load image after all those attempts
+ System.err.println("Could not find a method to load " + filename);
+ return null;
+ }
+
+
+ public PImage requestImage(String filename) {
+// return requestImage(filename, null, null);
+ return requestImage(filename, null);
+ }
+
+
+ /**
+ * ( begin auto-generated from requestImage.xml )
+ *
+ * This function load images on a separate thread so that your sketch does
+ * not freeze while images load during setup(). While the image is
+ * loading, its width and height will be 0. If an error occurs while
+ * loading the image, its width and height will be set to -1. You'll know
+ * when the image has loaded properly because its width and height will be
+ * greater than 0. Asynchronous image loading (particularly when
+ * downloading from a server) can dramatically improve performance.
+ * extension parameter is used to determine the image type in
+ * cases where the image filename does not end with a proper extension.
+ * Specify the extension as the second parameter to requestImage().
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:loading_displaying
+ * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
+ * @param extension the type of image to load, for example "png", "gif", "jpg"
+ * @see PImage
+ * @see PApplet#loadImage(String, String)
+ */
+ public PImage requestImage(String filename, String extension) {
+ // Make sure saving to this file completes before trying to load it
+ // Has to be called on main thread, because P2D and P3D need GL functions
+ if (g != null) {
+ g.awaitAsyncSaveCompletion(filename);
+ }
+ PImage vessel = createImage(0, 0, ARGB);
+ AsyncImageLoader ail =
+ new AsyncImageLoader(filename, extension, vessel);
+ ail.start();
+ return vessel;
+ }
+
+
+// /**
+// * @nowebref
+// */
+// public PImage requestImage(String filename, String extension, Object params) {
+// PImage vessel = createImage(0, 0, ARGB, params);
+// AsyncImageLoader ail =
+// new AsyncImageLoader(filename, extension, vessel);
+// ail.start();
+// return vessel;
+// }
+
+
+ /**
+ * By trial and error, four image loading threads seem to work best when
+ * loading images from online. This is consistent with the number of open
+ * connections that web browsers will maintain. The variable is made public
+ * (however no accessor has been added since it's esoteric) if you really
+ * want to have control over the value used. For instance, when loading local
+ * files, it might be better to only have a single thread (or two) loading
+ * images so that you're disk isn't simply jumping around.
+ */
+ public int requestImageMax = 4;
+ volatile int requestImageCount;
+
+ private static final String ASYNC_IMAGE_LOADER_THREAD_PREFIX = "ASYNC_IMAGE_LOADER";
+
+ class AsyncImageLoader extends Thread {
+ String filename;
+ String extension;
+ PImage vessel;
+
+ public AsyncImageLoader(String filename, String extension, PImage vessel) {
+ // Give these threads distinct name so we can check whether we are loading
+ // on the main/background thread; for now they are all named the same
+ super(ASYNC_IMAGE_LOADER_THREAD_PREFIX);
+ this.filename = filename;
+ this.extension = extension;
+ this.vessel = vessel;
+ }
+
+ @Override
+ public void run() {
+ while (requestImageCount == requestImageMax) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) { }
+ }
+ requestImageCount++;
+
+ PImage actual = loadImage(filename, extension);
+
+ // An error message should have already printed
+ if (actual == null) {
+ vessel.width = -1;
+ vessel.height = -1;
+
+ } else {
+ vessel.width = actual.width;
+ vessel.height = actual.height;
+ vessel.format = actual.format;
+ vessel.pixels = actual.pixels;
+
+ vessel.pixelWidth = actual.width;
+ vessel.pixelHeight = actual.height;
+ vessel.pixelDensity = 1;
+ }
+ requestImageCount--;
+ }
+ }
+
+
+ // done internally by ImageIcon
+// /**
+// * Load an AWT image synchronously by setting up a MediaTracker for
+// * a single image, and blocking until it has loaded.
+// */
+// protected PImage loadImageMT(Image awtImage) {
+// MediaTracker tracker = new MediaTracker(this);
+// tracker.addImage(awtImage, 0);
+// try {
+// tracker.waitForAll();
+// } catch (InterruptedException e) {
+// //e.printStackTrace(); // non-fatal, right?
+// }
+//
+// PImage image = new PImage(awtImage);
+// image.parent = this;
+// return image;
+// }
+
+
+ /**
+ * Use Java 1.4 ImageIO methods to load an image.
+ */
+ protected PImage loadImageIO(String filename) {
+ InputStream stream = createInput(filename);
+ if (stream == null) {
+ System.err.println("The image " + filename + " could not be found.");
+ return null;
+ }
+
+ try {
+ BufferedImage bi = ImageIO.read(stream);
+ PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
+ outgoing.parent = this;
+
+ bi.getRGB(0, 0, outgoing.width, outgoing.height,
+ outgoing.pixels, 0, outgoing.width);
+
+ // check the alpha for this image
+ // was gonna call getType() on the image to see if RGB or ARGB,
+ // but it's not actually useful, since gif images will come through
+ // as TYPE_BYTE_INDEXED, which means it'll still have to check for
+ // the transparency. also, would have to iterate through all the other
+ // types and guess whether alpha was in there, so.. just gonna stick
+ // with the old method.
+ outgoing.checkAlpha();
+
+ stream.close();
+ // return the image
+ return outgoing;
+
+ } catch (Exception e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+
+ /**
+ * Targa image loader for RLE-compressed TGA files.
+ *
+ * Rewritten for 0115 to read/write RLE-encoded targa images.
+ * For 0125, non-RLE encoded images are now supported, along with
+ * images whose y-order is reversed (which is standard for TGA files).
+ *
+ * A version of this function is in MovieMaker.java. Any fixes here
+ * should be applied over in MovieMaker as well.
+ *
+ * Known issue with RLE encoding and odd behavior in some apps:
+ * https://github.com/processing/processing/issues/2096
+ * Please help!
+ */
+ protected PImage loadImageTGA(String filename) throws IOException {
+ InputStream is = createInput(filename);
+ if (is == null) return null;
+
+ byte header[] = new byte[18];
+ int offset = 0;
+ do {
+ int count = is.read(header, offset, header.length - offset);
+ if (count == -1) return null;
+ offset += count;
+ } while (offset < 18);
+
+ /*
+ header[2] image type code
+ 2 (0x02) - Uncompressed, RGB images.
+ 3 (0x03) - Uncompressed, black and white images.
+ 10 (0x0A) - Run-length encoded RGB images.
+ 11 (0x0B) - Compressed, black and white images. (grayscale?)
+
+ header[16] is the bit depth (8, 24, 32)
+
+ header[17] image descriptor (packed bits)
+ 0x20 is 32 = origin upper-left
+ 0x28 is 32 + 8 = origin upper-left + 32 bits
+
+ 7 6 5 4 3 2 1 0
+ 128 64 32 16 8 4 2 1
+ */
+
+ int format = 0;
+
+ if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
+ (header[16] == 8) && // 8 bits
+ ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
+ format = ALPHA;
+
+ } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
+ (header[16] == 24) && // 24 bits
+ ((header[17] == 0x20) || (header[17] == 0))) { // origin
+ format = RGB;
+
+ } else if (((header[2] == 2) || (header[2] == 10)) &&
+ (header[16] == 32) &&
+ ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
+ format = ARGB;
+ }
+
+ if (format == 0) {
+ System.err.println("Unknown .tga file format for " + filename);
+ //" (" + header[2] + " " +
+ //(header[16] & 0xff) + " " +
+ //hex(header[17], 2) + ")");
+ return null;
+ }
+
+ int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
+ int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
+ PImage outgoing = createImage(w, h, format);
+
+ // where "reversed" means upper-left corner (normal for most of
+ // the modernized world, but "reversed" for the tga spec)
+ //boolean reversed = (header[17] & 0x20) != 0;
+ // https://github.com/processing/processing/issues/1682
+ boolean reversed = (header[17] & 0x20) == 0;
+
+ if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
+ if (reversed) {
+ int index = (h-1) * w;
+ switch (format) {
+ case ALPHA:
+ for (int y = h-1; y >= 0; y--) {
+ for (int x = 0; x < w; x++) {
+ outgoing.pixels[index + x] = is.read();
+ }
+ index -= w;
+ }
+ break;
+ case RGB:
+ for (int y = h-1; y >= 0; y--) {
+ for (int x = 0; x < w; x++) {
+ outgoing.pixels[index + x] =
+ is.read() | (is.read() << 8) | (is.read() << 16) |
+ 0xff000000;
+ }
+ index -= w;
+ }
+ break;
+ case ARGB:
+ for (int y = h-1; y >= 0; y--) {
+ for (int x = 0; x < w; x++) {
+ outgoing.pixels[index + x] =
+ is.read() | (is.read() << 8) | (is.read() << 16) |
+ (is.read() << 24);
+ }
+ index -= w;
+ }
+ }
+ } else { // not reversed
+ int count = w * h;
+ switch (format) {
+ case ALPHA:
+ for (int i = 0; i < count; i++) {
+ outgoing.pixels[i] = is.read();
+ }
+ break;
+ case RGB:
+ for (int i = 0; i < count; i++) {
+ outgoing.pixels[i] =
+ is.read() | (is.read() << 8) | (is.read() << 16) |
+ 0xff000000;
+ }
+ break;
+ case ARGB:
+ for (int i = 0; i < count; i++) {
+ outgoing.pixels[i] =
+ is.read() | (is.read() << 8) | (is.read() << 16) |
+ (is.read() << 24);
+ }
+ break;
+ }
+ }
+
+ } else { // header[2] is 10 or 11
+ int index = 0;
+ int px[] = outgoing.pixels;
+
+ while (index < px.length) {
+ int num = is.read();
+ boolean isRLE = (num & 0x80) != 0;
+ if (isRLE) {
+ num -= 127; // (num & 0x7F) + 1
+ int pixel = 0;
+ switch (format) {
+ case ALPHA:
+ pixel = is.read();
+ break;
+ case RGB:
+ pixel = 0xFF000000 |
+ is.read() | (is.read() << 8) | (is.read() << 16);
+ //(is.read() << 16) | (is.read() << 8) | is.read();
+ break;
+ case ARGB:
+ pixel = is.read() |
+ (is.read() << 8) | (is.read() << 16) | (is.read() << 24);
+ break;
+ }
+ for (int i = 0; i < num; i++) {
+ px[index++] = pixel;
+ if (index == px.length) break;
+ }
+ } else { // write up to 127 bytes as uncompressed
+ num += 1;
+ switch (format) {
+ case ALPHA:
+ for (int i = 0; i < num; i++) {
+ px[index++] = is.read();
+ }
+ break;
+ case RGB:
+ for (int i = 0; i < num; i++) {
+ px[index++] = 0xFF000000 |
+ is.read() | (is.read() << 8) | (is.read() << 16);
+ //(is.read() << 16) | (is.read() << 8) | is.read();
+ }
+ break;
+ case ARGB:
+ for (int i = 0; i < num; i++) {
+ px[index++] = is.read() | //(is.read() << 24) |
+ (is.read() << 8) | (is.read() << 16) | (is.read() << 24);
+ //(is.read() << 16) | (is.read() << 8) | is.read();
+ }
+ break;
+ }
+ }
+ }
+
+ if (!reversed) {
+ int[] temp = new int[w];
+ for (int y = 0; y < h/2; y++) {
+ int z = (h-1) - y;
+ System.arraycopy(px, y*w, temp, 0, w);
+ System.arraycopy(px, z*w, px, y*w, w);
+ System.arraycopy(temp, 0, px, z*w, w);
+ }
+ }
+ }
+ is.close();
+ return outgoing;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // DATA I/O
+
+
+// /**
+// * @webref input:files
+// * @brief Creates a new XML object
+// * @param name the name to be given to the root element of the new XML object
+// * @return an XML object, or null
+// * @see XML
+// * @see PApplet#loadXML(String)
+// * @see PApplet#parseXML(String)
+// * @see PApplet#saveXML(XML, String)
+// */
+// public XML createXML(String name) {
+// try {
+// return new XML(name);
+// } catch (Exception e) {
+// e.printStackTrace();
+// return null;
+// }
+// }
+
+
+ /**
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL.
+ * @see XML
+ * @see PApplet#parseXML(String)
+ * @see PApplet#saveXML(XML, 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
+ /**
+ * @nowebref
+ */
+ public XML loadXML(String filename, String options) {
+ try {
+ return new XML(createReader(filename), options);
+
+ // can't use catch-all exception, since it might catch the
+ // RuntimeException about the incorrect case sensitivity
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+
+ } catch (ParserConfigurationException e) {
+ throw new RuntimeException(e);
+
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ /**
+ * @webref input:files
+ * @brief Converts String content to an XML object
+ * @param xmlString the content to be parsed as XML
+ * @return an XML object, or null
+ * @see XML
+ * @see PApplet#loadXML(String)
+ * @see PApplet#saveXML(XML, String)
+ */
+ 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) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ /**
+ * @webref output:files
+ * @param xml the XML object to save to disk
+ * @param filename name of the file to write to
+ * @see XML
+ * @see PApplet#loadXML(String)
+ * @see PApplet#parseXML(String)
+ */
+ public boolean saveXML(XML xml, String filename) {
+ return saveXML(xml, filename, null);
+ }
+
+ /**
+ * @nowebref
+ */
+ 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) {
+ return new JSONObject(createReader(filename));
+ }
+
+ /**
+ * @nowebref
+ */
+ static public JSONObject loadJSONObject(File file) {
+ return new JSONObject(createReader(file));
+ }
+
+
+ /**
+ * @webref output:files
+ * @param json the JSONObject to save
+ * @param filename the name of the file to save to
+ * @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);
+ }
+
+ /**
+ * @param options "compact" and "indent=N", replace N with the number of spaces
+ */
+ 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) {
+ return new JSONArray(createReader(filename));
+ }
+
+
+ static public JSONArray loadJSONArray(File file) {
+ return new JSONArray(createReader(file));
+ }
+
+
+ /**
+ * @webref output:files
+ * @param json the JSONArray to save
+ * @param filename the name of the file to save to
+ * @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);
+ }
+
+ /**
+ * @param options "compact" and "indent=N", replace N with the number of spaces
+ */
+ public boolean saveJSONArray(JSONArray json, String filename, String options) {
+ return json.save(saveFile(filename), options);
+ }
+
+
+
+// /**
+// * @webref input:files
+// * @see Table
+// * @see PApplet#loadTable(String)
+// * @see PApplet#saveTable(Table, String)
+// */
+// public Table createTable() {
+// return new Table();
+// }
+
+
+ /**
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL.
+ * @see Table
+ * @see PApplet#saveTable(Table, String)
+ * @see PApplet#loadBytes(String)
+ * @see PApplet#loadStrings(String)
+ * @see PApplet#loadXML(String)
+ */
+ public Table loadTable(String filename) {
+ return loadTable(filename, null);
+ }
+
+
+ /**
+ * Options may contain "header", "tsv", "csv", or "bin" separated by commas.
+ *
+ * Another option is "dictionary=filename.tsv", which allows users to
+ * specify a "dictionary" file that contains a mapping of the column titles
+ * and the data types used in the table file. This can be far more efficient
+ * (in terms of speed and memory usage) for loading and parsing tables. The
+ * dictionary file can only be tab separated values (.tsv) and its extension
+ * will be ignored. This option was added in Processing 2.0.2.
+ *
+ * @param options may contain "header", "tsv", "csv", or "bin" separated by commas
+ */
+ public Table loadTable(String filename, String options) {
+ try {
+ String optionStr = Table.extensionOptions(true, filename, options);
+ String[] optionList = trim(split(optionStr, ','));
+
+ Table dictionary = null;
+ for (String opt : optionList) {
+ if (opt.startsWith("dictionary=")) {
+ dictionary = loadTable(opt.substring(opt.indexOf('=') + 1), "tsv");
+ return dictionary.typedParse(createInput(filename), optionStr);
+ }
+ }
+ InputStream input = createInput(filename);
+ if (input == null) {
+ System.err.println(filename + " does not exist or could not be read");
+ return null;
+ }
+ return new Table(input, optionStr);
+
+ } catch (IOException e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+
+
+ /**
+ * @webref output:files
+ * @param table the Table object to save to a file
+ * @param filename the filename to which the Table should be saved
+ * @see Table
+ * @see PApplet#loadTable(String)
+ */
+ public boolean saveTable(Table table, String filename) {
+ return saveTable(table, filename, null);
+ }
+
+
+ /**
+ * @param options can be one of "tsv", "csv", "bin", or "html"
+ */
+ public boolean saveTable(Table table, String filename, String options) {
+// String ext = checkExtension(filename);
+// if (ext != null) {
+// if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin") || ext.equals("html")) {
+// if (options == null) {
+// options = ext;
+// } else {
+// options = ext + "," + options;
+// }
+// }
+// }
+
+ try {
+ // Figure out location and make sure the target path exists
+ File outputFile = saveFile(filename);
+ // Open a stream and take care of .gz if necessary
+ return table.save(outputFile, options);
+
+ } catch (IOException e) {
+ printStackTrace(e);
+ return false;
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FONT I/O
+
+ /**
+ * ( begin auto-generated from loadFont.xml )
+ *
+ * Loads a font into a variable of type PFont. To load correctly,
+ * fonts must be located in the data directory of the current sketch. To
+ * create a font to use with Processing, select "Create Font..." from the
+ * Tools menu. This will create a font in the format Processing requires
+ * and also adds it to the current sketch's data directory.
+ *
+ * Like loadImage() and other functions that load data, the
+ * loadFont() function should not be used inside draw(),
+ * because it will slow down the sketch considerably, as the font will be
+ * re-loaded from the disk (or network) on each frame.
+ *
+ * For most renderers, Processing displays fonts using the .vlw font
+ * format, which uses images for each letter, rather than defining them
+ * through vector data. When hint(ENABLE_NATIVE_FONTS) is used with
+ * the JAVA2D renderer, the native version of a font will be used if it is
+ * installed on the user's machine.
+ *
+ * Using createFont() (instead of loadFont) enables vector data to
+ * be used with the JAVA2D (default) renderer setting. This can be helpful
+ * when many font sizes are needed, or when using any renderer based on
+ * JAVA2D, such as the PDF library.
+ *
+ * ( end auto-generated )
+ * @webref typography:loading_displaying
+ * @param filename name of the font to load
+ * @see PFont
+ * @see PGraphics#textFont(PFont, float)
+ * @see PApplet#createFont(String, float, boolean, char[])
+ */
+ public PFont loadFont(String filename) {
+ if (!filename.toLowerCase().endsWith(".vlw")) {
+ throw new IllegalArgumentException("loadFont() is for .vlw files, try createFont()");
+ }
+ try {
+ InputStream input = createInput(filename);
+ return new PFont(input);
+
+ } catch (Exception e) {
+ die("Could not load font " + filename + ". " +
+ "Make sure that the font has been copied " +
+ "to the data folder of your sketch.", e);
+ }
+ return null;
+ }
+
+
+ /**
+ * Used by PGraphics to remove the requirement for loading a font!
+ */
+ protected PFont createDefaultFont(float size) {
+// Font f = new Font("SansSerif", Font.PLAIN, 12);
+// println("n: " + f.getName());
+// println("fn: " + f.getFontName());
+// println("ps: " + f.getPSName());
+ return createFont("Lucida Sans", 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);
+ }
+
+
+ /**
+ * ( begin auto-generated from createFont.xml )
+ *
+ * Dynamically converts a font to the format used by Processing from either
+ * a font name that's installed on the computer, or from a .ttf or .otf
+ * file inside the sketches "data" folder. This function is an advanced
+ * feature for precise control. On most occasions you should create fonts
+ * through selecting "Create Font..." from the Tools menu.
+ *
+ * Use the PFont.list() method to first determine the names for the
+ * fonts recognized by the computer and are compatible with this function.
+ * Because of limitations in Java, not all fonts can be used and some might
+ * work with one operating system and not others. When sharing a sketch
+ * with other people or posting it on the web, you may need to include a
+ * .ttf or .otf version of your font in the data directory of the sketch
+ * because other people might not have the font installed on their
+ * computer. Only fonts that can legally be distributed should be included
+ * with a sketch.
+ *
+ * The size parameter states the font size you want to generate. The
+ * smooth parameter specifies if the font should be antialiased or
+ * not, and the charset parameter is an array of chars that
+ * specifies the characters to generate.
+ *
+ * This function creates a bitmapped version of a font in the same manner
+ * as the Create Font tool. It loads a font by name, and converts it to a
+ * series of images based on the size of the font. When possible, the
+ * text() function will use a native font rather than the bitmapped
+ * version created behind the scenes with createFont(). For
+ * instance, when using P2D, the actual native version of the font will be
+ * employed by the sketch, improving drawing quality and performance. With
+ * the P3D renderer, the bitmapped version will be used. While this can
+ * drastically improve speed and appearance, results are poor when
+ * exporting if the sketch does not include the .otf or .ttf file, and the
+ * requested font is not available on the machine running the sketch.
+ *
+ * ( end auto-generated )
+ * @webref typography:loading_displaying
+ * @param name name of the font to load
+ * @param size point size of the font
+ * @param smooth true for an antialiased font, false for aliased
+ * @param charset array containing characters to be generated
+ * @see PFont
+ * @see PGraphics#textFont(PFont, float)
+ * @see PGraphics#text(String, float, float, float, float)
+ * @see PApplet#loadFont(String)
+ */
+ public PFont createFont(String name, float size,
+ boolean smooth, char[] charset) {
+ if (g == null) {
+ throw new RuntimeException("createFont() can only be used inside setup() or after setup() has been called.");
+ }
+ return g.createFont(name, size, smooth, charset);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILE/FOLDER SELECTION
+
+
+ /*
+ private Frame selectFrame;
+
+ private Frame selectFrame() {
+ if (frame != null) {
+ selectFrame = frame;
+
+ } else if (selectFrame == null) {
+ Component comp = getParent();
+ while (comp != null) {
+ if (comp instanceof Frame) {
+ selectFrame = (Frame) comp;
+ break;
+ }
+ comp = comp.getParent();
+ }
+ // Who you callin' a hack?
+ if (selectFrame == null) {
+ selectFrame = new Frame();
+ }
+ }
+ return selectFrame;
+ }
+ */
+
+
+ static private boolean lookAndFeelCheck;
+
+ /**
+ * Initialize the Look & Feel if it hasn't been already.
+ * Call this before using any Swing-related code in PApplet methods.
+ */
+ static private void checkLookAndFeel() {
+ if (!lookAndFeelCheck) {
+ if (platform == WINDOWS) {
+ // Windows is defaulting to Metal or something else awful.
+ // Which also is not scaled properly with HiDPI interfaces.
+ try {
+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+ } catch (Exception e) { }
+ }
+ lookAndFeelCheck = true;
+ }
+ }
+
+ /**
+ * Open a platform-specific file chooser dialog to select a file for input.
+ * After the selection is made, the selected File will be passed to the
+ * 'callback' function. If the dialog is closed or canceled, null will be
+ * sent to the function, so that the program is not waiting for additional
+ * input. The callback is necessary because of how threading works.
+ *
+ *
+ * void setup() {
+ * selectInput("Select a file to process:", "fileSelected");
+ * }
+ *
+ * void fileSelected(File selection) {
+ * if (selection == null) {
+ * println("Window was closed or the user hit cancel.");
+ * } else {
+ * println("User selected " + fileSeleted.getAbsolutePath());
+ * }
+ * }
+ *
+ *
+ * For advanced users, the method must be 'public', which is true for all
+ * methods inside a sketch when run from the PDE, but must explicitly be
+ * set when using Eclipse or other development environments.
+ *
+ * @webref input:files
+ * @param prompt message to the user
+ * @param callback name of the method to be called when the selection is made
+ */
+ public void selectInput(String prompt, String callback) {
+ selectInput(prompt, callback, null);
+ }
+
+
+ public void selectInput(String prompt, String callback, File file) {
+ selectInput(prompt, callback, file, this);
+ }
+
+
+ public void selectInput(String prompt, String callback,
+ File file, Object callbackObject) {
+ selectInput(prompt, callback, file, callbackObject, null, this); //selectFrame());
+ }
+
+
+ static public void selectInput(String prompt, String callbackMethod,
+ File file, Object callbackObject, Frame parent,
+ PApplet sketch) {
+ selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD, sketch);
+ }
+
+
+ static public void selectInput(String prompt, String callbackMethod,
+ File file, Object callbackObject, Frame parent) {
+ selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD, null);
+ }
+
+
+ /**
+ * See selectInput() for details.
+ *
+ * @webref output:files
+ * @param prompt message to the user
+ * @param callback name of the method to be called when the selection is made
+ */
+ public void selectOutput(String prompt, String callback) {
+ selectOutput(prompt, callback, null);
+ }
+
+
+ public void selectOutput(String prompt, String callback, File file) {
+ selectOutput(prompt, callback, file, this);
+ }
+
+
+ public void selectOutput(String prompt, String callback,
+ File file, Object callbackObject) {
+ selectOutput(prompt, callback, file, callbackObject, null, this); //selectFrame());
+ }
+
+
+ static public void selectOutput(String prompt, String callbackMethod,
+ File file, Object callbackObject, Frame parent) {
+ selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE, null);
+ }
+
+
+ static public void selectOutput(String prompt, String callbackMethod,
+ File file, Object callbackObject, Frame parent,
+ PApplet sketch) {
+ selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE, sketch);
+ }
+
+
+ // Will remove the 'sketch' parameter once we get an upstream JOGL fix
+ // https://github.com/processing/processing/issues/3831
+ static protected void selectImpl(final String prompt,
+ final String callbackMethod,
+ final File defaultSelection,
+ final Object callbackObject,
+ final Frame parentFrame,
+ final int mode,
+ final PApplet sketch) {
+ EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ File selectedFile = null;
+
+ boolean hide = (sketch != null) &&
+ (sketch.g instanceof PGraphicsOpenGL) && (platform == WINDOWS);
+ if (hide) sketch.surface.setVisible(false);
+
+ if (useNativeSelect) {
+ FileDialog dialog = new FileDialog(parentFrame, prompt, mode);
+ if (defaultSelection != null) {
+ dialog.setDirectory(defaultSelection.getParent());
+ dialog.setFile(defaultSelection.getName());
+ }
+
+ dialog.setVisible(true);
+ String directory = dialog.getDirectory();
+ String filename = dialog.getFile();
+ if (filename != null) {
+ selectedFile = new File(directory, filename);
+ }
+
+ } else {
+ JFileChooser chooser = new JFileChooser();
+ chooser.setDialogTitle(prompt);
+ if (defaultSelection != null) {
+ chooser.setSelectedFile(defaultSelection);
+ }
+
+ int result = -1;
+ if (mode == FileDialog.SAVE) {
+ result = chooser.showSaveDialog(parentFrame);
+ } else if (mode == FileDialog.LOAD) {
+ result = chooser.showOpenDialog(parentFrame);
+ }
+ if (result == JFileChooser.APPROVE_OPTION) {
+ selectedFile = chooser.getSelectedFile();
+ }
+ }
+
+ if (hide) sketch.surface.setVisible(true);
+ selectCallback(selectedFile, callbackMethod, callbackObject);
+ }
+ });
+ }
+
+
+ /**
+ * See selectInput() for details.
+ *
+ * @webref input:files
+ * @param prompt message to the user
+ * @param callback name of the method to be called when the selection is made
+ */
+ public void selectFolder(String prompt, String callback) {
+ selectFolder(prompt, callback, null);
+ }
+
+
+ public void selectFolder(String prompt, String callback, File file) {
+ selectFolder(prompt, callback, file, this);
+ }
+
+
+ public void selectFolder(String prompt, String callback,
+ File file, Object callbackObject) {
+ selectFolder(prompt, callback, file, callbackObject, null, this); //selectFrame());
+ }
+
+
+ static public void selectFolder(final String prompt,
+ final String callbackMethod,
+ final File defaultSelection,
+ final Object callbackObject,
+ final Frame parentFrame) {
+ selectFolder(prompt, callbackMethod, defaultSelection, callbackObject, parentFrame, null);
+ }
+
+
+ // Will remove the 'sketch' parameter once we get an upstream JOGL fix
+ // https://github.com/processing/processing/issues/3831
+ static public void selectFolder(final String prompt,
+ final String callbackMethod,
+ final File defaultSelection,
+ final Object callbackObject,
+ final Frame parentFrame,
+ final PApplet sketch) {
+ EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ File selectedFile = null;
+
+ boolean hide = (sketch != null) &&
+ (sketch.g instanceof PGraphicsOpenGL) && (platform == WINDOWS);
+ if (hide) sketch.surface.setVisible(false);
+
+ if (platform == MACOSX && useNativeSelect != false) {
+ FileDialog fileDialog =
+ new FileDialog(parentFrame, prompt, FileDialog.LOAD);
+ if (defaultSelection != null) {
+ fileDialog.setDirectory(defaultSelection.getAbsolutePath());
+ }
+ System.setProperty("apple.awt.fileDialogForDirectories", "true");
+ fileDialog.setVisible(true);
+ System.setProperty("apple.awt.fileDialogForDirectories", "false");
+ String filename = fileDialog.getFile();
+ if (filename != null) {
+ selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
+ }
+ } else {
+ checkLookAndFeel();
+ JFileChooser fileChooser = new JFileChooser();
+ fileChooser.setDialogTitle(prompt);
+ fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ if (defaultSelection != null) {
+ fileChooser.setCurrentDirectory(defaultSelection);
+ }
+
+ int result = fileChooser.showOpenDialog(parentFrame);
+ if (result == JFileChooser.APPROVE_OPTION) {
+ selectedFile = fileChooser.getSelectedFile();
+ }
+ }
+
+ if (hide) sketch.surface.setVisible(true);
+ selectCallback(selectedFile, callbackMethod, callbackObject);
+ }
+ });
+ }
+
+
+ static private void selectCallback(File selectedFile,
+ String callbackMethod,
+ Object callbackObject) {
+ try {
+ Class> callbackClass = callbackObject.getClass();
+ Method selectMethod =
+ callbackClass.getMethod(callbackMethod, new Class[] { File.class });
+ selectMethod.invoke(callbackObject, new Object[] { selectedFile });
+
+ } catch (IllegalAccessException iae) {
+ System.err.println(callbackMethod + "() must be public");
+
+ } catch (InvocationTargetException ite) {
+ ite.printStackTrace();
+
+ } catch (NoSuchMethodException nsme) {
+ System.err.println(callbackMethod + "() could not be found");
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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
+
+
+ /**
+ * ( begin auto-generated from createReader.xml )
+ *
+ * Creates a BufferedReader object that can be used to read files
+ * line-by-line as individual String objects. This is the complement
+ * to the createWriter() function.
+ *
+ * Starting with Processing release 0134, all files loaded and saved by the
+ * Processing API use UTF-8 encoding. In previous releases, the default
+ * encoding for your platform was used, which causes problems when files
+ * are moved to other platforms.
+ *
+ * ( end auto-generated )
+ * @webref input:files
+ * @param filename name of the file to be opened
+ * @see BufferedReader
+ * @see PApplet#createWriter(String)
+ * @see PrintWriter
+ */
+ public BufferedReader createReader(String filename) {
+ InputStream is = createInput(filename);
+ if (is == null) {
+ 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;
+ }
+ return createReader(is);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ 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 (IOException e) {
+ // Re-wrap rather than forcing novices to learn about exceptions
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ /**
+ * @nowebref
+ * 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, StandardCharsets.UTF_8);
+
+ 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;
+ }
+
+
+ /**
+ * ( begin auto-generated from createWriter.xml )
+ *
+ * Creates a new file in the sketch folder, and a PrintWriter object
+ * to write to it. For the file to be made correctly, it should be flushed
+ * and must be closed with its flush() and close() methods
+ * (see above example).
+ *
+ * Starting with Processing release 0134, all files loaded and saved by the
+ * Processing API use UTF-8 encoding. In previous releases, the default
+ * encoding for your platform was used, which causes problems when files
+ * are moved to other platforms.
+ *
+ * ( end auto-generated )
+ *
+ * @webref output:files
+ * @param filename name of the file to be created
+ * @see PrintWriter
+ * @see PApplet#createReader
+ * @see BufferedReader
+ */
+ public PrintWriter createWriter(String filename) {
+ return createWriter(saveFile(filename));
+ }
+
+
+ /**
+ * @nowebref
+ * 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) {
+ if (file == null) {
+ throw new RuntimeException("File passed to createWriter() was null");
+ }
+ try {
+ createPath(file); // make sure in-between folders exist
+ OutputStream output = new FileOutputStream(file);
+ if (file.getName().toLowerCase().endsWith(".gz")) {
+ output = new GZIPOutputStream(output);
+ }
+ return createWriter(output);
+
+ } catch (Exception e) {
+ throw new RuntimeException("Couldn't create a writer for " +
+ file.getAbsolutePath(), e);
+ }
+ }
+
+ /**
+ * @nowebref
+ * 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, StandardCharsets.UTF_8);
+ return new PrintWriter(osw);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILE INPUT
+
+
+ /**
+ * ( begin auto-generated from createInput.xml )
+ *
+ * This is a function for advanced programmers to open a Java InputStream.
+ * It's useful if you want to use the facilities provided by PApplet to
+ * easily open files from the data folder or from a URL, but want an
+ * InputStream object so that you can use other parts of Java to take more
+ * control of how the stream is read.
+ *
+ * The filename passed in can be:
+ * - A URL, for instance openStream("http://processing.org/")
+ * - A file in the sketch's data folder
+ * - The full path to a file to be opened locally (when running as an
+ * application)
+ *
+ * If the requested item doesn't exist, null is returned. If not online,
+ * this will also check to see if the user is asking for a file whose name
+ * isn't properly capitalized. If capitalization is different, an error
+ * will be printed to the console. This helps prevent issues that appear
+ * when a sketch is exported to the web, where case sensitivity matters, as
+ * opposed to running from inside the Processing Development Environment on
+ * Windows or Mac OS, where case sensitivity is preserved but ignored.
+ *
+ * If the file ends with .gz, the stream will automatically be gzip
+ * decompressed. If you don't want the automatic decompression, use the
+ * related function createInputRaw().
+ *
+ * In earlier releases, this function was called openStream().
+ *
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Simplified method to open a Java InputStream.
+ *
+ * This method is useful if you want to use the facilities provided
+ * by PApplet to easily open things from the data folder or from a URL,
+ * but want an InputStream object so that you can use other Java
+ * methods to take more control of how the stream is read.
+ *
+ * If the requested item doesn't exist, null is returned.
+ * (Prior to 0096, die() would be called, killing the applet)
+ *
+ * For 0096+, the "data" folder is exported intact with subfolders,
+ * and openStream() properly handles subdirectories from the data folder
+ *
+ * If not online, this will also check to see if the user is asking
+ * for a file whose name isn't properly capitalized. This helps prevent
+ * issues when a sketch is exported to the web, where case sensitivity
+ * matters, as opposed to Windows and the Mac OS default where
+ * case sensitivity is preserved but ignored.
+ *
+ * It is strongly recommended that libraries use this method to open
+ * data files, so that the loading sequence is handled in the same way
+ * as functions like loadBytes(), loadImage(), etc.
+ *
+ * The filename passed in can be:
+ *
+ *
A URL, for instance openStream("http://processing.org/");
+ *
A file in the sketch's data folder
+ *
Another file to be opened locally (when running as an application)
+ *
+ *
+ * @webref input:files
+ * @param filename the name of the file to use as input
+ * @see PApplet#createOutput(String)
+ * @see PApplet#selectOutput(String,String)
+ * @see PApplet#selectInput(String,String)
+ *
+ */
+ public InputStream createInput(String filename) {
+ InputStream input = createInputRaw(filename);
+ if (input != null) {
+ // if it's gzip-encoded, automatically decode
+ final String lower = filename.toLowerCase();
+ if (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);
+ }
+ } else {
+ return new BufferedInputStream(input);
+ }
+ }
+ return null;
+ }
+
+
+ /**
+ * Call openStream() without automatic gzip decompression.
+ */
+ public InputStream createInputRaw(String filename) {
+ if (filename == null) return null;
+
+ if (sketchPath == null) {
+ System.err.println("The sketch path is not set.");
+ throw new RuntimeException("Files must be loaded inside setup() or after it has been called.");
+ }
+
+ 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;
+ }
+
+ // First check whether this looks like a URL
+ if (filename.contains(":")) { // at least smells like URL
+ try {
+ URL url = new URL(filename);
+ URLConnection conn = url.openConnection();
+
+ if (conn instanceof HttpURLConnection) {
+ HttpURLConnection httpConn = (HttpURLConnection) conn;
+ // Will not handle a protocol change (see below)
+ httpConn.setInstanceFollowRedirects(true);
+ int response = httpConn.getResponseCode();
+ // Default won't follow HTTP -> HTTPS redirects for security reasons
+ // http://stackoverflow.com/a/1884427
+ if (response >= 300 && response < 400) {
+ String newLocation = httpConn.getHeaderField("Location");
+ return createInputRaw(newLocation);
+ }
+ return conn.getInputStream();
+ } else if (conn instanceof JarURLConnection) {
+ return url.openStream();
+ }
+ } catch (MalformedURLException mfue) {
+ // not a url, that's fine
+
+ } catch (FileNotFoundException fnfe) {
+ // Added in 0119 b/c Java 1.5 throws FNFE when URL not available.
+ // 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);
+ }
+ }
+
+ InputStream stream = null;
+
+ // 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 = sketchFile(filename);
+ }
+
+ if (file.isDirectory()) {
+ return null;
+ }
+ if (file.exists()) {
+ try {
+ // handle case sensitivity check
+ String filePath = file.getCanonicalPath();
+ String filenameActual = new File(filePath).getName();
+ // make sure there isn't a subfolder prepended to the name
+ String filenameShort = new File(filename).getName();
+ // if the actual filename is the same, but capitalized
+ // differently, warn the user.
+ //if (filenameActual.equalsIgnoreCase(filenameShort) &&
+ //!filenameActual.equals(filenameShort)) {
+ if (!filenameActual.equals(filenameShort)) {
+ throw new RuntimeException("This file is named " +
+ filenameActual + " not " +
+ filename + ". Rename the file " +
+ "or change your code.");
+ }
+ } catch (IOException e) { }
+ }
+
+ // if this file is ok, may as well just load it
+ stream = new FileInputStream(file);
+ if (stream != null) return stream;
+
+ // have to break these out because a general Exception might
+ // catch the RuntimeException being thrown above
+ } catch (IOException ioe) {
+ } catch (SecurityException se) { }
+
+ // Using getClassLoader() prevents java from converting dots
+ // to slashes or requiring a slash at the beginning.
+ // (a slash as a prefix means that it'll load from the root of
+ // the jar, rather than trying to dig into the package location)
+ ClassLoader cl = getClass().getClassLoader();
+
+ // by default, data files are exported to the root path of the jar.
+ // (not the data folder) so check there first.
+ stream = cl.getResourceAsStream("data/" + filename);
+ if (stream != null) {
+ String cn = stream.getClass().getName();
+ // this is an irritation of sun's java plug-in, which will return
+ // a non-null stream for an object that doesn't exist. like all good
+ // things, this is probably introduced in java 1.5. awesome!
+ // http://dev.processing.org/bugs/show_bug.cgi?id=359
+ if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
+ return stream;
+ }
+ }
+
+ // When used with an online script, also need to check without the
+ // data folder, in case it's not in a subfolder called 'data'.
+ // http://dev.processing.org/bugs/show_bug.cgi?id=389
+ stream = cl.getResourceAsStream(filename);
+ if (stream != null) {
+ String cn = stream.getClass().getName();
+ if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
+ return stream;
+ }
+ }
+
+ try {
+ // attempt to load from a local file, used when running as
+ // an application, or as a signed applet
+ try { // first try to catch any security exceptions
+ try {
+ stream = new FileInputStream(dataPath(filename));
+ if (stream != null) return stream;
+ } catch (IOException e2) { }
+
+ try {
+ stream = new FileInputStream(sketchPath(filename));
+ if (stream != null) return stream;
+ } catch (Exception e) { } // ignored
+
+ try {
+ stream = new FileInputStream(filename);
+ if (stream != null) return stream;
+ } catch (IOException e1) { }
+
+ } catch (SecurityException se) { } // online, whups
+
+ } catch (Exception e) {
+ printStackTrace(e);
+ }
+
+ return null;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ static public InputStream createInput(File file) {
+ if (file == null) {
+ throw new IllegalArgumentException("File passed to createInput() was null");
+ }
+ if (!file.exists()) {
+ System.err.println(file + " does not exist, createInput() will return null");
+ return null;
+ }
+ try {
+ InputStream input = new FileInputStream(file);
+ final String lower = file.getName().toLowerCase();
+ if (lower.endsWith(".gz") || lower.endsWith(".svgz")) {
+ 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;
+ }
+ }
+
+
+ /**
+ * ( begin auto-generated from loadBytes.xml )
+ *
+ * Reads the contents of a file or url and places it in a byte array. If a
+ * file is specified, it must be located in the sketch's "data"
+ * directory/folder.
+ *
+ * The filename parameter can also be a URL to a file found online. For
+ * security reasons, a Processing sketch found online can only download
+ * files from the same server from which it came. Getting around this
+ * restriction requires a signed applet.
+ *
+ * ( end auto-generated )
+ * @webref input:files
+ * @param filename name of a file in the data folder or a URL.
+ * @see PApplet#loadStrings(String)
+ * @see PApplet#saveStrings(String, String[])
+ * @see PApplet#saveBytes(String, byte[])
+ *
+ */
+ public byte[] loadBytes(String filename) {
+ String lower = filename.toLowerCase();
+ // If it's not a .gz file, then we might be able to uncompress it into
+ // a fixed-size buffer, which should help speed because we won't have to
+ // reallocate and resize the target array each time it gets full.
+ if (!lower.endsWith(".gz")) {
+ // If this looks like a URL, try to load it that way. Use the fact that
+ // URL connections may have a content length header to size the array.
+ if (filename.contains(":")) { // at least smells like URL
+ try {
+ URL url = new URL(filename);
+ URLConnection conn = url.openConnection();
+ InputStream input = null;
+ int length = -1;
+
+ if (conn instanceof HttpURLConnection) {
+ HttpURLConnection httpConn = (HttpURLConnection) conn;
+ // Will not handle a protocol change (see below)
+ httpConn.setInstanceFollowRedirects(true);
+ int response = httpConn.getResponseCode();
+ // Default won't follow HTTP -> HTTPS redirects for security reasons
+ // http://stackoverflow.com/a/1884427
+ if (response >= 300 && response < 400) {
+ String newLocation = httpConn.getHeaderField("Location");
+ return loadBytes(newLocation);
+ }
+ length = conn.getContentLength();
+ input = conn.getInputStream();
+ } else if (conn instanceof JarURLConnection) {
+ length = conn.getContentLength();
+ input = url.openStream();
+ }
+
+ if (input != null) {
+ byte[] buffer = null;
+ if (length != -1) {
+ buffer = new byte[length];
+ int count;
+ int offset = 0;
+ while ((count = input.read(buffer, offset, length - offset)) > 0) {
+ offset += count;
+ }
+ } else {
+ buffer = loadBytes(input);
+ }
+ input.close();
+ return buffer;
+ }
+ } catch (MalformedURLException mfue) {
+ // not a url, that's fine
+
+ } catch (FileNotFoundException fnfe) {
+ // Java 1.5+ throws FNFE when URL not available
+ // http://dev.processing.org/bugs/show_bug.cgi?id=403
+
+ } catch (IOException e) {
+ printStackTrace(e);
+ return null;
+ }
+ }
+ }
+
+ InputStream is = createInput(filename);
+ if (is != null) {
+ byte[] outgoing = loadBytes(is);
+ try {
+ is.close();
+ } catch (IOException e) {
+ printStackTrace(e); // shouldn't happen
+ }
+ return outgoing;
+ }
+
+ 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;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ static public byte[] loadBytes(InputStream input) {
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[4096];
+
+ int bytesRead = input.read(buffer);
+ while (bytesRead != -1) {
+ out.write(buffer, 0, bytesRead);
+ bytesRead = input.read(buffer);
+ }
+ out.flush();
+ return out.toByteArray();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ static public byte[] loadBytes(File file) {
+ if (!file.exists()) {
+ System.err.println(file + " does not exist, loadBytes() will return null");
+ return null;
+ }
+
+ try {
+ InputStream input;
+ int length;
+
+ if (file.getName().toLowerCase().endsWith(".gz")) {
+ RandomAccessFile raf = new RandomAccessFile(file, "r");
+ raf.seek(raf.length() - 4);
+ int b4 = raf.read();
+ int b3 = raf.read();
+ int b2 = raf.read();
+ int b1 = raf.read();
+ length = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4;
+ raf.close();
+
+ // buffered has to go *around* the GZ, otherwise 25x slower
+ input = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));
+
+ } else {
+ long len = file.length();
+ // http://stackoverflow.com/a/3039805
+ int maxArraySize = Integer.MAX_VALUE - 5;
+ if (len > maxArraySize) {
+ System.err.println("Cannot use loadBytes() on a file larger than " + maxArraySize);
+ return null;
+ }
+ length = (int) len;
+ input = new BufferedInputStream(new FileInputStream(file));
+ }
+ byte[] buffer = new byte[length];
+ int count;
+ int offset = 0;
+ // count will come back 0 when complete (or -1 if somehow going long?)
+ while ((count = input.read(buffer, offset, length - offset)) > 0) {
+ offset += count;
+ }
+ input.close();
+ return buffer;
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+
+ /**
+ * @nowebref
+ */
+ static public String[] loadStrings(File file) {
+ if (!file.exists()) {
+ System.err.println(file + " does not exist, loadStrings() will return null");
+ return null;
+ }
+
+ InputStream is = createInput(file);
+ if (is != null) {
+ String[] outgoing = loadStrings(is);
+ try {
+ is.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return outgoing;
+ }
+ return null;
+ }
+
+
+ /**
+ * ( begin auto-generated from loadStrings.xml )
+ *
+ * Reads the contents of a file or url and creates a String array of its
+ * individual lines. If a file is specified, it must be located in the
+ * sketch's "data" directory/folder.
+ *
+ * The filename parameter can also be a URL to a file found online. For
+ * security reasons, a Processing sketch found online can only download
+ * files from the same server from which it came. Getting around this
+ * restriction requires a signed applet.
+ *
+ * If the file is not available or an error occurs, null will be
+ * returned and an error message will be printed to the console. The error
+ * message does not halt the program, however the null value may cause a
+ * NullPointerException if your code does not check whether the value
+ * returned is null.
+ *
+ * Starting with Processing release 0134, all files loaded and saved by the
+ * Processing API use UTF-8 encoding. In previous releases, the default
+ * encoding for your platform was used, which causes problems when files
+ * are moved to other platforms.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Load data from a file and shove it into a String array.
+ *
+ * Exceptions are handled internally, when an error, occurs, an
+ * exception is printed to the console and 'null' is returned,
+ * but the program continues running. This is a tradeoff between
+ * 1) showing the user that there was a problem but 2) not requiring
+ * that all i/o code is contained in try/catch blocks, for the sake
+ * of new users (or people who are just trying to get things done
+ * in a "scripting" fashion. If you want to handle exceptions,
+ * use Java methods for I/O.
+ *
+ * @webref input:files
+ * @param filename name of the file or url to load
+ * @see PApplet#loadBytes(String)
+ * @see PApplet#saveStrings(String, String[])
+ * @see PApplet#saveBytes(String, byte[])
+ */
+ public String[] loadStrings(String filename) {
+ InputStream is = createInput(filename);
+ if (is != null) {
+ String[] strArr = loadStrings(is);
+ try {
+ is.close();
+ } catch (IOException e) {
+ printStackTrace(e);
+ }
+ return strArr;
+ }
+
+ 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;
+ }
+
+ /**
+ * @nowebref
+ */
+ static public String[] loadStrings(InputStream input) {
+ try {
+ BufferedReader reader =
+ new BufferedReader(new InputStreamReader(input, "UTF-8"));
+ return loadStrings(reader);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ 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;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // FILE OUTPUT
+
+
+ /**
+ * ( begin auto-generated from createOutput.xml )
+ *
+ * Similar to createInput(), 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.
+ *
+ * This function is a convenience over the Java approach that requires you
+ * to 1) create a FileOutputStream object, 2) determine the exact file
+ * location, and 3) handle exceptions. Exceptions are handled internally by
+ * the function, which is more appropriate for "sketch" projects.
+ *
+ * If the output filename ends with .gz, the output will be
+ * automatically GZIP compressed as it is written.
+ *
+ * ( end auto-generated )
+ * @webref output:files
+ * @param filename name of the file to open
+ * @see PApplet#createInput(String)
+ * @see PApplet#selectOutput(String,String)
+ */
+ public OutputStream createOutput(String filename) {
+ return createOutput(saveFile(filename));
+ }
+
+ /**
+ * @nowebref
+ */
+ 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;
+ }
+
+
+ /**
+ * ( begin auto-generated from saveStream.xml )
+ *
+ * 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).
+ *
+ * When using the targetFile parameter, it writes to a File
+ * object for greater control over the file location. (Note that unlike
+ * some other functions, this will not automatically compress or uncompress
+ * gzip files.)
+ *
+ * ( end auto-generated )
+ *
+ * @webref output:files
+ * @param target name of the file to write to
+ * @param source location to read from (a filename, path, or URL)
+ * @see PApplet#createOutput(String)
+ */
+ public boolean saveStream(String target, String source) {
+ return saveStream(saveFile(target), source);
+ }
+
+ /**
+ * 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 target, String source) {
+ return saveStream(target, createInputRaw(source));
+ }
+
+ /**
+ * @nowebref
+ */
+ public boolean saveStream(String target, InputStream source) {
+ return saveStream(saveFile(target), source);
+ }
+
+ /**
+ * @nowebref
+ */
+ 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;
+ }
+ }
+
+ /**
+ * @nowebref
+ */
+ 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();
+ }
+
+
+ /**
+ * ( begin auto-generated from saveBytes.xml )
+ *
+ * Opposite of loadBytes(), will write an entire array of bytes to a
+ * file. The data is saved in binary format. This file is saved to the
+ * sketch's folder, which is opened by selecting "Show sketch folder" from
+ * the "Sketch" menu.
+ *
+ * It is not possible to use saveXxxxx() functions inside a web browser
+ * unless the sketch is signed applet. To
+ * save a file back to a server, see the save to
+ * web code snippet on the Processing Wiki.
+ *
+ * ( end auto-generated )
+ *
+ * @webref output:files
+ * @param filename name of the file to write to
+ * @param data array of bytes to be written
+ * @see PApplet#loadStrings(String)
+ * @see PApplet#loadBytes(String)
+ * @see PApplet#saveStrings(String, String[])
+ */
+ 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);
+ }
+
+
+ /**
+ * @nowebref
+ * 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();
+ }
+ }
+
+
+ /**
+ * @nowebref
+ * 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();
+ }
+ }
+
+
+ //
+
+ /**
+ * ( begin auto-generated from saveStrings.xml )
+ *
+ * Writes an array of strings to a file, one line per string. This file is
+ * saved to the sketch's folder, which is opened by selecting "Show sketch
+ * folder" from the "Sketch" menu.
+ *
+ * It is not possible to use saveXxxxx() functions inside a web browser
+ * unless the sketch is signed applet. To
+ * save a file back to a server, see the save to
+ * web code snippet on the Processing Wiki.
+ *
+ * Starting with Processing 1.0, all files loaded and saved by the
+ * Processing API use UTF-8 encoding. In previous releases, the default
+ * encoding for your platform was used, which causes problems when files
+ * are moved to other platforms.
+ *
+ * ( end auto-generated )
+ * @webref output:files
+ * @param filename filename for output
+ * @param data string array to be written
+ * @see PApplet#loadStrings(String)
+ * @see PApplet#loadBytes(String)
+ * @see PApplet#saveBytes(String, byte[])
+ */
+ public void saveStrings(String filename, String data[]) {
+ saveStrings(saveFile(filename), data);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ static public void saveStrings(File file, String data[]) {
+ saveStrings(createOutput(file), data);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ static public void saveStrings(OutputStream output, String[] data) {
+ PrintWriter writer = createWriter(output);
+ for (int i = 0; i < data.length; i++) {
+ writer.println(data[i]);
+ }
+ writer.flush();
+ writer.close();
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ static protected String calcSketchPath() {
+ // 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");
+
+ URL jarURL =
+ PApplet.class.getProtectionDomain().getCodeSource().getLocation();
+ // Decode URL
+ String jarPath = jarURL.toURI().getSchemeSpecificPart();
+
+ // Workaround for bug in Java for OS X from Oracle (7u51)
+ // https://github.com/processing/processing/issues/2181
+ if (platform == MACOSX) {
+ if (jarPath.contains("Contents/Java/")) {
+ String appPath = jarPath.substring(0, jarPath.indexOf(".app") + 4);
+ File containingFolder = new File(appPath).getParentFile();
+ folder = containingFolder.getAbsolutePath();
+ }
+ } else {
+ // Working directory may not be set properly, try some options
+ // https://github.com/processing/processing/issues/2195
+ if (jarPath.contains("/lib/")) {
+ // Windows or Linux, back up a directory to get the executable
+ folder = new File(jarPath, "../..").getCanonicalPath();
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return folder;
+ }
+
+
+ public String sketchPath() {
+ if (sketchPath == null) {
+ sketchPath = calcSketchPath();
+ }
+ return sketchPath;
+ }
+
+
+ /**
+ * 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;
+ }
+ // isAbsolute() could throw an access exception, but so will writing
+ // to the local disk using the sketch path, so this is safe here.
+ // for 0120, added a try/catch anyways.
+ try {
+ if (new File(where).isAbsolute()) return where;
+ } catch (Exception e) { }
+
+ return sketchPath() + File.separator + where;
+ }
+
+
+ public File sketchFile(String where) {
+ return new File(sketchPath(where));
+ }
+
+
+ /**
+ * Returns a path inside the applet folder to save to. Like sketchPath(),
+ * but creates any in-between folders so that things save properly.
+ *
+ * All saveXxxx() functions use the path to the sketch folder, rather than
+ * its data folder. Once exported, the data folder will be found inside the
+ * jar file of the exported application or applet. In this case, it's not
+ * possible to save data into the jar file, because it will often be running
+ * from a server, or marked in-use if running from a local file system.
+ * With this in mind, saving to the data path doesn't make sense anyway.
+ * If you know you're running locally, and want to save to the data folder,
+ * use saveXxxx("data/blah.dat").
+ */
+ public String savePath(String where) {
+ if (where == null) return null;
+ String filename = sketchPath(where);
+ createPath(filename);
+ return filename;
+ }
+
+
+ /**
+ * Identical to savePath(), but returns a File object.
+ */
+ public File saveFile(String where) {
+ return new File(savePath(where));
+ }
+
+
+ static File desktopFolder;
+
+ /** Not a supported function. For testing use only. */
+ static public File desktopFile(String what) {
+ if (desktopFolder == null) {
+ // Should work on Linux and OS X (on OS X, even with the localized version).
+ desktopFolder = new File(System.getProperty("user.home"), "Desktop");
+ if (!desktopFolder.exists()) {
+ if (platform == WINDOWS) {
+ FileSystemView filesys = FileSystemView.getFileSystemView();
+ desktopFolder = filesys.getHomeDirectory();
+ } else {
+ throw new UnsupportedOperationException("Could not find a suitable desktop foldder");
+ }
+ }
+ }
+ return new File(desktopFolder, what);
+ }
+
+
+ /** Not a supported function. For testing use only. */
+ static public String desktopPath(String what) {
+ return desktopFile(what).getAbsolutePath();
+ }
+
+
+ /**
+ * This function almost certainly does not do the thing you want it to.
+ * The data path is handled differently on each platform, and should not be
+ * considered a location to write files. It should also not be assumed that
+ * this location can be read from or listed. This function is used internally
+ * as a possible location for reading files. It's still "public" as a
+ * holdover from earlier code.
+ *
+ * Libraries should use createInput() to get an InputStream or createOutput()
+ * to get an OutputStream. sketchPath() can be used to get a location
+ * relative to the sketch. Again, do not use this to get relative
+ * locations of files. You'll be disappointed when your app runs on different
+ * platforms.
+ */
+ public String dataPath(String where) {
+ return dataFile(where).getAbsolutePath();
+ }
+
+
+ /**
+ * 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) {
+ // isAbsolute() could throw an access exception, but so will writing
+ // to the local disk using the sketch path, so this is safe here.
+ File why = new File(where);
+ if (why.isAbsolute()) return why;
+
+ URL jarURL = getClass().getProtectionDomain().getCodeSource().getLocation();
+ // Decode URL
+ String jarPath;
+ try {
+ jarPath = jarURL.toURI().getPath();
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ return null;
+ }
+ if (jarPath.contains("Contents/Java/")) {
+ File containingFolder = new File(jarPath).getParentFile();
+ File dataFolder = new File(containingFolder, "data");
+ return new File(dataFolder, where);
+ }
+ // Windows, Linux, or when not using a Mac OS X .app file
+ File workingDirItem =
+ new File(sketchPath + File.separator + "data" + File.separator + where);
+// if (workingDirItem.exists()) {
+ return workingDirItem;
+// }
+// // In some cases, the current working directory won't be set properly.
+ }
+
+
+ /**
+ * On Windows and Linux, this is simply the data folder. On Mac OS X, this is
+ * the path to the data folder buried inside Contents/Java
+ */
+// public File inputFile(String where) {
+// }
+
+
+// public String inputPath(String 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) {
+ return ""; // 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 str) {
+ try {
+ return URLEncoder.encode(str, "UTF-8");
+ } catch (UnsupportedEncodingException e) { // oh c'mon
+ return null;
+ }
+ }
+
+
+ // DO NOT use for file paths, URLDecoder can't handle RFC2396
+ // "The recommended way to manage the encoding and decoding of
+ // URLs is to use URI, and to convert between these two classes
+ // using toURI() and URI.toURL()."
+ // https://docs.oracle.com/javase/8/docs/api/java/net/URL.html
+ static public String urlDecode(String str) {
+ try {
+ return URLDecoder.decode(str, "UTF-8");
+ } catch (UnsupportedEncodingException e) { // safe per the JDK source
+ return null;
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SORT
+
+
+ /**
+ * ( begin auto-generated from sort.xml )
+ *
+ * Sorts an array of numbers from smallest to largest and puts an array of
+ * words in alphabetical order. The original array is not modified, a
+ * re-ordered array is returned. The count parameter states the
+ * number of elements to sort. For example if there are 12 elements in an
+ * array and if count is the value 5, only the first five elements on the
+ * array will be sorted.
+ *
+ * ( end auto-generated )
+ * @webref data:array_functions
+ * @param list array to sort
+ * @see PApplet#reverse(boolean[])
+ */
+ static public byte[] sort(byte list[]) {
+ return sort(list, list.length);
+ }
+
+ /**
+ * @param count number of elements to sort, starting from 0
+ */
+ static public byte[] sort(byte[] list, int count) {
+ byte[] outgoing = new byte[list.length];
+ System.arraycopy(list, 0, outgoing, 0, list.length);
+ Arrays.sort(outgoing, 0, count);
+ return outgoing;
+ }
+
+ static public char[] sort(char list[]) {
+ return sort(list, list.length);
+ }
+
+ static public char[] sort(char[] list, int count) {
+ char[] outgoing = new char[list.length];
+ System.arraycopy(list, 0, outgoing, 0, list.length);
+ Arrays.sort(outgoing, 0, count);
+ return outgoing;
+ }
+
+ static public int[] sort(int list[]) {
+ return sort(list, list.length);
+ }
+
+ static public int[] sort(int[] list, int count) {
+ int[] outgoing = new int[list.length];
+ System.arraycopy(list, 0, outgoing, 0, list.length);
+ Arrays.sort(outgoing, 0, count);
+ return outgoing;
+ }
+
+ static public float[] sort(float list[]) {
+ return sort(list, list.length);
+ }
+
+ static public float[] sort(float[] list, int count) {
+ float[] outgoing = new float[list.length];
+ System.arraycopy(list, 0, outgoing, 0, list.length);
+ Arrays.sort(outgoing, 0, count);
+ return outgoing;
+ }
+
+ static public String[] sort(String list[]) {
+ return sort(list, list.length);
+ }
+
+ static public String[] sort(String[] list, int count) {
+ String[] outgoing = new String[list.length];
+ System.arraycopy(list, 0, outgoing, 0, list.length);
+ Arrays.sort(outgoing, 0, count);
+ return outgoing;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ARRAY UTILITIES
+
+
+ /**
+ * ( begin auto-generated from arrayCopy.xml )
+ *
+ * Copies an array (or part of an array) to another array. The src
+ * array is copied to the dst array, beginning at the position
+ * specified by srcPos and into the position specified by
+ * dstPos. The number of elements to copy is determined by
+ * length. The simplified version with two arguments copies an
+ * entire array to another of the same size. It is equivalent to
+ * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
+ * efficient for copying array data than iterating through a for and
+ * copying each element.
+ *
+ * ( end auto-generated )
+ * @webref data:array_functions
+ * @param src the source array
+ * @param srcPosition starting position in the source array
+ * @param dst the destination array of the same data type as the source array
+ * @param dstPosition starting position in the destination array
+ * @param length number of array elements to be copied
+ * @see PApplet#concat(boolean[], boolean[])
+ */
+ static public void arrayCopy(Object src, int srcPosition,
+ Object dst, int dstPosition,
+ int length) {
+ System.arraycopy(src, srcPosition, dst, dstPosition, length);
+ }
+
+ /**
+ * Convenience method for arraycopy().
+ * Identical to arraycopy(src, 0, dst, 0, length);
+ */
+ static public void arrayCopy(Object src, Object dst, int length) {
+ System.arraycopy(src, 0, dst, 0, length);
+ }
+
+ /**
+ * Shortcut to copy the entire contents of
+ * the source into the destination array.
+ * Identical to arraycopy(src, 0, dst, 0, src.length);
+ */
+ static public void arrayCopy(Object src, Object dst) {
+ System.arraycopy(src, 0, dst, 0, Array.getLength(src));
+ }
+
+ //
+ /**
+ * @deprecated Use arrayCopy() instead.
+ */
+ static public void arraycopy(Object src, int srcPosition,
+ Object dst, int dstPosition,
+ int length) {
+ System.arraycopy(src, srcPosition, dst, dstPosition, length);
+ }
+
+ /**
+ * @deprecated Use arrayCopy() instead.
+ */
+ static public void arraycopy(Object src, Object dst, int length) {
+ System.arraycopy(src, 0, dst, 0, length);
+ }
+
+ /**
+ * @deprecated Use arrayCopy() instead.
+ */
+ static public void arraycopy(Object src, Object dst) {
+ System.arraycopy(src, 0, dst, 0, Array.getLength(src));
+ }
+
+ /**
+ * ( begin auto-generated from expand.xml )
+ *
+ * Increases the size of an array. By default, this function doubles the
+ * size of the array, but the optional newSize parameter provides
+ * precise control over the increase in size.
+ *
+ * When using an array of objects, the data returned from the function must
+ * be cast to the object array's data type. For example: SomeClass[]
+ * items = (SomeClass[]) expand(originalArray).
+ *
+ * ( end auto-generated )
+ *
+ * @webref data:array_functions
+ * @param list the array to expand
+ * @see PApplet#shorten(boolean[])
+ */
+ static public boolean[] expand(boolean list[]) {
+ return expand(list, list.length > 0 ? list.length << 1 : 1);
+ }
+
+ /**
+ * @param newSize new size for the array
+ */
+ 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 > 0 ? list.length << 1 : 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 > 0 ? list.length << 1 : 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 > 0 ? list.length << 1 : 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 > 0 ? list.length << 1 : 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 > 0 ? list.length << 1 : 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;
+ }
+
+ /**
+ * @nowebref
+ */
+ static public Object expand(Object array) {
+ int len = Array.getLength(array);
+ return expand(array, len > 0 ? len << 1 : 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)
+
+ /**
+ * ( begin auto-generated from append.xml )
+ *
+ * Expands an array by one element and adds data to the new position. The
+ * datatype of the element parameter must be the same as the
+ * datatype of the array.
+ *
+ * When using an array of objects, the data returned from the function must
+ * be cast to the object array's data type. For example: SomeClass[]
+ * items = (SomeClass[]) append(originalArray, element).
+ *
+ * ( end auto-generated )
+ *
+ * @webref data:array_functions
+ * @param array array to append
+ * @param value new data for the array
+ * @see PApplet#shorten(boolean[])
+ * @see PApplet#expand(boolean[])
+ */
+ static public byte[] append(byte array[], byte value) {
+ array = expand(array, array.length + 1);
+ array[array.length-1] = value;
+ return array;
+ }
+
+ static public char[] append(char array[], char value) {
+ array = expand(array, array.length + 1);
+ array[array.length-1] = value;
+ return array;
+ }
+
+ static public int[] append(int array[], int value) {
+ array = expand(array, array.length + 1);
+ array[array.length-1] = value;
+ return array;
+ }
+
+ static public float[] append(float array[], float value) {
+ array = expand(array, array.length + 1);
+ array[array.length-1] = value;
+ return array;
+ }
+
+ static public String[] append(String array[], String value) {
+ array = expand(array, array.length + 1);
+ array[array.length-1] = value;
+ return array;
+ }
+
+ static public Object append(Object array, Object value) {
+ int length = Array.getLength(array);
+ array = expand(array, length + 1);
+ Array.set(array, length, value);
+ return array;
+ }
+
+
+ /**
+ * ( begin auto-generated from shorten.xml )
+ *
+ * Decreases an array by one element and returns the shortened array.
+ *
+ * When using an array of objects, the data returned from the function must
+ * be cast to the object array's data type. For example: SomeClass[]
+ * items = (SomeClass[]) shorten(originalArray).
+ *
+ * ( end auto-generated )
+ *
+ * @webref data:array_functions
+ * @param list array to shorten
+ * @see PApplet#append(byte[], byte)
+ * @see PApplet#expand(boolean[])
+ */
+ 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);
+ }
+
+
+ /**
+ * ( begin auto-generated from splice.xml )
+ *
+ * Inserts a value or array of values into an existing array. The first two
+ * parameters must be of the same datatype. The array parameter
+ * defines the array which will be modified and the second parameter
+ * defines the data which will be inserted.
+ *
+ * When using an array of objects, the data returned from the function must
+ * be cast to the object array's data type. For example: SomeClass[]
+ * items = (SomeClass[]) splice(array1, array2, index).
+ *
+ * ( end auto-generated )
+ * @webref data:array_functions
+ * @param list array to splice into
+ * @param value value to be spliced in
+ * @param index position in the array from which to insert data
+ * @see PApplet#concat(boolean[], boolean[])
+ * @see PApplet#subset(boolean[], int, int)
+ */
+ static final public boolean[] splice(boolean list[],
+ boolean value, int index) {
+ boolean outgoing[] = new boolean[list.length + 1];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ outgoing[index] = value;
+ System.arraycopy(list, index, outgoing, index + 1,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public boolean[] splice(boolean list[],
+ boolean value[], int index) {
+ boolean outgoing[] = new boolean[list.length + value.length];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, value.length);
+ System.arraycopy(list, index, outgoing, index + value.length,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public byte[] splice(byte list[],
+ byte value, int index) {
+ byte outgoing[] = new byte[list.length + 1];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ outgoing[index] = value;
+ System.arraycopy(list, index, outgoing, index + 1,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public byte[] splice(byte list[],
+ byte value[], int index) {
+ byte outgoing[] = new byte[list.length + value.length];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, value.length);
+ System.arraycopy(list, index, outgoing, index + value.length,
+ list.length - index);
+ return outgoing;
+ }
+
+
+ static final public char[] splice(char list[],
+ char value, int index) {
+ char outgoing[] = new char[list.length + 1];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ outgoing[index] = value;
+ System.arraycopy(list, index, outgoing, index + 1,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public char[] splice(char list[],
+ char value[], int index) {
+ char outgoing[] = new char[list.length + value.length];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, value.length);
+ System.arraycopy(list, index, outgoing, index + value.length,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public int[] splice(int list[],
+ int value, int index) {
+ int outgoing[] = new int[list.length + 1];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ outgoing[index] = value;
+ System.arraycopy(list, index, outgoing, index + 1,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public int[] splice(int list[],
+ int value[], int index) {
+ int outgoing[] = new int[list.length + value.length];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, value.length);
+ System.arraycopy(list, index, outgoing, index + value.length,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public float[] splice(float list[],
+ float value, int index) {
+ float outgoing[] = new float[list.length + 1];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ outgoing[index] = value;
+ System.arraycopy(list, index, outgoing, index + 1,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public float[] splice(float list[],
+ float value[], int index) {
+ float outgoing[] = new float[list.length + value.length];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, value.length);
+ System.arraycopy(list, index, outgoing, index + value.length,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public String[] splice(String list[],
+ String value, int index) {
+ String outgoing[] = new String[list.length + 1];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ outgoing[index] = value;
+ System.arraycopy(list, index, outgoing, index + 1,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public String[] splice(String list[],
+ String value[], int index) {
+ String outgoing[] = new String[list.length + value.length];
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, value.length);
+ System.arraycopy(list, index, outgoing, index + value.length,
+ list.length - index);
+ return outgoing;
+ }
+
+ static final public Object splice(Object list, Object value, int index) {
+ Class> type = list.getClass().getComponentType();
+ Object outgoing = null;
+ int length = Array.getLength(list);
+
+ // check whether item being spliced in is an array
+ if (value.getClass().getName().charAt(0) == '[') {
+ int vlength = Array.getLength(value);
+ outgoing = Array.newInstance(type, length + vlength);
+ System.arraycopy(list, 0, outgoing, 0, index);
+ System.arraycopy(value, 0, outgoing, index, vlength);
+ System.arraycopy(list, index, outgoing, index + vlength, length - index);
+
+ } else {
+ outgoing = Array.newInstance(type, length + 1);
+ System.arraycopy(list, 0, outgoing, 0, index);
+ Array.set(outgoing, index, value);
+ 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);
+ }
+
+ /**
+ * ( begin auto-generated from subset.xml )
+ *
+ * Extracts an array of elements from an existing array. The array
+ * parameter defines the array from which the elements will be copied and
+ * the offset and length parameters determine which elements
+ * to extract. If no length is given, elements will be extracted
+ * from the offset to the end of the array. When specifying the
+ * offset remember the first array element is 0. This function does
+ * not change the source array.
+ *
+ * When using an array of objects, the data returned from the function must
+ * be cast to the object array's data type. For example: SomeClass[]
+ * items = (SomeClass[]) subset(originalArray, 0, 4).
+ *
+ * ( end auto-generated )
+ * @webref data:array_functions
+ * @param list array to extract from
+ * @param start position to begin
+ * @param count number of values to extract
+ * @see PApplet#splice(boolean[], boolean, int)
+ */
+ static public boolean[] subset(boolean list[], int start, int count) {
+ boolean output[] = new boolean[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+ static public byte[] subset(byte list[], int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public byte[] subset(byte list[], int start, int count) {
+ byte output[] = new byte[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+
+ static public char[] subset(char list[], int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public char[] subset(char list[], int start, int count) {
+ char output[] = new char[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+ static public int[] subset(int list[], int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public int[] subset(int list[], int start, int count) {
+ int output[] = new int[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+ static public float[] subset(float list[], int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public float[] subset(float list[], int start, int count) {
+ float output[] = new float[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+
+ static public String[] subset(String list[], int start) {
+ return subset(list, start, list.length - start);
+ }
+
+ static public String[] subset(String list[], int start, int count) {
+ String output[] = new String[count];
+ System.arraycopy(list, start, output, 0, count);
+ return output;
+ }
+
+
+ static public Object subset(Object list, int start) {
+ int length = Array.getLength(list);
+ return subset(list, start, length - start);
+ }
+
+ static public Object subset(Object list, int start, int count) {
+ Class> type = list.getClass().getComponentType();
+ Object outgoing = Array.newInstance(type, count);
+ System.arraycopy(list, start, outgoing, 0, count);
+ return outgoing;
+ }
+
+
+ /**
+ * ( begin auto-generated from concat.xml )
+ *
+ * Concatenates two arrays. For example, concatenating the array { 1, 2, 3
+ * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
+ * must be arrays of the same datatype.
+ *
+ * When using an array of objects, the data returned from the function must
+ * be cast to the object array's data type. For example: SomeClass[]
+ * items = (SomeClass[]) concat(array1, array2).
+ *
+ * ( end auto-generated )
+ * @webref data:array_functions
+ * @param a first array to concatenate
+ * @param b second array to concatenate
+ * @see PApplet#splice(boolean[], boolean, int)
+ * @see PApplet#arrayCopy(Object, int, Object, int, int)
+ */
+ 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;
+ }
+
+ //
+
+
+ /**
+ * ( begin auto-generated from reverse.xml )
+ *
+ * Reverses the order of an array.
+ *
+ * ( end auto-generated )
+ * @webref data:array_functions
+ * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
+ * @see PApplet#sort(String[], int)
+ */
+ 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
+
+
+ /**
+ * ( begin auto-generated from trim.xml )
+ *
+ * Removes whitespace characters from the beginning and end of a String. In
+ * addition to standard whitespace characters such as space, carriage
+ * return, and tab, this function also removes the Unicode "nbsp" character.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param str any string
+ * @see PApplet#split(String, String)
+ * @see PApplet#join(String[], char)
+ */
+ static public String trim(String str) {
+ if (str == null) {
+ return null;
+ }
+ return str.replace('\u00A0', ' ').trim();
+ }
+
+
+ /**
+ * @param array a String array
+ */
+ static public String[] trim(String[] array) {
+ if (array == null) {
+ return null;
+ }
+ String[] outgoing = new String[array.length];
+ for (int i = 0; i < array.length; i++) {
+ if (array[i] != null) {
+ outgoing[i] = trim(array[i]);
+ }
+ }
+ return outgoing;
+ }
+
+
+ /**
+ * ( begin auto-generated from join.xml )
+ *
+ * Combines an array of Strings into one String, each separated by the
+ * character(s) used for the separator parameter. To join arrays of
+ * ints or floats, it's necessary to first convert them to strings using
+ * nf() or nfs().
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param list array of Strings
+ * @param separator char or String to be placed between each item
+ * @see PApplet#split(String, String)
+ * @see PApplet#trim(String)
+ * @see PApplet#nf(float, int, int)
+ * @see PApplet#nfs(float, int, int)
+ */
+ static public String join(String[] list, char separator) {
+ return join(list, String.valueOf(separator));
+ }
+
+
+ static public String join(String[] list, String separator) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < list.length; i++) {
+ if (i != 0) sb.append(separator);
+ sb.append(list[i]);
+ }
+ return sb.toString();
+ }
+
+
+ static public String[] splitTokens(String value) {
+ return splitTokens(value, WHITESPACE);
+ }
+
+
+ /**
+ * ( begin auto-generated from splitTokens.xml )
+ *
+ * The splitTokens() function splits a String at one or many character
+ * "tokens." The tokens parameter specifies the character or
+ * characters to be used as a boundary.
+ *
+ * If no tokens character is specified, any whitespace character is
+ * used to split. Whitespace characters include tab (\\t), line feed (\\n),
+ * carriage return (\\r), form feed (\\f), and space. To convert a String
+ * to an array of integers or floats, use the datatype conversion functions
+ * int() and float() to convert the array of Strings.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param value the String to be split
+ * @param delim list of individual characters that will be used as separators
+ * @see PApplet#split(String, String)
+ * @see PApplet#join(String[], String)
+ * @see PApplet#trim(String)
+ */
+ static public String[] splitTokens(String value, String delim) {
+ StringTokenizer toker = new StringTokenizer(value, delim);
+ String pieces[] = new String[toker.countTokens()];
+
+ int index = 0;
+ while (toker.hasMoreTokens()) {
+ pieces[index++] = toker.nextToken();
+ }
+ return pieces;
+ }
+
+
+ /**
+ * ( begin auto-generated from split.xml )
+ *
+ * The split() function breaks a string into pieces using a character or
+ * string as the divider. The delim parameter specifies the
+ * character or characters that mark the boundaries between each piece. A
+ * String[] array is returned that contains each of the pieces.
+ *
+ * If the result is a set of numbers, you can convert the String[] array to
+ * to a float[] or int[] array using the datatype conversion functions
+ * int() and float() (see example above).
+ *
+ * The splitTokens() function works in a similar fashion, except
+ * that it splits using a range of characters instead of a specific
+ * character or sequence.
+ *
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @usage web_application
+ * @param value the String to be split
+ * @param delim the character or String used to separate the data
+ */
+ static public String[] split(String value, char delim) {
+ // do this so that the exception occurs inside the user's
+ // program, rather than appearing to be a bug inside split()
+ if (value == null) return null;
+ //return split(what, String.valueOf(delim)); // huh
+
+ char chars[] = value.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] = value;
+ 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;
+ }
+
+
+ static public String[] split(String value, String delim) {
+ List items = new ArrayList<>();
+ int index;
+ int offset = 0;
+ while ((index = value.indexOf(delim, offset)) != -1) {
+ items.add(value.substring(offset, index));
+ offset = index + delim.length();
+ }
+ items.add(value.substring(offset));
+ String[] outgoing = new String[items.size()];
+ items.toArray(outgoing);
+ return outgoing;
+ }
+
+
+ static protected LinkedHashMap matchPatterns;
+
+ static Pattern matchPattern(String regexp) {
+ Pattern p = null;
+ if (matchPatterns == null) {
+ matchPatterns = new LinkedHashMap(16, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ // Limit the number of match patterns at 10 most recently used
+ return size() == 10;
+ }
+ };
+ } else {
+ p = matchPatterns.get(regexp);
+ }
+ if (p == null) {
+ p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
+ matchPatterns.put(regexp, p);
+ }
+ return p;
+ }
+
+
+ /**
+ * ( begin auto-generated from match.xml )
+ *
+ * The match() function is used to apply a regular expression to a piece of
+ * text, and return matching groups (elements found inside parentheses) as
+ * a String array. No match will return null. If no groups are specified in
+ * the regexp, but the sequence matches, an array of length one (with the
+ * matched text as the first element of the array) will be returned.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match. If the sequence did
+ * match, an array is returned.
+ * If there are groups (specified by sets of parentheses) in the regexp,
+ * then the contents of each will be returned in the array.
+ * Element [0] of a regexp match returns the entire matching string, and
+ * the match groups start at element [1] (the first group is [1], the
+ * second [2], and so on).
+ *
+ * The syntax can be found in the reference for Java's Pattern class.
+ * For regular expression syntax, read the Java
+ * Tutorial on the topic.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param str the String to be searched
+ * @param regexp the regexp to be used for matching
+ * @see PApplet#matchAll(String, String)
+ * @see PApplet#split(String, String)
+ * @see PApplet#splitTokens(String, String)
+ * @see PApplet#join(String[], String)
+ * @see PApplet#trim(String)
+ */
+ static public String[] match(String str, String regexp) {
+ Pattern p = matchPattern(regexp);
+ Matcher m = p.matcher(str);
+ 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;
+ }
+
+
+ /**
+ * ( begin auto-generated from matchAll.xml )
+ *
+ * This function is used to apply a regular expression to a piece of text,
+ * and return a list of matching groups (elements found inside parentheses)
+ * as a two-dimensional String array. No matches will return null. If no
+ * groups are specified in the regexp, but the sequence matches, a two
+ * dimensional array is still returned, but the second dimension is only of
+ * length one.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, a 2D array is returned. If there are groups (specified by
+ * sets of parentheses) in the regexp, then the contents of each will be
+ * returned in the array.
+ * Assuming, a loop with counter variable i, element [i][0] of a regexp
+ * match returns the entire matching string, and the match groups start at
+ * element [i][1] (the first group is [i][1], the second [i][2], and so
+ * on).
+ *
+ * The syntax can be found in the reference for Java's Pattern class.
+ * For regular expression syntax, read the Java
+ * Tutorial on the topic.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param str the String to be searched
+ * @param regexp the regexp to be used for matching
+ * @see PApplet#match(String, String)
+ * @see PApplet#split(String, String)
+ * @see PApplet#splitTokens(String, String)
+ * @see PApplet#join(String[], String)
+ * @see PApplet#trim(String)
+ */
+ static public String[][] matchAll(String str, String regexp) {
+ Pattern p = matchPattern(regexp);
+ Matcher m = p.matcher(str);
+ List 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] = 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 Boolean.parseBoolean(what);
+ }
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+ /*
+ // 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] = Boolean.parseBoolean(what[i]);
+ }
+ 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 what;
+ }
+
+ static final public float parseFloat(String what) {
+ return parseFloat(what, Float.NaN);
+ }
+
+ static final public float parseFloat(String what, float otherwise) {
+ try {
+ return Float.parseFloat(what);
+ } 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[] parseFloat(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] = Float.parseFloat(what[i]);
+ } 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
+
+ static public String nf(float num) {
+ int inum = (int) num;
+ if (num == inum) {
+ return str(inum);
+ }
+ return str(num);
+ }
+
+ static public String[] nf(float[] nums) {
+ String[] outgoing = new String[nums.length];
+ for (int i = 0; i < nums.length; i++) {
+ outgoing[i] = nf(nums[i]);
+ }
+ return outgoing;
+ }
+
+ /**
+ * Integer number formatter.
+ */
+
+ static private NumberFormat int_nf;
+ static private int int_nf_digits;
+ static private boolean int_nf_commas;
+
+ /**
+ * ( begin auto-generated from nf.xml )
+ *
+ * Utility function for formatting numbers into strings. There are two
+ * versions, one for formatting floats and one for formatting ints. The
+ * values for the digits, left, and right parameters
+ * should always be positive integers.
As shown in the above
+ * example, nf() is used to add zeros to the left and/or right of a
+ * number. This is typically for aligning a list of numbers. To
+ * remove digits from a floating-point number, use the
+ * int(), ceil(), floor(), or round()
+ * functions.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param nums the numbers to format
+ * @param digits number of digits to pad with zero
+ * @see PApplet#nfs(float, int, int)
+ * @see PApplet#nfp(float, int, int)
+ * @see PApplet#nfc(float, int)
+ * @see int(float)
+ */
+
+ static public String[] nf(int nums[], int digits) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nf(nums[i], digits);
+ }
+ return formatted;
+ }
+
+ /**
+ * @param num the number to format
+ */
+ 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);
+ }
+
+ /**
+ * ( begin auto-generated from nfc.xml )
+ *
+ * Utility function for formatting numbers into strings and placing
+ * appropriate commas to mark units of 1000. There are two versions, one
+ * for formatting ints and one for formatting an array of ints. The value
+ * for the digits parameter should always be a positive integer.
+ *
+ * For a non-US locale, this will insert periods instead of commas, or
+ * whatever is apprioriate for that region.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param nums the numbers to format
+ * @see PApplet#nf(float, int, int)
+ * @see PApplet#nfp(float, int, int)
+ * @see PApplet#nfs(float, int, int)
+ */
+ static public String[] nfc(int nums[]) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfc(nums[i]);
+ }
+ return formatted;
+ }
+
+
+ /**
+ * @param num the number to format
+ */
+ 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.
+ */
+
+ /**
+ * ( begin auto-generated from nfs.xml )
+ *
+ * Utility function for formatting numbers into strings. Similar to
+ * nf() but leaves a blank space in front of positive numbers so
+ * they align with negative numbers in spite of the minus symbol. There are
+ * two versions, one for formatting floats and one for formatting ints. The
+ * values for the digits, left, and right parameters
+ * should always be positive integers.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param num the number to format
+ * @param digits number of digits to pad with zeroes
+ * @see PApplet#nf(float, int, int)
+ * @see PApplet#nfp(float, int, int)
+ * @see PApplet#nfc(float, int)
+ */
+ static public String nfs(int num, int digits) {
+ return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
+ }
+
+ /**
+ * @param nums the numbers to format
+ */
+ static public String[] nfs(int nums[], int digits) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfs(nums[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.
+ */
+ /**
+ * ( begin auto-generated from nfp.xml )
+ *
+ * Utility function for formatting numbers into strings. Similar to
+ * nf() but puts a "+" in front of positive numbers and a "-" in
+ * front of negative numbers. There are two versions, one for formatting
+ * floats and one for formatting ints. The values for the digits,
+ * left, and right parameters should always be positive integers.
+ *
+ * ( end auto-generated )
+ * @webref data:string_functions
+ * @param num the number to format
+ * @param digits number of digits to pad with zeroes
+ * @see PApplet#nf(float, int, int)
+ * @see PApplet#nfs(float, int, int)
+ * @see PApplet#nfc(float, int)
+ */
+ static public String nfp(int num, int digits) {
+ return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
+ }
+ /**
+ * @param nums the numbers to format
+ */
+ static public String[] nfp(int nums[], int digits) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfp(nums[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;
+
+ /**
+ * @param left number of digits to the left of the decimal point
+ * @param right number of digits to the right of the decimal point
+ */
+ static public String[] nf(float nums[], int left, int right) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nf(nums[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);
+ }
+
+ /**
+ * @param right number of digits to the right of the decimal point
+ */
+ static public String[] nfc(float nums[], int right) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfc(nums[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);
+ }
+
+
+ /**
+ * @param left the number of digits to the left of the decimal point
+ * @param right the number of digits to the right of the decimal point
+ */
+ static public String[] nfs(float nums[], int left, int right) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfs(nums[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));
+ }
+
+ /**
+ * @param left the number of digits to the left of the decimal point
+ * @param right the number of digits to the right of the decimal point
+ */
+ static public String[] nfp(float nums[], int left, int right) {
+ String formatted[] = new String[nums.length];
+ for (int i = 0; i < formatted.length; i++) {
+ formatted[i] = nfp(nums[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
+
+
+ /**
+ * ( begin auto-generated from hex.xml )
+ *
+ * Converts a byte, char, int, or color to a String containing the
+ * equivalent hexadecimal notation. For example color(0, 102, 153) will
+ * convert to the String "FF006699". This function can help make your geeky
+ * debugging sessions much happier.
+ *
+ * Note that the maximum number of digits is 8, because an int value can
+ * only represent up to 32 bits. Specifying more than eight digits will
+ * simply shorten the string to eight anyway.
+ *
+ * ( end auto-generated )
+ * @webref data:conversion
+ * @param value the value to convert
+ * @see PApplet#unhex(String)
+ * @see PApplet#binary(byte)
+ * @see PApplet#unbinary(String)
+ */
+ static final public String hex(byte value) {
+ return hex(value, 2);
+ }
+
+ static final public String hex(char value) {
+ return hex(value, 4);
+ }
+
+ static final public String hex(int value) {
+ return hex(value, 8);
+ }
+/**
+ * @param digits the number of digits (maximum 8)
+ */
+ static final public String hex(int value, int digits) {
+ String stuff = Integer.toHexString(value).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;
+ }
+
+ /**
+ * ( begin auto-generated from unhex.xml )
+ *
+ * Converts a String representation of a hexadecimal number to its
+ * equivalent integer value.
+ *
+ * ( end auto-generated )
+ *
+ * @webref data:conversion
+ * @param value String to convert to an integer
+ * @see PApplet#hex(int, int)
+ * @see PApplet#binary(byte)
+ * @see PApplet#unbinary(String)
+ */
+ static final public int unhex(String value) {
+ // has to parse as a Long so that it'll work for numbers bigger than 2^31
+ return (int) (Long.parseLong(value, 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 value) {
+ return binary(value, 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 value) {
+ return binary(value, 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 value) {
+ return binary(value, 32);
+ }
+
+ /*
+ * Returns a String that contains the binary value of an int.
+ * The digits parameter determines how many digits will be used.
+ */
+
+ /**
+ * ( begin auto-generated from binary.xml )
+ *
+ * Converts a byte, char, int, or color to a String containing the
+ * equivalent binary notation. For example color(0, 102, 153, 255) will
+ * convert to the String "11111111000000000110011010011001". This function
+ * can help make your geeky debugging sessions much happier.
+ *
+ * Note that the maximum number of digits is 32, because an int value can
+ * only represent up to 32 bits. Specifying more than 32 digits will simply
+ * shorten the string to 32 anyway.
+ *
+ * ( end auto-generated )
+ * @webref data:conversion
+ * @param value value to convert
+ * @param digits number of digits to return
+ * @see PApplet#unbinary(String)
+ * @see PApplet#hex(int,int)
+ * @see PApplet#unhex(String)
+ */
+ static final public String binary(int value, int digits) {
+ String stuff = Integer.toBinaryString(value);
+ 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;
+ }
+
+
+ /**
+ * ( begin auto-generated from unbinary.xml )
+ *
+ * Converts a String representation of a binary number to its equivalent
+ * integer value. For example, unbinary("00001000") will return 8.
+ *
+ * ( end auto-generated )
+ * @webref data:conversion
+ * @param value String to convert to an integer
+ * @see PApplet#binary(byte)
+ * @see PApplet#hex(int,int)
+ * @see PApplet#unhex(String)
+ */
+ static final public int unbinary(String value) {
+ return Integer.parseInt(value, 2);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR FUNCTIONS
+
+ // moved here so that they can work without
+ // the graphics actually being instantiated (outside setup)
+
+
+ /**
+ * ( begin auto-generated from color.xml )
+ *
+ * Creates colors for storing in variables of the color datatype.
+ * The parameters are interpreted as RGB or HSB values depending on the
+ * current colorMode(). The default mode is RGB values from 0 to 255
+ * and therefore, the function call color(255, 204, 0) will return a
+ * bright yellow color. More about how colors are stored can be found in
+ * the reference for the color datatype.
+ *
+ * ( end auto-generated )
+ * @webref color:creating_reading
+ * @param gray number specifying value between white and black
+ * @see PApplet#colorMode(int)
+ */
+ 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);
+ }
+
+
+ /**
+ * @nowebref
+ * @param fgray number specifying value between white and black
+ */
+ public final int color(float fgray) {
+ if (g == null) {
+ int gray = (int) fgray;
+ if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
+ return 0xff000000 | (gray << 16) | (gray << 8) | gray;
+ }
+ return g.color(fgray);
+ }
+
+
+ /**
+ * As of 0116 this also takes color(#FF8800, alpha)
+ * @param alpha relative to current color range
+ */
+ 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);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ 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 (alpha << 24) | (gray << 16) | (gray << 8) | gray;
+ }
+ return g.color(fgray, falpha);
+ }
+
+
+ /**
+ * @param v1 red or hue values relative to the current color range
+ * @param v2 green or saturation values relative to the current color range
+ * @param v3 blue or brightness values relative to the current color range
+ */
+ public final int color(int v1, int v2, int v3) {
+ if (g == null) {
+ if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
+ if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
+ if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
+
+ return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
+ }
+ return g.color(v1, v2, v3);
+ }
+
+
+ public final int color(int v1, int v2, int v3, int alpha) {
+ if (g == null) {
+ if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
+ if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
+ if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
+ if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
+
+ return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
+ }
+ return g.color(v1, v2, v3, alpha);
+ }
+
+
+ public final int color(float v1, float v2, float v3) {
+ if (g == null) {
+ if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
+ if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
+ if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
+
+ return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
+ }
+ return g.color(v1, v2, v3);
+ }
+
+
+ public final int color(float v1, float v2, float v3, float alpha) {
+ if (g == null) {
+ if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
+ if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
+ if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
+ if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
+
+ return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
+ }
+ return g.color(v1, v2, v3, alpha);
+ }
+
+
+ /**
+ * ( begin auto-generated from lerpColor.xml )
+ *
+ * Calculates a color or colors between two color at a specific increment.
+ * The amt parameter is the amount to interpolate between the two
+ * values where 0.0 equal to the first point, 0.1 is very near the first
+ * point, 0.5 is half-way in between, etc.
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param c1 interpolate from this color
+ * @param c2 interpolate to this color
+ * @param amt between 0.0 and 1.0
+ * @see PImage#blendColor(int, int, int)
+ * @see PGraphics#color(float, float, float, float)
+ * @see PApplet#lerp(float, float, float)
+ */
+ public int lerpColor(int c1, int c2, float amt) {
+ if (g != null) {
+ return g.lerpColor(c1, c2, amt);
+ }
+ // use the default mode (RGB) if lerpColor is called before setup()
+ return PGraphics.lerpColor(c1, c2, amt, RGB);
+ }
+
+
+ static public int blendColor(int c1, int c2, int mode) {
+ return PImage.blendColor(c1, c2, mode);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ public void frameMoved(int x, int y) {
+ if (!fullScreen) {
+ System.err.println(EXTERNAL_MOVE + " " + x + " " + y);
+ System.err.flush(); // doesn't seem to help or hurt
+ }
+ }
+
+
+ public void frameResized(int w, int h) {
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MAIN
+
+
+ /**
+ * main() method for running this class from the command line.
+ *
The [options] are one or several of the parameters seen below.
+ *
The class name is required. If you're running outside the PDE and
+ * your class is in a package, this should include the full name. That means
+ * that if the class is called Sketchy and the package is com.sketchycompany
+ * then com.sketchycompany.Sketchy should be used as the class name.
+ *
The [sketch args] are any command line parameters you want to send to
+ * the sketch itself. These will be passed into the args[] array in PApplet.
+ *
+ * The simplest way to turn and sketch into an application is to
+ * add the following code to your program:
+ *
+ * That will properly launch your code 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 Presentation mode: blanks the entire screen and
+ * shows the sketch by itself. If the sketch is
+ * smaller than the screen, the background around it
+ * will use the --window-color setting.
+ *
+ * --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.
+ *
+ * --window-color=#xxxxxx Background color of the window. The color used
+ * around the sketch when it's smaller than the
+ * minimum window size for the OS, and the matte
+ * color when using 'present' mode.
+ *
+ * --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 sketch.
+ * Displays are numbered starting from 1. This will
+ * be overridden by fullScreen() calls that specify
+ * a display. Omitting this option will cause the
+ * default display to be used.
+ *
+ * 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
+ *
+ * All parameters *after* the sketch class name are passed to the sketch
+ * itself and available from its 'args' array while the sketch is running.
+ *
+ * @see PApplet#args
+ *
+ */
+ static public void main(final String[] args) {
+ runSketch(args, null);
+ }
+
+
+ /**
+ * Convenience method so that PApplet.main(YourSketch.class)
+ * launches a sketch, rather than having to call getName() on it.
+ */
+ static public void main(final Class> mainClass, String... args) {
+ main(mainClass.getName(), args);
+ }
+
+
+ /**
+ * Convenience method so that PApplet.main("YourSketch") launches a sketch,
+ * rather than having to wrap it into a single element String array.
+ * @param mainClass name of the class to load (with package if any)
+ */
+ static public void main(final String mainClass) {
+ main(mainClass, null);
+ }
+
+
+ /**
+ * Convenience method so that PApplet.main("YourSketch", args) launches a
+ * sketch, rather than having to wrap it into a String array, and appending
+ * the 'args' array when not null.
+ * @param mainClass name of the class to load (with package if any)
+ * @param sketchArgs command line arguments to pass to the sketch's 'args'
+ * array. Note that this is not the same as the args passed
+ * to (and understood by) PApplet such as --display.
+ */
+ static public void main(final String mainClass, final String[] sketchArgs) {
+ String[] args = new String[] { mainClass };
+ if (sketchArgs != null) {
+ args = concat(args, sketchArgs);
+ }
+ runSketch(args, null);
+ }
+
+
+ // Moving this back off the EDT for alpha 10. Not sure if we're helping or
+ // hurting, but unless we do, errors inside settings() are never passed
+ // through to the PDE. There are other ways around that, no doubt, but I'm
+ // also suspecting that these "not showing up" bugs might be EDT issues.
+ static public void runSketch(final String[] args,
+ final PApplet constructedSketch) {
+// EventQueue.invokeLater(new Runnable() {
+// public void run() {
+// runSketchEDT(args, constructedSketch);
+// }
+// });
+// }
+//
+//
+// /**
+// * Moving this to the EDT for 3.0a6 because that's the proper thing to do
+// * when messing with Swing components. But mostly we're AWT, so who knows.
+// */
+// static protected void runSketchEDT(final String[] args,
+// final PApplet constructedSketch) {
+ // Supposed to help with flicker, but no effect on OS X.
+ // TODO IIRC this helped on Windows, but need to double check.
+ System.setProperty("sun.awt.noerasebackground", "true");
+
+ // Remove 60fps limit on the JavaFX "pulse" timer
+ System.setProperty("javafx.animation.fullspeed", "true");
+
+ // Doesn't seem to do anything helpful here (that can't be done via Runner)
+ //System.setProperty("com.apple.mrj.application.apple.menu.about.name", "potato");
+
+ Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+ public void uncaughtException(Thread t, Throwable e) {
+ e.printStackTrace();
+ uncaughtThrowable = e;
+ }
+ });
+
+ // This doesn't work, need to mess with Info.plist instead
+ /*
+ // In an exported application, add the Contents/Java folder to the
+ // java.library.path, so that native libraries work properly.
+ // Without this, the library path is only set to Contents/MacOS
+ // where the launcher binary lives.
+ if (platform == MACOSX) {
+ URL coreJarURL =
+ PApplet.class.getProtectionDomain().getCodeSource().getLocation();
+ // The jarPath from above will/may be URL encoded (%20 for spaces)
+ String coreJarPath = urlDecode(coreJarURL.getPath());
+ if (coreJarPath.endsWith("/Contents/Java/core.jar")) {
+ // remove the /core.jar part from the end
+ String javaPath = coreJarPath.substring(0, coreJarPath.length() - 9);
+ String libraryPath = System.getProperty("java.library.path");
+ libraryPath += File.pathSeparator + javaPath;
+ System.setProperty("java.library.path", libraryPath);
+ }
+ }
+ */
+
+ // Catch any HeadlessException to provide more useful feedback
+ try {
+ // Call validate() while resize events are in progress
+ Toolkit.getDefaultToolkit().setDynamicLayout(true);
+ } catch (HeadlessException e) {
+ System.err.println("Cannot run sketch without a display. Read this for possible solutions:");
+ System.err.println("https://github.com/processing/processing/wiki/Running-without-a-Display");
+ System.exit(1);
+ }
+
+ // So that the system proxy setting are used by default
+ System.setProperty("java.net.useSystemProxies", "true");
+
+ if (args.length < 1) {
+ System.err.println("Usage: PApplet [options] [sketch args]");
+ System.err.println("See the Javadoc for PApplet for an explanation.");
+ System.exit(1);
+ }
+
+ boolean external = false;
+ int[] location = null;
+ int[] editorLocation = null;
+
+ String name = null;
+ int windowColor = 0;
+ int stopColor = 0xff808080;
+ boolean hideStop = false;
+
+ int displayNum = -1; // use default
+// boolean fullScreen = false;
+ boolean present = false;
+// boolean spanDisplays = false;
+ int density = -1;
+
+ String param = null, value = null;
+ String folder = calcSketchPath();
+
+ 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)) {
+ displayNum = parseInt(value, -1);
+ if (displayNum == -1) {
+ System.err.println("Could not parse " + value + " for " + ARGS_DISPLAY);
+ }
+
+ } else if (param.equals(ARGS_WINDOW_COLOR)) {
+ if (value.charAt(0) == '#' && value.length() == 7) {
+ value = value.substring(1);
+ windowColor = 0xff000000 | Integer.parseInt(value, 16);
+ } else {
+ System.err.println(ARGS_WINDOW_COLOR + " should be a # followed by six digits");
+ }
+
+ } else if (param.equals(ARGS_STOP_COLOR)) {
+ if (value.charAt(0) == '#' && value.length() == 7) {
+ value = value.substring(1);
+ stopColor = 0xff000000 | Integer.parseInt(value, 16);
+ } else {
+ System.err.println(ARGS_STOP_COLOR + " should be a # followed by six digits");
+ }
+
+ } else if (param.equals(ARGS_SKETCH_FOLDER)) {
+ folder = value;
+
+ } else if (param.equals(ARGS_LOCATION)) {
+ location = parseInt(split(value, ','));
+
+ } else if (param.equals(ARGS_DENSITY)) {
+ density = parseInt(value, -1);
+ if (density == -1) {
+ System.err.println("Could not parse " + value + " for " + ARGS_DENSITY);
+ } else if (density != 1 && density != 2) {
+ density = -1;
+ System.err.println(ARGS_DENSITY + " should be 1 or 2");
+ }
+ }
+
+ } else {
+ if (args[argIndex].equals(ARGS_PRESENT)) {
+ present = true;
+
+// } else if (args[argIndex].equals(ARGS_SPAN_DISPLAYS)) {
+// spanDisplays = 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; // because of break, argIndex won't increment again
+ }
+ }
+ argIndex++;
+ }
+
+// // Now that sketch path is passed in args after the sketch name
+// // it's not set in the above loop(the above loop breaks after
+// // finding sketch name). So setting sketch path here.
+// // https://github.com/processing/processing/commit/0a14835e6f5f4766b022e73a8fe562318636727c
+// // TODO this is a hack added for PDE X and needs to be removed [fry 141104]
+// for (int i = 0; i < args.length; i++) {
+// if (args[i].startsWith(ARGS_SKETCH_FOLDER)){
+// folder = args[i].substring(args[i].indexOf('=') + 1);
+// }
+// }
+
+ final PApplet sketch;
+ if (constructedSketch != null) {
+ sketch = constructedSketch;
+ } else {
+ try {
+ Class> c =
+ Thread.currentThread().getContextClassLoader().loadClass(name);
+ sketch = (PApplet) c.getDeclaredConstructor().newInstance();
+ } catch (RuntimeException re) {
+ // Don't re-package runtime exceptions
+ throw re;
+ } catch (Exception e) {
+ // Package non-runtime exceptions so we can throw them freely
+ throw new RuntimeException(e);
+ }
+ }
+
+ if (platform == MACOSX) {
+ try {
+ final String td = "processing.core.ThinkDifferent";
+ Class> thinkDifferent =
+ Thread.currentThread().getContextClassLoader().loadClass(td);
+ Method method =
+ thinkDifferent.getMethod("init", new Class[] { PApplet.class });
+ method.invoke(null, new Object[] { sketch });
+ } catch (Exception e) {
+ e.printStackTrace(); // That's unfortunate
+ }
+ }
+
+ // Set the suggested display that's coming from the command line
+ // (and most likely, from the PDE's preference setting).
+ sketch.display = displayNum;
+
+ // Set the suggested density that is coming from command line
+ // (most likely set from the PDE based on a system DPI scaling)
+ sketch.suggestedDensity = density;
+
+ sketch.present = present;
+
+ // For 3.0.1, moved this above handleSettings() so that loadImage() can be
+ // used inside settings(). Sets a terrible precedent, but the alternative
+ // of not being able to size a sketch to an image is driving people loopy.
+ // A handful of things that need to be set before init/start.
+// if (folder == null) {
+// folder = calcSketchPath();
+// }
+ sketch.sketchPath = folder;
+
+ // Don't set 'args' to a zero-length array if it should be null [3.0a8]
+ if (args.length != argIndex + 1) {
+ // pass everything after the class name in as args to the sketch itself
+ // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts)
+ sketch.args = PApplet.subset(args, argIndex + 1);
+ }
+
+ // Call the settings() method which will give us our size() call
+// try {
+ sketch.handleSettings();
+// } catch (Throwable t) {
+// System.err.println("I think I'm gonna hurl");
+// }
+
+//// sketch.spanDisplays = spanDisplays;
+// // If spanning screens, that means we're also full screen.
+//// fullScreen |= spanDisplays;
+// if (spanDisplays) {
+// displayIndex = SPAN;
+//// fullScreen = true;
+// }
+
+// // If the applet doesn't call for full screen, but the command line does,
+// // enable it. Conversely, if the command line does not, don't disable it.
+// // Query the applet to see if it wants to be full screen all the time.
+// //fullScreen |= sketch.sketchFullScreen();
+// sketch.fullScreen |= fullScreen;
+
+ sketch.external = external;
+
+ if (windowColor != 0) {
+ sketch.windowColor = windowColor;
+ }
+
+ final PSurface surface = sketch.initSurface();
+// sketch.initSurface(windowColor, displayIndex, fullScreen, spanDisplays);
+
+ /*
+ // Wait until the applet has figured out its width. In a static mode app,
+ // everything happens inside setup(), so this will be after setup() has
+ // completed, and the empty draw() has set "finished" to true.
+ while (sketch.defaultSize && !sketch.finished) {
+ //System.out.println("default size");
+ try {
+ Thread.sleep(5);
+
+ } catch (InterruptedException e) {
+ //System.out.println("interrupt");
+ }
+ }
+ */
+
+ if (present) {
+ if (hideStop) {
+ stopColor = 0; // they'll get the hint
+ }
+ surface.placePresent(stopColor);
+ } else {
+ surface.placeWindow(location, editorLocation);
+ }
+
+ // not always running externally when in present mode
+ // moved above setVisible() in 3.0 alpha 11
+ if (sketch.external) {
+ surface.setupExternalMessages();
+ }
+
+ sketch.showSurface();
+ sketch.startSurface();
+ /*
+ if (sketch.getGraphics().displayable()) {
+ surface.setVisible(true);
+ }
+
+ //sketch.init();
+ surface.startThread();
+ */
+ }
+
+
+ /** Danger: available for advanced subclassing, but here be dragons. */
+ protected void showSurface() {
+ if (getGraphics().displayable()) {
+ surface.setVisible(true);
+ }
+ }
+
+
+ /** See warning in showSurface() */
+ protected void startSurface() {
+ surface.startThread();
+ }
+
+
+ protected PSurface initSurface() {
+ g = createPrimaryGraphics();
+ surface = g.createSurface();
+
+ // Create fake Frame object to warn user about the changes
+ if (g.displayable()) {
+ frame = new Frame() {
+ @Override
+ public void setResizable(boolean resizable) {
+ deprecationWarning("setResizable");
+ surface.setResizable(resizable);
+ }
+
+ @Override
+ public void setVisible(boolean visible) {
+ deprecationWarning("setVisible");
+ surface.setVisible(visible);
+ }
+
+ @Override
+ public void setTitle(String title) {
+ deprecationWarning("setTitle");
+ surface.setTitle(title);
+ }
+
+ @Override
+ public void setUndecorated(boolean ignored) {
+ throw new RuntimeException("'frame' has been removed from Processing 3, " +
+ "use fullScreen() to get an undecorated full screen frame");
+ }
+
+ // Can't override this one because it's called by Window's constructor
+ /*
+ @Override
+ public void setLocation(int x, int y) {
+ deprecationWarning("setLocation");
+ surface.setLocation(x, y);
+ }
+ */
+
+ @Override
+ public void setSize(int w, int h) {
+ deprecationWarning("setSize");
+ surface.setSize(w, h);
+ }
+
+ private void deprecationWarning(String method) {
+ PGraphics.showWarning("Use surface." + method + "() instead of " +
+ "frame." + method + " in Processing 3");
+ //new Exception(method).printStackTrace(System.out);
+ }
+ };
+
+ surface.initFrame(this); //, backgroundColor, displayNum, fullScreen, spanDisplays);
+ surface.setTitle(getClass().getSimpleName());
+
+ } else {
+ surface.initOffscreen(this); // for PDF/PSurfaceNone and friends
+ }
+
+// init();
+ return surface;
+ }
+
+
+// protected void createSurface() {
+// surface = g.createSurface();
+// if (surface == null) {
+// System.err.println("This renderer needs to be updated for Processing 3");
+// System.err.println("The createSurface() method returned null.");
+// System.exit(1);
+// }
+// }
+
+
+// /**
+// * Return a Canvas object that can be embedded into other Java GUIs.
+// * This is necessary because PApplet no longer subclasses Component.
+// *
+// *
+// * PApplet sketch = new EmbedSketch();
+// * Canvas canvas = sketch.getCanvas();
+// * // add the canvas object to your project and validate() it
+// * sketch.init() // start the animation thread
+// */
+// public Component getComponent() {
+// g = createPrimaryGraphics();
+// surface = g.createSurface();
+// return surface.initComponent(this);
+// }
+
+
+ /** Convenience method, should only be called by PSurface subclasses. */
+ static public void hideMenuBar() {
+ if (PApplet.platform == PConstants.MACOSX) {
+ // Call some native code to remove the menu bar on OS X. Not necessary
+ // on Linux and Windows, who are happy to make full screen windows.
+ japplemenubar.JAppleMenuBar.hide();
+ }
+ }
+
+
+ /**
+ * Convenience method for Python Mode to run an already-constructed sketch.
+ * This makes it makes it easy to launch a sketch in Jython:
+ *
+ *
class MySketch(PApplet):
+ * pass
+ *
+ *MySketch().runSketch();
+ */
+ protected void runSketch(final String[] args) {
+ final String[] argsWithSketchName = new String[args.length + 1];
+ System.arraycopy(args, 0, argsWithSketchName, 0, args.length);
+ final String className = this.getClass().getSimpleName();
+ final String cleanedClass =
+ className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", "");
+ argsWithSketchName[args.length] = cleanedClass;
+ runSketch(argsWithSketchName, this);
+ }
+
+
+ /** Convenience method for Python Mode */
+ protected void runSketch() {
+ runSketch(new String[0]);
+ }
+
+ /** Convenience method for propane with jdk9 */
+ public void runPropane() {
+ runSketch(new String[0]);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * ( begin auto-generated from beginRecord.xml )
+ *
+ * Opens a new file and all subsequent drawing functions are echoed to this
+ * file as well as the display window. The beginRecord() function
+ * requires two parameters, the first is the renderer and the second is the
+ * file name. This function is always used with endRecord() to stop
+ * the recording process and close the file.
+ *
+ * Note that beginRecord() will only pick up any settings that happen after
+ * it has been called. For instance, if you call textFont() before
+ * beginRecord(), then that font will not be set for the file that you're
+ * recording to.
+ *
+ * ( end auto-generated )
+ *
+ * @webref output:files
+ * @param renderer PDF or SVG
+ * @param filename filename for output
+ * @see PApplet#endRecord()
+ */
+ public PGraphics beginRecord(String renderer, String filename) {
+ filename = insertFrame(filename);
+ PGraphics rec = createGraphics(width, height, renderer, filename);
+ beginRecord(rec);
+ return rec;
+ }
+
+
+ /**
+ * @nowebref
+ * Begin recording (echoing) commands to the specified PGraphics object.
+ */
+ public void beginRecord(PGraphics recorder) {
+ this.recorder = recorder;
+ recorder.beginDraw();
+ }
+
+
+ /**
+ * ( begin auto-generated from endRecord.xml )
+ *
+ * Stops the recording process started by beginRecord() and closes
+ * the file.
+ *
+ * ( end auto-generated )
+ * @webref output:files
+ * @see PApplet#beginRecord(String, String)
+ */
+ public void endRecord() {
+ if (recorder != null) {
+ recorder.endDraw();
+ recorder.dispose();
+ recorder = null;
+ }
+ }
+
+
+ /**
+ * ( begin auto-generated from beginRaw.xml )
+ *
+ * To create vectors from 3D data, use the beginRaw() and
+ * endRaw() commands. These commands will grab the shape data just
+ * before it is rendered to the screen. At this stage, your entire scene is
+ * nothing but a long list of individual lines and triangles. This means
+ * that a shape created with sphere() function will be made up of
+ * hundreds of triangles, rather than a single object. Or that a
+ * multi-segment line shape (such as a curve) will be rendered as
+ * individual segments.
+ *
+ * When using beginRaw() and endRaw(), it's possible to write
+ * to either a 2D or 3D renderer. For instance, beginRaw() with the
+ * PDF library will write the geometry as flattened triangles and lines,
+ * even if recording from the P3D renderer.
+ *
+ * If you want a background to show up in your files, use rect(0, 0,
+ * width, height) after setting the fill() to the background
+ * color. Otherwise the background will not be rendered to the file because
+ * the background is not shape.
+ *
+ * Using hint(ENABLE_DEPTH_SORT) can improve the appearance of 3D
+ * geometry drawn to 2D file formats. See the hint() reference for
+ * more details.
+ *
+ * See examples in the reference for the PDF and DXF
+ * libraries for more information.
+ *
+ * ( end auto-generated )
+ *
+ * @webref output:files
+ * @param renderer for example, PDF or DXF
+ * @param filename filename for output
+ * @see PApplet#endRaw()
+ * @see PApplet#hint(int)
+ */
+ public PGraphics beginRaw(String renderer, String filename) {
+ filename = insertFrame(filename);
+ PGraphics rec = createGraphics(width, height, renderer, filename);
+ g.beginRaw(rec);
+ return rec;
+ }
+
+
+
+ /**
+ * @nowebref
+ * 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.
+ *
+ * @param rawGraphics ???
+ */
+ public void beginRaw(PGraphics rawGraphics) {
+ g.beginRaw(rawGraphics);
+ }
+
+
+ /**
+ * ( begin auto-generated from endRaw.xml )
+ *
+ * Complement to beginRaw(); they must always be used together. See
+ * the beginRaw() reference for details.
+ *
+ * ( end auto-generated )
+ *
+ * @webref output:files
+ * @see PApplet#beginRaw(String, String)
+ */
+ public void endRaw() {
+ g.endRaw();
+ }
+
+
+ /**
+ * Starts shape recording and returns the PShape object that will
+ * contain the geometry.
+ */
+ /*
+ public PShape beginRecord() {
+ return g.beginRecord();
+ }
+ */
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * ( begin auto-generated from loadPixels.xml )
+ *
+ * Loads the pixel data for the display window into the pixels[]
+ * array. This function must always be called before reading from or
+ * writing to pixels[].
+ *
renderers may or may not seem to require loadPixels()
+ * or updatePixels(). However, the rule is that any time you want to
+ * manipulate the pixels[] array, you must first call
+ * loadPixels(), and after changes have been made, call
+ * updatePixels(). Even if the renderer may not seem to use this
+ * function in the current Processing release, this will always be subject
+ * to change.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Override the g.pixels[] function to set the pixels[] array
+ * that's part of the PApplet object. Allows the use of
+ * pixels[] in the code, rather than g.pixels[].
+ *
+ * @webref image:pixels
+ * @see PApplet#pixels
+ * @see PApplet#updatePixels()
+ */
+ public void loadPixels() {
+ g.loadPixels();
+ pixels = g.pixels;
+ }
+
+ /**
+ * ( begin auto-generated from updatePixels.xml )
+ *
+ * Updates the display window with the data in the pixels[] array.
+ * Use in conjunction with loadPixels(). If you're only reading
+ * pixels from the array, there's no need to call updatePixels()
+ * unless there are changes.
+ *
renderers may or may not seem to require loadPixels()
+ * or updatePixels(). However, the rule is that any time you want to
+ * manipulate the pixels[] array, you must first call
+ * loadPixels(), and after changes have been made, call
+ * updatePixels(). Even if the renderer may not seem to use this
+ * function in the current Processing release, this will always be subject
+ * to change.
+ *
+ * Currently, none of the renderers use the additional parameters to
+ * updatePixels(), however this may be implemented in the future.
+ *
+ * ( end auto-generated )
+ * @webref image:pixels
+ * @see PApplet#loadPixels()
+ * @see PApplet#pixels
+ */
+ public void updatePixels() {
+ g.updatePixels();
+ }
+
+ /**
+ * @nowebref
+ * @param x1 x-coordinate of the upper-left corner
+ * @param y1 y-coordinate of the upper-left corner
+ * @param x2 width of the region
+ * @param y2 height of the region
+ */
+ public void updatePixels(int x1, int y1, int x2, int y2) {
+ g.updatePixels(x1, y1, x2, y2);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH!
+ // This includes the Javadoc comments, which are automatically copied from
+ // the PImage and PGraphics source code files.
+
+ // public functions for processing.core
+
+
+ public PGL beginPGL() {
+ return g.beginPGL();
+ }
+
+
+ public void endPGL() {
+ if (recorder != null) recorder.endPGL();
+ g.endPGL();
+ }
+
+
+ public void flush() {
+ if (recorder != null) recorder.flush();
+ g.flush();
+ }
+
+
+ public void hint(int which) {
+ if (recorder != null) recorder.hint(which);
+ g.hint(which);
+ }
+
+
+ /**
+ * Start a new shape of type POLYGON
+ */
+ public void beginShape() {
+ if (recorder != null) recorder.beginShape();
+ g.beginShape();
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.beginShape(kind);
+ g.beginShape(kind);
+ }
+
+
+ /**
+ * Sets whether the upcoming vertex is part of an edge.
+ * Equivalent to glEdgeFlag(), for people familiar with OpenGL.
+ */
+ public void edge(boolean edge) {
+ if (recorder != null) recorder.edge(edge);
+ g.edge(edge);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.normal(nx, ny, nz);
+ g.normal(nx, ny, nz);
+ }
+
+
+ public void attribPosition(String name, float x, float y, float z) {
+ if (recorder != null) recorder.attribPosition(name, x, y, z);
+ g.attribPosition(name, x, y, z);
+ }
+
+
+ public void attribNormal(String name, float nx, float ny, float nz) {
+ if (recorder != null) recorder.attribNormal(name, nx, ny, nz);
+ g.attribNormal(name, nx, ny, nz);
+ }
+
+
+ public void attribColor(String name, int color) {
+ if (recorder != null) recorder.attribColor(name, color);
+ g.attribColor(name, color);
+ }
+
+
+ public void attrib(String name, float... values) {
+ if (recorder != null) recorder.attrib(name, values);
+ g.attrib(name, values);
+ }
+
+
+ public void attrib(String name, int... values) {
+ if (recorder != null) recorder.attrib(name, values);
+ g.attrib(name, values);
+ }
+
+
+ public void attrib(String name, boolean... values) {
+ if (recorder != null) recorder.attrib(name, 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) {
+ if (recorder != null) recorder.textureMode(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) {
+ if (recorder != null) recorder.textureWrap(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) {
+ if (recorder != null) recorder.texture(image);
+ g.texture(image);
+ }
+
+
+ /**
+ * Removes texture image for current shape.
+ * Needs to be called between beginShape and endShape
+ *
+ */
+ public void noTexture() {
+ if (recorder != null) recorder.noTexture();
+ g.noTexture();
+ }
+
+
+ public void vertex(float x, float y) {
+ if (recorder != null) recorder.vertex(x, y);
+ g.vertex(x, y);
+ }
+
+
+ public void vertex(float x, float y, float z) {
+ if (recorder != null) recorder.vertex(x, y, z);
+ g.vertex(x, y, z);
+ }
+
+
+ /**
+ * Used by renderer subclasses or PShape to efficiently pass in already
+ * formatted vertex information.
+ * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
+ */
+ public void vertex(float[] v) {
+ if (recorder != null) recorder.vertex(v);
+ g.vertex(v);
+ }
+
+
+ public void vertex(float x, float y, float u, float v) {
+ if (recorder != null) recorder.vertex(x, y, u, v);
+ g.vertex(x, y, u, v);
+ }
+
+
+/**
+ * ( 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) {
+ if (recorder != null) recorder.vertex(x, y, z, u, v);
+ g.vertex(x, y, z, u, v);
+ }
+
+
+ /**
+ * @webref shape:vertex
+ */
+ public void beginContour() {
+ if (recorder != null) recorder.beginContour();
+ g.beginContour();
+ }
+
+
+ /**
+ * @webref shape:vertex
+ */
+ public void endContour() {
+ if (recorder != null) recorder.endContour();
+ g.endContour();
+ }
+
+
+ public void endShape() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.endShape(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) {
+ if (recorder != null) recorder.shader(shader);
+ g.shader(shader);
+ }
+
+
+ /**
+ * @param kind type of shader, either POINTS, LINES, or TRIANGLES
+ */
+ public void shader(PShader shader, int kind) {
+ if (recorder != null) recorder.shader(shader, 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() {
+ if (recorder != null) recorder.resetShader();
+ g.resetShader();
+ }
+
+
+ /**
+ * @param kind type of shader, either POINTS, LINES, or TRIANGLES
+ */
+ public void resetShader(int kind) {
+ if (recorder != null) recorder.resetShader(kind);
+ g.resetShader(kind);
+ }
+
+
+ /**
+ * @param shader the fragment shader to apply
+ */
+ public void filter(PShader shader) {
+ if (recorder != null) recorder.filter(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) {
+ if (recorder != null) recorder.clip(a, b, c, 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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.blendMode(mode);
+ g.blendMode(mode);
+ }
+
+
+ public void bezierVertex(float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
+ g.bezierVertex(x2, y2, x3, y3, x4, y4);
+ }
+
+
+/**
+ * ( 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) {
+ if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ }
+
+
+ /**
+ * @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) {
+ if (recorder != null) recorder.quadraticVertex(cx, cy, x3, 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) {
+ if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, 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) {
+ if (recorder != null) recorder.curveVertex(x, y);
+ g.curveVertex(x, y);
+ }
+
+
+ /**
+ * @param z the z-coordinate of the vertex
+ */
+ public void curveVertex(float x, float y, float z) {
+ if (recorder != null) recorder.curveVertex(x, y, 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) {
+ if (recorder != null) recorder.point(x, y);
+ g.point(x, y);
+ }
+
+
+ /**
+ * @param z z-coordinate of the point
+ */
+ public void point(float x, float y, float z) {
+ if (recorder != null) recorder.point(x, y, 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) {
+ if (recorder != null) recorder.line(x1, y1, x2, 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) {
+ if (recorder != null) recorder.line(x1, y1, z1, x2, y2, 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) {
+ if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, 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) {
+ if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, 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) {
+ if (recorder != null) recorder.rectMode(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) {
+ if (recorder != null) recorder.rect(a, b, c, 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) {
+ if (recorder != null) recorder.rect(a, b, c, d, 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) {
+ if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl);
+ g.rect(a, b, c, d, tl, tr, br, bl);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.ellipseMode(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) {
+ if (recorder != null) recorder.ellipse(a, b, c, 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) {
+ if (recorder != null) recorder.arc(a, b, c, d, start, 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) {
+ if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode);
+ g.arc(a, b, c, d, start, stop, mode);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.box(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) {
+ if (recorder != null) recorder.box(w, h, 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) {
+ if (recorder != null) recorder.sphereDetail(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) {
+ if (recorder != null) recorder.sphereDetail(ures, 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) {
+ if (recorder != null) recorder.sphere(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) {
+ if (recorder != null) recorder.bezierDetail(detail);
+ g.bezierDetail(detail);
+ }
+
+
+ public void bezier(float x1, float y1,
+ float x2, float y2,
+ float x3, float y3,
+ float x4, float y4) {
+ if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ }
+
+
+ /**
+ * ( 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 points on the curve, and b and c are
+ * the control points. This can be done once with the x coordinates and a
+ * second time with the y coordinates to get the location of a curve at t.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:curves
+ * @param a coordinate of first point on the curve
+ * @param b coordinate of second point on the curve
+ * @param c coordinate of third point on the curve
+ * @param d coordinate of fourth point on the curve
+ * @param t value between 0 and 1
+ * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#curveVertex(float, float)
+ * @see PGraphics#bezierPoint(float, float, float, float, float)
+ */
+ public float curvePoint(float a, float b, float c, float d, float t) {
+ return g.curvePoint(a, b, c, d, t);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.curveDetail(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) {
+ if (recorder != null) recorder.curveTightness(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) {
+ if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, 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) {
+ if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.imageMode(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) {
+ if (recorder != null) recorder.image(img, a, 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) {
+ if (recorder != null) recorder.image(img, a, b, c, 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) {
+ if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, 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) {
+ if (recorder != null) recorder.shapeMode(mode);
+ g.shapeMode(mode);
+ }
+
+
+ public void shape(PShape shape) {
+ if (recorder != null) recorder.shape(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) {
+ if (recorder != null) recorder.shape(shape, x, 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) {
+ if (recorder != null) recorder.shape(shape, a, b, c, d);
+ g.shape(shape, a, b, c, d);
+ }
+
+
+ public void textAlign(int alignX) {
+ if (recorder != null) recorder.textAlign(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) {
+ if (recorder != null) recorder.textAlign(alignX, 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) {
+ if (recorder != null) recorder.textFont(which);
+ g.textFont(which);
+ }
+
+
+ /**
+ * @param size the size of the letters in units of pixels
+ */
+ public void textFont(PFont which, float size) {
+ if (recorder != null) recorder.textFont(which, 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) {
+ if (recorder != null) recorder.textLeading(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) {
+ if (recorder != null) recorder.textMode(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) {
+ if (recorder != null) recorder.textSize(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) {
+ if (recorder != null) recorder.text(c, x, y);
+ g.text(c, x, y);
+ }
+
+
+ /**
+ * @param z z-coordinate of text
+ */
+ public void text(char c, float x, float y, float z) {
+ if (recorder != null) recorder.text(c, x, y, z);
+ g.text(c, x, y, z);
+ }
+
+
+ /**
+ *
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) {
+ if (recorder != null) recorder.text(str, x, 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) {
+ if (recorder != null) recorder.text(chars, start, stop, x, y);
+ g.text(chars, start, stop, x, y);
+ }
+
+
+ /**
+ * Same as above but with a z coordinate.
+ */
+ public void text(String str, float x, float y, float z) {
+ if (recorder != null) recorder.text(str, x, y, z);
+ g.text(str, x, y, z);
+ }
+
+
+ public void text(char[] chars, int start, int stop,
+ float x, float y, float z) {
+ if (recorder != null) recorder.text(chars, start, stop, x, y, z);
+ g.text(chars, start, stop, x, y, z);
+ }
+
+
+ /**
+ *
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) {
+ if (recorder != null) recorder.text(str, x1, y1, x2, y2);
+ g.text(str, x1, y1, x2, y2);
+ }
+
+
+ public void text(int num, float x, float y) {
+ if (recorder != null) recorder.text(num, x, y);
+ g.text(num, x, y);
+ }
+
+
+ public void text(int num, float x, float y, float z) {
+ if (recorder != null) recorder.text(num, x, y, z);
+ g.text(num, x, y, z);
+ }
+
+
+ /**
+ * This does a basic number formatting, to avoid the
+ * generally ugly appearance of printing floats.
+ * Users who want more control should use their own nf() cmmand,
+ * or if they want the long, ugly version of float,
+ * use String.valueOf() to convert the float to a String first.
+ *
+ * @param num the numeric value to be displayed
+ */
+ public void text(float num, float x, float y) {
+ if (recorder != null) recorder.text(num, x, y);
+ g.text(num, x, y);
+ }
+
+
+ public void text(float num, float x, float y, float z) {
+ if (recorder != null) recorder.text(num, x, y, z);
+ g.text(num, x, y, z);
+ }
+
+
+ /**
+ * ( 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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.translate(x, y);
+ g.translate(x, y);
+ }
+
+
+ /**
+ * @param z forward/backward translation
+ */
+ public void translate(float x, float y, float z) {
+ if (recorder != null) recorder.translate(x, y, 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) {
+ if (recorder != null) recorder.rotate(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) {
+ if (recorder != null) recorder.rotateX(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) {
+ if (recorder != null) recorder.rotateY(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) {
+ if (recorder != null) recorder.rotateZ(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) {
+ if (recorder != null) recorder.rotate(angle, x, y, 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) {
+ if (recorder != null) recorder.scale(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) {
+ if (recorder != null) recorder.scale(x, 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) {
+ if (recorder != null) recorder.scale(x, y, 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) {
+ if (recorder != null) recorder.shearX(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) {
+ if (recorder != null) recorder.shearY(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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.applyMatrix(source);
+ g.applyMatrix(source);
+ }
+
+
+ public void applyMatrix(PMatrix2D source) {
+ if (recorder != null) recorder.applyMatrix(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) {
+ if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
+ g.applyMatrix(n00, n01, n02, n10, n11, n12);
+ }
+
+
+ public void applyMatrix(PMatrix3D source) {
+ if (recorder != null) recorder.applyMatrix(source);
+ g.applyMatrix(source);
+ }
+
+
+ /**
+ * @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) {
+ if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
+ g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
+ }
+
+
+ public PMatrix getMatrix() {
+ return g.getMatrix();
+ }
+
+
+ /**
+ * Copy the current transformation matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix2D getMatrix(PMatrix2D target) {
+ return g.getMatrix(target);
+ }
+
+
+ /**
+ * Copy the current transformation matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getMatrix(PMatrix3D target) {
+ return g.getMatrix(target);
+ }
+
+
+ /**
+ * Set the current transformation matrix to the contents of another.
+ */
+ public void setMatrix(PMatrix source) {
+ if (recorder != null) recorder.setMatrix(source);
+ g.setMatrix(source);
+ }
+
+
+ /**
+ * Set the current transformation to the contents of the specified source.
+ */
+ public void setMatrix(PMatrix2D source) {
+ if (recorder != null) recorder.setMatrix(source);
+ g.setMatrix(source);
+ }
+
+
+ /**
+ * Set the current transformation to the contents of the specified source.
+ */
+ public void setMatrix(PMatrix3D source) {
+ if (recorder != null) recorder.setMatrix(source);
+ g.setMatrix(source);
+ }
+
+
+ /**
+ * ( 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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
+ g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
+ }
+
+
+/**
+ * ( 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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.ortho(left, right, bottom, 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) {
+ if (recorder != null) recorder.ortho(left, right, bottom, top, near, 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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.perspective(fovy, aspect, zNear, 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) {
+ if (recorder != null) recorder.frustum(left, right, bottom, top, near, 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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.popStyle();
+ g.popStyle();
+ }
+
+
+ public void style(PStyle s) {
+ if (recorder != null) recorder.style(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) {
+ if (recorder != null) recorder.strokeWeight(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) {
+ if (recorder != null) recorder.strokeJoin(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) {
+ if (recorder != null) recorder.strokeCap(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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.stroke(rgb);
+ g.stroke(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the stroke
+ */
+ public void stroke(int rgb, float alpha) {
+ if (recorder != null) recorder.stroke(rgb, alpha);
+ g.stroke(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void stroke(float gray) {
+ if (recorder != null) recorder.stroke(gray);
+ g.stroke(gray);
+ }
+
+
+ public void stroke(float gray, float alpha) {
+ if (recorder != null) recorder.stroke(gray, alpha);
+ g.stroke(gray, alpha);
+ }
+
+
+ /**
+ * @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) {
+ if (recorder != null) recorder.stroke(v1, v2, v3);
+ g.stroke(v1, v2, v3);
+ }
+
+
+ public void stroke(float v1, float v2, float v3, float alpha) {
+ if (recorder != null) recorder.stroke(v1, v2, v3, 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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.tint(rgb);
+ g.tint(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the image
+ */
+ public void tint(int rgb, float alpha) {
+ if (recorder != null) recorder.tint(rgb, alpha);
+ g.tint(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void tint(float gray) {
+ if (recorder != null) recorder.tint(gray);
+ g.tint(gray);
+ }
+
+
+ public void tint(float gray, float alpha) {
+ if (recorder != null) recorder.tint(gray, alpha);
+ g.tint(gray, alpha);
+ }
+
+
+/**
+ * @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) {
+ if (recorder != null) recorder.tint(v1, v2, v3);
+ g.tint(v1, v2, v3);
+ }
+
+
+ public void tint(float v1, float v2, float v3, float alpha) {
+ if (recorder != null) recorder.tint(v1, v2, v3, 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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.fill(rgb);
+ g.fill(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the fill
+ */
+ public void fill(int rgb, float alpha) {
+ if (recorder != null) recorder.fill(rgb, alpha);
+ g.fill(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray number specifying value between white and black
+ */
+ public void fill(float gray) {
+ if (recorder != null) recorder.fill(gray);
+ g.fill(gray);
+ }
+
+
+ public void fill(float gray, float alpha) {
+ if (recorder != null) recorder.fill(gray, alpha);
+ g.fill(gray, alpha);
+ }
+
+
+ /**
+ * @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) {
+ if (recorder != null) recorder.fill(v1, v2, v3);
+ g.fill(v1, v2, v3);
+ }
+
+
+ public void fill(float v1, float v2, float v3, float alpha) {
+ if (recorder != null) recorder.fill(v1, v2, v3, 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) {
+ if (recorder != null) recorder.ambient(rgb);
+ g.ambient(rgb);
+ }
+
+
+/**
+ * @param gray number specifying value between white and black
+ */
+ public void ambient(float gray) {
+ if (recorder != null) recorder.ambient(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) {
+ if (recorder != null) recorder.ambient(v1, v2, 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) {
+ if (recorder != null) recorder.specular(rgb);
+ g.specular(rgb);
+ }
+
+
+/**
+ * gray number specifying value between white and black
+ */
+ public void specular(float gray) {
+ if (recorder != null) recorder.specular(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) {
+ if (recorder != null) recorder.specular(v1, v2, 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) {
+ if (recorder != null) recorder.shininess(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) {
+ if (recorder != null) recorder.emissive(rgb);
+ g.emissive(rgb);
+ }
+
+
+ /**
+ * gray number specifying value between white and black
+ */
+ public void emissive(float gray) {
+ if (recorder != null) recorder.emissive(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) {
+ if (recorder != null) recorder.emissive(v1, v2, 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() {
+ if (recorder != null) recorder.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() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.ambientLight(v1, v2, 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) {
+ if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, 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) {
+ if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, 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) {
+ if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, 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) {
+ if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, 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) {
+ if (recorder != null) recorder.lightFalloff(constant, linear, 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) {
+ if (recorder != null) recorder.lightSpecular(v1, v2, 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) {
+ if (recorder != null) recorder.background(rgb);
+ g.background(rgb);
+ }
+
+
+ /**
+ * @param alpha opacity of the background
+ */
+ public void background(int rgb, float alpha) {
+ if (recorder != null) recorder.background(rgb, alpha);
+ g.background(rgb, alpha);
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void background(float gray) {
+ if (recorder != null) recorder.background(gray);
+ g.background(gray);
+ }
+
+
+ public void background(float gray, float alpha) {
+ if (recorder != null) recorder.background(gray, 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) {
+ if (recorder != null) recorder.background(v1, v2, v3);
+ g.background(v1, v2, v3);
+ }
+
+
+ public void background(float v1, float v2, float v3, float alpha) {
+ if (recorder != null) recorder.background(v1, v2, v3, alpha);
+ g.background(v1, v2, v3, alpha);
+ }
+
+
+ /**
+ * @webref color:setting
+ */
+ public void clear() {
+ if (recorder != null) recorder.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) {
+ if (recorder != null) recorder.background(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) {
+ if (recorder != null) recorder.colorMode(mode);
+ g.colorMode(mode);
+ }
+
+
+ /**
+ * @param max range for all color elements
+ */
+ public void colorMode(int mode, float max) {
+ if (recorder != null) recorder.colorMode(mode, 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) {
+ if (recorder != null) recorder.colorMode(mode, max1, max2, 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) {
+ if (recorder != null) recorder.colorMode(mode, max1, max2, max3, 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) {
+ if (recorder != null) recorder.set(x, y, 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) {
+ if (recorder != null) recorder.set(x, y, 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) {
+ if (recorder != null) recorder.mask(img);
+ g.mask(img);
+ }
+
+
+ public void filter(int kind) {
+ if (recorder != null) recorder.filter(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) {
+ if (recorder != null) recorder.filter(kind, 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) {
+ if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, 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) {
+ if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
+ g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
+ }
+
+
+ public void blend(int sx, int sy, int sw, int sh,
+ int dx, int dy, int dw, int dh, int mode) {
+ if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
+ g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
+ }
+
+
+ /**
+ * ( 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) {
+ if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
+ g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
+ }
+}
diff --git a/src/main/java/processing/core/PConstants.java b/src/main/java/processing/core/PConstants.java
new file mode 100644
index 0000000..6792ec0
--- /dev/null
+++ b/src/main/java/processing/core/PConstants.java
@@ -0,0 +1,527 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2004-11 Ben Fry and Casey Reas
+ Copyright (c) 2001-04 Massachusetts Institute of Technology
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.awt.Cursor;
+import java.awt.event.KeyEvent;
+
+
+/**
+ * Numbers shared throughout processing.core.
+ *
+ * An attempt is made to keep the constants as short/non-verbose
+ * as possible. For instance, the constant is TIFF instead of
+ * FILE_TYPE_TIFF. We'll do this as long as we can get away with it.
+ *
+ * @usage Web & Application
+ */
+public interface PConstants {
+
+ static public final int X = 0;
+ static public final int Y = 1;
+ static public final int Z = 2;
+
+
+ // renderers known to processing.core
+
+ /*
+ // List of renderers used inside PdePreprocessor
+ static final StringList rendererList = new StringList(new String[] {
+ "JAVA2D", "JAVA2D_2X",
+ "P2D", "P2D_2X", "P3D", "P3D_2X", "OPENGL",
+ "E2D", "FX2D", "FX2D_2X", // experimental
+ "LWJGL.P2D", "LWJGL.P3D", // hmm
+ "PDF" // no DXF because that's only for beginRaw()
+ });
+ */
+
+ static final String JAVA2D = "processing.awt.PGraphicsJava2D";
+
+ static final String P2D = "processing.opengl.PGraphics2D";
+ static final String P3D = "processing.opengl.PGraphics3D";
+
+ // When will it be time to remove this?
+ @Deprecated
+ static final String OPENGL = P3D;
+
+ // Experimental, higher-performance Java 2D renderer (but no pixel ops)
+// static final String E2D = PGraphicsDanger2D.class.getName();
+
+ // Experimental JavaFX renderer; even better 2D performance
+ static final String FX2D = "processing.javafx.PGraphicsFX2D";
+
+ static final String PDF = "processing.pdf.PGraphicsPDF";
+ static final String SVG = "processing.svg.PGraphicsSVG";
+ static final String DXF = "processing.dxf.RawDXF";
+
+ // platform IDs for PApplet.platform
+
+ static final int OTHER = 0;
+ static final int WINDOWS = 1;
+ static final int MACOSX = 2;
+ static final int LINUX = 3;
+
+ static final String[] platformNames = {
+ "other", "windows", "macosx", "linux"
+ };
+
+
+ static final float EPSILON = 0.0001f;
+
+
+ // max/min values for numbers
+
+ /**
+ * Same as Float.MAX_VALUE, but included for parity with MIN_VALUE,
+ * and to avoid teaching static methods on the first day.
+ */
+ static final float MAX_FLOAT = Float.MAX_VALUE;
+ /**
+ * Note that Float.MIN_VALUE is the smallest positive value
+ * for a floating point number, not actually the minimum (negative) value
+ * for a float. This constant equals 0xFF7FFFFF, the smallest (farthest
+ * negative) value a float can have before it hits NaN.
+ */
+ static final float MIN_FLOAT = -Float.MAX_VALUE;
+ /** Largest possible (positive) integer value */
+ static final int MAX_INT = Integer.MAX_VALUE;
+ /** Smallest possible (negative) integer value */
+ static final int MIN_INT = Integer.MIN_VALUE;
+
+ // 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
+
+ /**
+ * ( begin auto-generated from PI.xml )
+ *
+ * PI is a mathematical constant with the value 3.14159265358979323846. It
+ * is the ratio of the circumference of a circle to its diameter. It is
+ * useful in combination with the trigonometric functions sin() and
+ * cos().
+ *
+ * ( end auto-generated )
+ * @webref constants
+ * @see PConstants#TWO_PI
+ * @see PConstants#TAU
+ * @see PConstants#HALF_PI
+ * @see PConstants#QUARTER_PI
+ *
+ */
+ static final float PI = (float) Math.PI;
+ /**
+ * ( begin auto-generated from HALF_PI.xml )
+ *
+ * HALF_PI is a mathematical constant with the value
+ * 1.57079632679489661923. It is half the ratio of the circumference of a
+ * circle to its diameter. It is useful in combination with the
+ * trigonometric functions sin() and cos().
+ *
+ * ( end auto-generated )
+ * @webref constants
+ * @see PConstants#PI
+ * @see PConstants#TWO_PI
+ * @see PConstants#TAU
+ * @see PConstants#QUARTER_PI
+ */
+ static final float HALF_PI = (float) (Math.PI / 2.0);
+ static final float THIRD_PI = (float) (Math.PI / 3.0);
+ /**
+ * ( begin auto-generated from QUARTER_PI.xml )
+ *
+ * QUARTER_PI is a mathematical constant with the value 0.7853982. It is
+ * one quarter the ratio of the circumference of a circle to its diameter.
+ * It is useful in combination with the trigonometric functions
+ * sin() and cos().
+ *
+ * ( end auto-generated )
+ * @webref constants
+ * @see PConstants#PI
+ * @see PConstants#TWO_PI
+ * @see PConstants#TAU
+ * @see PConstants#HALF_PI
+ */
+ static final float QUARTER_PI = (float) (Math.PI / 4.0);
+ /**
+ * ( begin auto-generated from TWO_PI.xml )
+ *
+ * TWO_PI is a mathematical constant with the value 6.28318530717958647693.
+ * It is twice the ratio of the circumference of a circle to its diameter.
+ * It is useful in combination with the trigonometric functions
+ * sin() and cos().
+ *
+ * ( end auto-generated )
+ * @webref constants
+ * @see PConstants#PI
+ * @see PConstants#TAU
+ * @see PConstants#HALF_PI
+ * @see PConstants#QUARTER_PI
+ */
+ static final float TWO_PI = (float) (2.0 * Math.PI);
+ /**
+ * ( begin auto-generated from TAU.xml )
+ *
+ * TAU is an alias for TWO_PI, a mathematical constant with the value
+ * 6.28318530717958647693. It is twice the ratio of the circumference
+ * of a circle to its diameter. It is useful in combination with the
+ * trigonometric functions sin() and cos().
+ *
+ * ( end auto-generated )
+ * @webref constants
+ * @see PConstants#PI
+ * @see PConstants#TWO_PI
+ * @see PConstants#HALF_PI
+ * @see PConstants#QUARTER_PI
+ */
+ static final float TAU = (float) (2.0 * Math.PI);
+
+ static final float DEG_TO_RAD = PI/180.0f;
+ static final float RAD_TO_DEG = 180.0f/PI;
+
+
+ // angle modes
+
+ //static final int RADIANS = 0;
+ //static final int DEGREES = 1;
+
+
+ // used by split, all the standard whitespace chars
+ // (also includes unicode nbsp, that little bostage)
+
+ static final String WHITESPACE = " \t\n\r\f\u00A0";
+
+
+ // for colors and/or images
+
+ static final int RGB = 1; // image & color
+ static final int ARGB = 2; // image
+ static final int HSB = 3; // color
+ static final int ALPHA = 4; // image
+// static final int CMYK = 5; // image & color (someday)
+
+
+ // image file types
+
+ static final int TIFF = 0;
+ static final int TARGA = 1;
+ static final int JPEG = 2;
+ static final int GIF = 3;
+
+
+ // filter/convert types
+
+ static final int BLUR = 11;
+ static final int GRAY = 12;
+ static final int INVERT = 13;
+ static final int OPAQUE = 14;
+ static final int POSTERIZE = 15;
+ static final int THRESHOLD = 16;
+ static final int ERODE = 17;
+ static final int DILATE = 18;
+
+
+ // blend mode keyword definitions
+ // @see processing.core.PImage#blendColor(int,int,int)
+
+ public final static int REPLACE = 0;
+ public final static int BLEND = 1 << 0;
+ public final static int ADD = 1 << 1;
+ public final static int SUBTRACT = 1 << 2;
+ public final static int LIGHTEST = 1 << 3;
+ public final static int DARKEST = 1 << 4;
+ public final static int DIFFERENCE = 1 << 5;
+ public final static int EXCLUSION = 1 << 6;
+ public final static int MULTIPLY = 1 << 7;
+ public final static int SCREEN = 1 << 8;
+ public final static int OVERLAY = 1 << 9;
+ public final static int HARD_LIGHT = 1 << 10;
+ public final static int SOFT_LIGHT = 1 << 11;
+ public final static int DODGE = 1 << 12;
+ public final static int BURN = 1 << 13;
+
+ // 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 POINT_SPRITES = 52;
+// static public final int NON_STROKED_SHAPE = 60;
+// static public final int STROKED_SHAPE = 61;
+
+
+ // 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;
+ /**
+ * 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;
+
+
+ // 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 = 8;
+ static final char TAB = 9;
+ static final char ENTER = 10;
+ static final char RETURN = 13;
+ static final char ESC = 27;
+ static final char DELETE = 127;
+
+ // i.e. if ((key == CODED) && (keyCode == UP))
+ static final int CODED = 0xffff;
+
+ // key will be CODED and keyCode will be this value
+ static final int UP = KeyEvent.VK_UP;
+ static final int DOWN = KeyEvent.VK_DOWN;
+ static final int LEFT = KeyEvent.VK_LEFT;
+ static final int RIGHT = KeyEvent.VK_RIGHT;
+
+ // key will be CODED and keyCode will be this value
+ static final int ALT = KeyEvent.VK_ALT;
+ static final int CONTROL = KeyEvent.VK_CONTROL;
+ static final int SHIFT = KeyEvent.VK_SHIFT;
+
+
+ // orientations (only used on Android, ignored on desktop)
+
+ /** 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;
+
+ /** Use with fullScreen() to indicate all available displays. */
+ static final int SPAN = 0;
+
+ // cursor types
+
+ static final int ARROW = Cursor.DEFAULT_CURSOR;
+ static final int CROSS = Cursor.CROSSHAIR_CURSOR;
+ static final int HAND = Cursor.HAND_CURSOR;
+ static final int MOVE = Cursor.MOVE_CURSOR;
+ static final int TEXT = Cursor.TEXT_CURSOR;
+ static final int WAIT = Cursor.WAIT_CURSOR;
+
+
+ // hints - hint values are positive for the alternate version,
+ // negative of the same value returns to the normal/default state
+
+ @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;
+}
diff --git a/src/main/java/processing/core/PFont.java b/src/main/java/processing/core/PFont.java
new file mode 100644
index 0000000..632cd7e
--- /dev/null
+++ b/src/main/java/processing/core/PFont.java
@@ -0,0 +1,1098 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-15 The Processing Foundation
+ Copyright (c) 2004-12 Ben Fry & Casey Reas
+ Copyright (c) 2001-04 Massachusetts Institute of Technology
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of version 2.01 of the GNU Lesser General
+ Public License as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.awt.*;
+import java.awt.font.FontRenderContext;
+import java.awt.font.GlyphVector;
+import java.awt.geom.PathIterator;
+import java.awt.image.*;
+import java.io.*;
+import java.util.Arrays;
+import java.util.HashMap;
+
+
+/**
+ * Grayscale bitmap font class used by Processing.
+ *
+ * Awful (and by that, I mean awesome) ASCII (non-)art for how this works:
+ *
+ * |
+ * | height is the full used height of the image
+ * |
+ * | ..XX.. }
+ * | ..XX.. }
+ * | ...... }
+ * | XXXX.. } topExtent (top y is baseline - topExtent)
+ * | ..XX.. }
+ * | ..XX.. } dotted areas are where the image data
+ * | ..XX.. } is actually located for the character
+ * +---XXXXXX---- } (it extends to the right and down
+ * | for power of two texture sizes)
+ * ^^^^ leftExtent (amount to move over before drawing the image
+ *
+ * ^^^^^^^^^^^^^^ setWidth (width displaced by char)
+ *
+ * @webref typography
+ * @see PApplet#loadFont(String)
+ * @see PApplet#createFont(String, float, boolean, char[])
+ * @see PGraphics#textFont(PFont)
+ */
+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;
+
+ /** Default density set to 1 for backwards compatibility with loadFont(). */
+ protected int density = 1;
+
+ /** true if smoothing was enabled for this font, used for native impl */
+ protected boolean smooth;
+
+ /**
+ * The ascent of the font. If the 'd' character is present in this PFont,
+ * this value is replaced with its pixel height, because the values returned
+ * by FontMetrics.getAscent() seem to be terrible.
+ */
+ protected int ascent;
+
+ /**
+ * The descent of the font. If the 'p' character is present in this PFont,
+ * this value is replaced with its lowest pixel height, because the values
+ * returned by FontMetrics.getDescent() are gross.
+ */
+ protected int descent;
+
+ /**
+ * A more efficient array lookup for straight ASCII characters. For Unicode
+ * characters, a QuickSort-style search is used.
+ */
+ protected int[] ascii;
+
+ /**
+ * True if this font is set to load dynamically. This is the default when
+ * createFont() method is called without a character set. Bitmap versions of
+ * characters are only created when prompted by an index() call.
+ */
+ protected boolean lazy;
+
+ /**
+ * Native Java version of the font. If possible, this allows the
+ * PGraphics subclass to just use Java's font rendering stuff
+ * in situations where that's faster.
+ */
+ protected Font font;
+
+ /**
+ * True if this font was loaded from an InputStream, rather than by name
+ * from the OS. It's best to use the native version of a font loaded from
+ * a TTF file, since that will ensure that the font is available when the
+ * sketch is exported.
+ */
+ protected boolean stream;
+
+ /**
+ * 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 already tried to find the native AWT version of this font. */
+ protected boolean fontSearched;
+
+ /**
+ * Array of the native system fonts. Used to lookup native fonts by their
+ * PostScript name. This is a workaround for a several year old Apple Java
+ * bug that they can't be bothered to fix.
+ */
+ static protected Font[] fonts;
+ static protected HashMap fontDifferent;
+
+// /**
+// * If not null, 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 Font lazyFont;
+ protected BufferedImage lazyImage;
+ protected Graphics2D lazyGraphics;
+ protected FontMetrics lazyMetrics;
+ protected int[] lazySamples;
+
+
+ /** for subclasses that need to store metadata about the font */
+// protected HashMap cacheMap;
+
+ /**
+ * @nowebref
+ */
+ public PFont() { } // for subclasses
+
+
+ /**
+ * ( begin auto-generated from PFont.xml )
+ *
+ * PFont is the font class for Processing. To create a font to use with
+ * Processing, select "Create Font..." from the Tools menu. This will
+ * create a font in the format Processing requires and also adds it to the
+ * current sketch's data directory. Processing displays fonts using the
+ * .vlw font format, which uses images for each letter, rather than
+ * defining them through vector data. The loadFont() function
+ * constructs a new font and textFont() makes a font active. The
+ * list() method creates a list of the fonts installed on the
+ * computer, which is useful information to use with the
+ * createFont() function for dynamically converting fonts into a
+ * format to use with Processing.
+ *
+ * ( end auto-generated )
+ *
+ * @nowebref
+ * @param font font the font object to create from
+ * @param smooth smooth true to enable smoothing/anti-aliasing
+ */
+ public PFont(Font font, boolean smooth) {
+ this(font, smooth, null);
+ }
+
+
+ /**
+ * Create a new image-based font on the fly. If charset is set to null,
+ * the characters will only be created as bitmaps when they're drawn.
+ *
+ * @nowebref
+ * @param charset array of all unicode chars that should be included
+ */
+ public PFont(Font font, boolean smooth, char charset[]) {
+ // save this so that we can use the native version
+ this.font = font;
+ this.smooth = smooth;
+
+ name = font.getName();
+ psname = font.getPSName();
+ size = font.getSize();
+
+ // no, i'm not interested in getting off the couch
+ //lazy = true;
+ // not sure what else to do here
+ //mbox2 = 0;
+
+ int initialCount = 10;
+ glyphs = new Glyph[initialCount];
+
+ ascii = new int[128];
+ Arrays.fill(ascii, -1);
+
+ int mbox3 = size * 3;
+
+ lazyImage = new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB);
+ lazyGraphics = (Graphics2D) lazyImage.getGraphics();
+ lazyGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ smooth ?
+ RenderingHints.VALUE_ANTIALIAS_ON :
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ // adding this for post-1.0.9
+ lazyGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+ smooth ?
+ RenderingHints.VALUE_TEXT_ANTIALIAS_ON :
+ RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
+
+ lazyGraphics.setFont(font);
+ lazyMetrics = lazyGraphics.getFontMetrics();
+ lazySamples = new int[mbox3 * mbox3];
+
+ // These values are terrible/unusable. Verified again for Processing 1.1.
+ // They vary widely per-platform and per-font, so instead we'll use the
+ // calculate-by-hand method of measuring pixels in characters.
+ //ascent = lazyMetrics.getAscent();
+ //descent = lazyMetrics.getDescent();
+
+ if (charset == null) {
+ lazy = true;
+// lazyFont = font;
+
+ } else {
+ // charset needs to be sorted to make index lookup run more quickly
+ // http://dev.processing.org/bugs/show_bug.cgi?id=494
+ Arrays.sort(charset);
+
+ glyphs = new Glyph[charset.length];
+
+ glyphCount = 0;
+ for (char c : charset) {
+ if (font.canDisplay(c)) {
+ Glyph glyf = new Glyph(c);
+ if (glyf.value < 128) {
+ ascii[glyf.value] = glyphCount;
+ }
+ glyf.index = glyphCount;
+ glyphs[glyphCount++] = glyf;
+ }
+ }
+
+ // shorten the array if necessary
+ if (glyphCount != charset.length) {
+ glyphs = (Glyph[]) PApplet.subset(glyphs, 0, glyphCount);
+ }
+
+ // foreign font, so just make ascent the max topExtent
+ // for > 1.0.9, not doing this anymore.
+ // instead using getAscent() and getDescent() values for these cases.
+// if ((ascent == 0) && (descent == 0)) {
+// //for (int i = 0; i < charCount; i++) {
+// for (Glyph glyph : glyphs) {
+// char cc = (char) glyph.value;
+// //char cc = (char) glyphs[i].value;
+// if (Character.isWhitespace(cc) ||
+// (cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) {
+// continue;
+// }
+// if (glyph.topExtent > ascent) {
+// ascent = glyph.topExtent;
+// }
+// int d = -glyph.topExtent + glyph.height;
+// if (d > descent) {
+// descent = d;
+// }
+// }
+// }
+ }
+
+ // If not already created, just create these two characters to calculate
+ // the ascent and descent values for the font. This was tested to only
+ // require 5-10 ms on a 2.4 GHz MacBook Pro.
+ // In versions 1.0.9 and earlier, fonts that could not display d or p
+ // used the max up/down values as calculated by looking through the font.
+ // That's no longer valid with the auto-generating fonts, so we'll just
+ // use getAscent() and getDescent() in such (minor) cases.
+ if (ascent == 0) {
+ if (font.canDisplay('d')) {
+ new Glyph('d');
+ } else {
+ ascent = lazyMetrics.getAscent();
+ }
+ }
+ if (descent == 0) {
+ if (font.canDisplay('p')) {
+ new Glyph('p');
+ } else {
+ descent = lazyMetrics.getDescent();
+ }
+ }
+ }
+
+
+ /**
+ * Adds an additional parameter that indicates the font came from a file,
+ * not a built-in OS font.
+ *
+ * @nowebref
+ */
+ public PFont(Font font, boolean smooth, char charset[],
+ boolean stream, int density) {
+ this(font, smooth, charset);
+ this.stream = stream;
+ this.density = density;
+ }
+
+ /**
+ * @nowebref
+ * @param input InputStream
+ */
+ 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();
+ }
+ // See if there's a native version of this font that can be used,
+ // in case that's of interest later.
+// findNative();
+ }
+
+
+ /**
+ * 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;
+ }
+
+
+ public String getPostScriptName() {
+ return psname;
+ }
+
+
+ /**
+ * Set the native complement of this font. Might be set internally via the
+ * findFont() function, or externally by a deriveFont() call if the font
+ * is resized by PGraphicsJava2D.
+ */
+ public void setNative(Object font) {
+ this.font = (Font) font;
+ }
+
+
+ /**
+ * Use the getNative() method instead, which allows library interfaces to be
+ * written in a cross-platform fashion for desktop, Android, and others.
+ */
+ @Deprecated
+ public Font getFont() {
+ return font;
+ }
+
+
+ /**
+ * Return the native java.awt.Font associated with this PFont (if any).
+ */
+ public Object getNative() {
+ if (subsetting) {
+ return null; // don't return the font for use
+ }
+ return font;
+ }
+
+
+ /**
+ * Return size of this font.
+ */
+ public int getSize() {
+ return size;
+ }
+
+
+// public void setDefaultSize(int size) {
+// defaultSize = size;
+// }
+
+
+ /**
+ * Returns the size that will be used when textFont(font) is called.
+ * When drawing with 2x pixel density, bitmap fonts in OpenGL need to be
+ * created (behind the scenes) at double the requested size. This ensures
+ * that they're shown at half on displays (so folks don't have to change
+ * their sketch code).
+ */
+ public int getDefaultSize() {
+ //return defaultSize;
+ return size / density;
+ }
+
+
+ public boolean isSmooth() {
+ return smooth;
+ }
+
+
+ public boolean isStream() {
+ return stream;
+ }
+
+
+ public void setSubsetting() {
+ subsetting = true;
+ }
+
+
+ /**
+ * Attempt to find the native version of this font.
+ * (Public so that it can be used by OpenGL or other renderers.)
+ */
+ public Object findNative() {
+ if (font == null) {
+ if (!fontSearched) {
+ // this font may or may not be installed
+ font = new Font(name, Font.PLAIN, size);
+ // if the ps name matches, then we're in fine shape
+ if (!font.getPSName().equals(psname)) {
+ // on osx java 1.4 (not 1.3.. ugh), you can specify the ps name
+ // of the font, so try that in case this .vlw font was created on pc
+ // and the name is different, but the ps name is found on the
+ // java 1.4 mac that's currently running this sketch.
+ font = new Font(psname, Font.PLAIN, size);
+ }
+ // check again, and if still bad, screw em
+ if (!font.getPSName().equals(psname)) {
+ font = null;
+ }
+ fontSearched = true;
+ }
+ }
+ return font;
+ }
+
+
+ public Glyph getGlyph(char c) {
+ int index = index(c);
+ return (index == -1) ? null : glyphs[index];
+ }
+
+
+ /**
+ * Get index for the character.
+ * @return index into arrays or -1 if not found
+ */
+ protected int index(char c) {
+ if (lazy) {
+ int index = indexActual(c);
+ if (index != -1) {
+ return index;
+ }
+ if (font != null && 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);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ public int getGlyphCount() {
+ return glyphCount;
+ }
+
+
+ public Glyph getGlyph(int i) {
+ return glyphs[i];
+ }
+
+
+ public PShape getShape(char ch) {
+ return getShape(ch, 0);
+ }
+
+
+ public PShape getShape(char ch, float detail) {
+ Font font = (Font) getNative();
+ if (font == null) {
+ throw new IllegalArgumentException("getShape() only works on fonts loaded with createFont()");
+ }
+
+ PShape s = new PShape(PShape.PATH);
+
+ // six element array received from the Java2D path iterator
+ float[] iterPoints = new float[6];
+ // array passed to createGylphVector
+ char[] textArray = new char[] { ch };
+
+ //Graphics2D graphics = (Graphics2D) this.getGraphics();
+ //FontRenderContext frc = graphics.getFontRenderContext();
+ @SuppressWarnings("deprecation")
+ FontRenderContext frc =
+ Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext();
+ GlyphVector gv = font.createGlyphVector(frc, textArray);
+ Shape shp = gv.getOutline();
+ // make everything into moveto and lineto
+ PathIterator iter = (detail == 0) ?
+ shp.getPathIterator(null) : // maintain curves
+ shp.getPathIterator(null, detail); // convert to line segments
+
+ int contours = 0;
+ //boolean outer = true;
+// boolean contour = false;
+ while (!iter.isDone()) {
+ int type = iter.currentSegment(iterPoints);
+ switch (type) {
+ case PathIterator.SEG_MOVETO: // 1 point (2 vars) in textPoints
+// System.out.println("moveto");
+// if (!contour) {
+ if (contours == 0) {
+ s.beginShape();
+ } else {
+ s.beginContour();
+// contour = true;
+ }
+ contours++;
+ s.vertex(iterPoints[0], iterPoints[1]);
+ break;
+
+ case PathIterator.SEG_LINETO: // 1 point
+// System.out.println("lineto");
+// PApplet.println(PApplet.subset(iterPoints, 0, 2));
+ s.vertex(iterPoints[0], iterPoints[1]);
+ break;
+
+ case PathIterator.SEG_QUADTO: // 2 points
+// System.out.println("quadto");
+// PApplet.println(PApplet.subset(iterPoints, 0, 4));
+ s.quadraticVertex(iterPoints[0], iterPoints[1],
+ iterPoints[2], iterPoints[3]);
+ break;
+
+ case PathIterator.SEG_CUBICTO: // 3 points
+// System.out.println("cubicto");
+// PApplet.println(iterPoints);
+ s.quadraticVertex(iterPoints[0], iterPoints[1],
+ iterPoints[2], iterPoints[3],
+ iterPoints[4], iterPoints[5]);
+ break;
+
+ case PathIterator.SEG_CLOSE:
+// System.out.println("close");
+ if (contours > 1) {
+// contours--;
+// if (contours == 0) {
+//// s.endShape();
+// } else {
+ s.endContour();
+ }
+ break;
+ }
+// PApplet.println(iterPoints);
+ iter.next();
+ }
+ s.endShape(CLOSE);
+ return s;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ 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];
+ }
+ };
+
+
+ /**
+ * ( begin auto-generated from PFont_list.xml )
+ *
+ * Gets a list of the fonts installed on the system. The data is returned
+ * as a String array. This list provides the names of each font for input
+ * into createFont(), which allows Processing to dynamically format
+ * fonts. This function is meant as a tool for programming local
+ * applications and is not recommended for use in applets.
+ *
+ * ( end auto-generated )
+ *
+ * @webref pfont
+ * @usage application
+ * @brief Gets a list of the fonts installed on the system
+ */
+ static public String[] list() {
+ loadFonts();
+ String list[] = new String[fonts.length];
+ for (int i = 0; i < list.length; i++) {
+ list[i] = fonts[i].getName();
+ }
+ return list;
+ }
+
+
+ static public void loadFonts() {
+ if (fonts == null) {
+ GraphicsEnvironment ge =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+ fonts = ge.getAllFonts();
+ if (PApplet.platform == PConstants.MACOSX) {
+ fontDifferent = new HashMap();
+ for (Font font : fonts) {
+ // getName() returns the PostScript name on OS X 10.6 w/ Java 6.
+ fontDifferent.put(font.getName(), font);
+ //fontDifferent.put(font.getPSName(), font);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Starting with Java 1.5, Apple broke the ability to specify most fonts.
+ * This bug was filed years ago as #4769141 at bugreporter.apple.com. More:
+ * Bug 407.
+ */
+ static public Font findFont(String name) {
+ loadFonts();
+ if (PApplet.platform == PConstants.MACOSX) {
+ Font maybe = fontDifferent.get(name);
+ if (maybe != null) {
+ return maybe;
+ }
+// for (int i = 0; i < fonts.length; i++) {
+// if (name.equals(fonts[i].getName())) {
+// return fonts[i];
+// }
+// }
+ }
+ return new Font(name, Font.PLAIN, 1);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * A single character, and its visage.
+ */
+ public class Glyph {
+ 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 Glyph() {
+ index = -1;
+ // used when reading from a stream or for subclasses
+ }
+
+
+ public Glyph(DataInputStream is) throws IOException {
+ index = -1;
+ readHeader(is);
+ }
+
+
+ protected void readHeader(DataInputStream is) throws IOException {
+ value = is.readInt();
+ height = is.readInt();
+ width = is.readInt();
+ setWidth = is.readInt();
+ topExtent = is.readInt();
+ leftExtent = is.readInt();
+
+ // pointer from a struct in the c version, ignored
+ is.readInt();
+
+ // the values for getAscent() and getDescent() from FontMetrics
+ // seem to be way too large.. perhaps they're the max?
+ // as such, use a more traditional marker for ascent/descent
+ if (value == 'd') {
+ if (ascent == 0) ascent = topExtent;
+ }
+ if (value == 'p') {
+ if (descent == 0) descent = -topExtent + height;
+ }
+ }
+
+
+ protected void writeHeader(DataOutputStream os) throws IOException {
+ os.writeInt(value);
+ os.writeInt(height);
+ os.writeInt(width);
+ os.writeInt(setWidth);
+ os.writeInt(topExtent);
+ os.writeInt(leftExtent);
+ os.writeInt(0); // padding
+ }
+
+
+ protected void readBitmap(DataInputStream is) throws IOException {
+ image = new PImage(width, height, ALPHA);
+ int bitmapSize = width * height;
+
+ byte[] temp = new byte[bitmapSize];
+ is.readFully(temp);
+
+ // convert the bitmap to an alpha channel
+ int w = width;
+ int h = height;
+ int[] pixels = image.pixels;
+ for (int y = 0; y < h; y++) {
+ for (int x = 0; x < w; x++) {
+ pixels[y * width + x] = temp[y*w + x] & 0xff;
+// System.out.print((image.pixels[y*64+x] > 128) ? "*" : ".");
+ }
+// System.out.println();
+ }
+// System.out.println();
+ }
+
+
+ protected void writeBitmap(DataOutputStream os) throws IOException {
+ int[] pixels = image.pixels;
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ os.write(pixels[y * width + x] & 0xff);
+ }
+ }
+ }
+
+
+ protected Glyph(char c) {
+ int mbox3 = size * 3;
+ lazyGraphics.setColor(Color.white);
+ lazyGraphics.fillRect(0, 0, mbox3, mbox3);
+ lazyGraphics.setColor(Color.black);
+ lazyGraphics.drawString(String.valueOf(c), size, size * 2);
+
+ WritableRaster raster = lazyImage.getRaster();
+ raster.getDataElements(0, 0, mbox3, mbox3, lazySamples);
+
+ int minX = 1000, maxX = 0;
+ int minY = 1000, maxY = 0;
+ boolean pixelFound = false;
+
+ for (int y = 0; y < mbox3; y++) {
+ for (int x = 0; x < mbox3; x++) {
+ int sample = lazySamples[y * mbox3 + x] & 0xff;
+ if (sample != 255) {
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ pixelFound = true;
+ }
+ }
+ }
+
+ if (!pixelFound) {
+ minX = minY = 0;
+ maxX = maxY = 0;
+ // this will create a 1 pixel white (clear) character..
+ // maybe better to set one to -1 so nothing is added?
+ }
+
+ value = c;
+ height = (maxY - minY) + 1;
+ width = (maxX - minX) + 1;
+ setWidth = lazyMetrics.charWidth(c);
+
+ // offset from vertical location of baseline
+ // of where the char was drawn (size*2)
+ topExtent = size*2 - minY;
+
+ // offset from left of where coord was drawn
+ leftExtent = minX - size;
+
+ image = new PImage(width, height, ALPHA);
+ int[] pixels = image.pixels;
+ for (int y = minY; y <= maxY; y++) {
+ for (int x = minX; x <= maxX; x++) {
+ int val = 255 - (lazySamples[y * mbox3 + x] & 0xff);
+ int pindex = (y - minY) * width + (x - minX);
+ pixels[pindex] = val;
+ }
+ }
+
+ // replace the ascent/descent values with something.. err, decent.
+ if (value == 'd') {
+ if (ascent == 0) ascent = topExtent;
+ }
+ if (value == 'p') {
+ if (descent == 0) descent = -topExtent + height;
+ }
+ }
+ }
+}
diff --git a/src/main/java/processing/core/PGraphics.java b/src/main/java/processing/core/PGraphics.java
new file mode 100644
index 0000000..3bc19fe
--- /dev/null
+++ b/src/main/java/processing/core/PGraphics.java
@@ -0,0 +1,8467 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2013-15 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; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+// Used for color conversion functions
+import java.awt.Color;
+
+// Used for the 'image' object that's been here forever
+import java.awt.Font;
+import java.awt.Image;
+
+import java.io.File;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.WeakHashMap;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import processing.opengl.PGL;
+import processing.opengl.PShader;
+
+ /**
+ * ( begin auto-generated from PGraphics.xml )
+ *
+ * Main graphics and rendering context, as well as the base API
+ * implementation for processing "core". Use this class if you need to draw
+ * into an off-screen graphics buffer. A PGraphics object can be
+ * constructed with the createGraphics() function. The
+ * beginDraw() and endDraw() methods (see above example) are
+ * necessary to set up the buffer and to finalize it. The fields and
+ * methods for this class are extensive. For a complete list, visit the developer's reference.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Main graphics and rendering context, as well as the base API implementation.
+ *
+ *
Subclassing and initializing PGraphics objects
+ * Starting in release 0149, subclasses of PGraphics are handled differently.
+ * The constructor for subclasses takes no parameters, instead a series of
+ * functions are called by the hosting PApplet to specify its attributes.
+ *
+ *
setParent(PApplet) - is called to specify the parent PApplet.
+ *
setPrimary(boolean) - called with true if this PGraphics will be the
+ * primary drawing surface used by the sketch, or false if not.
+ *
setPath(String) - called when the renderer needs a filename or output
+ * path, such as with the PDF or DXF renderers.
+ *
setSize(int, int) - this is called last, at which point it's safe for
+ * the renderer to complete its initialization routine.
+ *
+ * The functions were broken out because of the growing number of parameters
+ * such as these that might be used by a renderer, yet with the exception of
+ * setSize(), it's not clear which will be necessary. So while the size could
+ * be passed in to the constructor instead of a setSize() function, a function
+ * would still be needed that would notify the renderer that it was time to
+ * finish its initialization. Thus, setSize() simply does both.
+ *
+ *
Know your rights: public vs. private methods
+ * Methods that are protected are often subclassed by other renderers, however
+ * they are not set 'public' because they shouldn't be part of the user-facing
+ * public API accessible from PApplet. That is, we don't want sketches calling
+ * textModeCheck() or vertexTexture() directly.
+ *
+ *
Handling warnings and exceptions
+ * Methods that are unavailable generally show a warning, unless their lack of
+ * availability will soon cause another exception. For instance, if a method
+ * like getMatrix() returns null because it is unavailable, an exception will
+ * be thrown stating that the method is unavailable, rather than waiting for
+ * the NullPointerException that will occur when the sketch tries to use that
+ * method. As of release 0149, warnings will only be shown once, and exceptions
+ * have been changed to warnings where possible.
+ *
+ *
Using xxxxImpl() for subclassing smoothness
+ * The xxxImpl() methods are generally renderer-specific handling for some
+ * subset if tasks for a particular function (vague enough for you?) For
+ * instance, imageImpl() handles drawing an image whose x/y/w/h and u/v coords
+ * have been specified, and screen placement (independent of imageMode) has
+ * been determined. There's no point in all renderers implementing the
+ * if (imageMode == BLAH) placement/sizing logic, so that's handled
+ * by PGraphics, which then calls imageImpl() once all that is figured out.
+ *
+ *
His brother PImage
+ * PGraphics subclasses PImage so that it can be drawn and manipulated in a
+ * similar fashion. As such, many methods are inherited from PGraphics,
+ * though many are unavailable: for instance, resize() is not likely to be
+ * implemented; the same goes for mask(), depending on the situation.
+ *
+ *
What's in PGraphics, what ain't
+ * For the benefit of subclasses, as much as possible has been placed inside
+ * PGraphics. For instance, bezier interpolation code and implementations of
+ * the strokeCap() method (that simply sets the strokeCap variable) are
+ * handled here. Features that will vary widely between renderers are located
+ * inside the subclasses themselves. For instance, all matrix handling code
+ * is per-renderer: Java 2D uses its own AffineTransform, P2D uses a PMatrix2D,
+ * and PGraphics3D needs to keep continually update forward and reverse
+ * transformations. A proper (future) OpenGL implementation will have all its
+ * matrix madness handled by the card. Lighting also falls under this
+ * category, however the base material property settings (emissive, specular,
+ * et al.) are handled in PGraphics because they use the standard colorMode()
+ * logic. Subclasses should override methods like emissiveFromCalc(), which
+ * is a point where a valid color has been defined internally, and can be
+ * applied in some manner based on the calcXxxx values.
+ *
+ *
What's in the PGraphics documentation, what ain't
+ * Some things are noted here, some things are not. For public API, always
+ * refer to the reference
+ * on Processing.org for proper explanations. No attempt has been made to
+ * keep the javadoc up to date or complete. It's an enormous task for
+ * which we simply do not have the time. That is, it's not something that
+ * to be done once—it's a matter of keeping the multiple references
+ * synchronized (to say nothing of the translation issues), while targeting
+ * them for their separate audiences. Ouch.
+ *
+ * We're working right now on synchronizing the two references, so the website reference
+ * is generated from the javadoc comments. Yay.
+ *
+ * @webref rendering
+ * @instanceName graphics any object of the type PGraphics
+ * @usage Web & Application
+ * @see PApplet#createGraphics(int, int, String)
+ */
+public class PGraphics extends PImage implements PConstants {
+
+// /// Canvas object that covers rendering this graphics on screen.
+// public Canvas canvas;
+
+ // ........................................................
+
+ // width and height are already inherited from PImage
+
+
+// /// width minus one (useful for many calculations)
+// protected int width1;
+//
+// /// height minus one (useful for many calculations)
+// protected int height1;
+
+ /// width * height (useful for many calculations)
+ public int pixelCount;
+
+// /// true if smoothing is enabled (read-only)
+// public boolean smooth;
+
+ /// the anti-aliasing level for renderers that support it
+ 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 graphics context for a sketch.
+ * False for offscreen buffers retrieved via createGraphics().
+ */
+ protected boolean primaryGraphics;
+
+// // TODO nervous about leaving this here since it seems likely to create
+// // back-references where we don't want them
+// protected PSurface surface;
+
+ // ........................................................
+
+ /**
+ * 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). Defaults to true so that color()
+ * used as part of a field declaration will properly assign values.
+ */
+ 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;
+
+ static final protected String ERROR_TEXTFONT_NULL_PFONT =
+ "A null PFont was passed to textFont()";
+
+ // ........................................................
+
+ // 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;
+
+ static final protected String ERROR_BACKGROUND_IMAGE_SIZE =
+ "background image must be the same size as your application";
+ static final protected String ERROR_BACKGROUND_IMAGE_FORMAT =
+ "background images should be RGB or ARGB";
+
+
+ /** 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 protected int MATRIX_STACK_DEPTH = 32;
+
+ static final protected String ERROR_PUSHMATRIX_OVERFLOW =
+ "Too many calls to pushMatrix().";
+ static final protected String ERROR_PUSHMATRIX_UNDERFLOW =
+ "Too many calls to popMatrix(), and not enough to pushMatrix().";
+
+
+ // ........................................................
+
+ /**
+ * Java AWT Image object associated with this renderer. For the 1.0 version
+ * of P2D and P3D, this was associated with their MemoryImageSource.
+ * For PGraphicsJava2D, it will be the offscreen drawing buffer.
+ */
+ public Image image;
+
+ /** Surface object that we're talking to */
+ protected PSurface surface;
+
+ // ........................................................
+
+ // 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
+ public 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;
+
+ // ........................................................
+
+ // [toxi031031] new & faster sphere code w/ support flexible 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;
+
+
+ //////////////////////////////////////////////////////////////
+
+ // INTERNAL
+
+ // Most renderers will only override the default implementation of one or
+ // two of the setXxxx() methods, so they're broken out here since the
+ // default implementations for each are simple, obvious, and common.
+ // They're also separate to avoid a monolithic and fragile constructor.
+
+
+ public PGraphics() {
+ // In 3.1.2, giving up on the async image saving as the default
+ hints[DISABLE_ASYNC_SAVEFRAME] = true;
+ }
+
+
+ public void setParent(PApplet parent) { // ignore
+ this.parent = parent;
+
+ // Some renderers (OpenGL) need to know what smoothing level will be used
+ // before the rendering surface is even created.
+ smooth = parent.sketchSmooth();
+ pixelDensity = parent.sketchPixelDensity();
+ }
+
+
+ /**
+ * 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 setQuality(int samples) { // ignore
+// this.quality = samples;
+// }
+
+
+ /**
+ * 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: this is ignored by the Methods task 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;
+
+ /** {@link PImage.pixelFactor} set in {@link PImage#PImage()} */
+ pixelWidth = width * pixelDensity;
+ pixelHeight = height * pixelDensity;
+
+// if (surface != null) {
+// allocate();
+// }
+// reapplySettings();
+ reapplySettings = true;
+ }
+
+
+// public void setSmooth(int level) {
+// this.smooth = level;
+// }
+
+
+// /**
+// * Allocate memory or an image buffer for this renderer.
+// */
+// protected void allocate() { }
+
+
+ /**
+ * Handle any takedown for this graphics context.
+ *
+ * This is called when a sketch is shut down and this renderer was
+ * specified using the size() command, or inside endRecord() and
+ * endRaw(), in order to shut things off.
+ */
+ public void dispose() { // ignore
+ if (primaryGraphics && asyncImageSaver != null) {
+ asyncImageSaver.dispose();
+ asyncImageSaver = null;
+ }
+ }
+
+
+ public PSurface createSurface() { // ignore
+ return surface = new PSurfaceNone(this);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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
+
+
+// /**
+// * Some renderers have requirements re: when they are ready to draw.
+// */
+// public boolean canDraw() { // ignore
+// return true;
+// }
+
+
+ // removing because renderers will have their own animation threads and
+ // can handle this however they wish
+// /**
+// * Try to draw, or put a draw request on the queue.
+// */
+// public void requestDraw() { // ignore
+// parent.handleDraw();
+// }
+
+
+ /**
+ * ( begin auto-generated from PGraphics_beginDraw.xml )
+ *
+ * Sets the default properties for a PGraphics object. It should be called
+ * before anything is drawn into the object.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * When creating your own PGraphics, you should call this before
+ * drawing anything.
+ *
+ * @webref pgraphics:method
+ * @brief Sets the default properties for a PGraphics object
+ */
+ public void beginDraw() { // ignore
+ }
+
+
+ /**
+ * ( begin auto-generated from PGraphics_endDraw.xml )
+ *
+ * Finalizes the rendering of a PGraphics object so that it can be shown on screen.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ *
+ * When creating your own PGraphics, you should call this when
+ * you're finished drawing.
+ *
+ * @webref pgraphics:method
+ * @brief Finalizes the rendering of a PGraphics object
+ */
+ public void endDraw() { // ignore
+ }
+
+
+ public PGL beginPGL() {
+ showMethodWarning("beginGL");
+ return null;
+ }
+
+
+ public void endPGL() {
+ showMethodWarning("endGL");
+ }
+
+
+ public void flush() {
+ // no-op, mostly for P3D to write sorted stuff
+ }
+
+
+ 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
+// System.out.println("PGraphics.defaultSettings() " + width + " " + height);
+
+// //smooth(); // 2.0a5
+// if (quality > 0) { // 2.0a5
+// smooth();
+// } else {
+// noSmooth();
+// }
+
+ colorMode(RGB, 255);
+ fill(255);
+ stroke(0);
+
+ // as of 0178, no longer relying on local versions of the variables
+ // being set, because subclasses may need to take extra action.
+ strokeWeight(DEFAULT_STROKE_WEIGHT);
+ strokeJoin(DEFAULT_STROKE_JOIN);
+ strokeCap(DEFAULT_STROKE_CAP);
+
+ // init shape stuff
+ shape = 0;
+
+ 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() {
+ // This might be called by allocate... So if beginDraw() has never run,
+ // we don't want to reapply here, we actually just need to let
+ // defaultSettings() get called a little from inside beginDraw().
+ if (!settingsInited) return; // if this is the initial setup, no need to reapply
+
+ 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;
+ }
+
+ // inherit from PImage
+ //public void resize(int wide, int high){ }
+
+ //////////////////////////////////////////////////////////////
+
+ // HINTS
+
+ /**
+ * ( begin auto-generated from hint.xml )
+ *
+ * Set various hints and hacks for the renderer. This is used to handle
+ * obscure rendering features that cannot be implemented in a consistent
+ * manner across renderers. Many options will often graduate to standard
+ * features instead of hints over time.
+ *
+ * hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for P3D. This
+ * can help force anti-aliasing if it has not been enabled by the user. On
+ * some graphics cards, this can also be set by the graphics driver's
+ * control panel, however not all cards make this available. This hint must
+ * be called immediately after the size() command because it resets the
+ * renderer, obliterating any settings and anything drawn (and like size(),
+ * re-running the code that came before it again).
+ *
+ * hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always
+ * enables 2x smoothing when the P3D renderer is used. This hint disables
+ * the default 2x smoothing and returns the smoothing behavior found in
+ * earlier releases, where smooth() and noSmooth() could be used to enable
+ * and disable smoothing, though the quality was inferior.
+ *
+ * hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are
+ * installed, rather than the bitmapped version from a .vlw file. This is
+ * useful with the default (or JAVA2D) renderer setting, as it will improve
+ * font rendering speed. This is not enabled by default, because it can be
+ * misleading while testing because the type will look great on your
+ * machine (because you have the font installed) but lousy on others'
+ * machines if the identical font is unavailable. This option can only be
+ * set per-sketch, and must be called before any use of textFont().
+ *
+ * hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on
+ * top of everything at will. When depth testing is disabled, items will be
+ * drawn to the screen sequentially, like a painting. This hint is most
+ * often used to draw in 3D, then draw in 2D on top of it (for instance, to
+ * draw GUI controls in 2D on top of a 3D interface). Starting in release
+ * 0149, this will also clear the depth buffer. Restore the default with
+ * hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared,
+ * any 3D drawing that happens later in draw() will ignore existing shapes
+ * on the screen.
+ *
+ * hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and
+ * lines in P3D and OPENGL. This can slow performance considerably, and the
+ * algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT).
+ *
+ * hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the P3D renderer setting
+ * by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT).
+ *
+ * hint(ENABLE_BUFFER_READING) - Depth and stencil buffers in P2D/P3D will be
+ * downsampled to make PGL#readPixels work with multisampling. Enabling this
+ * introduces some overhead, so if you experience bad performance, disable
+ * multisampling with noSmooth() instead. This hint is not intended to be
+ * enabled and disabled repeatedely, so call this once in setup() or after
+ * creating your PGraphics2D/3D. You can restore the default with
+ * hint(DISABLE_BUFFER_READING) if you don't plan to read depth from
+ * this PGraphics anymore.
+ *
+ * hint(ENABLE_KEY_REPEAT) - Auto-repeating key events are discarded
+ * by default (works only in P2D/P3D); use this hint to get all the key events
+ * (including auto-repeated). Call hint(DISABLE_KEY_REPEAT) to get events
+ * only when the key goes physically up or down.
+ *
+ * hint(DISABLE_ASYNC_SAVEFRAME) - P2D/P3D only - save() and saveFrame()
+ * will not use separate threads for saving and will block until the image
+ * is written to the drive. This was the default behavior in 3.0b7 and before.
+ * To enable, call hint(ENABLE_ASYNC_SAVEFRAME).
+ *
+ * As of release 0149, unhint() has been removed in favor of adding
+ * additional ENABLE/DISABLE constants to reset the default behavior. This
+ * prevents the double negatives, and also reinforces which hints can be
+ * enabled or disabled.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering
+ * @param which name of the hint to be enabled or disabled
+ * @see PGraphics
+ * @see PApplet#createGraphics(int, int, String, String)
+ * @see PApplet#size(int, int)
+ */
+ @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);
+ }
+
+
+ /**
+ * ( 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) {
+ 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;
+ }
+
+
+ /**
+ * ( 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) {
+ 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");
+ }
+
+
+ /**
+ * ( 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) {
+ if (mode != IMAGE && mode != NORMAL) {
+ throw new RuntimeException("textureMode() only supports IMAGE and NORMAL");
+ }
+ this.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) {
+ showMissingWarning("textureWrap");
+ }
+
+
+ /**
+ * ( 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) {
+ textureImage = image;
+ }
+
+
+ /**
+ * Removes texture image for current shape.
+ * Needs to be called between beginShape and 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;
+
+// if (fill) {
+// vertex[R] = fillR;
+// vertex[G] = fillG;
+// vertex[B] = fillB;
+// vertex[A] = fillA;
+// }
+ 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;
+ }
+
+ if (textured) {
+ 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;
+ }
+
+ 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;
+ }
+
+ if (textured) {
+ 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;
+
+ vertex[BEEN_LIT] = 0;
+
+ vertexCount++;
+ }
+
+
+ /**
+ * Used by renderer subclasses or PShape to efficiently pass in already
+ * formatted vertex information.
+ * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
+ */
+ public void vertex(float[] v) {
+ vertexCheck();
+ curveVertexCount = 0;
+ float[] vertex = vertices[vertexCount];
+ System.arraycopy(v, 0, vertex, 0, VERTEX_FIELD_COUNT);
+ vertexCount++;
+ }
+
+
+ public void vertex(float x, float y, float u, float v) {
+ vertexTexture(u, v);
+ vertex(x, y);
+ }
+
+/**
+ * ( 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) {
+ 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 /= textureImage.width;
+ v /= textureImage.height;
+ }
+
+ textureU = u;
+ textureV = v;
+
+ if (textureU < 0) textureU = 0;
+ else if (textureU > 1) textureU = 1;
+
+ if (textureV < 0) textureV = 0;
+ else if (textureV > 1) textureV = 1;
+ }
+
+
+// /** This feature is in testing, do not use or rely upon its implementation */
+// public void breakShape() {
+// showWarning("This renderer cannot currently handle concave shapes, " +
+// "or shapes with holes.");
+// }
+
+ /**
+ * @webref shape:vertex
+ */
+ public void beginContour() {
+ showMissingWarning("beginContour");
+ }
+
+
+ /**
+ * @webref shape:vertex
+ */
+ public void endContour() {
+ showMissingWarning("endContour");
+ }
+
+
+ public void endShape() {
+ endShape(OPEN);
+ }
+
+
+ /**
+ * ( 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) {
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SHAPE I/O
+
+
+ /**
+ * @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 loadShape(filename, null);
+ }
+
+
+ /**
+ * @nowebref
+ */
+ 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 (is2D() && 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 (is2D() && 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) {
+ throw new IllegalArgumentException("Wrong number of parameters for createShape(RECT), see the reference");
+ }
+ return createShapePrimitive(kind, p);
+
+ } else if (kind == ELLIPSE) {
+ if (len != 4) {
+ throw new IllegalArgumentException("Use createShape(ELLIPSE, x, y, w, h)");
+ }
+ 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) or createShape(ARC, x, y, w, h, start, stop, arcMode)");
+ }
+ 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
+
+ /**
+ * ( 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) {
+ showMissingWarning("loadShader");
+ return null;
+ }
+
+
+ /**
+ * @param vertFilename name of vertex shader file
+ */
+ public PShader loadShader(String fragFilename, String vertFilename) {
+ showMissingWarning("loadShader");
+ return null;
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("shader");
+ }
+
+
+ /**
+ * @param kind type of shader, either POINTS, LINES, or TRIANGLES
+ */
+ public void shader(PShader shader, int kind) {
+ showMissingWarning("shader");
+ }
+
+
+ /**
+ * ( 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() {
+ showMissingWarning("resetShader");
+ }
+
+
+ /**
+ * @param kind type of shader, either POINTS, LINES, or TRIANGLES
+ */
+ public void resetShader(int kind) {
+ showMissingWarning("resetShader");
+ }
+
+
+ /**
+ * @param shader the fragment shader to apply
+ */
+ public void filter(PShader shader) {
+ showMissingWarning("filter");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CLIPPING
+
+ /**
+ * ( 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) {
+ 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");
+ }
+
+ /**
+ * ( begin auto-generated from noClip.xml )
+ *
+ * Disables the clipping previously started by the clip() function.
+ *
+ * ( end auto-generated )
+ *
+ * @webref rendering
+ */
+ public void noClip() {
+ showMissingWarning("noClip");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BLEND
+
+ /**
+ * ( 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) {
+ this.blendMode = mode;
+ blendModeImpl();
+ }
+
+
+ protected void blendModeImpl() {
+ if (blendMode != BLEND) {
+ showMissingWarning("blendMode");
+ }
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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);
+ }
+ }
+
+
+/**
+ * ( 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) {
+ 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);
+ }
+ }
+
+
+ /**
+ * @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) {
+ 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);
+ }
+
+
+ /**
+ * @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) {
+ 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();
+ }
+
+
+ /**
+ * ( 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) {
+ 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]);
+ }
+ }
+
+ /**
+ * @param z the z-coordinate of the vertex
+ */
+ 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()
+
+
+ /**
+ * ( 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) {
+ beginShape(POINTS);
+ vertex(x, y);
+ endShape();
+ }
+
+ /**
+ * @param z z-coordinate of the point
+ */
+ public void point(float x, float y, float z) {
+ beginShape(POINTS);
+ vertex(x, y, z);
+ endShape();
+ }
+
+ /**
+ * ( 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) {
+ beginShape(LINES);
+ vertex(x1, y1);
+ vertex(x2, y2);
+ endShape();
+ }
+
+ /**
+ * @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) {
+ beginShape(LINES);
+ vertex(x1, y1, z1);
+ vertex(x2, y2, z2);
+ endShape();
+ }
+
+ /**
+ * ( 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) {
+ beginShape(TRIANGLES);
+ vertex(x1, y1);
+ vertex(x2, y2);
+ vertex(x3, y3);
+ endShape();
+ }
+
+
+ /**
+ * ( 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) {
+ beginShape(QUADS);
+ vertex(x1, y1);
+ vertex(x2, y2);
+ vertex(x3, y3);
+ vertex(x4, y4);
+ endShape();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // RECT
+
+ /**
+ * ( 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) {
+ 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) {
+ float hradius, vradius;
+ switch (rectMode) {
+ case CORNERS:
+ break;
+ case CORNER:
+ c += a; d += b;
+ break;
+ case RADIUS:
+ hradius = c;
+ vradius = d;
+ c = a + hradius;
+ d = b + vradius;
+ a -= hradius;
+ b -= vradius;
+ break;
+ case CENTER:
+ hradius = c / 2.0f;
+ vradius = d / 2.0f;
+ c = a + hradius;
+ d = b + vradius;
+ a -= hradius;
+ b -= vradius;
+ }
+
+ if (a > c) {
+ float temp = a; a = c; c = temp;
+ }
+
+ if (b > d) {
+ float temp = b; b = d; d = temp;
+ }
+
+ rectImpl(a, b, c, d);
+ }
+
+
+ protected void rectImpl(float x1, float y1, float x2, float y2) {
+ quad(x1, y1, x2, y1, x2, y2, x1, y2);
+ }
+
+
+ // Still need to do a lot of work here to make it behave across renderers
+ // (e.g. not all renderers use the vertices array)
+ // Also seems to be some issues on quality here (too dense)
+ // http://code.google.com/p/processing/issues/detail?id=265
+// private void quadraticVertex(float cpx, float cpy, float x, float y) {
+// float[] prev = vertices[vertexCount - 1];
+// float prevX = prev[X];
+// float prevY = prev[Y];
+// float cp1x = prevX + 2.0f/3.0f*(cpx - prevX);
+// float cp1y = prevY + 2.0f/3.0f*(cpy - prevY);
+// float cp2x = cp1x + (x - prevX)/3.0f;
+// float cp2y = cp1y + (y - prevY)/3.0f;
+// bezierVertex(cp1x, cp1y, cp2x, cp2y, x, y);
+// }
+
+ /**
+ * @param r radii for all four corners
+ */
+ public void rect(float a, float b, float c, float d, float r) {
+ rect(a, b, c, d, r, r, r, 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) {
+ 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);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ELLIPSE AND ARC
+
+
+ /**
+ * ( 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) {
+ 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) {
+ 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) {
+ }
+
+
+ /**
+ * ( 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) {
+ arc(a, b, c, d, start, stop, 0);
+ }
+
+ /*
+ * @param mode either OPEN, CHORD, or PIE
+ */
+ 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) {
+ // don't change start, it is visible in PIE mode
+ stop = start + TWO_PI;
+ }
+ arcImpl(x, y, w, h, start, stop, mode);
+ }
+ }
+ }
+
+
+// protected void arcImpl(float x, float y, float w, float h,
+// float start, float stop) {
+// }
+
+
+ /**
+ * Start and stop are in radians, converted by the parent function.
+ * Note that the radians can be greater (or less) than TWO_PI.
+ * This is so that an arc can be drawn that crosses zero mark,
+ * and the user will still collect $200.
+ */
+ protected void arcImpl(float x, float y, float w, float h,
+ float start, float stop, int mode) {
+ showMissingWarning("arc");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BOX
+
+ /**
+ * ( 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) {
+ box(size, size, 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) {
+ float x1 = -w/2f; float x2 = w/2f;
+ float y1 = -h/2f; float y2 = h/2f;
+ float z1 = -d/2f; float z2 = d/2f;
+
+ // TODO not the least bit efficient, it even redraws lines
+ // along the vertices. ugly ugly ugly!
+
+ beginShape(QUADS);
+
+ // front
+ normal(0, 0, 1);
+ vertex(x1, y1, z1);
+ vertex(x2, y1, z1);
+ vertex(x2, y2, z1);
+ vertex(x1, y2, z1);
+
+ // right
+ normal(1, 0, 0);
+ vertex(x2, y1, z1);
+ vertex(x2, y1, z2);
+ vertex(x2, y2, z2);
+ vertex(x2, y2, z1);
+
+ // back
+ normal(0, 0, -1);
+ vertex(x2, y1, z2);
+ vertex(x1, y1, z2);
+ vertex(x1, y2, z2);
+ vertex(x2, y2, z2);
+
+ // left
+ normal(-1, 0, 0);
+ vertex(x1, y1, z2);
+ vertex(x1, y1, z1);
+ vertex(x1, y2, z1);
+ vertex(x1, y2, z2);
+
+ // top
+ normal(0, 1, 0);
+ vertex(x1, y1, z2);
+ vertex(x2, y1, z2);
+ vertex(x2, y1, z1);
+ vertex(x1, y1, z1);
+
+ // bottom
+ normal(0, -1, 0);
+ vertex(x1, y2, z1);
+ vertex(x2, y2, z1);
+ vertex(x2, y2, z2);
+ vertex(x1, y2, z2);
+
+ endShape();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SPHERE
+
+ /**
+ * ( 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) {
+ sphereDetail(res, 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) {
+ 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;
+ }
+
+
+ /**
+ * ( 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) {
+ 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
+
+ /**
+ * ( 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) {
+ float t1 = 1.0f - t;
+ return (a*t1 + 3*b*t)*t1*t1 + (3*c*t1 + d*t)*t*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 (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;
+ }
+
+
+ /**
+ * ( 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) {
+ 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);
+ }
+
+
+
+ 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();
+ }
+
+ /**
+ * ( 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) {
+ beginShape();
+ vertex(x1, y1, z1);
+ bezierVertex(x2, y2, z2,
+ x3, y3, z3,
+ x4, y4, z4);
+ endShape();
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CATMULL-ROM CURVE
+
+ /**
+ * ( 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 points on the curve, and b and c are
+ * the control points. This can be done once with the x coordinates and a
+ * second time with the y coordinates to get the location of a curve at t.
+ *
+ * ( end auto-generated )
+ *
+ * @webref shape:curves
+ * @param a coordinate of first point on the curve
+ * @param b coordinate of second point on the curve
+ * @param c coordinate of third point on the curve
+ * @param d coordinate of fourth point on the curve
+ * @param t value between 0 and 1
+ * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
+ * @see PGraphics#curveVertex(float, float)
+ * @see PGraphics#bezierPoint(float, float, float, float, float)
+ */
+ public float curvePoint(float a, float b, float c, float d, float t) {
+ curveInitCheck();
+
+ float tt = t * t;
+ float ttt = t * tt;
+ PMatrix3D cb = curveBasisMatrix;
+
+ // not optimized (and probably need not be)
+ return (a * (ttt*cb.m00 + tt*cb.m10 + t*cb.m20 + cb.m30) +
+ b * (ttt*cb.m01 + tt*cb.m11 + t*cb.m21 + cb.m31) +
+ c * (ttt*cb.m02 + tt*cb.m12 + t*cb.m22 + cb.m32) +
+ d * (ttt*cb.m03 + tt*cb.m13 + t*cb.m23 + cb.m33));
+ }
+
+
+ /**
+ * ( 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) {
+ 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) );
+ }
+
+
+ /**
+ * ( 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) {
+ curveDetail = detail;
+ curveInit();
+ }
+
+
+ /**
+ * ( 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) {
+ 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);
+ }
+
+
+ /**
+ * ( 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) {
+ beginShape();
+ curveVertex(x1, y1);
+ curveVertex(x2, y2);
+ curveVertex(x3, y3);
+ curveVertex(x4, y4);
+ endShape();
+ }
+
+ /**
+ * @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) {
+ 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
+
+
+ /**
+ * ( 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) {
+ if ((mode == CORNER) || (mode == CORNERS) || (mode == CENTER)) {
+ imageMode = mode;
+ } else {
+ String msg =
+ "imageMode() only works with CORNER, CORNERS, or CENTER";
+ throw new RuntimeException(msg);
+ }
+ }
+
+
+ /**
+ * ( 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) {
+ // Starting in release 0144, image errors are simply ignored.
+ // loadImageAsync() sets width and height to -1 when loading fails.
+ if (img.width == -1 || img.height == -1) return;
+
+ if (imageMode == CORNER || imageMode == CORNERS) {
+ imageImpl(img,
+ a, b, a+img.width, b+img.height,
+ 0, 0, img.width, img.height);
+
+ } else if (imageMode == CENTER) {
+ float x1 = a - img.width/2;
+ float y1 = b - img.height/2;
+ imageImpl(img,
+ x1, y1, x1+img.width, y1+img.height,
+ 0, 0, img.width, img.height);
+ }
+ }
+
+ /**
+ * @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) {
+ image(img, a, b, c, d, 0, 0, img.width, img.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().
+ *
+ * @nowebref
+ */
+ public void image(PImage img,
+ 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 (img.width == -1 || img.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(img,
+ 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(img,
+ 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(img,
+ 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 img,
+ 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;
+// }
+
+ u1 *= img.pixelDensity;
+ u2 *= img.pixelDensity;
+ v1 *= img.pixelDensity;
+ v2 *= img.pixelDensity;
+
+ beginShape(QUADS);
+ texture(img);
+ 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
+
+
+ /**
+ * ( 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) {
+ this.shapeMode = mode;
+ }
+
+
+ public void shape(PShape shape) {
+ if (shape.isVisible()) { // don't do expensive matrix ops if invisible
+ // Flushing any remaining geometry generated in the immediate mode
+ // to avoid depth-sorting issues.
+ flush();
+
+ if (shapeMode == CENTER) {
+ pushMatrix();
+ translate(-shape.getWidth()/2, -shape.getHeight()/2);
+ }
+
+ shape.draw(this); // needs to handle recorder too
+
+ if (shapeMode == CENTER) {
+ popMatrix();
+ }
+ }
+ }
+
+
+
+ /**
+ * ( 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) {
+ if (shape.isVisible()) { // don't do expensive matrix ops if invisible
+ flush();
+
+ 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");
+ }
+
+
+ /**
+ * @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) {
+ if (shape.isVisible()) { // don't do expensive matrix ops if invisible
+ flush();
+
+ pushMatrix();
+
+ if (shapeMode == CENTER) {
+ // x and y are center, c and d refer to a diameter
+ translate(a - c/2f, b - d/2f);
+ scale(c / shape.getWidth(), d / shape.getHeight());
+
+ } else if (shapeMode == CORNER) {
+ translate(a, b);
+ scale(c / shape.getWidth(), d / shape.getHeight());
+
+ } else if (shapeMode == CORNERS) {
+ // c and d are x2/y2, make them into width/height
+ c -= a;
+ d -= b;
+ // then same as above
+ translate(a, b);
+ 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
+
+
+ protected PFont createFont(String name, float size,
+ boolean smooth, char[] charset) {
+ String lowerName = name.toLowerCase();
+ Font baseFont = null;
+
+ try {
+ InputStream stream = null;
+ if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
+ stream = parent.createInput(name);
+ if (stream == null) {
+ System.err.println("The font \"" + name + "\" " +
+ "is missing or inaccessible, make sure " +
+ "the URL is valid or that the file has been " +
+ "added to your sketch and is readable.");
+ return null;
+ }
+ baseFont = Font.createFont(Font.TRUETYPE_FONT, parent.createInput(name));
+
+ } else {
+ baseFont = PFont.findFont(name);
+ }
+ return new PFont(baseFont.deriveFont(size * parent.pixelDensity),
+ smooth, charset, stream != null,
+ parent.pixelDensity);
+
+ } catch (Exception e) {
+ System.err.println("Problem with createFont(\"" + name + "\")");
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+
+ public void textAlign(int alignX) {
+ textAlign(alignX, BASELINE);
+ }
+
+
+ /**
+ * ( 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) {
+ textAlign = alignX;
+ textAlignY = 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() {
+ if (textFont == null) {
+ defaultFontOrDeath("textAscent");
+ }
+ return textFont.ascent() * textSize;
+ }
+
+
+ /**
+ * ( 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() {
+ if (textFont == null) {
+ defaultFontOrDeath("textDescent");
+ }
+ return textFont.descent() * textSize;
+ }
+
+
+ /**
+ * ( 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) {
+ if (which == null) {
+ throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT);
+ }
+ textFontImpl(which, which.getDefaultSize());
+ }
+
+
+ /**
+ * @param size the size of the letters in units of pixels
+ */
+ 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);
+ }
+
+
+ /**
+ * ( 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) {
+ 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) {
+ // CENTER and MODEL overlap (they're both 3)
+ if ((mode == LEFT) || (mode == RIGHT)) {
+ showWarning("Since Processing 1.0 beta, textMode() is now textAlign().");
+ return;
+ }
+ if (mode == SCREEN) {
+ showWarning("textMode(SCREEN) has been removed from Processing 2.0.");
+ return;
+ }
+
+ 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;
+ }
+
+
+ /**
+ * ( 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) {
+ // 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;
+ }
+
+
+ // ........................................................
+
+
+ /**
+ * @param c the character to measure
+ */
+ public float textWidth(char c) {
+ textWidthBuffer[0] = c;
+ return textWidthImpl(textWidthBuffer, 0, 1);
+ }
+
+
+ /**
+ * ( 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) {
+ 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;
+ }
+
+
+ /**
+ * @nowebref
+ */
+ 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;
+ }
+
+
+ // ........................................................
+
+
+ /**
+ * ( 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) {
+ 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);
+ }
+
+
+ /**
+ * @param z z-coordinate of text
+ */
+ 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);
+ }
+
+
+ /**
+ * @param str the alphanumeric symbols to be displayed
+ */
+// public void text(String str) {
+// text(str, textX, textY, textZ);
+// }
+
+
+ /**
+ *
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) {
+ if (textFont == null) {
+ defaultFontOrDeath("text");
+ }
+
+ int length = str.length();
+ if (length > textBuffer.length) {
+ textBuffer = new char[length + 10];
+ }
+ str.getChars(0, length, textBuffer, 0);
+ text(textBuffer, 0, length, x, y);
+ }
+
+
+ /**
+ *
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) {
+ // 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) translate(0, 0, z); // slow!
+
+ text(str, x, y);
+// textZ = z;
+
+ if (z != 0) translate(0, 0, -z); // inaccurate!
+ }
+
+
+ public void text(char[] chars, int start, int stop,
+ float x, float y, float z) {
+ if (z != 0) translate(0, 0, z); // slow!
+
+ text(chars, start, stop, x, y);
+// textZ = z;
+
+ if (z != 0) translate(0, 0, -z); // inaccurate!
+ }
+
+
+ /**
+ *
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) {
+ 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
+ * @return false if cannot fit
+ */
+ 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)) {
+// System.out.println((index == stop) + " " + wordStart + " " + index);
+ float wordWidth = 0;
+ if (index > wordStart) {
+ // we have a non-empty word, measure it
+ 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 before the first word on the next 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.
+ if (index - wordStart < 25) {
+ do {
+ index--;
+ if (index == wordStart) {
+ // Not a single char will fit on this line. screw 'em.
+ return false;
+ }
+ wordWidth = textWidthImpl(buffer, wordStart, index);
+ } while (wordWidth > boxWidth);
+ } else {
+ // This word is more than 25 characters long, might be faster to
+ // start from the beginning of the text rather than shaving from
+ // the end of it, which is super slow if it's 1000s of letters.
+ // https://github.com/processing/processing/issues/211
+ int lastIndex = index;
+ index = wordStart + 1;
+ // walk to the right while things fit
+ while ((wordWidth = textWidthImpl(buffer, wordStart, index)) < boxWidth) {
+ index++;
+ if (index > lastIndex) { // Unreachable?
+ break;
+ }
+ }
+ index--;
+ if (index == wordStart) {
+ return false; // nothing fits
+ }
+ }
+
+ //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;
+ wordStart = index ; // move on to the next word including the space before the 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 a, float b, float c, float d, float z) {
+// if (z != 0) translate(0, 0, z); // slowness, badness
+//
+// text(s, a, b, c, d);
+// 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.
+ *
+ * @param num the numeric value to be displayed
+ */
+ public void text(float num, float x, float y) {
+ text(PApplet.nfs(num, 0, 3), x, y);
+ }
+
+
+ public void text(float num, float x, float y, float z) {
+ text(PApplet.nfs(num, 0, 3), x, y, z);
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // TEXT IMPL
+
+ // These are most likely to be overridden by subclasses, since the other
+ // (public) functions handle generic features like setting alignment.
+
+
+ /**
+ * Handles placement of a text line, then calls textLineImpl
+ * to actually render at the specific point.
+ */
+ protected void textLineAlignImpl(char buffer[], int start, int stop,
+ float x, float y) {
+ if (textAlign == CENTER) {
+ x -= textWidthImpl(buffer, start, stop) / 2f;
+
+ } else if (textAlign == RIGHT) {
+ x -= textWidthImpl(buffer, start, stop);
+ }
+
+ textLineImpl(buffer, start, stop, x, y);
+ }
+
+
+ /**
+ * Implementation of actual drawing for a line of text.
+ */
+ protected void textLineImpl(char buffer[], int start, int stop,
+ float x, float y) {
+ for (int index = start; index < stop; index++) {
+ textCharImpl(buffer[index], x, y);
+
+ // this doesn't account for kerning
+ x += textWidth(buffer[index]);
+ }
+// textX = x;
+// textY = y;
+// textZ = 0; // this will get set by the caller if non-zero
+ }
+
+
+ protected void textCharImpl(char ch, float x, float y) { //, float z) {
+ PFont.Glyph glyph = textFont.getGlyph(ch);
+ if (glyph != null) {
+ if (textMode == MODEL) {
+ float high = glyph.height / (float) textFont.getSize();
+ float bwidth = glyph.width / (float) textFont.getSize();
+ float lextent = glyph.leftExtent / (float) textFont.getSize();
+ float textent = glyph.topExtent / (float) textFont.getSize();
+
+ float x1 = x + lextent * textSize;
+ float y1 = y - textent * textSize;
+ float x2 = x1 + bwidth * textSize;
+ float y2 = y1 + high * textSize;
+
+ textCharModelImpl(glyph.image,
+ x1, y1, x2, y2,
+ glyph.width, glyph.height);
+ }
+ } else if (ch != ' ' && ch != 127) {
+ showWarning("No glyph found for the " + ch + " (\\u" + PApplet.hex(ch, 4) + ") character");
+ }
+ }
+
+
+ protected void textCharModelImpl(PImage glyph,
+ float x1, float y1, //float z1,
+ float x2, float y2, //float z2,
+ int u2, int v2) {
+ boolean savedTint = tint;
+ int savedTintColor = tintColor;
+ float savedTintR = tintR;
+ float savedTintG = tintG;
+ float savedTintB = tintB;
+ float savedTintA = tintA;
+ boolean savedTintAlpha = tintAlpha;
+
+ tint = true;
+ tintColor = fillColor;
+ tintR = fillR;
+ tintG = fillG;
+ tintB = fillB;
+ tintA = fillA;
+ tintAlpha = fillAlpha;
+
+ imageImpl(glyph, x1, y1, x2, y2, 0, 0, u2, v2);
+
+ tint = savedTint;
+ tintColor = savedTintColor;
+ tintR = savedTintR;
+ tintG = savedTintG;
+ tintB = savedTintB;
+ tintA = savedTintA;
+ tintAlpha = savedTintAlpha;
+ }
+
+
+ /*
+ protected void textCharScreenImpl(PImage glyph,
+ int xx, int yy,
+ int w0, int h0) {
+ int x0 = 0;
+ int y0 = 0;
+
+ if ((xx >= width) || (yy >= height) ||
+ (xx + w0 < 0) || (yy + h0 < 0)) return;
+
+ if (xx < 0) {
+ x0 -= xx;
+ w0 += xx;
+ xx = 0;
+ }
+ if (yy < 0) {
+ y0 -= yy;
+ h0 += yy;
+ yy = 0;
+ }
+ if (xx + w0 > width) {
+ w0 -= ((xx + w0) - width);
+ }
+ if (yy + h0 > height) {
+ h0 -= ((yy + h0) - height);
+ }
+
+ int fr = fillRi;
+ int fg = fillGi;
+ int fb = fillBi;
+ int fa = fillAi;
+
+ int pixels1[] = glyph.pixels; //images[glyph].pixels;
+
+ // TODO this can be optimized a bit
+ for (int row = y0; row < y0 + h0; row++) {
+ for (int col = x0; col < x0 + w0; col++) {
+ //int a1 = (fa * pixels1[row * textFont.twidth + col]) >> 8;
+ int a1 = (fa * pixels1[row * glyph.width + col]) >> 8;
+ int a2 = a1 ^ 0xff;
+ //int p1 = pixels1[row * glyph.width + col];
+ int p2 = pixels[(yy + row-y0)*width + (xx+col-x0)];
+
+ pixels[(yy + row-y0)*width + xx+col-x0] =
+ (0xff000000 |
+ (((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
+ (( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
+ (( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
+ }
+ }
+ }
+ */
+
+
+// /**
+// * Convenience method to get a legit FontMetrics object. Where possible,
+// * override this any renderer subclass so that you're not using what's
+// * returned by getDefaultToolkit() to get your metrics.
+// */
+// @SuppressWarnings("deprecation")
+// public FontMetrics getFontMetrics(Font font) { // ignore
+// Frame frame = parent.frame;
+// if (frame != null) {
+// return frame.getToolkit().getFontMetrics(font);
+// }
+// return Toolkit.getDefaultToolkit().getFontMetrics(font);
+// }
+//
+//
+// /**
+// * Convenience method to jump through some Java2D hoops and get an FRC.
+// */
+// public FontRenderContext getFontRenderContext(Font font) { // ignore
+// return getFontMetrics(font).getFontRenderContext();
+// }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX STACK
+
+
+ /**
+ * ( 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() {
+ showMethodWarning("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() {
+ showMethodWarning("popMatrix");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX TRANSFORMATIONS
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("translate");
+ }
+
+
+ /**
+ * @param z forward/backward translation
+ */
+ public void translate(float x, float y, float z) {
+ showMissingWarning("translate");
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("rotate");
+ }
+
+
+ /**
+ * ( 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) {
+ showMethodWarning("rotateX");
+ }
+
+
+ /**
+ * ( 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) {
+ showMethodWarning("rotateY");
+ }
+
+
+ /**
+ * ( 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) {
+ showMethodWarning("rotateZ");
+ }
+
+
+ /**
+ *
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) {
+ showMissingWarning("rotate");
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("scale");
+ }
+
+
+ /**
+ *
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) {
+ showMissingWarning("scale");
+ }
+
+
+ /**
+ * @param z percentage to scale the object in the z-axis
+ */
+ public void scale(float x, float y, float z) {
+ showMissingWarning("scale");
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("shearX");
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("shearY");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX FULL MONTY
+
+
+ /**
+ * ( 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() {
+ showMethodWarning("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) {
+ 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);
+ }
+
+
+ /**
+ * @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) {
+ 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);
+ }
+
+
+ /**
+ * @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) {
+ showMissingWarning("applyMatrix");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // MATRIX GET/SET/PRINT
+
+
+ public PMatrix getMatrix() {
+ showMissingWarning("getMatrix");
+ return null;
+ }
+
+
+ /**
+ * Copy the current transformation matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix2D getMatrix(PMatrix2D target) {
+ showMissingWarning("getMatrix");
+ return null;
+ }
+
+
+ /**
+ * Copy the current transformation matrix into the specified target.
+ * Pass in null to create a new matrix.
+ */
+ public PMatrix3D getMatrix(PMatrix3D target) {
+ showMissingWarning("getMatrix");
+ return null;
+ }
+
+
+ /**
+ * Set the current transformation matrix to the contents of another.
+ */
+ public void setMatrix(PMatrix source) {
+ if (source instanceof PMatrix2D) {
+ setMatrix((PMatrix2D) source);
+ } else if (source instanceof PMatrix3D) {
+ setMatrix((PMatrix3D) source);
+ }
+ }
+
+
+ /**
+ * Set the current transformation to the contents of the specified source.
+ */
+ public void setMatrix(PMatrix2D source) {
+ showMissingWarning("setMatrix");
+ }
+
+
+ /**
+ * Set the current transformation to the contents of the specified source.
+ */
+ public void setMatrix(PMatrix3D source) {
+ showMissingWarning("setMatrix");
+ }
+
+
+ /**
+ * ( 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() {
+ showMethodWarning("printMatrix");
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // CAMERA
+
+ /**
+ * ( 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() {
+ showMethodWarning("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() {
+ showMethodWarning("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() {
+ showMissingWarning("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) {
+ showMissingWarning("camera");
+ }
+
+/**
+ * ( 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() {
+ showMethodWarning("printCamera");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // PROJECTION
+
+ /**
+ * ( 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() {
+ showMissingWarning("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) {
+ showMissingWarning("ortho");
+ }
+
+ /**
+ * @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) {
+ showMissingWarning("ortho");
+ }
+
+ /**
+ * ( 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() {
+ showMissingWarning("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) {
+ showMissingWarning("perspective");
+ }
+
+ /**
+ * ( 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) {
+ showMethodWarning("frustum");
+ }
+
+ /**
+ * ( 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() {
+ showMethodWarning("printProjection");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // SCREEN TRANSFORMS
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("screenX");
+ return 0;
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("screenY");
+ return 0;
+ }
+
+
+ /**
+ * @param z 3D z-coordinate to be mapped
+ */
+ public float screenX(float x, float y, float z) {
+ showMissingWarning("screenX");
+ return 0;
+ }
+
+
+ /**
+ * @param z 3D z-coordinate to be mapped
+ */
+ public float screenY(float x, float y, float z) {
+ showMissingWarning("screenY");
+ return 0;
+ }
+
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("screenZ");
+ return 0;
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("modelX");
+ return 0;
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("modelY");
+ return 0;
+ }
+
+
+ /**
+ * ( 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) {
+ showMissingWarning("modelZ");
+ return 0;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STYLE
+
+ /**
+ * ( 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() {
+ if (styleStackDepth == styleStack.length) {
+ styleStack = (PStyle[]) PApplet.expand(styleStack);
+ }
+ if (styleStack[styleStackDepth] == null) {
+ styleStack[styleStackDepth] = new PStyle();
+ }
+ PStyle s = styleStack[styleStackDepth++];
+ getStyle(s);
+ }
+
+ /**
+ * ( 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() {
+ 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
+
+ /**
+ * ( 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) {
+ 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) {
+ 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) {
+ strokeCap = cap;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // STROKE COLOR
+
+
+ /**
+ * ( 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() {
+ stroke = false;
+ }
+
+
+ /**
+ * ( 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) {
+ colorCalc(rgb);
+ strokeFromCalc();
+ }
+
+
+ /**
+ * @param alpha opacity of the stroke
+ */
+ public void stroke(int rgb, float alpha) {
+ colorCalc(rgb, alpha);
+ strokeFromCalc();
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void stroke(float gray) {
+ colorCalc(gray);
+ strokeFromCalc();
+ }
+
+
+ public void stroke(float gray, float alpha) {
+ colorCalc(gray, alpha);
+ strokeFromCalc();
+ }
+
+
+ /**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ strokeFromCalc();
+ }
+
+
+ public void stroke(float v1, float v2, float v3, float alpha) {
+ colorCalc(v1, v2, v3, alpha);
+ 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
+
+
+ /**
+ * ( 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() {
+ tint = false;
+ }
+
+
+ /**
+ * ( 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) {
+ colorCalc(rgb);
+ tintFromCalc();
+ }
+
+
+ /**
+ * @param alpha opacity of the image
+ */
+ public void tint(int rgb, float alpha) {
+ colorCalc(rgb, alpha);
+ tintFromCalc();
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void tint(float gray) {
+ colorCalc(gray);
+ tintFromCalc();
+ }
+
+
+ public void tint(float gray, float alpha) {
+ colorCalc(gray, alpha);
+ tintFromCalc();
+ }
+
+/**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ tintFromCalc();
+ }
+
+
+ public void tint(float v1, float v2, float v3, float alpha) {
+ colorCalc(v1, v2, v3, alpha);
+ 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
+
+
+ /**
+ * ( 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() {
+ fill = false;
+ }
+
+
+ /**
+ * ( 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) {
+ colorCalc(rgb);
+ fillFromCalc();
+ }
+
+ /**
+ * @param alpha opacity of the fill
+ */
+ public void fill(int rgb, float alpha) {
+ colorCalc(rgb, alpha);
+ fillFromCalc();
+ }
+
+
+ /**
+ * @param gray number specifying value between white and black
+ */
+ public void fill(float gray) {
+ colorCalc(gray);
+ fillFromCalc();
+ }
+
+
+ public void fill(float gray, float alpha) {
+ colorCalc(gray, alpha);
+ fillFromCalc();
+ }
+
+
+ /**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ fillFromCalc();
+ }
+
+
+ public void fill(float v1, float v2, float v3, float alpha) {
+ colorCalc(v1, v2, v3, alpha);
+ 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
+
+ /**
+ * ( 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) {
+// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
+// ambient((float) rgb);
+//
+// } else {
+// colorCalcARGB(rgb, colorModeA);
+// ambientFromCalc();
+// }
+ colorCalc(rgb);
+ ambientFromCalc();
+ }
+
+/**
+ * @param gray number specifying value between white and black
+ */
+ public void ambient(float gray) {
+ colorCalc(gray);
+ ambientFromCalc();
+ }
+
+/**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ ambientFromCalc();
+ }
+
+
+ protected void ambientFromCalc() {
+ ambientColor = calcColor;
+ ambientR = calcR;
+ ambientG = calcG;
+ ambientB = calcB;
+ setAmbient = true;
+ }
+
+ /**
+ * ( 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) {
+// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
+// specular((float) rgb);
+//
+// } else {
+// colorCalcARGB(rgb, colorModeA);
+// specularFromCalc();
+// }
+ colorCalc(rgb);
+ specularFromCalc();
+ }
+
+
+/**
+ * gray number specifying value between white and black
+ */
+ public void specular(float gray) {
+ colorCalc(gray);
+ specularFromCalc();
+ }
+
+
+/**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ specularFromCalc();
+ }
+
+
+ protected void specularFromCalc() {
+ specularColor = calcColor;
+ specularR = calcR;
+ specularG = calcG;
+ specularB = calcB;
+ }
+
+
+ /**
+ * ( 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) {
+ 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) {
+// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
+// emissive((float) rgb);
+//
+// } else {
+// colorCalcARGB(rgb, colorModeA);
+// emissiveFromCalc();
+// }
+ colorCalc(rgb);
+ emissiveFromCalc();
+ }
+
+ /**
+ * gray number specifying value between white and black
+ */
+ public void emissive(float gray) {
+ colorCalc(gray);
+ emissiveFromCalc();
+ }
+
+ /**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ 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.
+
+ /**
+ * ( 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() {
+ showMethodWarning("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() {
+ showMethodWarning("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) {
+ showMethodWarning("ambientLight");
+ }
+
+ /**
+ * @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) {
+ showMethodWarning("ambientLight");
+ }
+
+ /**
+ * ( 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) {
+ showMethodWarning("directionalLight");
+ }
+
+ /**
+ * ( 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) {
+ showMethodWarning("pointLight");
+ }
+
+ /**
+ * ( 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) {
+ showMethodWarning("spotLight");
+ }
+
+ /**
+ * ( 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) {
+ showMethodWarning("lightFalloff");
+ }
+
+ /**
+ * ( 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) {
+ showMethodWarning("lightSpecular");
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BACKGROUND
+
+
+ /**
+ * ( 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) {
+// 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();
+ }
+
+
+ /**
+ * @param alpha opacity of the background
+ */
+ 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();
+ }
+
+
+ /**
+ * @param gray specifies a value between white and black
+ */
+ public void background(float gray) {
+ colorCalc(gray);
+ backgroundFromCalc();
+// backgroundImpl();
+ }
+
+
+ public void background(float gray, float alpha) {
+ if (format == RGB) {
+ background(gray); // ignore alpha for main drawing surface
+
+ } else {
+ colorCalc(gray, alpha);
+ backgroundFromCalc();
+// backgroundImpl();
+ }
+ }
+
+
+ /**
+ * @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) {
+ colorCalc(v1, v2, v3);
+ backgroundFromCalc();
+// backgroundImpl();
+ }
+
+
+ public void background(float v1, float v2, float v3, float alpha) {
+ colorCalc(v1, v2, v3, alpha);
+ backgroundFromCalc();
+ }
+
+ /**
+ * @webref color:setting
+ */
+ public void clear() {
+ background(0, 0, 0, 0);
+ }
+
+
+ protected void backgroundFromCalc() {
+ backgroundR = calcR;
+ backgroundG = calcG;
+ backgroundB = calcB;
+ //backgroundA = (format == RGB) ? colorModeA : calcA;
+ // If drawing surface is opaque, this maxes out at 1.0. [fry 150513]
+ backgroundA = (format == RGB) ? 1 : 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. 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) {
+ if ((image.pixelWidth != pixelWidth) || (image.pixelHeight != pixelHeight)) {
+ 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
+
+ /**
+ * ( 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) {
+ 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 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) {
+ colorMode(mode, max1, max2, max3, colorModeA);
+ }
+
+
+ /**
+ * @param maxA range for the alpha
+ */
+ public void colorMode(int mode,
+ float max1, float max2, float max3, float maxA) {
+ colorMode = mode;
+
+ colorModeX = max1; // still needs to be set for hsb
+ colorModeY = max2;
+ colorModeZ = max3;
+ colorModeA = maxA;
+
+ // if color max values are all 1, then no need to scale
+ colorModeScale =
+ ((maxA != 1) || (max1 != max2) || (max2 != max3) || (max3 != 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 for 'argb' since it's a 32 bit number.
+ * Bounds now checked on alpha, however (rev 0225).
+ */
+ protected void colorCalcARGB(int argb, float alpha) {
+ if (alpha == colorModeA) {
+ calcAi = (argb >> 24) & 0xff;
+ calcColor = argb;
+ } else {
+ calcAi = (int) (((argb >> 24) & 0xff) * PApplet.constrain((alpha / colorModeA), 0, 1));
+ 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);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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 c) { // ignore
+// if (((c & 0xff000000) == 0) && (c <= colorModeX)) {
+// if (colorModeDefault) {
+// // bounds checking to make sure the numbers aren't to high or low
+// if (c > 255) c = 255; else if (c < 0) c = 0;
+// return 0xff000000 | (c << 16) | (c << 8) | c;
+// } else {
+// colorCalc(c);
+// }
+// } else {
+// colorCalcARGB(c, colorModeA);
+// }
+ colorCalc(c);
+ return calcColor;
+ }
+
+
+ public final int color(float gray) { // ignore
+ colorCalc(gray);
+ return calcColor;
+ }
+
+
+ /**
+ * @param c can be packed ARGB or a gray in this case
+ */
+ public final int color(int c, int alpha) { // ignore
+// if (colorModeDefault) {
+// // bounds checking to make sure the numbers aren't to high or low
+// if (c > 255) c = 255; else if (c < 0) c = 0;
+// if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
+//
+// return ((alpha & 0xff) << 24) | (c << 16) | (c << 8) | c;
+// }
+ colorCalc(c, alpha);
+ return calcColor;
+ }
+
+
+ /**
+ * @param c can be packed ARGB or a gray in this case
+ */
+ public final int color(int c, float alpha) { // ignore
+// if (((c & 0xff000000) == 0) && (c <= colorModeX)) {
+ colorCalc(c, alpha);
+// } else {
+// colorCalcARGB(c, alpha);
+// }
+ return calcColor;
+ }
+
+
+ public final int color(float gray, float alpha) { // ignore
+ colorCalc(gray, alpha);
+ return calcColor;
+ }
+
+
+ public final int color(int v1, int v2, int v3) { // ignore
+ colorCalc(v1, v2, v3);
+ return calcColor;
+ }
+
+
+ public final int color(float v1, float v2, float v3) { // ignore
+ colorCalc(v1, v2, v3);
+ return calcColor;
+ }
+
+
+ public final int color(int v1, int v2, int v3, int a) { // ignore
+ colorCalc(v1, v2, v3, a);
+ return calcColor;
+ }
+
+
+ public final int color(float v1, float v2, float v3, float a) { // ignore
+ colorCalc(v1, v2, v3, a);
+ return calcColor;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR DATATYPE EXTRACTION
+
+ // Vee have veys of making the colors talk.
+
+ /**
+ * ( 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) {
+ float outgoing = (rgb >> 24) & 0xff;
+ if (colorModeA == 255) return outgoing;
+ return (outgoing / 255.0f) * colorModeA;
+ }
+
+
+ /**
+ * ( 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) {
+ float c = (rgb >> 16) & 0xff;
+ if (colorModeDefault) return c;
+ return (c / 255.0f) * colorModeX;
+ }
+
+
+ /**
+ * ( 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) {
+ float c = (rgb >> 8) & 0xff;
+ if (colorModeDefault) return c;
+ return (c / 255.0f) * colorModeY;
+ }
+
+
+ /**
+ * ( 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) {
+ float c = (rgb) & 0xff;
+ if (colorModeDefault) return c;
+ return (c / 255.0f) * colorModeZ;
+ }
+
+
+ /**
+ * ( 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) {
+ if (rgb != cacheHsbKey) {
+ Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff,
+ rgb & 0xff, cacheHsbValue);
+ cacheHsbKey = rgb;
+ }
+ return cacheHsbValue[0] * colorModeX;
+ }
+
+
+ /**
+ * ( 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) {
+ if (rgb != cacheHsbKey) {
+ Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff,
+ rgb & 0xff, cacheHsbValue);
+ cacheHsbKey = rgb;
+ }
+ return cacheHsbValue[1] * colorModeY;
+ }
+
+
+ /**
+ * ( 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) {
+ if (rgb != cacheHsbKey) {
+ Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff,
+ rgb & 0xff, cacheHsbValue);
+ cacheHsbKey = rgb;
+ }
+ return cacheHsbValue[2] * colorModeZ;
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COLOR DATATYPE INTERPOLATION
+
+ // Against our better judgement.
+
+
+ /**
+ * ( begin auto-generated from lerpColor.xml )
+ *
+ * Calculates a color or colors between two color at a specific increment.
+ * The amt parameter is the amount to interpolate between the two
+ * values where 0.0 equal to the first point, 0.1 is very near the first
+ * point, 0.5 is half-way in between, etc.
+ *
+ * ( end auto-generated )
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param c1 interpolate from this color
+ * @param c2 interpolate to this color
+ * @param amt between 0.0 and 1.0
+ * @see PImage#blendColor(int, int, int)
+ * @see PGraphics#color(float, float, float, float)
+ * @see PApplet#lerp(float, float, float)
+ */
+ public int lerpColor(int c1, int c2, float amt) { // ignore
+ return lerpColor(c1, c2, amt, colorMode);
+ }
+
+ static float[] lerpColorHSB1;
+ static float[] lerpColorHSB2;
+
+ /**
+ * @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) {
+ if (amt < 0) amt = 0;
+ if (amt > 1) amt = 1;
+
+ 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 ((PApplet.round(a1 + (a2-a1)*amt) << 24) |
+ (PApplet.round(r1 + (r2-r1)*amt) << 16) |
+ (PApplet.round(g1 + (g2-g1)*amt) << 8) |
+ (PApplet.round(b1 + (b2-b1)*amt)));
+
+ } else if (mode == HSB) {
+ if (lerpColorHSB1 == null) {
+ lerpColorHSB1 = new float[3];
+ lerpColorHSB2 = new float[3];
+ }
+
+ float a1 = (c1 >> 24) & 0xff;
+ float a2 = (c2 >> 24) & 0xff;
+ int alfa = (PApplet.round(a1 + (a2-a1)*amt)) << 24;
+
+ Color.RGBtoHSB((c1 >> 16) & 0xff, (c1 >> 8) & 0xff, c1 & 0xff,
+ lerpColorHSB1);
+ Color.RGBtoHSB((c2 >> 16) & 0xff, (c2 >> 8) & 0xff, c2 & 0xff,
+ lerpColorHSB2);
+
+ /* If mode is HSB, this will take the shortest path around the
+ * color wheel to find the new color. For instance, red to blue
+ * will go red violet blue (backwards in hue space) rather than
+ * cycling through ROYGBIV.
+ */
+ // Disabling rollover (wasn't working anyway) for 0126.
+ // Otherwise it makes full spectrum scale impossible for
+ // those who might want it...in spite of how despicable
+ // a full spectrum scale might be.
+ // roll around when 0.9 to 0.1
+ // more than 0.5 away means that it should roll in the other direction
+ /*
+ float h1 = lerpColorHSB1[0];
+ float h2 = lerpColorHSB2[0];
+ if (Math.abs(h1 - h2) > 0.5f) {
+ if (h1 > h2) {
+ // i.e. h1 is 0.7, h2 is 0.1
+ h2 += 1;
+ } else {
+ // i.e. h1 is 0.1, h2 is 0.7
+ h1 += 1;
+ }
+ }
+ float ho = (PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt)) % 1.0f;
+ */
+ float ho = PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt);
+ float so = PApplet.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt);
+ float bo = PApplet.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt);
+
+ return alfa | (Color.HSBtoRGB(ho, so, bo) & 0xFFFFFF);
+ }
+ return 0;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BEGINRAW/ENDRAW
+
+
+ /**
+ * Record individual lines and triangles by echoing them to another renderer.
+ */
+ public void beginRaw(PGraphics rawGraphics) { // ignore
+ this.raw = rawGraphics;
+ rawGraphics.beginDraw();
+ }
+
+
+ public void endRaw() { // ignore
+ if (raw != null) {
+ // for 3D, need to flush any geometry that's been stored for sorting
+ // (particularly if the ENABLE_DEPTH_SORT hint is set)
+ flush();
+
+ // just like beginDraw, this will have to be called because
+ // endDraw() will be happening outside of draw()
+ raw.endDraw();
+ raw.dispose();
+ raw = null;
+ }
+ }
+
+
+ public boolean haveRaw() { // ignore
+ return raw != null;
+ }
+
+
+ public PGraphics getRaw() { // ignore
+ return raw;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // WARNINGS and EXCEPTIONS
+
+
+ static protected Map 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.");
+ }
+
+
+ /**
+ * 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. " +
+ "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() { // ignore
+ return true;
+ }
+
+
+ /**
+ * Return true if this renderer supports 2D drawing. Defaults to true.
+ */
+ public boolean is2D() { // ignore
+ return true;
+ }
+
+
+ /**
+ * Return true if this renderer supports 3D drawing. Defaults to false.
+ */
+ public boolean is3D() { // ignore
+ return false;
+ }
+
+
+ /**
+ * Return true if this renderer does rendering through OpenGL. Defaults to false.
+ */
+ public boolean isGL() { // ignore
+ return false;
+ }
+
+
+ public boolean is2X() {
+ return pixelDensity == 2;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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, parent.sketchFile(filename));
+
+ return true;
+ }
+
+ protected void processImageBeforeAsyncSave(PImage image) { }
+
+
+ /**
+ * If there is running async save task for this file, blocks until it completes.
+ * Has to be called on main thread because OpenGL overrides this and calls GL.
+ * @param filename
+ */
+ protected void awaitAsyncSaveCompletion(String filename) {
+ if (asyncImageSaver != null) {
+ asyncImageSaver.awaitAsyncSaveCompletion(parent.sketchFile(filename));
+ }
+ }
+
+
+ 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;
+
+ Map> runningTasks = new HashMap<>();
+ final Object runningTasksLock = new Object();
+
+
+ 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.pixelWidth != requestedWidth ||
+ target.pixelHeight != requestedHeight) {
+ // TODO: this kills performance when saving different sizes
+ target = new PImage(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 File file) {
+ 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();
+
+ awaitAsyncSaveCompletion(file);
+
+ // Explicit lock, because submitting a task and putting it into map
+ // has to be atomic (and happen before task tries to remove itself)
+ synchronized (runningTasksLock) {
+ try {
+ Future> task = saveExecutor.submit(() -> {
+ try {
+ long startTime = System.nanoTime();
+ renderer.processImageBeforeAsyncSave(target);
+ target.save(file.getAbsolutePath());
+ 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);
+ synchronized (runningTasksLock) {
+ runningTasks.remove(file);
+ }
+ }
+ });
+ runningTasks.put(file, task);
+ } catch (RejectedExecutionException e) {
+ // the executor service was probably shut down, no more saving for us
+ }
+ }
+ }
+
+
+ public void awaitAsyncSaveCompletion(final File file) { // ignore
+ Future> taskWithSameFilename;
+ synchronized (runningTasksLock) {
+ taskWithSameFilename = runningTasks.get(file);
+ }
+
+ if (taskWithSameFilename != null) {
+ try {
+ taskWithSameFilename.get();
+ } catch (InterruptedException | ExecutionException e) { }
+ }
+ }
+
+ }
+
+}
diff --git a/src/main/java/processing/core/PImage.java b/src/main/java/processing/core/PImage.java
new file mode 100644
index 0000000..049d198
--- /dev/null
+++ b/src/main/java/processing/core/PImage.java
@@ -0,0 +1,3438 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2004-14 Ben Fry and Casey Reas
+ Copyright (c) 2001-04 Massachusetts Institute of Technology
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.awt.*;
+import java.awt.image.*;
+import java.io.*;
+import java.util.Iterator;
+
+import javax.imageio.*;
+import javax.imageio.metadata.*;
+
+
+/**
+ * ( begin auto-generated from PImage.xml )
+ *
+ * Datatype for storing images. Processing can display .gif,
+ * .jpg, .tga, and .png images. Images may be
+ * displayed in 2D and 3D space. Before an image is used, it must be loaded
+ * with the loadImage() function. The PImage class contains
+ * fields for the width and height of the image, as well as
+ * an array called pixels[] that contains the values for every pixel
+ * in the image. The methods described below allow easy access to the
+ * image's pixels and alpha channel and simplify the process of compositing.
+ * using the pixels[] array, be sure to use the
+ * loadPixels() method on the image to make sure that the pixel data
+ * is properly loaded.
+ * create a new image, use the createImage() function. Do not
+ * use the syntax new PImage().
+ *
+ * ( end auto-generated )
+ *
+ * @webref image
+ * @usage Web & Application
+ * @instanceName pimg any object of type PImage
+ * @see PApplet#loadImage(String)
+ * @see PApplet#imageMode(int)
+ * @see PApplet#createImage(int, int, int)
+ */
+public class PImage implements PConstants, Cloneable {
+
+ /**
+ * Format for this image, one of RGB, ARGB or ALPHA.
+ * note that RGB images still require 0xff in the high byte
+ * because of how they'll be manipulated by other functions
+ */
+ public int format;
+
+ /**
+ * ( begin auto-generated from pixels.xml )
+ *
+ * Array containing the values for all the pixels in the display window.
+ * These values are of the color datatype. This array is the size of the
+ * display window. For example, if the image is 100x100 pixels, there will
+ * be 10000 values and if the window is 200x300 pixels, there will be 60000
+ * values. The index value defines the position of a value within
+ * the array. For example, the statement color b = pixels[230] will
+ * set the variable b to be equal to the value at that location in
+ * the array.
+ *
+ * Before accessing this array, the data must loaded with the
+ * loadPixels() function. After the array data has been modified,
+ * the updatePixels() function must be run to update the changes.
+ * Without loadPixels(), running the code may (or will in future
+ * releases) result in a NullPointerException.
+ *
+ * ( end auto-generated )
+ *
+ * @webref image:pixels
+ * @usage web_application
+ * @brief Array containing the color of every pixel in the image
+ */
+ public int[] pixels;
+
+ /** 1 for most images, 2 for hi-dpi/retina */
+ public int pixelDensity = 1;
+
+ /** Actual dimensions of pixels array, taking into account the 2x setting. */
+ public int pixelWidth;
+ public int pixelHeight;
+
+ /**
+ * ( begin auto-generated from PImage_width.xml )
+ *
+ * The width of the image in units of pixels.
+ *
+ * ( end auto-generated )
+ * @webref pimage:field
+ * @usage web_application
+ * @brief Image width
+ */
+ public int width;
+
+ /**
+ * ( begin auto-generated from PImage_height.xml )
+ *
+ * The height of the image in units of pixels.
+ *
+ * ( end auto-generated )
+ * @webref pimage:field
+ * @usage web_application
+ * @brief Image height
+ */
+ public int height;
+
+ /**
+ * Path to parent object that will be used with save().
+ * This prevents users from needing savePath() to use PImage.save().
+ */
+ public PApplet parent;
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ /** 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;
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * ( begin auto-generated from PImage.xml )
+ *
+ * Datatype for storing images. Processing can display .gif,
+ * .jpg, .tga, and .png images. Images may be
+ * displayed in 2D and 3D space. Before an image is used, it must be loaded
+ * with the loadImage() function. The PImage object contains
+ * fields for the width and height of the image, as well as
+ * an array called pixels[] which contains the values for every
+ * pixel in the image. A group of methods, described below, allow easy
+ * access to the image's pixels and alpha channel and simplify the process
+ * of compositing.
+ *
+ * Before using the pixels[] array, be sure to use the
+ * loadPixels() method on the image to make sure that the pixel data
+ * is properly loaded.
+ *
+ * To create a new image, use the createImage() function (do not use
+ * new PImage()).
+ * ( end auto-generated )
+ * @nowebref
+ * @usage web_application
+ * @see PApplet#loadImage(String, String)
+ * @see PApplet#imageMode(int)
+ * @see PApplet#createImage(int, int, int)
+ */
+ public PImage() {
+ format = ARGB; // default to ARGB images for release 0116
+ pixelDensity = 1;
+ }
+
+
+ /**
+ * @nowebref
+ * @param width image width
+ * @param height image height
+ */
+ public PImage(int width, int height) {
+ init(width, height, RGB, 1);
+
+ // toxi: is it maybe better to init the image with max alpha enabled?
+ //for(int i=0; ipixels[] array. This
+ * function must always be called before reading from or writing to pixels[].
+ *
renderers may or may not seem to require loadPixels()
+ * or updatePixels(). However, the rule is that any time you want to
+ * manipulate the pixels[] array, you must first call
+ * loadPixels(), and after changes have been made, call
+ * updatePixels(). Even if the renderer may not seem to use this
+ * function in the current Processing release, this will always be subject
+ * to change.
+ *
+ * ( end auto-generated )
+ *
+ *
Advanced
+ * Call this when you want to mess with the pixels[] array.
+ *
+ * For subclasses where the pixels[] buffer isn't set by default,
+ * this should copy all data into the pixels[] array
+ *
+ * @webref pimage:pixels
+ * @brief Loads the pixel data for the image into its pixels[] array
+ * @usage web_application
+ */
+ public void loadPixels() { // ignore
+ if (pixels == null || pixels.length != pixelWidth*pixelHeight) {
+ pixels = new int[pixelWidth*pixelHeight];
+ }
+ setLoaded();
+ }
+
+
+ public void updatePixels() { // ignore
+ updatePixels(0, 0, pixelWidth, pixelHeight);
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_updatePixels.xml )
+ *
+ * Updates the image with the data in its pixels[] array. Use in
+ * conjunction with loadPixels(). If you're only reading pixels from
+ * the array, there's no need to call updatePixels().
+ *
renderers may or may not seem to require loadPixels()
+ * or updatePixels(). However, the rule is that any time you want to
+ * manipulate the pixels[] array, you must first call
+ * loadPixels(), and after changes have been made, call
+ * updatePixels(). Even if the renderer may not seem to use this
+ * function in the current Processing release, this will always be subject
+ * to change.
+ *
+ * Currently, none of the renderers use the additional parameters to
+ * updatePixels(), however this may be implemented in the future.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Mark the pixels in this region as needing an update.
+ * This is not currently used by any of the renderers, however the api
+ * is structured this way in the hope of being able to use this to
+ * speed things up in the future.
+ * @webref pimage:pixels
+ * @brief Updates the image with the data in its pixels[] array
+ * @usage web_application
+ * @param x x-coordinate of the upper-left corner
+ * @param y y-coordinate of the upper-left corner
+ * @param w width
+ * @param h height
+ */
+ public void updatePixels(int x, int y, int w, int h) { // ignore
+ int x2 = x + w;
+ int y2 = y + h;
+
+ if (!modified) {
+ mx1 = PApplet.max(0, x);
+ mx2 = PApplet.min(pixelWidth, x2);
+ my1 = PApplet.max(0, y);
+ my2 = PApplet.min(pixelHeight, y2);
+ modified = true;
+
+ } else {
+ if (x < mx1) mx1 = PApplet.max(0, x);
+ if (x > mx2) mx2 = PApplet.min(pixelWidth, x);
+ if (y < my1) my1 = PApplet.max(0, y);
+ if (y > my2) my2 = PApplet.min(pixelHeight, y);
+
+ if (x2 < mx1) mx1 = PApplet.max(0, x2);
+ if (x2 > mx2) mx2 = PApplet.min(pixelWidth, x2);
+ if (y2 < my1) my1 = PApplet.max(0, y2);
+ if (y2 > my2) my2 = PApplet.min(pixelHeight, 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();
+ }
+
+
+ /**
+ * ( begin auto-generated from PImage_resize.xml )
+ *
+ * Resize the image to a new width and height. To make the image scale
+ * proportionally, use 0 as the value for the wide or high
+ * parameter. For instance, to make the width of an image 150 pixels, and
+ * change the height using the same proportion, use resize(150, 0).
+ *
+ * Even though a PGraphics is technically a PImage, it is not possible to
+ * rescale the image data found in a PGraphics. (It's simply not possible
+ * to do this consistently across renderers: technically infeasible with
+ * P3D, or what would it even do with PDF?) If you want to resize PGraphics
+ * content, first get a copy of its image data using the get()
+ * method, and call resize() on the PImage that is returned.
+ *
+ * ( end auto-generated )
+ * @webref pimage:method
+ * @brief Changes the size of an image to a new width and height
+ * @usage web_application
+ * @param w the resized image width
+ * @param h the resized image height
+ * @see PImage#get(int, int, int, int)
+ */
+ public void resize(int w, int h) { // ignore
+ 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);
+ }
+
+ BufferedImage img =
+ shrinkImage((BufferedImage) getNative(), w*pixelDensity, h*pixelDensity);
+
+ PImage temp = new PImage(img);
+ this.pixelWidth = temp.width;
+ this.pixelHeight = temp.height;
+
+ // Get the resized pixel array
+ this.pixels = temp.pixels;
+
+ this.width = pixelWidth / pixelDensity;
+ this.height = pixelHeight / pixelDensity;
+
+ // Mark the pixels array as altered
+ updatePixels();
+ }
+
+
+ // Adapted from getFasterScaledInstance() method from page 111 of
+ // "Filthy Rich Clients" by Chet Haase and Romain Guy
+ // Additional modifications and simplifications have been added,
+ // plus a fix to deal with an infinite loop if images are expanded.
+ // http://code.google.com/p/processing/issues/detail?id=1463
+ static private BufferedImage shrinkImage(BufferedImage img,
+ int targetWidth, int targetHeight) {
+ int type = (img.getTransparency() == Transparency.OPAQUE) ?
+ BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
+ BufferedImage outgoing = img;
+ BufferedImage scratchImage = null;
+ Graphics2D g2 = null;
+ int prevW = outgoing.getWidth();
+ int prevH = outgoing.getHeight();
+ boolean isTranslucent = img.getTransparency() != Transparency.OPAQUE;
+
+ // Use multi-step technique: start with original size, then scale down in
+ // multiple passes with drawImage() until the target size is reached
+ int w = img.getWidth();
+ int h = img.getHeight();
+
+ do {
+ if (w > targetWidth) {
+ w /= 2;
+ // if this is the last step, do the exact size
+ if (w < targetWidth) {
+ w = targetWidth;
+ }
+ } else if (targetWidth >= w) {
+ w = targetWidth;
+ }
+ if (h > targetHeight) {
+ h /= 2;
+ if (h < targetHeight) {
+ h = targetHeight;
+ }
+ } else if (targetHeight >= h) {
+ h = targetHeight;
+ }
+ if (scratchImage == null || isTranslucent) {
+ // Use a single scratch buffer for all iterations and then copy
+ // to the final, correctly-sized image before returning
+ scratchImage = new BufferedImage(w, h, type);
+ g2 = scratchImage.createGraphics();
+ }
+ g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+ g2.drawImage(outgoing, 0, 0, w, h, 0, 0, prevW, prevH, null);
+ prevW = w;
+ prevH = h;
+ outgoing = scratchImage;
+ } while (w != targetWidth || h != targetHeight);
+
+ if (g2 != null) {
+ g2.dispose();
+ }
+
+ // If we used a scratch buffer that is larger than our target size,
+ // create an image of the right size and copy the results into it
+ if (targetWidth != outgoing.getWidth() ||
+ targetHeight != outgoing.getHeight()) {
+ scratchImage = new BufferedImage(targetWidth, targetHeight, type);
+ g2 = scratchImage.createGraphics();
+ g2.drawImage(outgoing, 0, 0, null);
+ g2.dispose();
+ outgoing = scratchImage;
+ }
+ return outgoing;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+ // 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
+
+
+ /**
+ * ( 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) {
+ if ((x < 0) || (y < 0) || (x >= pixelWidth) || (y >= pixelHeight)) return 0;
+
+ switch (format) {
+ case RGB:
+ return pixels[y*pixelWidth + x] | 0xff000000;
+
+ case ARGB:
+ return pixels[y*pixelWidth + x];
+
+ case ALPHA:
+ return (pixels[y*pixelWidth + x] << 24) | 0xffffff;
+ }
+ return 0;
+ }
+
+
+ /**
+ * @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 > pixelWidth) {
+ w = pixelWidth - x;
+ cropped = true;
+ }
+ if (y + h > pixelHeight) {
+ h = pixelHeight - 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 / pixelDensity,
+ targetHeight / pixelDensity,
+ targetFormat, pixelDensity);
+ 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);
+ }
+ return target;
+ }
+
+
+ /**
+ * Returns a copy of this PImage. Equivalent to get(0, 0, width, height).
+ * Deprecated, just use copy() instead.
+ */
+ 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, pixelWidth, pixelHeight);
+ }
+
+
+ public PImage copy() {
+ return get(0, 0, pixelWidth, pixelHeight);
+ }
+
+
+ /**
+ * 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) {
+ int sourceIndex = sourceY*pixelWidth + sourceX;
+ int targetIndex = targetY*target.pixelWidth + targetX;
+ for (int row = 0; row < sourceHeight; row++) {
+ System.arraycopy(pixels, sourceIndex, target.pixels, targetIndex, sourceWidth);
+ sourceIndex += pixelWidth;
+ targetIndex += target.pixelWidth;
+ }
+ }
+
+
+ /**
+ * ( 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) {
+ if ((x < 0) || (y < 0) || (x >= pixelWidth) || (y >= pixelHeight)) return;
+ pixels[y*pixelWidth + x] = c;
+ updatePixels(x, y, 1, 1); // slow...
+ }
+
+
+ /**
+ *
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) {
+ int sx = 0;
+ int sy = 0;
+ int sw = img.pixelWidth;
+ int sh = img.pixelHeight;
+
+ 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 > pixelWidth) { // off right edge
+ sw = pixelWidth - x;
+ }
+ if (y + sh > pixelHeight) { // off bottom edge
+ sh = pixelHeight - 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) {
+ int sourceOffset = sourceY * sourceImage.pixelWidth + sourceX;
+ int targetOffset = targetY * pixelWidth + targetX;
+
+ for (int y = sourceY; y < sourceY + sourceHeight; y++) {
+ System.arraycopy(sourceImage.pixels, sourceOffset, pixels, targetOffset, sourceWidth);
+ sourceOffset += sourceImage.pixelWidth;
+ targetOffset += pixelWidth;
+ }
+
+ //updatePixelsImpl(targetX, targetY, sourceWidth, sourceHeight);
+ updatePixels(targetX, targetY, sourceWidth, sourceHeight);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // ALPHA CHANNEL
+
+
+ /**
+ * @param maskArray array of integers used as the alpha channel, needs to be
+ * the same length as the image's pixel array.
+ */
+ public void mask(int maskArray[]) { // ignore
+ loadPixels();
+ // don't execute if mask image is different size
+ if (maskArray.length != pixels.length) {
+ throw new IllegalArgumentException("mask() can only be used with an image that's the same size.");
+ }
+ for (int i = 0; i < pixels.length; i++) {
+ pixels[i] = ((maskArray[i] & 0xff) << 24) | (pixels[i] & 0xffffff);
+ }
+ format = ARGB;
+ updatePixels();
+ }
+
+
+ /**
+ * ( 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) {
+ img.loadPixels();
+ mask(img.pixels);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // IMAGE FILTERS
+
+
+ public void filter(int kind) {
+ loadPixels();
+
+ switch (kind) {
+ case BLUR:
+ // TODO write basic low-pass filter blur here
+ // what does photoshop do on the edges with this guy?
+ // better yet.. why bother? just use gaussian with radius 1
+ filter(BLUR, 1);
+ break;
+
+ case GRAY:
+ if (format == ALPHA) {
+ // for an alpha image, convert it to an opaque grayscale
+ for (int i = 0; i < pixels.length; i++) {
+ int col = 255 - pixels[i];
+ pixels[i] = 0xff000000 | (col << 16) | (col << 8) | col;
+ }
+ format = RGB;
+
+ } else {
+ // Converts RGB image data into grayscale using
+ // weighted RGB components, and keeps alpha channel intact.
+ // [toxi 040115]
+ for (int i = 0; i < pixels.length; i++) {
+ int col = pixels[i];
+ // luminance = 0.3*red + 0.59*green + 0.11*blue
+ // 0.30 * 256 = 77
+ // 0.59 * 256 = 151
+ // 0.11 * 256 = 28
+ int lum = (77*(col>>16&0xff) + 151*(col>>8&0xff) + 28*(col&0xff))>>8;
+ pixels[i] = (col & ALPHA_MASK) | lum<<16 | lum<<8 | lum;
+ }
+ }
+ break;
+
+ case INVERT:
+ for (int i = 0; i < pixels.length; i++) {
+ //pixels[i] = 0xff000000 |
+ pixels[i] ^= 0xffffff;
+ }
+ break;
+
+ case POSTERIZE:
+ throw new RuntimeException("Use filter(POSTERIZE, int levels) " +
+ "instead of filter(POSTERIZE)");
+
+ case OPAQUE:
+ for (int i = 0; i < pixels.length; i++) {
+ pixels[i] |= 0xff000000;
+ }
+ format = RGB;
+ break;
+
+ case THRESHOLD:
+ filter(THRESHOLD, 0.5f);
+ break;
+
+ // [toxi 050728] added new filters
+ case ERODE:
+ erode(); // former dilate(true);
+ break;
+
+ case DILATE:
+ dilate(); // former dilate(false);
+ break;
+ }
+ updatePixels(); // mark as modified
+ }
+
+
+ /**
+ * ( 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) {
+ 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
+ }
+
+
+ /** Set the high bits of all pixels to opaque. */
+ protected void opaque() {
+ for (int i = 0; i < pixels.length; i++) {
+ pixels[i] = 0xFF000000 | pixels[i];
+ }
+ }
+
+
+ /**
+ * 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 < pixelHeight; y++) {
+ for (int x = 0; x < pixelWidth; x++) {
+ //cb = cg = cr = sum = 0;
+ cb = sum = 0;
+ read = x - blurRadius;
+ if (read<0) {
+ bk0=-read;
+ read=0;
+ } else {
+ if (read >= pixelWidth)
+ break;
+ bk0=0;
+ }
+ for (int i = bk0; i < blurKernelSize; i++) {
+ if (read >= pixelWidth)
+ 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 += pixelWidth;
+ }
+
+ yi = 0;
+ ym = -blurRadius;
+ ymi = ym * pixelWidth;
+
+ for (int y = 0; y < pixelHeight; y++) {
+ for (int x = 0; x < pixelWidth; x++) {
+ cb = sum = 0;
+ if (ym < 0) {
+ bk0 = ri = -ym;
+ read = x;
+ } else {
+ if (ym >= pixelHeight)
+ break;
+ bk0 = 0;
+ ri = ym;
+ read = x + ymi;
+ }
+ for (int i = bk0; i < blurKernelSize; i++) {
+ if (ri >= pixelHeight)
+ break;
+ int[] bm = blurMult[i];
+ cb += bm[b2[read]];
+ sum += blurKernel[i];
+ ri++;
+ read += pixelWidth;
+ }
+ pixels[x+yi] = (cb/sum);
+ }
+ yi += pixelWidth;
+ ymi += pixelWidth;
+ 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 < pixelHeight; y++) {
+ for (int x = 0; x < pixelWidth; x++) {
+ cb = cg = cr = sum = 0;
+ read = x - blurRadius;
+ if (read < 0) {
+ bk0 = -read;
+ read = 0;
+ } else {
+ if (read >= pixelWidth) {
+ break;
+ }
+ bk0 = 0;
+ }
+ for (int i = bk0; i < blurKernelSize; i++) {
+ if (read >= pixelWidth) {
+ 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 += pixelWidth;
+ }
+
+ yi = 0;
+ ym = -blurRadius;
+ ymi = ym * pixelWidth;
+
+ for (int y = 0; y < pixelHeight; y++) {
+ for (int x = 0; x < pixelWidth; x++) {
+ cb = cg = cr = sum = 0;
+ if (ym < 0) {
+ bk0 = ri = -ym;
+ read = x;
+ } else {
+ if (ym >= pixelHeight) {
+ break;
+ }
+ bk0 = 0;
+ ri = ym;
+ read = x + ymi;
+ }
+ for (int i = bk0; i < blurKernelSize; i++) {
+ if (ri >= pixelHeight) {
+ break;
+ }
+ int[] bm = blurMult[i];
+ cr += bm[r2[read]];
+ cg += bm[g2[read]];
+ cb += bm[b2[read]];
+ sum += blurKernel[i];
+ ri++;
+ read += pixelWidth;
+ }
+ pixels[x+yi] = 0xff000000 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum);
+ }
+ yi += pixelWidth;
+ ymi += pixelWidth;
+ 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 < pixelHeight; y++) {
+ for (int x = 0; x < pixelWidth; x++) {
+ cb = cg = cr = ca = sum = 0;
+ read = x - blurRadius;
+ if (read < 0) {
+ bk0 = -read;
+ read = 0;
+ } else {
+ if (read >= pixelWidth) {
+ break;
+ }
+ bk0=0;
+ }
+ for (int i = bk0; i < blurKernelSize; i++) {
+ if (read >= pixelWidth) {
+ 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 += pixelWidth;
+ }
+
+ yi = 0;
+ ym = -blurRadius;
+ ymi = ym * pixelWidth;
+
+ for (int y = 0; y < pixelHeight; y++) {
+ for (int x = 0; x < pixelWidth; x++) {
+ cb = cg = cr = ca = sum = 0;
+ if (ym < 0) {
+ bk0 = ri = -ym;
+ read = x;
+ } else {
+ if (ym >= pixelHeight) {
+ break;
+ }
+ bk0 = 0;
+ ri = ym;
+ read = x + ymi;
+ }
+ for (int i = bk0; i < blurKernelSize; i++) {
+ if (ri >= pixelHeight) {
+ 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 += pixelWidth;
+ }
+ pixels[x+yi] = (ca/sum)<<24 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum);
+ }
+ yi += pixelWidth;
+ ymi += pixelWidth;
+ ym++;
+ }
+ }
+
+
+ /**
+ * Generic dilate/erode filter using luminance values
+ * as decision factor. [toxi 050728]
+ */
+ protected void dilate() { // formerly dilate(false)
+ int index = 0;
+ int maxIndex = pixels.length;
+ int[] outgoing = new int[maxIndex];
+
+ // erosion (grow light areas)
+ while (index < maxIndex) {
+ int curRowIndex = index;
+ int maxRowIndex = index + pixelWidth;
+ while (index < maxRowIndex) {
+ int orig = pixels[index];
+ int result = orig;
+ int idxLeft = index - 1;
+ int idxRight = index + 1;
+ int idxUp = index - pixelWidth;
+ int idxDown = index + pixelWidth;
+ if (idxLeft < curRowIndex) {
+ idxLeft = index;
+ }
+ if (idxRight >= maxRowIndex) {
+ idxRight = index;
+ }
+ if (idxUp < 0) {
+ idxUp = index;
+ }
+ if (idxDown >= maxIndex) {
+ idxDown = index;
+ }
+
+ int colUp = pixels[idxUp];
+ int colLeft = pixels[idxLeft];
+ int colDown = pixels[idxDown];
+ int colRight = pixels[idxRight];
+
+ // compute luminance
+ int currLum =
+ 77*(orig>>16&0xff) + 151*(orig>>8&0xff) + 28*(orig&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) {
+ result = colLeft;
+ currLum = lumLeft;
+ }
+ if (lumRight > currLum) {
+ result = colRight;
+ currLum = lumRight;
+ }
+ if (lumUp > currLum) {
+ result = colUp;
+ currLum = lumUp;
+ }
+ if (lumDown > currLum) {
+ result = colDown;
+ currLum = lumDown;
+ }
+ outgoing[index++] = result;
+ }
+ }
+ System.arraycopy(outgoing, 0, pixels, 0, maxIndex);
+ }
+
+
+ protected void erode() { // formerly dilate(true)
+ int index = 0;
+ int maxIndex = pixels.length;
+ int[] outgoing = new int[maxIndex];
+
+ // dilate (grow dark areas)
+ while (index < maxIndex) {
+ int curRowIndex = index;
+ int maxRowIndex = index + pixelWidth;
+ while (index < maxRowIndex) {
+ int orig = pixels[index];
+ int result = orig;
+ int idxLeft = index - 1;
+ int idxRight = index + 1;
+ int idxUp = index - pixelWidth;
+ int idxDown = index + pixelWidth;
+ if (idxLeft < curRowIndex) {
+ idxLeft = index;
+ }
+ if (idxRight >= maxRowIndex) {
+ idxRight = index;
+ }
+ if (idxUp < 0) {
+ idxUp = index;
+ }
+ if (idxDown >= maxIndex) {
+ idxDown = index;
+ }
+
+ int colUp = pixels[idxUp];
+ int colLeft = pixels[idxLeft];
+ int colDown = pixels[idxDown];
+ int colRight = pixels[idxRight];
+
+ // compute luminance
+ int currLum =
+ 77*(orig>>16&0xff) + 151*(orig>>8&0xff) + 28*(orig&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) {
+ result = colLeft;
+ currLum = lumLeft;
+ }
+ if (lumRight < currLum) {
+ result = colRight;
+ currLum = lumRight;
+ }
+ if (lumUp < currLum) {
+ result = colUp;
+ currLum = lumUp;
+ }
+ if (lumDown < currLum) {
+ result = colDown;
+ currLum = lumDown;
+ }
+ outgoing[index++] = result;
+ }
+ }
+ System.arraycopy(outgoing, 0, pixels, 0, maxIndex);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // COPY
+
+
+ /**
+ * ( 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) {
+ blend(this, sx, sy, sw, sh, dx, dy, dw, dh, REPLACE);
+ }
+
+
+/**
+ * @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) {
+ blend(src, sx, sy, sw, sh, dx, dy, dw, dh, REPLACE);
+ }
+
+
+
+ //////////////////////////////////////////////////////////////
+
+ // BLEND
+
+
+ /**
+ * ( begin auto-generated from blendColor.xml )
+ *
+ * Blends two color values together based on the blending mode given as the
+ * MODE parameter. The possible modes are described in the reference
+ * for the blend() function.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ *
+ *
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.
+ *
+ * @webref color:creating_reading
+ * @usage web_application
+ * @param c1 the first color to blend
+ * @param c2 the second color to blend
+ * @param mode either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN
+ * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int)
+ * @see PApplet#color(float, float, float, float)
+ */
+ 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;
+ }
+
+
+ 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);
+ }
+
+
+ /**
+ * ( 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) {
+ 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);
+ 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) ((pixelWidth >> 8) & 0xff);
+ tiff[31] = (byte) ((pixelWidth) & 0xff);
+ tiff[42] = tiff[102] = (byte) ((pixelHeight >> 8) & 0xff);
+ tiff[43] = tiff[103] = (byte) ((pixelHeight) & 0xff);
+
+ int count = pixelWidth*pixelHeight*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) (pixelWidth & 0xff);
+ header[13] = (byte) (pixelWidth >> 8);
+ header[14] = (byte) (pixelHeight & 0xff);
+ header[15] = (byte) (pixelHeight >> 8);
+
+ try {
+ output.write(header);
+
+ int maxLen = pixelHeight * pixelWidth;
+ 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 boolean saveImageIO(String path) throws IOException {
+ try {
+ int outputFormat = (format == ARGB) ?
+ BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
+
+ String extension =
+ path.substring(path.lastIndexOf('.') + 1).toLowerCase();
+
+ // JPEG and BMP images that have an alpha channel set get pretty unhappy.
+ // BMP just doesn't write, and JPEG writes it as a CMYK image.
+ // http://code.google.com/p/processing/issues/detail?id=415
+ if (extension.equals("bmp") || extension.equals("jpg") || extension.equals("jpeg")) {
+ outputFormat = BufferedImage.TYPE_INT_RGB;
+ }
+
+ BufferedImage bimage = new BufferedImage(pixelWidth, pixelHeight, outputFormat);
+ bimage.setRGB(0, 0, pixelWidth, pixelHeight, pixels, 0, pixelWidth);
+
+ File file = new File(path);
+
+ ImageWriter writer = null;
+ ImageWriteParam param = null;
+ IIOMetadata metadata = null;
+
+ if (extension.equals("jpg") || extension.equals("jpeg")) {
+ if ((writer = imageioWriter("jpeg")) != null) {
+ // Set JPEG quality to 90% with baseline optimization. Setting this
+ // to 1 was a huge jump (about triple the size), so this seems good.
+ // Oddly, a smaller file size than Photoshop at 90%, but I suppose
+ // it's a completely different algorithm.
+ param = writer.getDefaultWriteParam();
+ param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+ param.setCompressionQuality(0.9f);
+ }
+ }
+
+ if (extension.equals("png")) {
+ if ((writer = imageioWriter("png")) != null) {
+ param = writer.getDefaultWriteParam();
+ if (false) {
+ metadata = imageioDPI(writer, param, 100);
+ }
+ }
+ }
+
+ if (writer != null) {
+ BufferedOutputStream output =
+ new BufferedOutputStream(PApplet.createOutput(file));
+ writer.setOutput(ImageIO.createImageOutputStream(output));
+// writer.write(null, new IIOImage(bimage, null, null), param);
+ writer.write(metadata, new IIOImage(bimage, null, metadata), param);
+ writer.dispose();
+
+ output.flush();
+ output.close();
+ return true;
+ }
+ // If iter.hasNext() somehow fails up top, it falls through to here
+ return javax.imageio.ImageIO.write(bimage, extension, file);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new IOException("image save failed.");
+ }
+ }
+
+
+ private ImageWriter imageioWriter(String extension) {
+ Iterator iter = ImageIO.getImageWritersByFormatName(extension);
+ if (iter.hasNext()) {
+ return iter.next();
+ }
+ return null;
+ }
+
+
+ private IIOMetadata imageioDPI(ImageWriter writer, ImageWriteParam param, double dpi) {
+ // http://stackoverflow.com/questions/321736/how-to-set-dpi-information-in-an-image
+ ImageTypeSpecifier typeSpecifier =
+ ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
+ IIOMetadata metadata =
+ writer.getDefaultImageMetadata(typeSpecifier, param);
+
+ if (!metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
+ // for PNG, it's dots per millimeter
+ double dotsPerMilli = dpi / 25.4;
+
+ IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
+ horiz.setAttribute("value", Double.toString(dotsPerMilli));
+
+ IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
+ vert.setAttribute("value", Double.toString(dotsPerMilli));
+
+ IIOMetadataNode dim = new IIOMetadataNode("Dimension");
+ dim.appendChild(horiz);
+ dim.appendChild(vert);
+
+ IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
+ root.appendChild(dim);
+
+ try {
+ metadata.mergeTree("javax_imageio_1.0", root);
+ return metadata;
+
+ } catch (IIOInvalidTreeException e) {
+ System.err.println("Could not set the DPI of the output image");
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+
+ protected String[] saveImageFormats;
+
+ /**
+ * ( begin auto-generated from PImage_save.xml )
+ *
+ * Saves the image into a file. Append a file extension to the name of
+ * the file, to indicate the file format to be used: either TIFF (.tif),
+ * TARGA (.tga), JPEG (.jpg), or PNG (.png). If no extension is included
+ * in the filename, the image will save in TIFF format and .tif will be
+ * added to the name. These files are saved to the sketch's folder, which
+ * may be opened by selecting "Show sketch folder" from the "Sketch" menu.
+ *
To save an image created within the code, rather
+ * than through loading, it's necessary to make the image with the
+ * createImage() function so it is aware of the location of the
+ * program and can therefore save the file to the right place. See the
+ * createImage() reference for more information.
+ *
+ * ( end auto-generated )
+ *
Advanced
+ * Save this image to disk.
+ *
+ * As of revision 0100, this function requires an absolute path,
+ * in order to avoid confusion. To save inside the sketch folder,
+ * use the function savePath() from PApplet, or use saveFrame() instead.
+ * As of revision 0116, savePath() is not needed if this object has been
+ * created (as recommended) via createImage() or createGraphics() or
+ * one of its neighbors.
+ *
+ * As of revision 0115, when using Java 1.4 and later, you can write
+ * to several formats besides tga and tiff. If Java 1.4 is installed
+ * and the extension used is supported (usually png, jpg, jpeg, bmp,
+ * and tiff), then those methods will be used to write the image.
+ * To get a list of the supported formats for writing, use:
+ * println(javax.imageio.ImageIO.getReaderFormatNames())
+ *
+ * To use the original built-in image writers, use .tga or .tif as the
+ * extension, or don't include an extension. When no extension is used,
+ * the extension .tif will be added to the file name.
+ *
+ * The ImageIO API claims to support wbmp files, however they probably
+ * require a black and white image. Basic testing produced a zero-length
+ * file with no error.
+ *
+ * @webref pimage:method
+ * @brief Saves the image to a TIFF, TARGA, PNG, or JPEG file
+ * @usage application
+ * @param filename a sequence of letters and numbers
+ */
+ public boolean save(String filename) { // ignore
+ boolean success = false;
+
+ if (parent != null) {
+ // use savePath(), so that the intermediate directories are created
+ filename = parent.savePath(filename);
+
+ } else {
+ File file = new File(filename);
+ if (file.isAbsolute()) {
+ // make sure that the intermediate folders have been created
+ PApplet.createPath(file);
+ } else {
+ String msg =
+ "PImage.save() requires an absolute path. " +
+ "Use createImage(), or pass savePath() to save().";
+ PGraphics.showException(msg);
+ }
+ }
+
+ // Make sure the pixel data is ready to go
+ loadPixels();
+
+ try {
+ OutputStream os = null;
+
+ if (saveImageFormats == null) {
+ saveImageFormats = javax.imageio.ImageIO.getWriterFormatNames();
+ }
+ if (saveImageFormats != null) {
+ for (int i = 0; i < saveImageFormats.length; i++) {
+ if (filename.endsWith("." + saveImageFormats[i])) {
+ if (!saveImageIO(filename)) {
+ System.err.println("Error while saving image.");
+ return false;
+ }
+ return true;
+ }
+ }
+ }
+
+ if (filename.toLowerCase().endsWith(".tga")) {
+ os = new BufferedOutputStream(new FileOutputStream(filename), 32768);
+ success = saveTGA(os); //, pixels, width, height, format);
+
+ } else {
+ if (!filename.toLowerCase().endsWith(".tif") &&
+ !filename.toLowerCase().endsWith(".tiff")) {
+ // if no .tif extension, add it..
+ filename += ".tif";
+ }
+ os = new BufferedOutputStream(new FileOutputStream(filename), 32768);
+ success = saveTIFF(os); //, pixels, width, height);
+ }
+ os.flush();
+ os.close();
+
+ } catch (IOException e) {
+ System.err.println("Error while saving image.");
+ e.printStackTrace();
+ success = false;
+ }
+ return success;
+ }
+}
diff --git a/src/main/java/processing/core/PMatrix.java b/src/main/java/processing/core/PMatrix.java
new file mode 100644
index 0000000..edb1d26
--- /dev/null
+++ b/src/main/java/processing/core/PMatrix.java
@@ -0,0 +1,208 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2005-08 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+
+/**
+ * A matrix is used to define graphical transformations. PMatrix is the common
+ * interface for both the 2D and 3D matrix classes in Processing. A matrix is a
+ * grid of numbers, which can be multiplied by a vector to give another vector.
+ * Multiplying a point by a particular matrix might translate it, rotate it,
+ * or carry out a combination of transformations.
+ *
+ * Multiplying matrices by each other combines their effects; use the
+ * {@code apply} and {@code preApply} methods for this.
+ */
+public interface PMatrix {
+
+ /**
+ * Make this an identity matrix. Multiplying by it will have no effect.
+ */
+ 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);
+
+
+ /**
+ * Make this matrix become a copy of src.
+ */
+ public void set(PMatrix src);
+
+ /**
+ * Set the contents of this matrix to the contents of source. Fills the
+ * matrix left-to-right, starting in the top row.
+ */
+ public void set(float[] source);
+
+ /**
+ * Set the matrix content to this 2D matrix or its 3D equivalent.
+ */
+ public void set(float m00, float m01, float m02,
+ float m10, float m11, float m12);
+
+ /**
+ * Set the matrix content to the 3D matrix supplied, if this matrix is 3D.
+ */
+ 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);
+
+ /**
+ * Multiply this matrix by another.
+ */
+ public void apply(PMatrix2D source);
+
+ /**
+ * Multiply this matrix by another.
+ */
+ public void apply(PMatrix3D source);
+
+ /**
+ * Multiply this matrix by another.
+ */
+ public void apply(float n00, float n01, float n02,
+ float n10, float n11, float n12);
+
+ /**
+ * Multiply this matrix by another.
+ */
+ 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();
+}
diff --git a/src/main/java/processing/core/PMatrix2D.java b/src/main/java/processing/core/PMatrix2D.java
new file mode 100644
index 0000000..38f82bd
--- /dev/null
+++ b/src/main/java/processing/core/PMatrix2D.java
@@ -0,0 +1,534 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2005-08 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+
+/**
+ * 3x2 affine matrix implementation.
+ * Matrices are used to describe a transformation; see {@link PMatrix} for a
+ * general description. This matrix looks like the following when multiplying
+ * a vector (x, y) in {@code mult()}.
+ *
+ * (x', y', z', w') is returned. The values in the matrix determine the
+ * transformation. They are modified by the various transformation functions.
+ *
+ * To transform 3D coordinates, w is set to 1, amd w' is made to be 1 by
+ * setting the bottom row of the matrix to [0 0 0 1]. The
+ * resulting point is then (x', y', z').
+ */
+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 the 3D equivalent of the 2D matrix supplied to the left of this one.
+ */
+ 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(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(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);
+ }
+
+
+ /**
+ * Apply the 3D equivalent of the 2D matrix supplied to the left of this one.
+ */
+ 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);
+ }
+
+
+ /**
+ * Apply another matrix to the left of this one.
+ */
+ 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;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+
+
+ /**
+ * 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) {
+ 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.
+ * 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) {
+ 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;
+ }
+
+
+ /**
+ * Returns the x-coordinate of the result of multiplying the point (x, y)
+ * by this matrix.
+ */
+ public float multX(float x, float y) {
+ return m00*x + m01*y + m03;
+ }
+
+
+ /**
+ * Returns the y-coordinate of the result of multiplying the point (x, y)
+ * by this matrix.
+ */
+ public float multY(float x, float y) {
+ return m10*x + m11*y + m13;
+ }
+
+
+ /**
+ * Returns the x-coordinate of the result of multiplying the point (x, y, z)
+ * by this matrix.
+ */
+ public float multX(float x, float y, float z) {
+ return m00*x + m01*y + m02*z + m03;
+ }
+
+
+ /**
+ * Returns the y-coordinate of the result of multiplying the point (x, y, z)
+ * by this matrix.
+ */
+ public float multY(float x, float y, float z) {
+ return m10*x + m11*y + m12*z + m13;
+ }
+
+
+ /**
+ * Returns the z-coordinate of the result of multiplying the point (x, y, z)
+ * by this matrix.
+ */
+ public float multZ(float x, float y, float z) {
+ return m20*x + m21*y + m22*z + m23;
+ }
+
+
+ /**
+ * Returns the fourth element of the result of multiplying the vector
+ * (x, y, z) by this matrix. (Acts as if w = 1 was supplied.)
+ */
+ public float multW(float x, float y, float z) {
+ return m30*x + m31*y + m32*z + m33;
+ }
+
+
+ /**
+ * Returns the x-coordinate of the result of multiplying the vector
+ * (x, y, z, w) by this matrix.
+ */
+ public float multX(float x, float y, float z, float w) {
+ return m00*x + m01*y + m02*z + m03*w;
+ }
+
+
+ /**
+ * Returns the y-coordinate of the result of multiplying the vector
+ * (x, y, z, w) by this matrix.
+ */
+ public float multY(float x, float y, float z, float w) {
+ return m10*x + m11*y + m12*z + m13*w;
+ }
+
+
+ /**
+ * Returns the z-coordinate of the result of multiplying the vector
+ * (x, y, z, w) by this matrix.
+ */
+ public float multZ(float x, float y, float z, float w) {
+ return m20*x + m21*y + m22*z + m23*w;
+ }
+
+
+ /**
+ * Returns the w-coordinate of the result of multiplying the vector
+ * (x, y, z, w) by this matrix.
+ */
+ public float multW(float x, float y, float z, float w) {
+ return m30*x + m31*y + m32*z + m33*w;
+ }
+
+
+ /**
+ * Transpose this matrix; rows become columns and columns rows.
+ */
+ 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. 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() {
+ 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/src/main/java/processing/core/PShape.java b/src/main/java/processing/core/PShape.java
new file mode 100644
index 0000000..7d6f1d7
--- /dev/null
+++ b/src/main/java/processing/core/PShape.java
@@ -0,0 +1,3445 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2006-10 Ben Fry and Casey Reas
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License version 2.1 as published by the Free Software Foundation.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+*/
+
+package processing.core;
+
+import java.util.HashMap;
+import 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;
+
+ 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 (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);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ 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;
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
+ public boolean contains(float x, float y) {
+ if (family == PATH) {
+ boolean c = false;
+ for (int i = 0, j = vertexCount-1; i < vertexCount; j = i++) {
+ if (((vertices[i][Y] > y) != (vertices[j][Y] > y)) &&
+ (x <
+ (vertices[j][X]-vertices[i][X]) *
+ (y-vertices[i][Y]) /
+ (vertices[j][1]-vertices[i][Y]) +
+ vertices[i][X])) {
+ c = !c;
+ }
+ }
+ return c;
+ } else {
+ throw new IllegalArgumentException("The contains() method is only implemented for paths.");
+ }
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ // translate, rotate, scale, apply (no push/pop)
+ // these each call matrix.translate, etc
+ // if matrix is null when one is called,
+ // it is created and set to identity
+
+
+/**
+ * ( 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/src/main/java/processing/core/PShapeOBJ.java b/src/main/java/processing/core/PShapeOBJ.java
new file mode 100644
index 0000000..a46e6ab
--- /dev/null
+++ b/src/main/java/processing/core/PShapeOBJ.java
@@ -0,0 +1,469 @@
+package processing.core;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 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, texIdx;
+ PVector vert, norms, tex;
+
+ vert = norms = tex = 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);
+ }
+ }
+
+ if (j < face.texIdx.size()) {
+ texIdx = face.texIdx.get(j).intValue() - 1;
+ if (-1 < texIdx) {
+ tex = texcoords.get(texIdx);
+ }
+ }
+
+ 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 (tex != null) {
+ vertices[j][PGraphics.U] = tex.x;
+ vertices[j][PGraphics.V] = tex.y;
+ }
+
+ if (mtl != null && mtl.kdMap != null) {
+ image = mtl.kdMap;
+ }
+ }
+ }
+
+
+ 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) {
+ Map mtlTable = new HashMap();
+ 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, fn, path, mreader, materials, mtlTable);
+ mreader.close();
+ }
+ }
+ } 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 mtlfn, String path,
+ BufferedReader reader,
+ ArrayList materials,
+ Map 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 = addMaterial(mtlname, materials, materialsHash);
+ } else {
+ if (currentMtl == null) {
+ currentMtl = addMaterial("material" + materials.size(),
+ materials, materialsHash);
+ }
+ 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;
+ }
+
+ File file = new File(parent.dataPath(texname));
+ if (file.exists()) {
+ currentMtl.kdMap = parent.loadImage(texname);
+ } else {
+ System.err.println("The texture map \"" + texname + "\" " +
+ "in the materials definition file \"" + mtlfn + "\" " +
+ "is missing or inaccessible, make sure " +
+ "the URL is valid or that the file has been " +
+ "added to your sketch and is readable.");
+ }
+ } 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 OBJMaterial addMaterial(String mtlname,
+ ArrayList materials,
+ Map materialsHash) {
+ OBJMaterial currentMtl = new OBJMaterial(mtlname);
+ materialsHash.put(mtlname, Integer.valueOf(materials.size()));
+ materials.add(currentMtl);
+ return currentMtl;
+ }
+
+ 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) {
+ // Obtaining the path
+ File file = new File(parent.dataPath(filename));
+ if (!file.exists()) {
+ file = parent.sketchFile(filename);
+ }
+ String absolutePath = file.getAbsolutePath();
+ return absolutePath.substring(0,
+ absolutePath.lastIndexOf(File.separator));
+ }
+
+
+ // 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/src/main/java/processing/core/PShapeSVG.java b/src/main/java/processing/core/PShapeSVG.java
new file mode 100644
index 0000000..bf5cdc2
--- /dev/null
+++ b/src/main/java/processing/core/PShapeSVG.java
@@ -0,0 +1,1787 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-15 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 processing.data.*;
+
+// TODO replace these with PMatrix2D
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+
+import java.util.Map;
+import java.util.HashMap;
+
+
+/**
+ * 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