diff --git a/.gitattributes b/.gitattributes index 7bb8fd7..ef77940 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5,4 +5,4 @@ data/documentation-data.yml binary .eslintrc.js linguist-detectable=false -rollup.config.js linguist-detectable=false +rollup.config.mjs linguist-detectable=false diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1b17bfc..d706c44 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -25,12 +25,12 @@ jobs: run: pnpm --filter rollup-plugins run build - name: build - run: pnpm vsce package + run: pnpm package - name: Release uses: softprops/action-gh-release@v1 with: - files: ./processing-vscode-*.vsix + files: ./processing-vscode.vsix env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 3992fc7..c48a0f1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ node_modules lib processing-vscode.js .eslintcache +.env diff --git a/.vscodeignore b/.vscodeignore index c967b09..16b8c2a 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -1,24 +1,26 @@ *.log -.github +__testsEE/ +.github/ .vscode/ data/ legacy/ media/ -node_modules/** +node_modules/ rollup/ scripts/ src/ .editorconfig .eslintcache .eslintignore -.eslintrc.js +.eslintrc.* .gitattributes .gitignore .prettierignore -.prettierrc.yml +.prettierrc.* .vscodeignore +jest.config.* pnpm-lock.yaml pnpm-workspace.yaml -rollup.config.js +rollup.config.* tsconfig.json diff --git a/data/documentation-data.yml b/data/documentation-data.yml index bd71a46..7b479b1 100644 --- a/data/documentation-data.yml +++ b/data/documentation-data.yml @@ -1,4 +1,6 @@ # THIS IS AN AUTOGENERATED FILE; DO NOT EDIT DIRECTLY +# All documentation is by the Processing Foundation (https://processing.org/reference/strokeJoin_.html) +# and licensed under CC BY-NC-SA 4.0 Deed (https://creativecommons.org/licenses/by-nc-sa/4.0/) Array: description: >- @@ -9,19 +11,83 @@ Array: objects, so they must be created with the keyword `new`. - Each array has a variable `length`, which is an integer value for the total number of elements in the array. Note that since index numbering begins at zero (not 1), the last value in an array with a `length` of 5 should be referenced as `array[4]` (that is, the `length` minus 1), not `array[5]`, which would trigger an error. + Each array has a variable `length`, which is an integer value for the total + number of elements in the array. Note that since index numbering begins at + zero (not 1), the last value in an array with a `length` of 5 should be + referenced as `array[4]` (that is, the `length` minus 1), not `array[5]`, + which would trigger an error. + + + Another common source of confusion is the difference between using `length` + to get the size of an array and `length()` to get the size of a String. + Notice the presence of parentheses when working with Strings. + (`array.length` is a variable, while `String.length()` is a method specific + to the String class.) + examples: + - | + int[] numbers = new int[3]; + numbers[0] = 90; // Assign value to first element in the array + numbers[1] = 150; // Assign value to second element in the array + numbers[2] = 30; // Assign value to third element in the array + int a = numbers[0] + numbers[1]; // Sets variable 'a' to 240 + int b = numbers[1] + numbers[2]; // Sets variable 'b' to 180 + - | + int[] numbers = { 90, 150, 30 }; // Alternate syntax + int a = numbers[0] + numbers[1]; // Sets variable 'a' to 240 + int b = numbers[1] + numbers[2]; // Sets variable 'b' to 180 + - | + int degrees = 360; + float[] cos_vals = new float[degrees]; + // Use a for() loop to quickly iterate + // through all values in an array. + for (int i=0; i < degrees; i++) { + cos_vals[i] = cos(TWO_PI/degrees * i); + } + - | + float[] randoms = new float[100]; + for (int i = 0; i < randoms.length; i++) { + randoms[i] = random(100); + } + + // You can also use an enhanced loop + // to access the elements of an array + for (float val : randoms) { + println(val); + } + // This works with arrays of objects, too, + // but not when first making the array + PVector[] vectors = new PVector[5]; + for (int i = 0; i < vectors.length; i++) { + vectors[i] = new PVector(); + } - Another common source of confusion is the difference between using `length` to get the size of an array and `length()` to get the size of a String. Notice the presence of parentheses when working with Strings. (`array.length` is a variable, while `String.length()` is a method specific to the String class.) - docUrl: https://processing.org/reference/Array.html + // The syntax only applies when iterating + // over an existing array + for (PVector v : vectors) { + point(v.x, v.y); + } fields: {} + fileName: Array methods: {} - name: null parameters: - datatype: any primitive or compound datatype, including user-defined classes - element: "int: must not exceed the length of the array minus 1" - value: data to assign to the array element; must be the same datatype as the array - var: any valid variable name + datatype: + desc: any primitive or compound datatype, including user-defined classes + type: [] + element: + desc: "int: must not exceed the length of the array minus 1" + type: [] + value: + desc: data to assign to the array element; must be the same datatype as the + array + type: [] + var: + desc: any valid variable name + type: [] + syntax: + - datatype[] var + - var[element] = value + - var.length type: class ArrayList: description: >- @@ -34,64 +100,351 @@ ArrayList: StringList. - An ArrayList is a resizable-array implementation of the Java List interface. It has many methods used to control and search its contents. For example, the length of the `ArrayList` is returned by its `size()` method, which is an integer value for the total number of elements in the list. An element is added to an `ArrayList` with the `add()` method and is deleted with the `remove()` method. The `get()` method returns the element at the specified position in the list. (See the above example for context.) + An ArrayList is a resizable-array implementation of the Java List interface. + It has many methods used to control and search its contents. For example, + the length of the `ArrayList` is returned by its `size()` method, which is + an integer value for the total number of elements in the list. An element is + added to an `ArrayList` with the `add()` method and is deleted with the + `remove()` method. The `get()` method returns the element at the specified + position in the list. (See the above example for context.) + + + For a list of the numerous `ArrayList` features, please read the Java + reference description. + examples: + - > + // These are code fragments that show how to use an ArrayList. + + // They won't compile because they assume the existence of a Particle + class. + + + // Declaring the ArrayList, note the use of the syntax "" to + indicate + + // our intention to fill this ArrayList with Particle objects + + ArrayList particles = new ArrayList(); + + + // Objects can be added to an ArrayList with add() + + particles.add(new Particle()); + + + // Particles can be pulled out of an ArrayList with get() + + Particle part = particles.get(0); + + part.display(); + + + // The size() method returns the current number of items in the list + + int total = particles.size(); + + println("The total number of particles is: " + total); + + + // You can iterate over an ArrayList in two ways. + + // The first is by counting through the elements: + + for (int i = 0; i < particles.size(); i++) { + Particle part = particles.get(i); + part.display(); + } + + + // The second is using an enhanced loop: + + for (Particle part : particles) { + part.display(); + } + + + // You can delete particles from an ArrayList with remove() + + particles.remove(0); + + println(particles.size()); // Now one less! + + + // If you are modifying an ArrayList during the loop, + + // then you cannot use the enhanced loop syntax. + // In addition, when deleting in order to hit all elements, - For a list of the numerous `ArrayList`. . . - docUrl: https://processing.org/reference/ArrayList.html + // you should loop through it backwards, as shown here: + + for (int i = particles.size() - 1; i >= 0; i--) { + Particle part = particles.get(i); + if (part.finished()) { + particles.remove(i); + } + } fields: {} + fileName: ArrayList methods: {} - name: null parameters: - Type: "Class Name: the data type for the objects to be placed in the ArrayList." - initialCapacity: "int: defines the initial capacity of the list; it's empty by default" - syntax: | - ArrayList() - ArrayList(initialCapacity) + Type: + desc: "Class Name: the data type for the objects to be placed in the ArrayList." + type: [] + initialCapacity: + desc: "int: defines the initial capacity of the list; it's empty by default" + type: [] + syntax: + - ArrayList() + - ArrayList(initialCapacity) + type: class +BufferedReader: + description: >- + A `BufferedReader` object is used to read files line-by-line as individual + `String` objects. + + + 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. + examples: + - | + BufferedReader reader; + String line; + + void setup() { + // Open the file from the createWriter() example + reader = createReader("positions.txt"); + } + + void draw() { + try { + line = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + line = null; + } + if (line == null) { + // Stop reading because of an error or file is empty + noLoop(); + } else { + String[] pieces = split(line, TAB); + int x = int(pieces[0]); + int y = int(pieces[1]); + point(x, y); + } + } + fields: {} + fileName: BufferedReader + methods: + readLine: + anchor: BufferedReader_readLine_ + desc: Returns a String that is the current line in the BufferedReader. + parameters: {} + syntax: [] type: class FloatDict: - description: A simple class to use a String as a lookup for an float value. - String "keys" are associated with floating-point values. - docUrl: https://processing.org/reference/FloatDict.html + description: >- + A simple class to use a `String` as a lookup for a float value. String + "keys" + are associated with floating-point values. + examples: + - |+ + FloatDict inventory; + + void setup() { + size(200, 200); + inventory = new FloatDict(); + inventory.set("coffee",108.6); + inventory.set("flour",5.8); + inventory.set("tea",8.2); + println(inventory); + noLoop(); + fill(0); + textAlign(CENTER); + } + + void draw() { + float weight = inventory.get("coffee"); + text(weight, width/2, height/2); + } + fields: {} - methods: {} - name: null + fileName: FloatDict + methods: + add: + anchor: FloatDict_add_ + desc: Add to a value + clear: + anchor: FloatDict_clear_ + desc: Remove all entries + div: + anchor: FloatDict_div_ + desc: Divide a value + get: + anchor: FloatDict_get_ + desc: Return a value for the specified key + hasKey: + anchor: FloatDict_hasKey_ + desc: Check if a key is a part of the data structure + keyArray: + anchor: FloatDict_keyArray_ + desc: Return a copy of the internal keys array + keys: + anchor: FloatDict_keys_ + desc: Return the internal array being used to store the keys + maxIndex: + anchor: FloatDict_maxIndex_ + desc: Return the largest value + minIndex: + anchor: FloatDict_minIndex_ + desc: Return the smallest value + mult: + anchor: FloatDict_mult_ + desc: Multiply a value + remove: + anchor: FloatDict_remove_ + desc: Remove a key/value pair + set: + anchor: FloatDict_set_ + desc: Create a new key/value pair or change the value of one + size: + anchor: FloatDict_size_ + desc: Returns the number of key/value pairs + sortKeys: + anchor: FloatDict_sortKeys_ + desc: Sort the keys alphabetically + sortKeysReverse: + anchor: FloatDict_sortKeysReverse_ + desc: Sort the keys alphabetically in reverse + sortValues: + anchor: FloatDict_sortValues_ + desc: Sort by values in ascending order + sortValuesReverse: + anchor: FloatDict_sortValuesReverse_ + desc: Sort by values in descending order + sub: + anchor: FloatDict_sub_ + desc: Subtract from a value + valueArray: + anchor: FloatDict_valueArray_ + desc: Create a new array and copy each of the values into it + values: + anchor: FloatDict_values_ + desc: Return the internal array being used to store the values parameters: {} - syntax: | - FloatDict() - FloatDict(pairs) + syntax: + - FloatDict() + - FloatDict(pairs) type: class FloatList: description: |- - Helper class for a list of floats. Lists are designed to have some of the - features of ArrayLists, but to maintain the simplicity and efficiency of - working with arrays. + Helper class for a list of `float` values. Lists are designed + to have some features of `ArrayList`, but to maintain the + simplicity and efficiency of working with arrays. + Functions such as `sort()` and `shuffle()` always act on + the list itself. To get a sorted copy, use `list.copy().sort()`. + examples: + - |+ + FloatList inventory; + + void setup() { + size(200, 200); + inventory = new FloatList(); + inventory.append(108.6); + inventory.append(5.8); + inventory.append(8.2); + println(inventory); + noLoop(); + fill(0); + textAlign(CENTER); + } + + void draw() { + float nums = inventory.get(2); + text(nums, width/2, height/2); + } - Functions like sort() and shuffle() always act on the list itself. To get - a sorted copy, use list.copy().sort(). - docUrl: https://processing.org/reference/FloatList.html fields: {} - methods: {} - name: null + fileName: FloatList + methods: + add: + anchor: FloatList_add_ + desc: Add to a value + append: + anchor: FloatList_append_ + desc: Add a new entry to the list + clear: + anchor: FloatList_clear_ + desc: Remove all entries from the list + div: + anchor: FloatList_div_ + desc: Divide a value + get: + anchor: FloatList_get_ + desc: Get an entry at a particular index + hasValue: + anchor: FloatList_hasValue_ + desc: Check if a number is a part of the list + max: + anchor: FloatList_max_ + desc: Return the largest value + min: + anchor: FloatList_min_ + desc: Return the smallest value + mult: + anchor: FloatList_mult_ + desc: Multiply a value + remove: + anchor: FloatList_remove_ + desc: Remove an element from the specified index + reverse: + anchor: FloatList_reverse_ + desc: Reverse the order of the list + set: + anchor: FloatList_set_ + desc: Set the entry at a particular index + shuffle: + anchor: FloatList_shuffle_ + desc: Randomize the order of the list elements + size: + anchor: FloatList_size_ + desc: Get the length of the list + sort: + anchor: FloatList_sort_ + desc: Sorts an array, lowest to highest + sortReverse: + anchor: FloatList_sortReverse_ + desc: A sort in reverse + sub: + anchor: FloatList_sub_ + desc: Subtract from a value + toArray: + anchor: FloatList_toArray_ + desc: Create a new array with a copy of all the values parameters: {} - syntax: | - FloatList() - FloatList(items) + syntax: + - FloatList() + - FloatList(items) type: class HALF_PI: - description: "`HALF_PI` is a mathematical constant with the value 1.5707964. 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()`." - docUrl: https://processing.org/reference/HALF_PI.html - examples: | - float x = width/2; - float y = height/2; - float d = width * 0.8; - arc(x, y, d, d, 0, QUARTER_PI); - arc(x, y, d-20, d-20, 0, HALF_PI); - arc(x, y, d-40, d-40, 0, PI); - arc(x, y, d-60, d-60, 0, TWO_PI); - name: null + description: >- + `HALF_PI` is a mathematical constant with the value 1.5707964. 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()`. + examples: + - | + float x = width/2; + float y = height/2; + float d = width * 0.8; + size(400,400); + arc(x, y, d, d, 0, QUARTER_PI); + arc(x, y, d-80, d-80, 0, HALF_PI); + arc(x, y, d-160, d-160, 0, PI); + arc(x, y, d-240, d-240, 0, TWO_PI); + fileName: HALF_PI type: const HashMap: description: >- @@ -105,255 +458,1057 @@ HashMap: FloatDict, and StringDict classes. - For a list of the numerous `HashMap` features, please read the Java reference description. - docUrl: https://processing.org/reference/HashMap.html + For a list of the numerous `HashMap` features, please read the Java + reference description. + examples: + - |+ + import java.util.Map; + + // Note the HashMap's "key" is a String and "value" is an Integer + HashMap hm = new HashMap(); + + // Putting key-value pairs in the HashMap + hm.put("Ava", 1); + hm.put("Cait", 35); + hm.put("Casey", 36); + + // Using an enhanced loop to iterate over each entry + for (Map.Entry me : hm.entrySet()) { + print(me.getKey() + " is "); + println(me.getValue()); + } + + // We can also access values by their key + int val = hm.get("Casey"); + println("Casey is " + val); + fields: {} + fileName: HashMap methods: {} - name: null - parameters: - Key: "Class Name: the data type for the HashMap's keys" - Value: "Class Name: the data type for the HashMap's values" - initialCapacity: "int: defines the initial capacity of the map; the default is 16" - loadFactor: "float: the load factor for the map; the default is 0.75" - m: "Map: gives the new HashMap the same mappings as this Map" - syntax: | - HashMap() - HashMap(initialCapacity) - HashMap(initialCapacity, loadFactor) - HashMap(m) + parameters: + Key: + desc: "Class Name: the data type for the HashMap's keys" + type: [] + Value: + desc: "Class Name: the data type for the HashMap's values" + type: [] + initialCapacity: + desc: "int: defines the initial capacity of the map; the default is 16" + type: [] + loadFactor: + desc: "float: the load factor for the map; the default is 0.75" + type: [] + m: + desc: "Map: gives the new HashMap the same mappings as this Map" + type: [] + syntax: + - HashMap() + - HashMap(initialCapacity) + - HashMap(initialCapacity, loadFactor) + - HashMap(m) type: class IntDict: - description: A simple class to use a String as a lookup for an int value. String - "keys" are associated with integer values. - docUrl: https://processing.org/reference/IntDict.html + description: >- + A simple class to use a `String` as a lookup for an int value. String "keys" + are + associated with integer values. + examples: + - |+ + IntDict inventory; + + void setup() { + size(200, 200); + inventory = new IntDict(); + inventory.set("cd", 84); + inventory.set("tapes", 15); + inventory.set("records", 102); + println(inventory); + noLoop(); + fill(0); + textAlign(CENTER); + } + + void draw() { + int numRecords = inventory.get("records"); + text(numRecords, width/2, height/2); + } + fields: {} - methods: {} - name: null + fileName: IntDict + methods: + add: + anchor: IntDict_add_ + desc: Add to a value + clear: + anchor: IntDict_clear_ + desc: Remove all entries from the data structure + div: + anchor: IntDict_div_ + desc: Divide a value + get: + anchor: IntDict_get_ + desc: Return a value for the specified key + hasKey: + anchor: IntDict_hasKey_ + desc: Check if a key is a part of the data structure + increment: + anchor: IntDict_increment_ + desc: Increase the value of a specific key value by 1 + keyArray: + anchor: IntDict_keyArray_ + desc: Return a copy of the internal keys array + keys: + anchor: IntDict_keys_ + desc: Return the internal array being used to store the keys + mult: + anchor: IntDict_mult_ + desc: Multiply a value + remove: + anchor: IntDict_remove_ + desc: Remove a key/value pair + set: + anchor: IntDict_set_ + desc: Create a new key/value pair or change the value of one + size: + anchor: IntDict_size_ + desc: Returns the number of key/value pairs + sortKeys: + anchor: IntDict_sortKeys_ + desc: Sort the keys alphabetically + sortKeysReverse: + anchor: IntDict_sortKeysReverse_ + desc: Sort the keys alphabetically in reverse + sortValues: + anchor: IntDict_sortValues_ + desc: Sort by values in ascending order + sortValuesReverse: + anchor: IntDict_sortValuesReverse_ + desc: Sort by values in descending order + sub: + anchor: IntDict_sub_ + desc: Subtract from a value + valueArray: + anchor: IntDict_valueArray_ + desc: Create a new array and copy each of the values into it + values: + anchor: IntDict_values_ + desc: Return the internal array being used to store the values parameters: {} - syntax: | - IntDict() - IntDict(pairs) + syntax: + - IntDict() + - IntDict(pairs) type: class IntList: description: |- - Helper class for a list of ints. Lists are designed to have some of the - features of ArrayLists, but to maintain the simplicity and efficiency of - working with arrays. + Helper class for a list of `int` values. Lists are designed + to have some features of `ArrayList`, but to maintain the + simplicity and efficiency of working with arrays. + Functions such as `sort()` and `shuffle()` always act on + the list itself. To get a sorted copy, use `list.copy().sort()`. + examples: + - |+ + IntList inventory; + + void setup() { + size(200, 200); + inventory = new IntList(); + inventory.append(84); + inventory.append(15); + inventory.append(102); + println(inventory); + noLoop(); + fill(0); + textAlign(CENTER); + } + + void draw() { + int nums = inventory.get(2); + text(nums, width/2, height/2); + } - Functions like sort() and shuffle() always act on the list itself. To get - a sorted copy, use list.copy().sort(). - docUrl: https://processing.org/reference/IntList.html fields: {} - methods: {} - name: null + fileName: IntList + methods: + add: + anchor: IntList_add_ + desc: Add to a value + append: + anchor: IntList_append_ + desc: Add a new entry to the list + clear: + anchor: IntList_clear_ + desc: Remove all entries from the list + div: + anchor: IntList_div_ + desc: Divide a value + get: + anchor: IntList_get_ + desc: Get an entry at a particular index + hasValue: + anchor: IntList_hasValue_ + desc: Check if a number is a part of the list + increment: + anchor: IntList_increment_ + desc: Add one to a value + max: + anchor: IntList_max_ + desc: Return the largest value + min: + anchor: IntList_min_ + desc: Return the smallest value + mult: + anchor: IntList_mult_ + desc: Multiply a value + remove: + anchor: IntList_remove_ + desc: Remove an element from the specified index + reverse: + anchor: IntList_reverse_ + desc: Reverse the order of the list elements + set: + anchor: IntList_set_ + desc: Set the entry at a particular index + shuffle: + anchor: IntList_shuffle_ + desc: Randomize the order of the list elements + size: + anchor: IntList_size_ + desc: Get the length of the list + sort: + anchor: IntList_sort_ + desc: Sorts the array, lowest to highest + sortReverse: + anchor: IntList_sortReverse_ + desc: Reverse sort, orders values from highest to lowest + sub: + anchor: IntList_sub_ + desc: Subtract from a value + toArray: + anchor: IntList_toArray_ + desc: Create a new array with a copy of all the values parameters: {} - syntax: | - IntList() - IntList(items) + syntax: + - IntList() + - IntList(items) type: class JSONArray: - description: A `JSONArray` stores an array of JSON objects. `JSONArray`s can be - generated from scratch, dynamically, or using data from an existing - file. JSON can also be output and saved to disk, as in the example above. - docUrl: https://processing.org/reference/JSONArray.html + description: >- + A `JSONArray` stores an array of JSON objects. `JSONArray`s can + be generated from scratch, dynamically, or using data from an existing file. + JSON can also be output and saved to disk, as in the example above. + examples: + - | + String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" }; + String[] names = { "Goat", "Leopard", "Zebra" }; + + JSONArray values; + + void setup() { + + values = new JSONArray(); + + for (int i = 0; i < species.length; i++) { + + JSONObject animal = new JSONObject(); + + animal.setInt("id", i); + animal.setString("species", species[i]); + animal.setString("name", names[i]); + + values.setJSONObject(i, animal); + } + + saveJSONArray(values, "data/new.json"); + } + + // Sketch saves the following to a file called "new.json": + // [ + // { + // "id": 0, + // "species": "Capra hircus", + // "name": "Goat" + // }, + // { + // "id": 1, + // "species": "Panthera pardus", + // "name": "Leopard" + // }, + // { + // "id": 2, + // "species": "Equus zebra", + // "name": "Zebra" + // } + // ] fields: {} - methods: {} - name: null + fileName: JSONArray + methods: + append: + anchor: JSONArray_append_ + desc: Appends a value, increasing the array's length by one + getBoolean: + anchor: JSONArray_getBoolean_ + desc: Gets the boolean value associated with the specified index + getFloat: + anchor: JSONArray_getFloat_ + desc: Gets the float value associated with the specified index + getInt: + anchor: JSONArray_getInt_ + desc: Gets the int value associated with the specified index + getJSONArray: + anchor: JSONArray_getJSONArray_ + desc: Retrieves the `JSONArray` with the associated index value + getJSONObject: + anchor: JSONArray_getJSONObject_ + desc: Retrieves the `JSONObject` with the associated index value + getString: + anchor: JSONArray_getString_ + desc: Gets the String value associated with an index + isNull: + anchor: JSONArray_isNull_ + desc: Determines if the value associated with the index is `null` + remove: + anchor: JSONArray_remove_ + desc: Removes the element from a `JSONArray` in the specified index position + setBoolean: + anchor: JSONArray_setBoolean_ + desc: Inserts a new value into the `JSONArray` at the specified index position + setFloat: + anchor: JSONArray_setFloat_ + desc: Put a float value in the JSONArray + setInt: + anchor: JSONArray_setInt_ + desc: Put an int value in the JSONArray + setJSONArray: + anchor: JSONArray_setJSONArray_ + desc: Sets the value of the `JSONArray` with the associated index value + setJSONObject: + anchor: JSONArray_setJSONObject_ + desc: Sets the value of the `JSONObject` with the index value + setString: + anchor: JSONArray_setString_ + desc: Inserts a new value into the `JSONArray` at the specified index position + size: + anchor: JSONArray_size_ + desc: Gets the total number of elements in a `JSONArray` + toIntArray: + anchor: JSONArray_toIntArray_ + desc: Returns the entire `JSONArray` as an array of `ints` + toStringArray: + anchor: JSONArray_toStringArray_ + desc: Returns the entire `JSONArray` as an array of `Strings` parameters: {} - syntax: | - JSONArray() + syntax: + - JSONArray() type: class JSONObject: description: >- - A `JSONObject` stores JSON data with multiple name/value pairs. Values can - be numeric, Strings, booleans, other `JSONObject`s or `JSONArray`s, or - null. `JSONObject` and `JSONArray` objects are quite similar and share most - of the same methods; the primary difference is that the latter stores an - array of JSON objects, while the former represents a single JSON object. + A `JSONObject` stores JSON data with multiple name/value pairs. Values + can be numeric, `Strings`, `booleans`, other `JSONObject`s or + `JSONArray`s, or null. `JSONObject` and `JSONArray` objects + are quite similar and share most of the same methods; the primary difference + is that the latter stores an array of JSON objects, while the former + represents a single JSON object. + + JSON can be generated from scratch, dynamically, or using data from an + existing file. JSON can also be output and saved to disk, as in the example + above. + examples: + - | + JSONObject json; + + void setup() { + + json = new JSONObject(); + + json.setInt("id", 0); + json.setString("species", "Panthera leo"); + json.setString("name", "Lion"); + saveJSONObject(json, "data/new.json"); + } - JSON can be generated from scratch, dynamically, or using data from an existing file. JSON can also be output and saved to disk, as in the example above. - docUrl: https://processing.org/reference/JSONObject.html + // Sketch saves the following to a file called "new.json": + // { + // "id": 0, + // "species": "Panthera leo", + // "name": "Lion" + // } fields: {} - methods: {} - name: null + fileName: JSONObject + methods: + getBoolean: + anchor: JSONObject_getBoolean_ + desc: Gets the `boolean` value associated with the specified key + getFloat: + anchor: JSONObject_getFloat_ + desc: Gets the `float` value associated with a key + getInt: + anchor: JSONObject_getInt_ + desc: Gets the `int` value associated with the specified key + getJSONArray: + anchor: JSONObject_getJSONArray_ + desc: Retrieves the `JSONArray` with the associated key + getJSONObject: + anchor: JSONObject_getJSONObject_ + desc: Given a key value, retrieves the associated `JSONObject` + getString: + anchor: JSONObject_getString_ + desc: Gets the `String` value associated with the specified key + isNull: + anchor: JSONObject_isNull_ + desc: |- + Determines if the value associated with the key is `null`, that is has + no defined value (`false`) or if it has a value (`true`) + setBoolean: + anchor: JSONObject_setBoolean_ + desc: Put a key/boolean pair in the `JSONObject` + setFloat: + anchor: JSONObject_setFloat_ + desc: Put a key/float pair in the `JSONObject` + setInt: + anchor: JSONObject_setInt_ + desc: Inserts a new key/int pair into the `JSONObject` + setJSONArray: + anchor: JSONObject_setJSONArray_ + desc: Sets the value of the `JSONArray` with the associated key + setJSONObject: + anchor: JSONObject_setJSONObject_ + desc: Sets the value of the `JSONObject` with the associated key + setString: + anchor: JSONObject_setString_ + desc: Inserts a new key/String pair into the `JSONObject` parameters: {} + syntax: [] type: class Object: description: Objects are instances of classes. A class is a grouping of related methods (functions) and fields (variables and constants). - docUrl: https://processing.org/reference/Object.html + examples: + - | + // Declare and construct two objects (h1, h2) from the class HLine + HLine h1 = new HLine(20, 2.0); + HLine h2 = new HLine(50, 2.5); + + void setup() + { + size(200, 200); + frameRate(30); + } + + void draw() { + background(204); + h1.update(); + h2.update(); + } + + class HLine { + float ypos, speed; + HLine (float y, float s) { + ypos = y; + speed = s; + } + void update() { + ypos += speed; + if (ypos > height) { + ypos = 0; + } + line(0, ypos, width, ypos); + } + } fields: {} + fileName: Object methods: {} - name: null parameters: - ClassName: the class from which to create the new object - instanceName: the name for the new object + ClassName: + desc: the class from which to create the new object + type: [] + instanceName: + desc: the name for the new object + type: [] + syntax: [] type: class PFont: description: >- 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. - - - To create a new font dynamically, use the `createFont()` function. Do not use the syntax `new PFont()`. - docUrl: https://processing.org/reference/PFont.html + 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. + + To create a new font dynamically, use the `createFont()` function. Do + not use the syntax `new PFont()`. + examples: + - |- + size(400, 400); + PFont font; + // The font must be located in the sketch's + // "data" directory to load successfully + font = createFont("LetterGothicStd.otf", 128); + textFont(font); + text("word", 50, 200); fields: {} - methods: {} - name: null + fileName: PFont + methods: + list: + anchor: PFont_list_ + desc: Gets a list of the fonts installed on the system parameters: {} + syntax: [] type: class PGraphics: description: >- 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. - + 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. + + To create a new graphics context, use the `createGraphics()` function. + Do not use the syntax `new PGraphics()`. + examples: + - | + PGraphics pg; + + void setup() { + size(100, 100); + pg = createGraphics(40, 40); + } - To create a new graphics context, use the `createGraphics()` function. Do not use the syntax `new PGraphics()`. - docUrl: https://processing.org/reference/PGraphics.html + void draw() { + pg.beginDraw(); + pg.background(100); + pg.stroke(255); + pg.line(20, 20, mouseX, mouseY); + pg.endDraw(); + image(pg, 9, 30); + image(pg, 51, 30); + } fields: {} - methods: {} - name: null + fileName: PGraphics + methods: + beginDraw: + anchor: PGraphics_beginDraw_ + desc: Sets the default properties for a `PGraphics` object + endDraw: + anchor: PGraphics_endDraw_ + desc: Finalizes the rendering of a `PGraphics` object so that it can be shown on + screen parameters: {} - syntax: | - PGraphics() + syntax: + - PGraphics() type: class PI: - description: "`PI` is a mathematical constant with the value 3.1415927. 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()`." - docUrl: https://processing.org/reference/PI.html - examples: | - float x = width/2; - float y = height/2; - float d = width * 0.8; - arc(x, y, d, d, 0, QUARTER_PI); - arc(x, y, d-20, d-20, 0, HALF_PI); - arc(x, y, d-40, d-40, 0, PI); - arc(x, y, d-60, d-60, 0, TWO_PI); - name: null + description: |- + `PI` is a mathematical constant with the value 3.1415927. 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()`. + examples: + - | + size(400, 400); + float x = width/2; + float y = height/2; + float d = width * 0.8; + arc(x, y, d, d, 0, QUARTER_PI); + arc(x, y, d-80, d-80, 0, HALF_PI); + arc(x, y, d-160, d-160, 0, PI); + arc(x, y, d-240, d-240, 0, TWO_PI); + fileName: PI type: const PImage: description: >- - 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. - - - 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. - + 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. + + 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 the + syntax `new PImage()`. + examples: + - |- + PImage photo; + + void setup() { + size(400, 400); + photo = loadImage("Toyokawa-city.jpg"); + } - To create a new image, use the `createImage()` function. Do not use the syntax `new PImage()`. - docUrl: https://processing.org/reference/PImage.html - fields: {} - methods: {} - name: null + void draw() { + image(photo, 0, 0); + } + fields: + height: + anchor: PImage_height + desc: The height of the image in units of pixels + pixels[]: + anchor: PImage_pixels + desc: Array containing the color of every pixel in the image + width: + anchor: PImage_width + desc: The width of the image in units of pixels + fileName: PImage + methods: + blend: + anchor: PImage_blend_ + desc: Copies a pixel or rectangle of pixels using different blending modes + blendColor: + anchor: PImage_blendColor_ + desc: |- + Blends two color values together based on the blending mode given as the + `MODE` parameter + copy: + anchor: PImage_copy_ + desc: Copies the entire image + filter: + anchor: PImage_filter_ + desc: Converts the image to grayscale or black and white + get: + anchor: PImage_get_ + desc: Reads the color of any pixel or grabs a rectangle of pixels + loadPixels: + anchor: PImage_loadPixels_ + desc: Loads the pixel data for the image into its `pixels[]` array + mask: + anchor: PImage_mask_ + desc: Masks part of an image with another image as an alpha channel + resize: + anchor: PImage_resize_ + desc: Resize the image to a new width and height + save: + anchor: PImage_save_ + desc: Saves the image to a TIFF, TARGA, PNG, or JPEG file + set: + anchor: PImage_set_ + desc: Writes a color to any pixel or writes an image into another + updatePixels: + anchor: PImage_updatePixels_ + desc: Updates the image with the data in its `pixels[]` array parameters: {} - syntax: | - PImage(width, height, format, factor) + syntax: + - PImage(width, height, format, factor) + - PImage(width, height, pixels, requiresCheckAlpha, parent) + - PImage(width, height, pixels, requiresCheckAlpha, parent, format, factor) + - PImage(img) type: class PShader: - description: "This class encapsulates a GLSL shader program, including a vertex - and a fragment shader. It's compatible with the P2D and P3D renderers, but - not with the default renderer. Use the `loadShader()` function to load your - shader code. [Note: It's strongly encouraged to use `loadShader()` to create - a PShader object, rather than calling the PShader constructor manually.]" - docUrl: https://processing.org/reference/PShader.html + description: |- + This class encapsulates a GLSL shader program, including a vertex + and a fragment shader. It is compatible with P2D and P3D, but not + with the default renderer. + + Use the `loadShader()` function to load your shader code. + Note: It's strongly encouraged to use `loadShader()` to create + a `PShader` object, rather than calling the `PShader` + constructor manually. + examples: + - | + PShader blur; + + void setup() { + size(640, 360, P2D); + // Shaders files must be in the "data" folder to load correctly + blur = loadShader("blur.glsl"); + stroke(0, 102, 153); + rectMode(CENTER); + } + + void draw() { + filter(blur); + rect(mouseX-75, mouseY, 150, 150); + ellipse(mouseX+75, mouseY, 150, 150); + } + - | + PImage tex; + PShader deform; + + void setup() { + size(640, 360, P2D); + tex = loadImage("tex1.jpg"); + deform = loadShader("deform.glsl"); + deform.set("resolution", float(width), float(height)); + } + + void draw() { + deform.set("time", millis() / 1000.0); + deform.set("mouse", float(mouseX), float(mouseY)); + shader(deform); + image(tex, 0, 0, width, height); + } fields: {} - methods: {} - name: null - parameters: - fragFilename: "String: name of the fragment shader" - fragURL: "URL: network location of the fragment shader" - parent: "PApplet: the parent program" - vertFilename: "String: name of the vertex shader" - vertURL: "URL: network location of the vertex shader" - syntax: | - PShader() - PShader(parent) - PShader(parent, vertFilename, fragFilename) - PShader(parent, vertURL, fragURL) - PShader(parent, vertSource, fragSource) + fileName: PShader + methods: + set: + anchor: PShader_set_ + desc: Sets a variable within the shader + parameters: + fragFilename: + desc: name of the fragment shader + type: + - String + fragURL: + desc: network location of the fragment shader + type: + - URL + parent: + desc: the parent program + type: + - PApplet + vertFilename: + desc: name of the vertex shader + type: + - String + vertURL: + desc: network location of the vertex shader + type: + - URL + syntax: + - PShader() + - PShader(parent) + - PShader(parent, vertFilename, fragFilename) + - PShader(parent, vertURL, fragURL) + - PShader(parent, vertSource, fragSource) type: class PShape: description: >- Datatype for storing shapes. Before a shape is used, it must be loaded with - the `loadShape()` or created with the `createShape()`. The `shape()` - function is used to draw the shape to the display window. Processing can - currently load and display SVG (Scalable Vector Graphics) and OBJ shapes. - OBJ files can only be opened using the `P3D` renderer. 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. - - - The `PShape` object contains a group of methods that can operate on the shape data. Some of the methods are listed below, but the full list used for creating and modifying shapes is available here in the Processing Javadoc. + the `loadShape()` or created with the `createShape()`. The + `shape()` function is used to draw the shape to the display window. + Processing can currently load and display SVG (Scalable Vector Graphics) and + OBJ shapes. OBJ files can only be opened using the `P3D` renderer. 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. + + The `PShape` object contains a group of methods that can operate on the + shape data. Some of the methods are listed below, but the full list used for + creating and modifying shapes is + available + here in the Processing Javadoc. + + To create a new shape, use the `createShape()` function. Do not use the + syntax `new PShape()`. + examples: + - |2- + + PShape s; + + void setup() { + size(400, 400); + // The file "bot.svg" must be in the data folder + // of the current sketch to load successfully + s = loadShape("bot.svg"); + } + void draw() { + shape(s, 40, 40, 320, 320); + } + - | + PShape square; // The PShape object + + void setup() { + size(100, 100); + // Creating the PShape as a square. The corner + // is 0,0 so that the center is at 40,40 + square = createShape(RECT, 0, 0, 80, 80); + } - To create a new shape, use the `createShape()` function. Do not use the syntax `new PShape()`. - docUrl: https://processing.org/reference/PShape.html - fields: {} - methods: {} - name: null + void draw() { + shape(square, 10, 10); + } + fields: + height: + anchor: PShape_height + desc: Shape document height + width: + anchor: PShape_width + desc: Shape document width + fileName: PShape + methods: + addChild: + anchor: PShape_addChild_ + desc: Adds a new child + beginContour: + anchor: PShape_beginContour_ + desc: Starts a new contour + beginShape: + anchor: PShape_beginShape_ + desc: Starts the creation of a new `PShape` + disableStyle: + anchor: PShape_disableStyle_ + desc: Disables the shape's style data and uses Processing styles + enableStyle: + anchor: PShape_enableStyle_ + desc: Enables the shape's style data and ignores the Processing styles + endContour: + anchor: PShape_endContour_ + desc: Ends a contour + endShape: + anchor: PShape_endShape_ + desc: Finishes the creation of a new `PShape` + getChild: + anchor: PShape_getChild_ + desc: Returns a child element of a shape as a `PShape` object + getChildCount: + anchor: PShape_getChildCount_ + desc: Returns the number of children + getVertex: + anchor: PShape_getVertex_ + desc: Returns the vertex at the index position + getVertexCount: + anchor: PShape_getVertexCount_ + desc: Returns the total number of vertices as an int + isVisible: + anchor: PShape_isVisible_ + desc: |- + Returns a boolean value `true` if the image is set to be visible, + `false` if not + resetMatrix: + anchor: PShape_resetMatrix_ + desc: Replaces the current matrix of a shape with the identity matrix + rotate: + anchor: PShape_rotate_ + desc: Rotates the shape + rotateX: + anchor: PShape_rotateX_ + desc: Rotates the shape around the x-axis + rotateY: + anchor: PShape_rotateY_ + desc: Rotates the shape around the y-axis + rotateZ: + anchor: PShape_rotateZ_ + desc: Rotates the shape around the z-axis + scale: + anchor: PShape_scale_ + desc: Increases and decreases the size of a shape + setFill: + anchor: PShape_setFill_ + desc: Set the fill value + setStroke: + anchor: PShape_setStroke_ + desc: Set the stroke value + setVertex: + anchor: PShape_setVertex_ + desc: Sets the vertex at the index position + setVisible: + anchor: PShape_setVisible_ + desc: Sets the shape to be visible or invisible + translate: + anchor: PShape_translate_ + desc: Displaces the shape parameters: {} - syntax: | - PShape(g, kind, params) + syntax: + - PShape(g, kind, params) type: class PVector: description: >- A class to describe a two or three dimensional vector, specifically a - Euclidean (also known as geometric) vector. A vector is an entity that has - both magnitude and direction. The datatype, however, stores the components - of the vector (x,y for 2D, and x,y,z for 3D). The magnitude and direction - can be accessed via the methods `mag()` and `heading()`. + Euclidean (also known as geometric) vector. A vector is an entity that has + both magnitude and direction. The datatype, however, stores the components of + the vector (x,y for 2D, and x,y,z for 3D). The magnitude and direction can be + accessed via the methods `mag()` and `heading()`. + + In many of the Processing examples, you will see `PVector` used to + describe a position, velocity, or acceleration. For example, if you consider + a rectangle moving across the screen, at any given instant it has a position + (a vector that points from the origin to its location), a velocity (the rate + at which the object's position changes per time unit, expressed as a vector), + and acceleration (the rate at which the object's velocity changes per time + unit, expressed as a vector). Since vectors represent groupings of values, we + cannot simply use traditional addition/multiplication/etc. Instead, we'll + need to do some "vector" math, which is made easy by the methods inside the + `PVector` class. + examples: + - | + PVector v1, v2; + + void setup() { + noLoop(); + v1 = new PVector(40, 20); + v2 = new PVector(25, 50); + } + + void draw() { + ellipse(v1.x, v1.y, 12, 12); + ellipse(v2.x, v2.y, 12, 12); + v2.add(v1); + ellipse(v2.x, v2.y, 24, 24); + } + fields: + x: + anchor: PVector_x + desc: The x component of the vector + y: + anchor: PVector_y + desc: The y component of the vector + z: + anchor: PVector_z + desc: The z component of the vector + fileName: PVector + methods: + add: + anchor: PVector_add_ + desc: |- + Adds x, y, and z components to a vector, one vector to another, or + two independent vectors + angleBetween: + anchor: PVector_angleBetween_ + desc: Calculate and return the angle between two vectors + array: + anchor: PVector_array_ + desc: Return a representation of the vector as a float array + copy: + anchor: PVector_copy_ + desc: Get a copy of the vector + cross: + anchor: PVector_cross_ + desc: Calculate and return the cross product + dist: + anchor: PVector_dist_ + desc: Calculate the distance between two points + div: + anchor: PVector_div_ + desc: Divide a vector by a scalar + dot: + anchor: PVector_dot_ + desc: Calculate the dot product of two vectors + fromAngle: + anchor: PVector_fromAngle_ + desc: Make a new 2D unit vector from an angle + heading: + anchor: PVector_heading_ + desc: Calculate the angle of rotation for this vector + lerp: + anchor: PVector_lerp_ + desc: Linear interpolate the vector to another vector + limit: + anchor: PVector_limit_ + desc: Limit the magnitude of the vector + mag: + anchor: PVector_mag_ + desc: Calculate the magnitude of the vector + magSq: + anchor: PVector_magSq_ + desc: Calculate the magnitude of the vector, squared + mult: + anchor: PVector_mult_ + desc: Multiply a vector by a scalar + normalize: + anchor: PVector_normalize_ + desc: Normalize the vector to a length of 1 + random2D: + anchor: PVector_random2D_ + desc: Make a new 2D unit vector with a random direction + random3D: + anchor: PVector_random3D_ + desc: Make a new 3D unit vector with a random direction + rotate: + anchor: PVector_rotate_ + desc: Rotate the vector by an angle (2D only) + set: + anchor: PVector_set_ + desc: Set the components of the vector + setMag: + anchor: PVector_setMag_ + desc: Set the magnitude of the vector + sub: + anchor: PVector_sub_ + desc: |- + Subtract x, y, and z components from a vector, one vector from + another, or two independent vectors + parameters: + x: + desc: the x coordinate. + type: + - float + y: + desc: the y coordinate. + type: + - float + z: + desc: the z coordinate. + type: + - float + syntax: + - PVector() + - PVector(x, y, z) + - PVector(x, y) + type: class +PrintWriter: + description: Allows characters to print to a text-output stream. A new + PrintWriter object is created with the `createWriter()` function. For the + file to be made correctly, it should be flushed and must be closed with its + `flush()` and `close()` methods (see above example). + examples: + - |+ + PrintWriter output; + + void setup() { + // Create a new file in the sketch directory + output = createWriter("positions.txt"); + } + + void draw() { + point(mouseX, mouseY); + output.println(mouseX); // Write the coordinate to the file + } + void keyPressed() { + output.flush(); // Writes the remaining data to the file + output.close(); // Finishes the file + exit(); // Stops the program + } - In many of the Processing examples, you will see `PVector` used to describe a position, velocity, or acceleration. For example, if you consider a rectangle moving across the screen, at any given instant it has a position (a vector that points from the origin to its location), a velocity (the rate at which the object's position changes per time unit, expressed as a vector), and acceleration (the rate at which the object's velocity changes per time unit, expressed as a vector). Since vectors represent groupings of values, we cannot simply use traditional addition/multiplication/etc. Instead, we'll need to do some "vector" math, which is . . . - docUrl: https://processing.org/reference/PVector.html fields: {} - methods: {} - name: null - parameters: - x: "float: the x coordinate." - y: "float: the y coordinate." - z: "float: the z coordinate." - syntax: | - PVector() - PVector(x, y, z) - PVector(x, y) + fileName: PrintWriter + methods: + close: + anchor: PrintWriter_close_ + desc: Closes the stream + flush: + anchor: PrintWriter_flush_ + desc: Flushes the stream + print: + anchor: PrintWriter_print_ + desc: Adds data to the stream + println: + anchor: PrintWriter_println_ + desc: Adds data to the stream and starts a new line + parameters: {} + syntax: [] type: class QUARTER_PI: - description: "`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()`." - docUrl: https://processing.org/reference/QUARTER_PI.html - examples: | - float x = width/2; - float y = height/2; - float d = width * 0.8; - arc(x, y, d, d, 0, QUARTER_PI); - arc(x, y, d-20, d-20, 0, HALF_PI); - arc(x, y, d-40, d-40, 0, PI); - arc(x, y, d-60, d-60, 0, TWO_PI); - name: null + description: |- + `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()`. + examples: + - | + float x = width/2; + float y = height/2; + float d = width * 0.8; + size(400,400); + arc(x, y, d, d, 0, QUARTER_PI); + arc(x, y, d-80, d-80, 0, HALF_PI); + arc(x, y, d-160, d-160, 0, PI); + arc(x, y, d-240, d-240, 0, TWO_PI); + fileName: QUARTER_PI type: const String: description: >- @@ -364,721 +1519,2058 @@ String: and characters are always defined inside single quotes (`'A'`). - To compare the contents of two Strings, use the `equals()` method, as in `if (a.equals(b))`, instead of `if (a == b)`. A String is an Object, so comparing them with the `==` operator only compares whether both Strings are stored in the same memory location. Using the `equals()` method will ensure that the actual contents are compared. (The troubleshooting reference has a longer explanation.) - - - Because a String is defined between double quotation marks, to include such marks within the String itself you must use the `\` (backslash) character. (See the third example above.) This is known as an escape sequence. Other escape sequen. . . - docUrl: https://processing.org/reference/String.html + To compare the contents of two Strings, use the `equals()` method, as in `if + (a.equals(b))`, instead of `if (a == b)`. A String is an Object, so + comparing them with the `==` operator only compares whether both Strings are + stored in the same memory location. Using the `equals()` method will ensure + that the actual contents are compared. (The troubleshooting reference has a + longer explanation.) + + + Because a String is defined between double quotation marks, to include such + marks within the String itself you must use the `\` (backslash) + character. (See the third example above.) This is known as an escape + sequence. Other escape sequences include `\t` for the tab character and + `\n` for new line. Because backslash is the escape character, to include + a single backslash within a String, you must use two consecutive + backslashes, as in: `\\` + + + There are more string methods than those linked from this page. Additional + documentation is located online in the official Java documentation. + examples: + - | + String str1 = "CCCP"; + char data[] = {'C', 'C', 'C', 'P'}; + String str2 = new String(data); + println(str1); // Prints "CCCP" to the console + println(str2); // Prints "CCCP" to the console + - | + // Comparing String objects, see reference below. + String p = "potato"; + // The correct way to compare two Strings + if (p.equals("potato")) { + println("Yes, the values are the same."); + } + - | + // Use a backslash to include quotes in a String + String quoted = "This one has \"quotes\""; + println(quoted); // This one has "quotes" fields: {} - methods: {} - name: null - parameters: - data: "byte[] or char[]: either an array of bytes to be decoded into characters, - or an array of characters to be combined into a string" - length: "int: number of characters" - offset: "int: index of the first character" - syntax: | - String(data) - String(data, offset, length) + fileName: String + methods: + charAt: + anchor: String_charAt_ + desc: Returns the character at the specified index + equals: + anchor: String_equals_ + desc: Compares two strings to see if they are the same + indexOf: + anchor: String_indexOf_ + desc: Returns the index value of the first occurrence of a substring within the + input string + length: + anchor: String_length_ + desc: Returns the total number of characters included in the `String` as an + integer number + substring: + anchor: String_substring_ + desc: Returns a new string that is a part of the original string + toLowerCase: + anchor: String_toLowerCase_ + desc: Converts all of the characters in the string to lowercase + toUpperCase: + anchor: String_toUpperCase_ + desc: Converts all of the characters in the string to uppercase + parameters: + data: + desc: "byte[] or char[]: either an array of bytes to be decoded into characters, + or an array of characters to be combined into a string" + type: [] + length: + desc: "int: number of characters" + type: [] + offset: + desc: "int: index of the first character" + type: [] + syntax: + - String(data) + - String(data, offset, length) type: class StringDict: - description: A simple class to use a String as a lookup for an String value. - String "keys" are associated with String values. - docUrl: https://processing.org/reference/StringDict.html + description: >- + A simple class to use a `String` as a lookup for a `String` value. String + "keys" + are associated with `String` values. + examples: + - |+ + StringDict inventory; + + void setup() { + size(200, 200); + inventory = new StringDict(); + inventory.set("coffee","black"); + inventory.set("flour","white"); + inventory.set("tea","green"); + println(inventory); + noLoop(); + fill(0); + textAlign(CENTER); + } + + void draw() { + String s = inventory.get("tea"); + text(s, width/2, height/2); + } + fields: {} - methods: {} - name: null + fileName: StringDict + methods: + clear: + anchor: StringDict_clear_ + desc: Remove all entries + get: + anchor: StringDict_get_ + desc: Return a value for the specified key + hasKey: + anchor: StringDict_hasKey_ + desc: Check if a key is a part of the data structure + keyArray: + anchor: StringDict_keyArray_ + desc: Return a copy of the internal keys array + keys: + anchor: StringDict_keys_ + desc: Return the internal array being used to store the keys + remove: + anchor: StringDict_remove_ + desc: Remove a key/value pair + set: + anchor: StringDict_set_ + desc: Create a new key/value pair or change the value of one + size: + anchor: StringDict_size_ + desc: Returns the number of key/value pairs + sortKeys: + anchor: StringDict_sortKeys_ + desc: Sort the keys alphabetically + sortKeysReverse: + anchor: StringDict_sortKeysReverse_ + desc: Sort the keys alphabetically in reverse + sortValues: + anchor: StringDict_sortValues_ + desc: Sort by values in descending order + sortValuesReverse: + anchor: StringDict_sortValuesReverse_ + desc: Sort by values in descending order + valueArray: + anchor: StringDict_valueArray_ + desc: Create a new array and copy each of the values into it + values: + anchor: StringDict_values_ + desc: Return the internal array being used to store the values parameters: {} - syntax: | - StringDict() - StringDict(pairs) - StringDict(row) + syntax: + - StringDict() + - StringDict(pairs) + - StringDict(row) type: class StringList: description: |- - Helper class for a list of Strings. Lists are designed to have some of the - features of ArrayLists, but to maintain the simplicity and efficiency of - working with arrays. + Helper class for a list of `String` objects. Lists are designed + to have some features of `ArrayList`, but to maintain the + simplicity and efficiency of working with arrays. + Functions such as `sort()` and `shuffle()` always act on + the list itself. To get a sorted copy, use `list.copy().sort()`. + examples: + - |+ + StringList inventory; + + void setup() { + size(200, 200); + inventory = new StringList(); + inventory.append("coffee"); + inventory.append("flour"); + inventory.append("tea"); + println(inventory); + noLoop(); + fill(0); + textAlign(CENTER); + } + + void draw() { + String item = inventory.get(2); + text(item, width/2, height/2); + } - Functions like sort() and shuffle() always act on the list itself. To get - a sorted copy, use list.copy().sort(). - docUrl: https://processing.org/reference/StringList.html fields: {} - methods: {} - name: null + fileName: StringList + methods: + append: + anchor: StringList_append_ + desc: Add a new entry to the list + clear: + anchor: StringList_clear_ + desc: Remove all entries from the list + get: + anchor: StringList_get_ + desc: Get an entry at a particular index + hasValue: + anchor: StringList_hasValue_ + desc: Check if a value is a part of the list + lower: + anchor: StringList_lower_ + desc: Make the entire list lower case + remove: + anchor: StringList_remove_ + desc: Remove an element from the specified index + reverse: + anchor: StringList_reverse_ + desc: Reverse the order of the list + set: + anchor: StringList_set_ + desc: Set an entry at a particular index + shuffle: + anchor: StringList_shuffle_ + desc: Randomize the order of the list elements + size: + anchor: StringList_size_ + desc: Get the length of the list + sort: + anchor: StringList_sort_ + desc: Sorts the array in place + sortReverse: + anchor: StringList_sortReverse_ + desc: A sort in reverse + toArray: + anchor: StringList_toArray_ + desc: Create a new array with a copy of all the values + upper: + anchor: StringList_upper_ + desc: Make the entire list upper case parameters: {} - syntax: | - StringList() + syntax: + - StringList() type: class TAU: - description: "`TAU` is a mathematical constant with the value 6.2831855. It is - the circle constant relating the circumference of a circle to its linear - dimension, the ratio of the circumference of a circle to its radius. It is - useful in combination with trigonometric functions such as `sin()` and - `cos()`." - docUrl: https://processing.org/reference/TAU.html - examples: | - float x = width/2; - float y = height/2; - float d = width * 0.8; - arc(x, y, d, d, 0, QUARTER_PI); - arc(x, y, d-20, d-20, 0, HALF_PI); - arc(x, y, d-40, d-40, 0, PI); - arc(x, y, d-60, d-60, 0, TAU); - name: null + description: |- + `TAU` is a mathematical constant with the value 6.2831855. It is the + circle constant relating the circumference of a circle to its linear + dimension, the ratio of the circumference of a circle to its radius. It is + useful in combination with trigonometric functions such as `sin()` and + `cos()`. + examples: + - | + float x = width/2; + float y = height/2; + float d = width * 0.8; + arc(x, y, d, d, 0, QUARTER_PI); + arc(x, y, d-20, d-20, 0, HALF_PI); + arc(x, y, d-40, d-40, 0, PI); + arc(x, y, d-60, d-60, 0, TAU); + fileName: TAU type: const TWO_PI: - description: "`TWO_PI` is a mathematical constant with the value 6.2831855. 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()`." - docUrl: https://processing.org/reference/TWO_PI.html - examples: | - float x = width/2; - float y = height/2; - float d = width * 0.8; - arc(x, y, d, d, 0, QUARTER_PI); - arc(x, y, d-20, d-20, 0, HALF_PI); - arc(x, y, d-40, d-40, 0, PI); - arc(x, y, d-60, d-60, 0, TWO_PI); - name: null + description: |- + `TWO_PI` is a mathematical constant with the value 6.2831855. + 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()`. + examples: + - | + float x = width/2; + float y = height/2; + float d = width * 0.8; + size(400,400); + arc(x, y, d, d, 0, QUARTER_PI); + arc(x, y, d-80, d-80, 0, HALF_PI); + arc(x, y, d-160, d-160, 0, PI); + arc(x, y, d-240, d-240, 0, TWO_PI); + fileName: TWO_PI type: const Table: description: >- - `Table` objects store data with multiple rows and columns, much like in a - traditional spreadsheet. Tables can be generated from scratch, dynamically, - or using data from an existing file. Tables can also be output and saved to - disk, as in the example above. + `Table` objects store data with multiple rows and columns, much like in + a traditional spreadsheet. Tables can be generated from scratch, dynamically, + or using data from an existing file. Tables can also be output and saved to + disk, as in the example above. + + Additional `Table` methods are documented in the Processing + Table Javadoc. + examples: + - | + Table table; + + void setup() { + + table = new Table(); + + table.addColumn("id"); + table.addColumn("species"); + table.addColumn("name"); + + TableRow newRow = table.addRow(); + newRow.setInt("id", table.lastRowIndex()); + newRow.setString("species", "Panthera leo"); + newRow.setString("name", "Lion"); + saveTable(table, "data/new.csv"); + } - Additional `Table` methods are documented in the Processing Table Javadoc. - docUrl: https://processing.org/reference/Table.html + // Sketch saves the following to a file called "new.csv": + // id,species,name + // 0,Panthera leo,Lion fields: {} - methods: {} - name: null + fileName: Table + methods: + addColumn: + anchor: Table_addColumn_ + desc: Adds a new column to a table + addRow: + anchor: Table_addRow_ + desc: Adds a new row of data to a `Table` object + clearRows: + anchor: Table_clearRows_ + desc: Removes all rows from a `Table` + findRow: + anchor: Table_findRow_ + desc: Finds a row that contains the given value + findRows: + anchor: Table_findRows_ + desc: Finds multiple rows that contain the given value + getColumnCount: + anchor: Table_getColumnCount_ + desc: Returns the total number of columns in a table + getFloat: + anchor: Table_getFloat_ + desc: Retrieves a float value from the `Table`'s specified row and column + getInt: + anchor: Table_getInt_ + desc: Retrieves an integer value from the `Table`'s specified row and column + getRow: + anchor: Table_getRow_ + desc: Returns a reference to the specified `TableRow` + getRowCount: + anchor: Table_getRowCount_ + desc: Returns the total number of rows in a `Table` + getString: + anchor: Table_getString_ + desc: Retrieves a String value from the `Table`'s specified row and column + getStringColumn: + anchor: Table_getStringColumn_ + desc: Retrieves all values in the specified column + matchRow: + anchor: Table_matchRow_ + desc: Finds a row that matches the given expression + matchRowIterator: + anchor: Table_matchRowIterator_ + desc: Finds multiple rows that match the given expression + matchRows: + anchor: Table_matchRows_ + desc: Finds multiple rows that match the given expression + removeColumn: + anchor: Table_removeColumn_ + desc: Removes a column from a table + removeRow: + anchor: Table_removeRow_ + desc: Removes a row from a `Table` object + removeTokens: + anchor: Table_removeTokens_ + desc: Removes characters from the table + rows: + anchor: Table_rows_ + desc: Gets all rows from the table + setFloat: + anchor: Table_setFloat_ + desc: Stores a float value in the `Table`'s specified row and column + setInt: + anchor: Table_setInt_ + desc: Stores an integer value in the `Table`'s specified row and column + setString: + anchor: Table_setString_ + desc: Stores a String value in the `Table`'s specified row and column + sort: + anchor: Table_sort_ + desc: Orders a table based on the values in a column + trim: + anchor: Table_trim_ + desc: Trims whitespace from values parameters: {} - syntax: | - Table() - Table(rows) + syntax: + - Table() + - Table(rows) type: class TableRow: - description: >- - A `TableRow` object represents a single row of data values, stored in - columns, from a table. + description: |- + A `TableRow` object represents a single row of data values, + stored in columns, from a `Table`. + + Additional `TableRow` methods are documented in the + Processing Data Javadoc. + examples: + - | + Table table; + + void setup() { + + table = new Table(); + + table.addColumn("number", Table.INT); + table.addColumn("mass", Table.FLOAT); + table.addColumn("name", Table.STRING); + TableRow row = table.addRow(); + row.setInt("number", 8); + row.setFloat("mass", 15.9994); + row.setString("name", "Oxygen"); - Additional `TableRow` methods are documented in the Processing Data Javadoc. - docUrl: https://processing.org/reference/TableRow.html + println(row.getInt("number")); // Prints 8 + println(row.getFloat("mass")); // Prints 15.9994 + println(row.getString("name")); // Prints "Oxygen + } fields: {} - methods: {} - name: null + fileName: TableRow + methods: + getColumnCount: + anchor: TableRow_getColumnCount_ + desc: Get the column count + getColumnTitle: + anchor: TableRow_getColumnTitle_ + desc: Get the column title. + getFloat: + anchor: TableRow_getFloat_ + desc: Get a `float` value from the specified column + getInt: + anchor: TableRow_getInt_ + desc: Get an `integer` value from the specified column + getString: + anchor: TableRow_getString_ + desc: Get a `String` value from the specified column + setFloat: + anchor: TableRow_setFloat_ + desc: Store a `float` value in the specified column + setInt: + anchor: TableRow_setInt_ + desc: Store an `integer` value in the specified column + setString: + anchor: TableRow_setString_ + desc: Store a `String` value in the specified column parameters: {} + syntax: [] type: class XML: - description: >- - `XML` is a representation of an XML object, able to parse XML code. Use - `loadXML()` to load external XML files and create `XML` objects. - + description: |- + `XML` is a representation of an `XML` object, able to parse `XML` code. Use + `loadXML()` to load external XML files and create `XML` + objects. + + Only files encoded as UTF-8 (or plain ASCII) are parsed properly; the + encoding parameter inside `XML` files is ignored. + examples: + - | + // The following short XML file called "mammals.xml" is parsed + // in the code below. It must be in the project's "data" folder. + // + // + // + // Goat + // Leopard + // Zebra + // + + XML xml; + + void setup() { + xml = loadXML("mammals.xml"); + XML[] children = xml.getChildren("animal"); + + for (int i = 0; i < children.length; i++) { + int id = children[i].getInt("id"); + String coloring = children[i].getString("species"); + String name = children[i].getContent(); + println(id + ", " + coloring + ", " + name); + } + } - Only files encoded as UTF-8 (or plain ASCII) are parsed properly; the encoding parameter inside XML files is ignored. - docUrl: https://processing.org/reference/XML.html + // Sketch prints: + // 0, Capra hircus, Goat + // 1, Panthera pardus, Leopard + // 2, Equus zebra, Zebra fields: {} - methods: {} - name: null - parameters: - name: "String: creates a node with this name" - syntax: | - XML(name) + fileName: XML + methods: + addChild: + anchor: XML_addChild_ + desc: Appends a new child to the element + format: + anchor: XML_format_ + desc: Formats `XML` data as a `String` + getAttributeCount: + anchor: XML_getAttributeCount_ + desc: Counts the specified element's number of attributes + getChild: + anchor: XML_getChild_ + desc: Returns the child element with the specified index value or path + getChildCount: + anchor: XML_getChildCount_ + desc: Returns the element's number of children + getChildren: + anchor: XML_getChildren_ + desc: Returns an array containing all child elements + getContent: + anchor: XML_getContent_ + desc: Gets the content of an element + getFloat: + anchor: XML_getFloat_ + desc: Gets the content of an attribute as a `float` + getFloatContent: + anchor: XML_getFloatContent_ + desc: Gets the content of an element as a `float` + getInt: + anchor: XML_getInt_ + desc: Gets the content of an attribute as an `int` + getIntContent: + anchor: XML_getIntContent_ + desc: Gets the content of an element as an `int` + getName: + anchor: XML_getName_ + desc: Gets the element's full name + getParent: + anchor: XML_getParent_ + desc: Gets a copy of the element's parent + getString: + anchor: XML_getString_ + desc: Gets the content of an attribute as a `String` + hasAttribute: + anchor: XML_hasAttribute_ + desc: Checks whether or not an element has the specified attribute + hasChildren: + anchor: XML_hasChildren_ + desc: Checks whether or not an element has any children + listAttributes: + anchor: XML_listAttributes_ + desc: Returns a list of names of all attributes as an array + listChildren: + anchor: XML_listChildren_ + desc: Returns the names of all children as an array + parse: + anchor: XML_parse_ + desc: Converts `String` content to an `XML` object + removeChild: + anchor: XML_removeChild_ + desc: Removes the specified child + setContent: + anchor: XML_setContent_ + desc: Sets the content of an element + setFloat: + anchor: XML_setFloat_ + desc: Sets the content of an attribute as a `float` + setInt: + anchor: XML_setInt_ + desc: Sets the content of an attribute as an `int` + setName: + anchor: XML_setName_ + desc: Sets the element's name + setString: + anchor: XML_setString_ + desc: Sets the content of an attribute as a `String` + toString: + anchor: XML_toString_ + desc: Gets `XML` data as a `String` using default formatting + parameters: + name: + desc: creates a node with this name + type: + - String + syntax: + - XML(name) type: class abs: - description: Calculates the absolute value (magnitude) of a number. The absolute - value of a number is always positive. - docUrl: https://processing.org/reference/abs_.html - name: null - parameters: - n: "int, or float: number to compute" + description: |- + Calculates the absolute value (magnitude) of a number. The absolute + value of a number is always positive. + examples: + - | + int a = abs(153); // Asigna a 'a' 153 + int b = abs(-15); // Asigna a 'b' 15 + float c = abs(12.234); // Asigna a 'c' 12.234 + float d = abs(-9.23); // Asigna a 'd' 9.23 + - | + int a = abs(153); // Sets 'a' to 153 + int b = abs(-15); // Sets 'b' to 15 + float c = abs(12.234); // Sets 'c' to 12.234 + float d = abs(-9.23); // Sets 'd' to 9.23 + fileName: abs_ + parameters: + n: + desc: number to compute + type: + - float + - int returns: float or int - syntax: abs(n) + syntax: + - abs(n) type: function acos: - description: 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)`. - docUrl: https://processing.org/reference/acos_.html - name: null - parameters: - value: "float: the value whose arc cosine is to be returned" + description: |- + 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)`. + examples: + - | + float a = PI; + float c = cos(a); + float ac = acos(c); + // Prints "3.1415927 : -1.0 : 3.1415927" + println(a + " : " + c + " : " + ac); + - | + float a = PI + PI/4.0; + float c = cos(a); + float ac = acos(c); + // Prints "3.926991 : -0.70710665 : 2.3561943" + println(a + " : " + c + " : " + ac); + fileName: acos_ + parameters: + value: + desc: the value whose arc cosine is to be returned + type: + - float returns: float - syntax: acos(value) + syntax: + - acos(value) type: function alpha: description: Extracts the alpha value from a color. - docUrl: https://processing.org/reference/alpha_.html - name: null - parameters: - rgb: "int: any value of the color datatype" + examples: + - | + size(400,400); + noStroke(); + color c = color(0, 126, 255, 102); + fill(c); + rect(60, 60, 140, 280); + float value = alpha(c); // Sets 'value' to 102 + fill(value); + rect(200, 60, 140, 280); + fileName: alpha_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int returns: float - syntax: alpha(rgb) + syntax: + - alpha(rgb) type: function ambient: - description: 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=127, 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. - docUrl: https://processing.org/reference/ambient_.html - name: null - parameters: - gray: "float: number specifying value between white and black" - rgb: "int: any value of the color datatype" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: |- - ambient(rgb) - ambient(gray) - ambient(v1, v2, v3) + description: |- + 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. + examples: + - | + size(400, 400, P3D); + background(0); + noStroke(); + directionalLight(153, 153, 153, .5, 0, -1); + ambientLight(153, 102, 0); + ambient(51, 26, 0); + translate(280, 200, 0); + sphere(120); + fileName: ambient_ + parameters: + gray: + desc: number specifying value between white and black + type: + - float + rgb: + desc: any value of the color datatype + type: + - int + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - ambient(rgb) + - ambient(gray) + - ambient(v1, v2, v3) type: function ambientLight: - description: Adds an ambient light. Ambient light doesn't come from a specific - direction, the rays of 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 `v1`, `v2`, and `v3` parameters are - interpreted as either RGB or HSB values, depending on the current color - mode. - docUrl: https://processing.org/reference/ambientLight_.html - name: null - parameters: - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - x: "float: x-coordinate of the light" - y: "float: y-coordinate of the light" - z: "float: z-coordinate of the light" - returns: void - syntax: |- - ambientLight(v1, v2, v3) - ambientLight(v1, v2, v3, x, y, z) + description: >- + Adds an ambient light. Ambient light doesn't come from a specific direction, + the rays of 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 `v1`, `v2`, and `v3` parameters are + interpreted as either RGB or HSB values, depending on the current color mode. + examples: + - | + size(400, 400, P3D); + background(0); + noStroke(); + // The spheres are white by default so + // the ambient light changes their color + ambientLight(51, 102, 126); + translate(40, 200, 0); + sphere(120); + translate(240, 0, 0); + sphere(120); + - | + size(400, 400, P3D); + background(0); + noStroke(); + directionalLight(126, 126, 126, 0, 0, -1); + ambientLight(102, 102, 102); + translate(128, 200, 0); + rotateY(PI/5); + box(160); + translate(240, 0, 0); + sphere(120); + fileName: ambientLight_ + parameters: + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + x: + desc: x-coordinate of the light + type: + - float + y: + desc: y-coordinate of the light + type: + - float + z: + desc: z-coordinate of the light + type: + - float + returns: void + syntax: + - ambientLight(v1, v2, v3) + - ambientLight(v1, v2, v3, x, y, z) type: function append: - description: >- - Expands a one-dimensional 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) - docUrl: https://processing.org/reference/append_.html - name: null - parameters: - array: "Object, String[], float[], int[], char[], or byte[]: array to append" - value: "Object, String, float, int, char, or byte: new data for the array" + description: |- + 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). + examples: + - | + String[] sa1 = { "OH", "NY", "CA"}; + String[] sa2 = append(sa1, "MA"); + println(sa2); + // Prints updated array contents to the console: + // [0] "OH" + // [1] "NY" + // [2] "CA" + // [3] "MA" + fileName: append_ + parameters: + array: + desc: array to append + type: + - byte[] + - char[] + - int[] + - float[] + - String[] + - Object + value: + desc: new data for the array + type: + - byte + - char + - int + - float + - String + - Object returns: byte[], char[], int[], float[], String[], or Object - syntax: append(array, value) + syntax: + - append(array, value) type: function applyMatrix: - description: 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(). - docUrl: https://processing.org/reference/applyMatrix_.html - name: null - parameters: - n00: "float: numbers which define the 4x4 matrix to be multiplied" - n01: "float: numbers which define the 4x4 matrix to be multiplied" - n02: "float: numbers which define the 4x4 matrix to be multiplied" - n03: "float: numbers which define the 4x4 matrix to be multiplied" - n10: "float: numbers which define the 4x4 matrix to be multiplied" - n11: "float: numbers which define the 4x4 matrix to be multiplied" - n12: "float: numbers which define the 4x4 matrix to be multiplied" - n13: "float: numbers which define the 4x4 matrix to be multiplied" - n20: "float: numbers which define the 4x4 matrix to be multiplied" - n21: "float: numbers which define the 4x4 matrix to be multiplied" - n22: "float: numbers which define the 4x4 matrix to be multiplied" - n23: "float: numbers which define the 4x4 matrix to be multiplied" - n30: "float: numbers which define the 4x4 matrix to be multiplied" - n31: "float: numbers which define the 4x4 matrix to be multiplied" - n32: "float: numbers which define the 4x4 matrix to be multiplied" - n33: "float: numbers which define the 4x4 matrix to be multiplied" - returns: void - syntax: >- - applyMatrix(source) - - applyMatrix(n00, n01, n02, n10, n11, n12) - - applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33) + description: |- + 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()`. + examples: + - |- + size(400, 400, P3D); + noFill(); + translate(200, 200, 0); + rotateY(PI/6); + stroke(153); + box(140); + // Set rotation angles + float ct = cos(PI/9.0); + float st = sin(PI/9.0); + // Matrix for rotation around the Y axis + applyMatrix( ct, 0.0, st, 0.0, + 0.0, 1.0, 0.0, 0.0, + -st, 0.0, ct, 0.0, + 0.0, 0.0, 0.0, 1.0); + stroke(255); + box(200); + fileName: applyMatrix_ + parameters: + n00: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n01: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n02: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n03: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n10: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n11: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n12: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n13: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n20: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n21: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n22: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n23: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n30: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n31: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n32: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + n33: + desc: numbers which define the 4x4 matrix to be multiplied + type: + - float + returns: void + syntax: + - applyMatrix(source) + - applyMatrix(n00, n01, n02, n10, n11, n12) + - applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, + n30, n31, n32, n33) type: function arc: description: >- Draws an arc to the screen. Arcs are drawn along the outer edge of an - ellipse defined by the `a`, `b`, `c`, and `d` parameters. The origin of the - arc's ellipse may be changed with the `ellipseMode()` function. Use the - `start` and `stop` parameters to specify the angles (in radians) at which to - draw the arc. The start/stop values must be in clockwise order. - - - There are three ways to draw an arc; the rendering technique used is defined by the optional seventh parameter. The three options, depicted in the above examples, are PIE, OPEN, and CHORD. The default mode is the OPEN stroke with a PIE fill. - - - In some cases, the `arc()` function isn't accurate enough for smooth drawing. For example, the shape may jitter on screen when rotating slowly. If you're having an issue with how arcs are rendered, you'll need to draw the arc yourself with `beginShape()`/`endShape()` or a `PShape`. - docUrl: https://processing.org/reference/arc_.html - name: null - parameters: - a: "float: x-coordinate of the arc's ellipse" - b: "float: y-coordinate of the arc's ellipse" - c: "float: width of the arc's ellipse by default" - d: "float: height of the arc's ellipse by default" - start: "float: angle to start the arc, specified in radians" - stop: "float: angle to stop the arc, specified in radians" - returns: void - syntax: |- - arc(a, b, c, d, start, stop) - arc(a, b, c, d, start, stop, mode) + ellipse + defined by the `a`, `b`, `c`, and `d` parameters. The + origin of the arc's ellipse may be changed with the `ellipseMode()` + function. Use the `start` and `stop` parameters to specify the + angles (in radians) at which to draw the arc. The start/stop values must be + in clockwise order. + + There are three ways to draw an arc; the rendering technique used is defined + by the optional seventh parameter. The three options, depicted in the above + examples, are PIE, OPEN, and CHORD. The default mode is the OPEN stroke with + a PIE fill. + + In some cases, the `arc()` function isn't accurate enough for smooth + drawing. For example, the shape may jitter on screen when rotating slowly. If + you're having an issue with how arcs are rendered, you'll need to draw the + arc yourself with `beginShape()`/`endShape()` or a `PShape`. + examples: + - |- + size(400,400); + arc(50, 55, 50, 50, 0, HALF_PI); + noFill(); + arc(50, 55, 60, 60, HALF_PI, PI); + arc(50, 55, 70, 70, PI, PI+QUARTER_PI); + arc(50, 55, 80, 80, PI+QUARTER_PI, TWO_PI); + - |- + size(400,400); + arc(200, 200, 320, 320, 0, PI+QUARTER_PI, OPEN); + - |- + size(400,400); + arc(200, 200, 320, 320, 0, PI+QUARTER_PI, CHORD); + - |- + size(400,400); + arc(200, 200, 320, 320, 0, PI+QUARTER_PI, PIE); + fileName: arc_ + parameters: + a: + desc: x-coordinate of the arc's ellipse + type: + - float + b: + desc: y-coordinate of the arc's ellipse + type: + - float + c: + desc: width of the arc's ellipse by default + type: + - float + d: + desc: height of the arc's ellipse by default + type: + - float + start: + desc: angle to start the arc, specified in radians + type: + - float + stop: + desc: angle to stop the arc, specified in radians + type: + - float + returns: void + syntax: + - arc(a, b, c, d, start, stop) + - arc(a, b, c, d, start, stop, mode) type: function arrayCopy: - description: >- - 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 - `srcPosition` and into the position specified by `dstPosition`. The number - of elements to copy is determined by `length`. Note that copying values - overwrites existing values in the destination array. To append values - instead of overwriting them, use `concat()`. - - - The simplified version with only two arguments — `arrayCopy(src, dst)` — copies an entire array to another of the same size. It is equivalent to `arrayCopy(src, 0, dst, 0, src.length)`. - - - Using this function is far more efficient for copying array data than iterating through a `for()` loop and copying each element individually. This function only copies references, which means that for most purposes it only copies one-dimensional arrays (a single set of brackets). If used with a two (or three or more) dimensional array, it will only copy the references at the first level, because a two dime. . . - docUrl: https://processing.org/reference/arrayCopy_.html - name: null - parameters: - dst: "Object: the destination array of the same data type as the source array" - dstPosition: "int: starting position in the destination array" - length: "int: number of array elements to be copied" - src: "Object: the source array" - srcPosition: "int: starting position in the source array" - returns: void - syntax: |- - arrayCopy(src, srcPosition, dst, dstPosition, length) - arrayCopy(src, dst, length) - arrayCopy(src, dst) + description: |- + 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 `srcPosition` and into the position specified by + `dstPosition`. The number of elements to copy is determined by + `length`. Note that copying values overwrites existing values in the + destination array. To append values instead of overwriting them, use + `concat()`. + + The simplified version with only two arguments — `arrayCopy(src, + dst)` — copies an entire array to another of the same size. It is + equivalent to `arrayCopy(src, 0, dst, 0, src.length)`. + + Using this function is far more efficient for copying array data than + iterating through a `for()` loop and copying each element + individually. This function only copies references, which means that for + most purposes it only copies one-dimensional arrays (a single set of + brackets). If used with a two (or three or more) dimensional array, it will + only copy the references at the first level, because a two-dimensional + array is simply an "array of arrays". This does not produce an error, + however, because this is often the desired behavior. Internally, this + function calls Java's System.arraycopy() + method, so most things that apply there are inherited. + examples: + - | + String[] north = { "OH", "IN", "MI"}; + String[] south = { "GA", "FL", "NC"}; + arrayCopy(north, 1, south, 0, 2); + println(south); + // Prints updated array contents to the console: + // [0] "IN" + // [1] "MI" + // [2] "NC" + - | + String[] north = { "OH", "IN", "MI" }; + String[] south = { "GA", "FL", "NC" }; + arrayCopy(north, south); + println(south); + // Prints updated array contents to the console: + // [0] "OH" + // [1] "IN" + // [2] "MI" + fileName: arrayCopy_ + parameters: + dst: + desc: the destination array of the same data type as the source array + type: + - Object + dstPosition: + desc: starting position in the destination array + type: + - int + length: + desc: number of array elements to be copied + type: + - int + src: + desc: the source array + type: + - Object + srcPosition: + desc: starting position in the source array + type: + - int + returns: void + syntax: + - arrayCopy(src, srcPosition, dst, dstPosition, length) + - arrayCopy(src, dst, length) + - arrayCopy(src, dst) type: function asin: - description: 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`. - docUrl: https://processing.org/reference/asin_.html - name: null - parameters: - value: "float: the value whose arc sine is to be returned" + description: |- + 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`. + examples: + - | + float a = PI/3; + float s = sin(a); + float as = asin(s); + // Prints "1.0471976 : 0.86602545 : 1.0471976" + println(a + " : " + s + " : " + as); + - | + float a = PI + PI/3.0; + float s = sin(a); + float as = asin(s); + // Prints "4.1887903 : -0.86602545 : -1.0471976" + println(a + " : " + s + " : " + as); + fileName: asin_ + parameters: + value: + desc: the value whose arc sine is to be returned + type: + - float returns: float - syntax: asin(value) + syntax: + - asin(value) type: function atan: - description: 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 `. - docUrl: https://processing.org/reference/atan_.html - name: null - parameters: - value: "float: -Infinity to Infinity (exclusive)" + description: |- + 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 `. + examples: + - | + float a = PI/3; + float t = tan(a); + float at = atan(t); + // Prints "1.0471976 : 1.7320509 : 1.0471976" + println(a + " : " + t + " : " + at); + - | + float a = PI + PI/3.0; + float t = tan(a); + float at = atan(t); + // Prints "4.1887903 : 1.7320513 : 1.0471977" + println(a + " : " + t + " : " + at); + fileName: atan_ + parameters: + value: + desc: -Infinity to Infinity (exclusive) + type: + - float returns: float - syntax: atan(value) + syntax: + - atan(value) + type: function +atan2: + description: |- + 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 structure + of calculating the tangent. + examples: + - | + void draw() { + background(204); + translate(width/2, height/2); + float a = atan2(mouseY-height/2, mouseX-width/2); + rotate(a); + rect(-30, -5, 60, 10); + } + fileName: atan2_ + parameters: + x: + desc: x-coordinate of the point + type: + - float + y: + desc: y-coordinate of the point + type: + - float + returns: float + syntax: + - atan2(y, x) type: function background: description: >- - The `background()` function sets the color used for the background of the - Processing window. The default background is light gray. This function is - typically used within `draw()` to clear the display window at the beginning - of each frame, but it can be used inside `setup()` to set the background on - the first frame of animation or if the backgound need only be set once. - - An image can also be used as the background for a sketch, although the image's width and height must match that of the sketch window. Images used with `background()` will ignore the current `tint()` setting. To resize an image to the size of the sketch window, use image.resize(width, height). - - It is not possible to use the transparency `alpha` parameter with background colors on the main drawing surface. It can only be used along with a `PGraphics` object and `createGraphics()`. - docUrl: https://processing.org/reference/background_.html - name: null - parameters: - alpha: "float: opacity of the background" - gray: "float: specifies a value between white and black" - image: "PImage: PImage to set as background (must be same size as the sketch - window)" - rgb: "int: any value of the color datatype" - v1: "float: red or hue value (depending on the current color mode)" - v2: "float: green or saturation value (depending on the current color mode)" - v3: "float: blue or brightness value (depending on the current color mode)" - returns: void - syntax: |- - background(rgb) - background(rgb, alpha) - background(gray) - background(gray, alpha) - background(v1, v2, v3) - background(v1, v2, v3, alpha) - background(image) + The `background()` function sets the color used for the background of + the Processing window. The default background is light gray. This function is + typically used within `draw()` to clear the display window at the + beginning of each frame, but it can be used inside `setup()` to set the + background on the first frame of animation or if the background need only be + set once. + + An image can also be used as the background for a sketch, although the + image's width and height must match that of the sketch window. Images used + with `background()` will ignore the current `tint()` setting. To + resize an image to the size of the sketch window, use image.resize(width, + height). + + It is not possible to use the transparency `alpha` parameter with + background colors on the main drawing surface. It can only be used along with + a `PGraphics` object and `createGraphics()`. + examples: + - background(51); + - background(152,190,100); + - |- + PImage img; + img = loadImage("Hokkaido.jpg"); + background(img); + fileName: background_ + parameters: + alpha: + desc: opacity of the background + type: + - float + gray: + desc: specifies a value between white and black + type: + - float + image: + desc: PImage to set as background (must be same size as the sketch window) + type: + - PImage + rgb: + desc: any value of the color datatype + type: + - int + v1: + desc: red or hue value (depending on the current color mode) + type: + - float + v2: + desc: green or saturation value (depending on the current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on the current color mode) + type: + - float + returns: void + syntax: + - background(rgb) + - background(rgb, alpha) + - background(gray) + - background(gray, alpha) + - background(v1, v2, v3) + - background(v1, v2, v3, alpha) + - background(image) type: function beginCamera: - description: 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. - docUrl: https://processing.org/reference/beginCamera_.html - name: null + description: >- + 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. + examples: + - |+ + size(400, 400, P3D); + noFill(); + + beginCamera(); + camera(); + rotateX(-PI/6); + endCamera(); + + translate(200, 200, 0); + rotateY(PI/3); + box(180); + + fileName: beginCamera_ parameters: {} returns: void - syntax: beginCamera() + syntax: + - beginCamera() type: function beginContour: - description: >- - Use the `beginContour()` and `endContour()` function to create negative - shapes within shapes such as the center of the letter 'O'. `beginContour()` - begins recording vertices for the shape and `endContour()` stops recording. - The vertices that define a negative shape must "wind" in the opposite - direction from the exterior shape. First draw vertices for the exterior - shape in clockwise order, then for internal shapes, draw vertices - counterclockwise. - - - These functions can only be used within a `beginShape()`/`endShape()` pair and transformations such as `translate()`, `rotate()`, and `scale()` do not work within a `beginContour()`/`endContour()` pair. It is also not possible to use other shapes, such as `ellipse()` or `rect()` within. - docUrl: https://processing.org/reference/beginContour_.html - name: null + description: |- + Use the `beginContour()` and `endContour()` function to + create negative shapes within shapes such as the center of the + letter "O". `beginContour()` begins recording vertices for the + shape and `endContour()` stops recording. The vertices that + define a negative shape must "wind" in the opposite direction from + the exterior shape. First draw vertices for the exterior shape in + clockwise order, then for internal shapes, draw vertices counterclockwise. + + These functions can only be used within a `beginShape()`/`endShape()` + pair and transformations such as `translate()`, `rotate()`, and + `scale()` do not work within a `beginContour()`/`endContour()` + pair. It is also not possible to use other shapes, such as `ellipse()` + or `rect()` within. + examples: + - | + size(400,400); + translate(200, 200); + stroke(255, 0, 0); + beginShape(); + // Exterior part of shape, clockwise winding + vertex(-160, -160); + vertex(160, -160); + vertex(160, 160); + vertex(-160, 160); + // Interior part of shape, counter-clockwise winding + beginContour(); + vertex(-80, -80); + vertex(-80, 80); + vertex(80, 80); + vertex(80, -80); + endContour(); + endShape(CLOSE); + fileName: beginContour_ parameters: {} returns: void - syntax: beginContour() + syntax: + - beginContour() type: function beginRaw: - description: >- - 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. + description: |- + 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. + examples: + - | + import processing.pdf.*; + + void setup() { + size(400, 400); + beginRaw(PDF, "raw.pdf"); + } + void draw() { + line(pmouseX, pmouseY, mouseX, mouseY); + } - Using `hint(ENABLE_DEPTH_SORT)` can improve th. . . - docUrl: https://processing.org/reference/beginRaw_.html - name: null - parameters: - filename: "String: filename for output" - renderer: "String: for example, PDF or DXF" + void keyPressed() { + if (key == ' ') { + endRaw(); + exit(); + } + } + fileName: beginRaw_ + parameters: + filename: + desc: filename for output + type: + - String + renderer: + desc: for example, PDF or DXF + type: + - String returns: PGraphics or void - syntax: beginRaw(renderer, filename) + syntax: + - beginRaw(renderer, filename) type: function beginRecord: - description: >- + description: |- 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. + 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. + + `beginRecord()` works only with the PDF and SVG renderers. + examples: + - | + import processing.pdf.*; + + void setup() { + size(400, 400); + beginRecord(PDF, "everything.pdf"); + } + void draw() { + ellipse(mouseX, mouseY, 10, 10); + } - `beginRecord()` works only with the PDF and SVG renderers. - docUrl: https://processing.org/reference/beginRecord_.html - name: null - parameters: - filename: "String: filename for output" - renderer: "String: PDF or SVG" + void mousePressed() { + endRecord(); + exit(); + } + fileName: beginRecord_ + parameters: + filename: + desc: filename for output + type: + - String + renderer: + desc: PDF or SVG + type: + - String returns: PGraphics or void - syntax: beginRecord(renderer, filename) + syntax: + - beginRecord(renderer, filename) type: function beginShape: description: >- - 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 `kind` 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 `ellip. . . - docUrl: https://processing.org/reference/beginShape_.html - name: null - parameters: - kind: "int: Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, - QUADS, or QUAD_STRIP" - returns: void - syntax: |- - beginShape() - beginShape(kind) + 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 `kind` 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 P2D and P3D renderers allow `stroke()` and `fill()` to be + altered on a per-vertex basis, but the default renderer does not. Settings + such as `strokeWeight()`, `strokeCap()`, and `strokeJoin()` + cannot be changed while inside a `beginShape()`/`endShape()` block + with any renderer. + examples: + - |- + beginShape(); + vertex(120, 80); + vertex(340, 80); + vertex(340, 300); + vertex(120, 300); + endShape(CLOSE); + - |- + beginShape(POINTS); + vertex(120, 80); + vertex(340, 80); + vertex(340, 300); + vertex(120, 300); + endShape(); + - |- + beginShape(); + vertex(120, 80); + vertex(230, 80); + vertex(230, 190); + vertex(340, 190); + vertex(340, 300); + vertex(120, 300); + endShape(CLOSE); + - |- + beginShape(LINES); + vertex(120, 80); + vertex(340, 80); + vertex(340, 300); + vertex(120, 300); + endShape(); + - | + noFill(); + beginShape(); + vertex(120, 80); + vertex(340, 80); + vertex(340, 300); + vertex(120, 300); + endShape(); + - |- + noFill(); + beginShape(); + vertex(120, 80); + vertex(340, 80); + vertex(340, 300); + vertex(120, 300); + endShape(CLOSE); + - | + beginShape(TRIANGLES); + vertex(120, 300); + vertex(160, 120); + vertex(200, 300); + vertex(270, 80); + vertex(280, 300); + vertex(320, 80); + endShape(); + - |- + beginShape(TRIANGLE_STRIP); + vertex(120, 300); + vertex(160, 80); + vertex(200, 300); + vertex(240, 80); + vertex(280, 300); + vertex(320, 80); + vertex(360, 300); + endShape(); + - |- + beginShape(TRIANGLE_FAN); + vertex(230, 200); + vertex(230, 60); + vertex(368, 200); + vertex(230, 340); + vertex(88, 200); + vertex(230, 60); + endShape(); + - |- + beginShape(QUADS); + vertex(120, 80); + vertex(120, 300); + vertex(200, 300); + vertex(200, 80); + vertex(260, 80); + vertex(260, 300); + vertex(340, 300); + vertex(340, 80); + endShape(); + - | + beginShape(QUAD_STRIP); + vertex(120, 80); + vertex(120, 300); + vertex(200, 80); + vertex(200, 300); + vertex(260, 80); + vertex(260, 300); + vertex(340, 80); + vertex(340, 300); + endShape(); + fileName: beginShape_ + parameters: + kind: + desc: |- + Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, + QUADS, or QUAD_STRIP + type: + - int + returns: void + syntax: + - beginShape() + - beginShape(kind) type: function bezier: - description: 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). - docUrl: https://processing.org/reference/bezier_.html - name: null - parameters: - x1: "float: coordinates for the first anchor point" - x2: "float: coordinates for the first control point" - x3: "float: coordinates for the second control point" - x4: "float: coordinates for the second anchor point" - y1: "float: coordinates for the first anchor point" - y2: "float: coordinates for the first control point" - y3: "float: coordinates for the second control point" - y4: "float: coordinates for the second anchor point" - z1: "float: coordinates for the first anchor point" - z2: "float: coordinates for the first control point" - z3: "float: coordinates for the second control point" - z4: "float: coordinates for the second anchor point" - returns: void - syntax: |- - bezier(x1, y1, x2, y2, x3, y3, x4, y4) - bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) + description: |- + Draws a Bézier 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. The curves were developed by French engineer Pierre + Bezier. Using the 3D version requires rendering with P3D (see the + Environment reference for more information). + examples: + - |- + noFill(); + stroke(255, 102, 0); + line(340, 80, 40, 40); + line(360, 360, 60, 320); + stroke(0, 0, 0); + bezier(340, 80, 40, 40, 360, 360, 60, 320); + - |- + size(400,400); + noFill(); + stroke(255, 102, 0); + line(120, 80, 320, 20); + line(320, 300, 120, 300); + stroke(0, 0, 0); + bezier(120, 80, 320, 20, 320, 300, 120, 300); + fileName: bezier_ + parameters: + x1: + desc: coordinates for the first anchor point + type: + - float + x2: + desc: coordinates for the first control point + type: + - float + x3: + desc: coordinates for the second control point + type: + - float + x4: + desc: coordinates for the second anchor point + type: + - float + y1: + desc: coordinates for the first anchor point + type: + - float + y2: + desc: coordinates for the first control point + type: + - float + y3: + desc: coordinates for the second control point + type: + - float + y4: + desc: coordinates for the second anchor point + type: + - float + z1: + desc: coordinates for the first anchor point + type: + - float + z2: + desc: coordinates for the first control point + type: + - float + z3: + desc: coordinates for the second control point + type: + - float + z4: + desc: coordinates for the second anchor point + type: + - float + returns: void + syntax: + - bezier(x1, y1, x2, y2, x3, y3, x4, y4) + - bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) type: function bezierDetail: - description: Sets the resolution at which Beziers display. The default value is - 20. This function is only useful when using the `P3D` renderer; the default - `P2D` renderer does not use this information. - docUrl: https://processing.org/reference/bezierDetail_.html - name: null + description: |- + Sets the resolution at which Bézier curves display. The default value is 20. + This function is only useful when using the `P2D` or `P3D` renderer; + the default (JAVA2D) renderer does not use this information. + examples: + - | + // Move the mouse left and right to see the detail change + + void setup() { + size(100, 100, P3D); + noFill(); + } + + void draw() { + background(204); + int d = int(map(mouseX, 0, 100, 1, 20)); + bezierDetail(d); + bezier(85, 20, 10, 10, 90, 90, 15, 80); + } + fileName: bezierDetail_ parameters: - detail: "int: resolution of the curves" + detail: + desc: resolution of the curves + type: + - int returns: void - syntax: bezierDetail(detail) + syntax: + - bezierDetail(detail) type: function bezierPoint: - description: 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. - docUrl: https://processing.org/reference/bezierPoint_.html - name: null - parameters: - a: "float: coordinate of first point on the curve" - b: "float: coordinate of first control point" - c: "float: coordinate of second control point" - d: "float: coordinate of second point on the curve" - t: "float: value between 0 and 1" - returns: float - syntax: bezierPoint(a, b, c, d, t) + description: |- + 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 Bézier curve + at t. + examples: + - |- + size(400,400); + noFill(); + bezier(340, 80, 40, 40, 360, 360, 60, 320); + fill(255); + int steps = 10; + for (int i = 0; i <= steps; i++) { + float t = i / float(steps); + float x = bezierPoint(340, 40, 360, 60, t); + float y = bezierPoint(80, 40, 360, 320, t); + ellipse(x, y, 10, 10); + } + fileName: bezierPoint_ + parameters: + a: + desc: coordinate of first point on the curve + type: + - float + b: + desc: coordinate of first control point + type: + - float + c: + desc: coordinate of second control point + type: + - float + d: + desc: coordinate of second point on the curve + type: + - float + t: + desc: value between 0 and 1 + type: + - float + returns: float + syntax: + - bezierPoint(a, b, c, d, t) type: function bezierTangent: - description: Calculates the tangent of a point on a Bezier curve. There is a - good definition of tangent on Wikipedia. - docUrl: https://processing.org/reference/bezierTangent_.html - name: null - parameters: - a: "float: coordinate of first point on the curve" - b: "float: coordinate of first control point" - c: "float: coordinate of second control point" - d: "float: coordinate of second point on the curve" - t: "float: value between 0 and 1" + description: |- + Calculates the tangent of a point on a Bézier curve. There is a good + definition of tangent on Wikipedia. + examples: + - |- + size(400,400); + noFill(); + bezier(340, 80, 40, 40, 360, 360, 60, 320); + + int steps = 6; + fill(255); + for (int i = 0; i <= steps; i++) { + float t = i / float(steps); + // Get the location of the point + float x = bezierPoint(340, 40, 360, 60, t); + float y = bezierPoint(80, 40, 360, 320, t); + // Get the tangent points + float tx = bezierTangent(340, 40, 360, 60, t); + float ty = bezierTangent(80, 40, 360, 320, t); + // Calculate an angle from the tangent points + float a = atan2(ty, tx); + a += PI; + stroke(255, 102, 0); + line(x, y, cos(a)*120 + x, sin(a)*120 + y); + // The following line of code makes a line + // inverse of the above line + //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y); + stroke(0); + ellipse(x, y, 10, 10); + } + - | + size(400,400); + + noFill(); + bezier(340, 80, 40, 40, 360, 360, 60, 320); + stroke(255, 102, 0); + int steps = 16; + for (int i = 0; i <= steps; i++) { + float t = i / float(steps); + float x = bezierPoint(340, 40, 360, 60, t); + float y = bezierPoint(80, 40, 360, 320, t); + float tx = bezierTangent(340, 40, 360, 60, t); + float ty = bezierTangent(80, 40, 360, 320, t); + float a = atan2(ty, tx); + a -= HALF_PI; + line(x, y, cos(a)*32 + x, sin(a)*32 + y); + } + fileName: bezierTangent_ + parameters: + a: + desc: coordinate of first point on the curve + type: + - float + b: + desc: coordinate of first control point + type: + - float + c: + desc: coordinate of second control point + type: + - float + d: + desc: coordinate of second point on the curve + type: + - float + t: + desc: value between 0 and 1 + type: + - float returns: float - syntax: bezierTangent(a, b, c, d, t) + syntax: + - bezierTangent(a, b, c, d, t) type: function bezierVertex: - description: 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). - docUrl: https://processing.org/reference/bezierVertex_.html - name: null - parameters: - x2: "float: the x-coordinate of the 1st control point" - x3: "float: the x-coordinate of the 2nd control point" - x4: "float: the x-coordinate of the anchor point" - y2: "float: the y-coordinate of the 1st control point" - y3: "float: the y-coordinate of the 2nd control point" - y4: "float: the y-coordinate of the anchor point" - z2: "float: the z-coordinate of the 1st control point" - z3: "float: the z-coordinate of the 2nd control point" - z4: "float: the z-coordinate of the anchor point" - returns: void - syntax: |- - bezierVertex(x2, y2, x3, y3, x4, y4) - bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4) + description: |- + Specifies vertex coordinates for Bézier curves. Each call to + `bezierVertex()` defines the position of two control points and one + anchor point of a Bézier 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). + examples: + - | + size(400,400); + noFill(); + beginShape(); + vertex(120, 80); + bezierVertex(320, 0, 320, 300, 120, 300); + endShape(); + - |- + size(400,400); + beginShape(); + vertex(120, 80); + bezierVertex(320, 0, 320, 300, 90, 300); + bezierVertex(200, 320, 240, 100, 120, 80); + endShape(); + fileName: bezierVertex_ + parameters: + x2: + desc: the x-coordinate of the 1st control point + type: + - float + x3: + desc: the x-coordinate of the 2nd control point + type: + - float + x4: + desc: the x-coordinate of the anchor point + type: + - float + y2: + desc: the y-coordinate of the 1st control point + type: + - float + y3: + desc: the y-coordinate of the 2nd control point + type: + - float + y4: + desc: the y-coordinate of the anchor point + type: + - float + z2: + desc: the z-coordinate of the 1st control point + type: + - float + z3: + desc: the z-coordinate of the 2nd control point + type: + - float + z4: + desc: the z-coordinate of the anchor point + type: + - float + returns: void + syntax: + - bezierVertex(x2, y2, x3, y3, x4, y4) + - bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4) type: function binary: - description: >- - Converts an `int`, `byte`, `char`, or `color` to a `String` containing the - equivalent binary notation. For example, the `color` value produced by - `color(0, 102, 153, 255)` will convert to the `String` value - `"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 have no effect. - docUrl: https://processing.org/reference/binary_.html - name: null - parameters: - digits: "int: number of digits to return" - value: "char, byte, or int: value to convert" + description: |- + Converts an `int`, `byte`, `char`, or `color` to a + `String` containing the equivalent binary notation. For example, the + `color` value produced by `color(0, 102, 153, 255)` will convert + to the `String` value `"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 have + no effect. + examples: + - |+ + color c = color(255, 204, 0); + println(c); // Prints "-13312" + println(binary(c)); // Prints "11111111111111111100110000000000" + println(binary(c, 16)); // Prints "1100110000000000" + + fileName: binary_ + parameters: + digits: + desc: number of digits to return + type: + - int + value: + desc: value to convert + type: + - int + - char returns: String - syntax: |- - binary(value) - binary(value, digits) + syntax: + - binary(value) + - binary(value, digits) type: function blend: - description: >- - Blends a region of pixels from one image into another (or in itself again) - with full alpha channel support. There is a choice of the following modes to - blend the source pixels (A) with the ones of pixels in the destination image - (B): - - - BLEND - linear interpolation of colors: 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 color succeeds: C = min(A*factor, B) - - - LIGHTEST - only the lightest color 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 LIGH. . . - docUrl: https://processing.org/reference/blend_.html - name: null - parameters: - dh: "int: destination image height" - dw: "int: destination image width" - dx: "int: X coordinate of the destinations's upper left corner" - dy: "int: Y coordinate of the destinations's upper left corner" - mode: "int: Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, - EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN" - sh: "int: source image height" - src: "PImage: an image variable referring to the source image" - sw: "int: source image width" - sx: "int: X coordinate of the source's upper left corner" - sy: "int: Y coordinate of the source's upper left corner" - returns: void - syntax: |- - blend(sx, sy, sw, sh, dx, dy, dw, dh, mode) - blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode) + description: |- + 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 (the 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()`. + examples: + - |- + size(400,400); + background(loadImage("mt-fuji.jpg")); + PImage img = loadImage("dandelions.jpg"); + image(img, 0, 0); + blend(img, 0, 0, 132, 400, 268, 0, 132, 400, ADD); + - |- + size(400,400); + background(loadImage("mt-fuji.jpg")); + PImage img = loadImage("dandelions.jpg"); + image(img, 0, 0); + blend(img, 0, 0, 132, 400, 268, 0, 132, 400, SUBTRACT); + - |- + size(400,400); + background(loadImage("mt-fuji.jpg")); + PImage img = loadImage("dandelions.jpg"); + image(img, 0, 0); + blend(img, 0, 0, 132, 400, 268, 0, 132, 400, DARKEST); + - |- + size(400,400); + background(loadImage("mt-fuji.jpg")); + PImage img = loadImage("dandelions.jpg"); + image(img, 0, 0); + blend(img, 0, 0, 132, 400, 268, 0, 132, 400, LIGHTEST); + fileName: blend_ + parameters: + dh: + desc: destination image height + type: + - int + dw: + desc: destination image width + type: + - int + dx: + desc: X coordinate of the destination's upper left corner + type: + - int + dy: + desc: Y coordinate of the destination's upper left corner + type: + - int + mode: + desc: Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, + MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN + type: + - int + sh: + desc: source image height + type: + - int + src: + desc: an image variable referring to the source image + type: + - PImage + sw: + desc: source image width + type: + - int + sx: + desc: X coordinate of the source's upper left corner + type: + - int + sy: + desc: Y coordinate of the source's upper left corner + type: + - int + returns: void + syntax: + - blend(sx, sy, sw, sh, dx, dy, dw, dh, mode) + - blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode) type: function blendMode: description: >- - Blends the pixels in the display window according to a defined mode. There - is a choice of the following modes to blend the source pixels (A) with the - ones of pixels already in the display window (B). Each pixel's final color - is the result of applying one of the blend modes with each channel of (A) - and (B) independently. The red channel is compared with red, green with - green, and blue with blue. - - - BLEND - linear interpolation of colors: C = A*factor + B. This is the default. - - - ADD - additive blending with white clip: C = min(A*factor + B, 255) - - - SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0) - + Blends the pixels in the display window according to a defined mode. + There is a choice of the following modes to blend the source pixels (A) + with the ones of pixels already in the display window (B). Each pixel's + final color is the result of applying one of the blend modes with each + channel of (A) and (B) independently. The red channel is compared with + red, green with green, and blue with blue. - DARKEST - only the darkest color succeeds: C = min(A*factor, B) + BLEND - linear interpolation of colors: `C = A*factor + B`. This is the default. + ADD - additive blending with white clip: `C = min(A*factor + B, 255)` - LIGHTEST - only the lightest color succeeds: C = max(A*factor, B) + SUBTRACT - subtractive blending with black clip: `C = max(B - A*factor, 0)` + DARKEST - only the darkest color succeeds: `C = min(A*factor, B)` - DIFFERENCE - subtract colors from underlying image. + LIGHTEST - only the lightest color succeeds: `C = max(A*factor, B)` + DIFFERENCE - subtract colors from underlying image. - EXCLUSION - similar to DIFFERENCE, but less extreme. + EXCLUSION - similar to DIFFERENCE, but less extreme. + MULTIPLY - multiply the colors, result will always be darker. - MULTIPLY - multiply the colors, result will always be darker. + SCREEN - opposite multiply, uses inverse values of the colors. + REPLACE - the pixels entirely replace the others and don't utilize alpha (transparency) values - SCREEN - opposite multiply, uses inverse values of the colors. - - - REPLACE - t. . . - docUrl: https://processing.org/reference/blendMode_.html - name: null + We recommend using `blendMode()` and not the previous `blend()` + function. However, unlike `blend()`, the `blendMode()` function + does not support the following: HARD_LIGHT, SOFT_LIGHT, OVERLAY, DODGE, + BURN. On older hardware, the LIGHTEST, DARKEST, and DIFFERENCE modes might + not be available as well. + examples: + - | + size(100, 100); + background(0); + blendMode(ADD); + stroke(102); + strokeWeight(30); + line(25, 25, 75, 75); + line(75, 25, 25, 75); + - | + size(100, 100, P2D); + blendMode(MULTIPLY); + stroke(51); + strokeWeight(30); + line(25, 25, 75, 75); + line(75, 25, 25, 75); + fileName: blendMode_ parameters: - mode: "int: the blending mode to use" + mode: + desc: the blending mode to use + type: + - int returns: void - syntax: blendMode(mode) + syntax: + - blendMode(mode) type: function blue: description: >- - Extracts the blue value from a color, scaled to match current `colorMode()`. - The 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 understand, but it is slower than a technique called bit masking. When working in `colorMode(RGB, 255)`, you can acheive the same results as `blue()` but with greater speed by using a bit mask to remove the other color components. For example, the following two lines of code are equivalent means of getting the blue value of the color value `c`: - - - `float b1 = blue(c); // Simpler, but slower to calculate - - float b2 = c & 0xFF; // Very fast to calculate` - docUrl: https://processing.org/reference/blue_.html - name: null - parameters: - rgb: "int: any value of the color datatype" + Extracts the blue value from a color, scaled to match current + `colorMode()`. The 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 understand, but it is slower + than a technique called bit masking. When working in `colorMode(RGB, + 255)`, you can achieve the same results as `blue()` but with greater + speed by using a bit mask to remove the other color components. For example, + the following two lines of code are equivalent means of getting the blue + value of the color value `c`: + + + ` + float b1 = blue(c); // Simpler, but slower to calculate + float b2 = c & 0xFF; // Very fast to calculate + ` + examples: + - | + size(400,400); + color c = color(175, 100, 220); // Define color 'c' + fill(c); // Use color variable 'c' as fill color + rect(60, 80, 140, 240); // Draw left rectangle + + float blueValue = blue(c); // Get blue in 'c' + println(blueValue); // Prints "220.0" + fill(0, 0, blueValue); // Use 'blueValue' in new fill + rect(200, 80, 140, 240); // Draw right rectangle + fileName: blue_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int returns: float - syntax: blue(rgb) + syntax: + - blue(rgb) type: function boolean: description: >- @@ -1089,34 +3581,105 @@ boolean: false. - When an array of `int` or `String` values is passed in, then a `boolean` array of the same length is returned. - docUrl: https://processing.org/reference/booleanconvert_.html - name: null + When an array of `int` or `String` values is passed in, then a `boolean` + array of the same length is returned. + examples: + - | + String s = "true"; + boolean b = boolean(s); + if (b) { + println("The boolean is true"); + } else { + println("The boolean is false"); + } + fileName: booleanconvert_ parameters: {} + syntax: [] type: function box: - description: A box is an extruded rectangle. A box with equal dimensions on all - sides is a cube. - docUrl: https://processing.org/reference/box_.html - name: null - parameters: - d: "float: dimension of the box in the z-dimension" - h: "float: dimension of the box in the y-dimension" - size: "float: dimension of the box in all dimensions (creates a cube)" - w: "float: dimension of the box in the x-dimension" - returns: void - syntax: |- - box(size) - box(w, h, d) + description: |- + A box is an extruded `rectangle`. A box with equal dimension + on all sides is a cube. + examples: + - |- + size(400,400,P3D); + translate(232, 192, 0); + rotateY(0.5); + noFill(); + box(160); + - |- + translate(232, 192, 0); + rotateY(0.5); + noFill(); + box(160, 80, 200); + fileName: box_ + parameters: + d: + desc: dimension of the box in the z-dimension + type: + - float + h: + desc: dimension of the box in the y-dimension + type: + - float + size: + desc: dimension of the box in all dimensions (creates a cube) + type: + - float + w: + desc: dimension of the box in the x-dimension + type: + - float + returns: void + syntax: + - box(size) + - box(w, h, d) + type: function +break: + description: Ends the execution of a structure such as `switch`, `for`, or + `while` and jumps to the next statement after. + examples: + - | + char letter = 'B'; + + switch(letter) { + case 'A': + println("Alpha"); // Does not execute + break; + case 'B': + println("Bravo"); // Prints "Bravo" + break; + default: + println("Zulu"); // Does not execute + break; + } + fileName: break + parameters: {} + returns: "" + syntax: [] type: function brightness: description: Extracts the brightness value from a color. - docUrl: https://processing.org/reference/brightness_.html - name: null - parameters: - rgb: "int: any value of the color datatype" + examples: + - | + size(400,400); + noStroke(); + colorMode(HSB, 255); + color c = color(0, 126, 255); + fill(c); + rect(60, 80, 140, 240); + float value = brightness(c); // Sets 'value' to 255 + fill(value); + rect(200, 80, 140, 240); + fileName: brightness_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int returns: float - syntax: brightness(rgb) + syntax: + - brightness(rgb) type: function byte: description: >- @@ -1127,47 +3690,184 @@ byte: byte representation. (For example, `byte(128)` evaluates to `-128`.) - When an array of values is passed in, then a `byte` array of the same length is returned. - docUrl: https://processing.org/reference/byteconvert_.html - name: null + When an array of values is passed in, then a `byte` array of the same length + is returned. + examples: + - | + char c = 'E'; + byte b = byte(c); + println(c + " : " + b); // Prints "E : 69" + + int i = 130; + b = byte(i); + println(i + " : " + b); // Prints "130 : -126" + fileName: byteconvert_ parameters: {} + syntax: [] type: function camera: - description: 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. - docUrl: https://processing.org/reference/camera_.html - name: null - parameters: - centerX: "float: x-coordinate for the center of the scene" - centerY: "float: y-coordinate for the center of the scene" - centerZ: "float: z-coordinate for the center of the scene" - eyeX: "float: x-coordinate for the eye" - eyeY: "float: y-coordinate for the eye" - eyeZ: "float: z-coordinate for the eye" - upX: "float: usually 0.0, 1.0, or -1.0" - upY: "float: usually 0.0, 1.0, or -1.0" - upZ: "float: usually 0.0, 1.0, or -1.0" - returns: void - syntax: |- - camera() - camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) + description: >- + 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. + examples: + - |- + size(400, 400, P3D); + noFill(); + background(204); + camera(70.0, 35.0, 120.0, 50.0, 50.0, 0.0, + 0.0, 1.0, 0.0); + translate(50, 50, 0); + rotateX(-PI/6); + rotateY(PI/3); + box(45); + fileName: camera_ + parameters: + centerX: + desc: x-coordinate for the center of the scene + type: + - float + centerY: + desc: y-coordinate for the center of the scene + type: + - float + centerZ: + desc: z-coordinate for the center of the scene + type: + - float + eyeX: + desc: x-coordinate for the eye + type: + - float + eyeY: + desc: y-coordinate for the eye + type: + - float + eyeZ: + desc: z-coordinate for the eye + type: + - float + upX: + desc: usually 0.0, 1.0, or -1.0 + type: + - float + upY: + desc: usually 0.0, 1.0, or -1.0 + type: + - float + upZ: + desc: usually 0.0, 1.0, or -1.0 + type: + - float + returns: void + syntax: + - camera() + - camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) + type: function +case: + description: Denotes the different names to be evaluated with the parameter in + the `switch` structure. + examples: + - | + char letter = 'B'; + + switch(letter) { + case 'A': + println("Alpha"); // Does not execute + break; + case 'B': + println("Bravo"); // Prints "Bravo" + break; + default: + println("Zulu"); // Does not execute + break; + } + fileName: case + parameters: + name: + desc: byte, char, or int + type: [] + statements: + desc: one or more valid statements + type: [] + returns: "" + syntax: + - "case name: statements" + type: function +catch: + description: The `catch` keyword is used with `try` to handle exceptions. Sun's + Java documentation defines an exception as "an event, which occurs during + the execution of a program, that disrupts the normal flow of the program's + instructions." This could be, for example, an error while a file is read. + examples: + - | + BufferedReader reader; + String line; + + void setup() { + // Open the file from the createWriter() example + reader = createReader("positions.txt"); + } + + void draw() { + try { + line = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + line = null; + } + if (line == null) { + // Stop reading because of an error or file is empty + noLoop(); + } else { + String[] pieces = split(line, TAB); + int x = int(pieces[0]); + int y = int(pieces[1]); + point(x, y); + } + } + fileName: catch + parameters: + catchStatements: + desc: code that handles the exception + type: [] + exception: + desc: the Java exception that was thrown + type: [] + tryStatements: + desc: if this code throws an exception, then the code in "catch" is run + type: [] + returns: "" + syntax: + - try { + - " tryStatements" + - "} catch (exception) {" + - " catchStatements" + - "} " type: function ceil: - description: 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. - docUrl: https://processing.org/reference/ceil_.html - name: null - parameters: - n: "float: number to round up" + description: |- + 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. + examples: + - | + float x = 8.22; + int a = ceil(x); // Sets 'a' to 9 + fileName: ceil_ + parameters: + n: + desc: number to round up + type: + - float returns: int - syntax: ceil(n) + syntax: + - ceil(n) type: function char: description: >- @@ -1176,867 +3876,2427 @@ char: representation. - When an array of values is passed in, then a `char` array of the same length is returned. - docUrl: https://processing.org/reference/charconvert_.html - name: null + When an array of values is passed in, then a `char` array of the same length + is returned. + examples: + - | + int i = 65; + char c = char(i); + println(i + " : " + c); // Prints "65 : A" + + byte b = 65; + c = char(b); + println(b + " : " + c); // Prints "65 : A" + fileName: charconvert_ parameters: {} + syntax: [] type: function circle: - description: Draws a circle to the screen. By default, the first two parameters - set the location of the center, and the third sets the shape's width and - height. The origin may be changed with the `ellipseMode()` function. - docUrl: https://processing.org/reference/circle_.html - name: null - parameters: - extent: "float: width and height of the ellipse by default" - x: "float: x-coordinate of the ellipse" - y: "float: y-coordinate of the ellipse" - returns: void - syntax: circle(x, y, extent) + description: |- + Draws a circle to the screen. By default, the first two parameters + set the location of the center, and the third sets the shape's width + and height. The origin may be changed with the `ellipseMode()` + function. + examples: + - circle(224, 184, 220); + fileName: circle_ + parameters: + extent: + desc: width and height of the ellipse by default + type: + - float + x: + desc: x-coordinate of the ellipse + type: + - float + y: + desc: y-coordinate of the ellipse + type: + - float + returns: void + syntax: + - circle(x, y, extent) + type: function +class: + description: Keyword used to indicate the declaration of a class. A class is a + composite of fields (data) and methods (functions that are a part of the + class) which may be instantiated as objects. The first letter of a class + name is usually uppercase to separate it from other kinds of variables. A + related tutorial on Object-Oriented Programming is hosted on the Oracle + website. + examples: + - | + // Declare and construct two objects (h1, h2) from the class HLine + HLine h1 = new HLine(20, 2.0); + HLine h2 = new HLine(50, 2.5); + + void setup() + { + size(200, 200); + frameRate(30); + } + + void draw() { + background(204); + h1.update(); + h2.update(); + } + + class HLine { + float ypos, speed; + HLine (float y, float s) { + ypos = y; + speed = s; + } + void update() { + ypos += speed; + if (ypos > height) { + ypos = 0; + } + line(0, ypos, width, ypos); + } + } + fileName: class + parameters: + ClassName: + desc: Any valid variable name + type: [] + statements: + desc: any valid statements + type: [] + returns: "" + syntax: + - class ClassName { + - " statements" + - "}" type: function clear: - description: Clears the pixels within a buffer. This function only works on - `PGraphics` objects created with the `createGraphics()` function. Unlike the - main graphics context (the display window), pixels in additional graphics - areas created with `createGraphics()` can be entirely or partially - transparent. This function clears everything in a `PGraphics` object to make - all of the pixels 100% transparent. - docUrl: https://processing.org/reference/clear_.html - name: null + description: |- + Clears the pixels within a buffer. This function only works on + `PGraphics` objects created with the `createGraphics()` + function. Unlike the main graphics context (the display window), + pixels in additional graphics areas created with `createGraphics()` + can be entirely or partially transparent. This function clears + everything in a `PGraphics` object to make all the pixels + 100% transparent. + examples: + - | + PGraphics pg; + + void setup() { + size(200, 200); + pg = createGraphics(width, height); + } + + void draw() { + background(204); + + // Clear the PGraphics when the mouse is pressed + if (mousePressed == true) { + pg.beginDraw(); + pg.clear(); + pg.endDraw(); + } else { + pg.beginDraw(); + pg.stroke(0, 102, 153); + pg.line(width/2, height/2, mouseX, mouseY); + pg.endDraw(); + } + + image(pg, 0, 0); + } + fileName: clear_ parameters: {} returns: void - syntax: clear() + syntax: + - clear() type: function clip: - description: 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. - docUrl: https://processing.org/reference/clip_.html - name: null - parameters: - a: "float: x-coordinate of the rectangle, by default" - b: "float: y-coordinate of the rectangle, by default" - c: "float: width of the rectangle, by default" - d: "float: height of the rectangle, by default" - returns: void - syntax: clip(a, b, c, d) + description: |- + Limits the rendering to the boundaries of a rectangle defined + by the parameters. The boundaries are drawn based on the state + of the `imageMode()` function, either CORNER, CORNERS, or CENTER. + examples: + - | + void setup() { + size(200, 200); + imageMode(CENTER); + } + + void draw() { + background(204); + if (mousePressed) { + clip(mouseX, mouseY, 100, 100); + } else { + noClip(); + } + line(0, 0, width, height); + line(0, height, width, 0); + } + fileName: clip_ + parameters: + a: + desc: x-coordinate of the rectangle, by default + type: + - float + b: + desc: y-coordinate of the rectangle, by default + type: + - float + c: + desc: width of the rectangle, by default + type: + - float + d: + desc: height of the rectangle, by default + type: + - float + returns: void + syntax: + - clip(a, b, c, d) type: function color: description: >- - 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, - `color(255, 204, 0)` will return a bright yellow color (see the first - example above). - - - Note that if only one value is provided to `color()`, it will be interpreted as a grayscale value. Add a second value, and it will be used for alpha transparency. When three values are specified, they are interpreted as either RGB or HSB values. Adding a fourth value applies alpha transparency. - - - Note that when using hexadecimal notation, it is not necessary to use `color()`, as in: `color c = #006699` - - - More about how colors are stored can be found in the reference for the color datatype. - docUrl: https://processing.org/reference/color_.html - name: null - parameters: - alpha: "float, or int: relative to current color range" - gray: "int: number specifying value between white and black" - v1: "float, or int: red or hue values relative to the current color range" - v2: "float, or int: green or saturation values relative to the current color - range" - v3: "float, or int: blue or brightness values relative to the current color - range" - returns: int - syntax: |- - color(gray) - color(gray, alpha) - color(v1, v2, v3) - color(v1, v2, v3, alpha) + Datatype for storing color values. Colors may be assigned with `get()` and + `color()` or they may be specified directly using hexadecimal notation such + as `#FFCC00` or `0xFFFFCC00`. + + Using `print()` or `println()` on a color will produce strange results + (usually negative numbers) because of the way colors are stored in memory. A + better technique is to use the `hex()` function to format the color data, or + use the `red()`, `green()`, and `blue()` functions to get individual values + and print those. The `hue()`, `saturation()`, and `brightness()` functions + work in a similar fashion. To extract red, green, and blue values more + quickly (for instance when analyzing an image or a frame of video), use bit + shifting. + + Values can also be created using web color notation. For example: `color c = + #006699` + + Web color notation only works for opaque colors. To define a color with an + alpha value, you can either use `color()` or hexadecimal notation. For hex + notation, prefix the values with `0x`, for instance `color c = 0xCC006699`. + In that example, `CC` (the hex value of 204) is the alpha value, and the + remainder is identical to a web color. Note that in hexadecimal notation, + the alpha value appears in the first position. (The alpha value appears last + when used within `color()`, `fill()`, and `stroke()`.) The following is an + equivalent way of writing the preceding example, but using `color()` and + specifying the alpha value as its second parameter: `color c = + color(#006699, 191)` + + From a technical standpoint, colors are 32 bits of information ordered as + `AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB` where the A's contain the alpha value, + the R's are the red value, G's are green, and B's are blue. Each component + is 8 bits (a number between 0 and 255). These values can be manipulated with + bit shifting. + examples: + - | + color c1 = color(204, 153, 0); + color c2 = #FFCC00; + noStroke(); + fill(c1); + rect(0, 0, 25, 100); + fill(c2); + rect(25, 0, 25, 100); + color c3 = get(10, 50); + fill(c3); + rect(50, 0, 50, 100); + fileName: color_datatype + parameters: {} + syntax: [] type: function colorMode: - description: >- + description: |- 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 `max`, `max1`, `max2`, `max3`, - and `maxA`. - - - After changing the range of values for colors with code like `colorMode(HSB, 360, 100, 100)`, those ranges remain in use until they are explicitly changed again. For example, after running `colorMode(HSB, 360, 100, 100)` and then changing back to `colorMode(RGB)`, the range for R will be 0 to 360 and the range for G and B will be 0 to 100. To avoid this, be explicit about the ranges when changing the color mode. For instance, instead of `colorMode(RGB)`, write `c. . . - docUrl: https://processing.org/reference/colorMode_.html - name: null - parameters: - max: "float: range for all color elements" - max1: "float: range for the red or hue depending on the current color mode" - max2: "float: range for the green or saturation depending on the current color - mode" - max3: "float: range for the blue or brightness depending on the current color - mode" - maxA: "float: range for the alpha" - mode: "int: Either RGB or HSB, corresponding to Red/Green/Blue and - Hue/Saturation/Brightness" - returns: void - syntax: |- - colorMode(mode) - colorMode(mode, max) - colorMode(mode, max1, max2, max3) - colorMode(mode, max1, max2, max3, maxA) + 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 + `max`, `max1`, `max2`, `max3`, and `maxA`. + + After changing the range of values for colors with code like + `colorMode(HSB, 360, 100, 100)`, those ranges remain in use until they + are explicitly changed again. For example, after running `colorMode(HSB, + 360, 100, 100)` and then changing back to `colorMode(RGB)`, the range + for R will be 0 to 360 and the range for G and B will be 0 to 100. To avoid + this, be explicit about the ranges when changing the color mode. For + instance, instead of `colorMode(RGB)`, write `colorMode(RGB, 255, 255, + 255)`. + examples: + - | + size(400,400); + noStroke(); + colorMode(RGB, 400); + for (int i = 0; i < 400; i++) { + for (int j = 0; j < 400; j++) { + stroke(i, j, 0); + point(i, j); + } + } + - | + noStroke(); + colorMode(HSB, 400); + for (int i = 0; i < 400; i++) { + for (int j = 0; j < 400; j++) { + stroke(i, j, 400); + point(i, j); + } + } + - |- + // If the color is defined here, it won't be + // affected by the colorMode() in setup(). + // Instead, just declare the variable here and + // assign the value after the colorMode() in setup() + //color bg = color(180, 50, 50); // No + color bg; // Yes, but assign it in setup() + + void setup() { + size(400, 400); + colorMode(HSB, 360, 100, 100); + bg = color(180, 50, 50); + } + + void draw() { + background(bg); + } + fileName: colorMode_ + parameters: + max: + desc: range for all color elements + type: + - float + max1: + desc: range for the red or hue depending on the current color mode + type: + - float + max2: + desc: range for the green or saturation depending on the current color mode + type: + - float + max3: + desc: range for the blue or brightness depending on the current color mode + type: + - float + maxA: + desc: range for the alpha + type: + - float + mode: + desc: |- + Either RGB or HSB, corresponding to Red/Green/Blue and + Hue/Saturation/Brightness + type: + - int + returns: void + syntax: + - colorMode(mode) + - colorMode(mode, max) + - colorMode(mode, max1, max2, max3) + - colorMode(mode, max1, max2, max3, maxA) type: function concat: - description: >- + description: |- 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). - docUrl: https://processing.org/reference/concat_.html - name: null - parameters: - a: "Object, String[], float[], int[], char[], byte[], or boolean[]: first array - to concatenate" - b: "Object, String[], float[], int[], char[], byte[], or boolean[]: second array - to concatenate" + 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). + examples: + - | + String[] sa1 = { "OH", "NY", "CA"}; + String[] sa2 = { "KY", "IN", "MA"}; + String[] sa3 = concat(sa1, sa2); + println(sa3); + // Prints updated array contents to the console: + // [0] "OH" + // [1] "NY" + // [2] "CA" + // [3] "KY" + // [4] "IN" + // [5] "MA" + fileName: concat_ + parameters: + a: + desc: first array to concatenate + type: + - boolean[] + - byte[] + - char[] + - int[] + - float[] + - String[] + - Object + b: + desc: second array to concatenate + type: + - boolean[] + - byte[] + - char[] + - int[] + - float[] + - String[] + - Object returns: boolean[], byte[], char[], int[], float[], String[], or Object - syntax: concat(a, b) + syntax: + - concat(a, b) type: function constrain: description: Constrains a value to not exceed a maximum and minimum value. - docUrl: https://processing.org/reference/constrain_.html - name: null - parameters: - amt: "int, or float: the value to constrain" - high: "int, or float: maximum limit" - low: "int, or float: minimum limit" + examples: + - | + void draw() + { + background(204); + float mx = constrain(mouseX, 30, 70); + rect(mx-10, 40, 20, 20); + } + fileName: constrain_ + parameters: + amt: + desc: the value to constrain + type: + - float + - int + high: + desc: maximum limit + type: + - float + - int + low: + desc: minimum limit + type: + - float + - int returns: float or int - syntax: constrain(amt, low, high) + syntax: + - constrain(amt, low, high) + type: function +continue: + description: When run inside of a `for` or `while`, it skips the remainder of + the block and starts the next iteration. + examples: + - | + for (int i = 0; i < 100; i += 10) { + if (i == 70) { // If 'i' is 70, + continue; // skip to the next iteration, + } // therefore not drawing the line. + line(i, 0, i, height); + } + fileName: continue + parameters: {} + returns: "" + syntax: + - continue type: function copy: - description: >- - Copies a region of pixels from the display window to another area of the - display window and copies a region of pixels from an image used as the - `srcImg` parameter into the display window. If the source and destination - regions aren't the same size, it will automatically resize the 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()`. - docUrl: https://processing.org/reference/copy_.html - name: null - parameters: - dh: "int: destination image height" - dw: "int: destination image width" - dx: "int: X coordinate of the destination's upper left corner" - dy: "int: Y coordinate of the destination's upper left corner" - sh: "int: source image height" - src: "PImage: an image variable referring to the source image." - sw: "int: source image width" - sx: "int: X coordinate of the source's upper left corner" - sy: "int: Y coordinate of the source's upper left corner" + description: |- + 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()`. + examples: + - |- + size(400,400); + PImage img = loadImage("hometown.jpg"); + image(img, 0, 0, width, height); + copy(56, 176, 80, 80, 280, 200, 400, 400); + stroke(255); + noFill(); + // Rectangle shows area being copied + rect(56, 176, 80, 80); + fileName: copy_ + parameters: + dh: + desc: destination image height + type: + - int + dw: + desc: destination image width + type: + - int + dx: + desc: X coordinate of the destination's upper left corner + type: + - int + dy: + desc: Y coordinate of the destination's upper left corner + type: + - int + sh: + desc: source image height + type: + - int + src: + desc: an image variable referring to the source image. + type: + - PImage + sw: + desc: source image width + type: + - int + sx: + desc: X coordinate of the source's upper left corner + type: + - int + sy: + desc: Y coordinate of the source's upper left corner + type: + - int returns: void or PImage - syntax: |- - copy() - copy(sx, sy, sw, sh, dx, dy, dw, dh) - copy(src, sx, sy, sw, sh, dx, dy, dw, dh) + syntax: + - copy() + - copy(sx, sy, sw, sh, dx, dy, dw, dh) + - copy(src, sx, sy, sw, sh, dx, dy, dw, dh) type: function cos: - description: 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. - docUrl: https://processing.org/reference/cos_.html - name: null + description: |- + 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. + examples: + - |- + size(400,400); + float a = 0.0; + float inc = TWO_PI/25.0; + for (int i = 0; i < 25; i++) { + line(i*16, 200, i*16, 200+cos(a)*160.0); + a = a + inc; + } + fileName: cos_ parameters: - angle: "float: an angle in radians" + angle: + desc: an angle in radians + type: + - float returns: float - syntax: cos(angle) + syntax: + - cos(angle) type: function createFont: - description: >- + description: |- Dynamically converts a font to the format used by Processing from a .ttf or - .otf file inside the sketch's "data" folder or a font that's installed - elsewhere on the computer. If you want to use a font installed on your - computer, use the `PFont.list()` method to first determine the names for the - fonts recognized by the computer and are compatible with this function. 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. The `charset` parameter is an array of chars that specifies the characters to generate. - + .otf file inside the sketch's "data" folder or a font that's installed + elsewhere on the computer. If you want to use a font installed on your + computer, use the `PFont.list()` method to first determine the names + for the fonts recognized by the computer and are compatible with this + function. 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 anti-aliased or not. + The `charset` parameter is an array of chars that specifies the + characters to generate. + + This function allows Processing to work with the font natively in the + default renderer, so the letters are defined by vector geometry and are + rendered quickly. In the `P2D` and `P3D` renderers, the function + sets the project to render the font as a series of small textures. For + instance, when using the default renderer, the actual native version of the + font will be employed by the sketch, improving drawing quality and + performance. With the `P2D` and `P3D` renderers, the bitmapped + version will be used to improve speed and appearance, but the 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. + examples: + - |+ + PFont myFont; + + void setup() { + size(200, 200); + // Uncomment the following two lines to see the available fonts + //String[] fontList = PFont.list(); + //printArray(fontList); + myFont = createFont("Georgia", 32); + textFont(myFont); + textAlign(CENTER, CENTER); + text("!@#$%", width/2, height/2); + } - Thi. . . - docUrl: https://processing.org/reference/createFont_.html - name: null - parameters: - charset: "char[]: array containing characters to be generated" - name: "String: name of the font to load" - size: "float: point size of the font" - smooth: "boolean: true for an antialiased font, false for aliased" + fileName: createFont_ + parameters: + charset: + desc: array containing characters to be generated + type: + - char[] + name: + desc: name of the font to load + type: + - String + size: + desc: point size of the font + type: + - float + smooth: + desc: true for an anti-aliased font, false for aliased + type: + - boolean returns: PFont - syntax: |- - createFont(name, size) - createFont(name, size, smooth) - createFont(name, size, smooth, charset) + syntax: + - createFont(name, size) + - createFont(name, size, smooth) + - createFont(name, size, smooth, charset) type: function createGraphics: - description: >- - Creates and returns a new `PGraphics` object. Use this class if you need to - draw into an off-screen graphics buffer. The first two parameters define the - width and height in pixels. The third, optional parameter specifies the - renderer. It can be defined as P2D, P3D, PDF, or SVG. If the third parameter - isn't used, the default renderer is set. The PDF and SVG renderers require - the filename parameter. - - - It's important to consider the renderer used with `createGraphics()` in relation to the main renderer specified in `size()`. For example, it's only possible to use P2D or P3D with `createGraphics()` when one of them is defined in `size()`. Unlike Processing 1.0, P2D and P3D use OpenGL for drawing, and when using an OpenGL renderer it's necessary for the main drawing surface to be OpenGL-based. If P2D or P3D are used as the renderer in `size()`, then any of the options can be used with `createGraphics()`. If the default renderer is used in `size()`, then only the default, PDF, or SVG can be u. . . - docUrl: https://processing.org/reference/createGraphics_.html - name: null - parameters: - h: "int: height in pixels" - path: "String: the name of the file (can be an absolute or relative path)" - renderer: "String: Either P2D, P3D, or PDF" - w: "int: width in pixels" + description: |- + Creates and returns a new `PGraphics` object. Use this class if you + need to draw into an offscreen graphics buffer. The first two parameters + define the width and height in pixels. The third, optional parameter + specifies the renderer. It can be defined as P2D, P3D, PDF, or SVG. If the + third parameter isn't used, the default renderer is set. The PDF and SVG + renderers require the filename parameter. + + It's important to consider the renderer used with `createGraphics()` + in relation to the main renderer specified in `size()`. For example, + it's only possible to use P2D or P3D with `createGraphics()` when one + of them is defined in `size()`. Unlike Processing 1.0, P2D and P3D use + OpenGL for drawing, and when using an OpenGL renderer it's necessary for + the main drawing surface to be OpenGL-based. If P2D or P3D are used as the + renderer in `size()`, then any of the options can be used with + `createGraphics()`. If the default renderer is used in `size()`, + then only the default, PDF, or SVG can be used with + `createGraphics()`. + + It's important to run all drawing functions between the `beginDraw()` + and `endDraw()`. As the exception to this rule, `smooth()` should + be run on the PGraphics object before `beginDraw()`. See the reference + for `smooth()` for more detail. + + The `createGraphics()` function should almost never be used inside + `draw()` because of the memory and time needed to set up the graphics. + One-time or occasional use during `draw()` might be acceptable, but + code that calls `createGraphics()` at 60 frames per second might run + out of memory or freeze your sketch. + + Unlike the main drawing surface which is completely opaque, surfaces + created with `createGraphics()` can have transparency. This makes it + possible to draw into a graphics and maintain the alpha channel. By using + `save()` to write a PNG or TGA file, the transparency of the graphics + object will be honored. + examples: + - | + PGraphics pg; + + void setup() { + size(200, 200); + pg = createGraphics(100, 100); + } + + void draw() { + pg.beginDraw(); + pg.background(102); + pg.stroke(255); + pg.line(pg.width*0.5, pg.height*0.5, mouseX, mouseY); + pg.endDraw(); + image(pg, 50, 50); + } + fileName: createGraphics_ + parameters: + h: + desc: height in pixels + type: + - int + path: + desc: the name of the file (can be an absolute or relative path) + type: + - String + renderer: + desc: Either P2D, P3D, or PDF + type: + - String + w: + desc: width in pixels + type: + - int returns: PGraphics - syntax: |- - createGraphics(w, h) - createGraphics(w, h, renderer) - createGraphics(w, h, renderer, path) + syntax: + - createGraphics(w, h) + - createGraphics(w, h, renderer) + - createGraphics(w, h, renderer, path) type: function createImage: description: >- 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(). - docUrl: https://processing.org/reference/createImage_.html - name: null - parameters: - format: "int: Either RGB, ARGB, ALPHA (grayscale alpha channel)" - h: "int: height in pixels" - w: "int: width in pixels" + 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(). + examples: + - | + size(400,400); + PImage img = createImage(264, 264, RGB); + img.loadPixels(); + for (int i = 0; i < img.pixels.length; i++) { + img.pixels[i] = color(0, 90, 102); + } + img.updatePixels(); + image(img, 68, 68); + - |- + size(400,400); + PImage img = createImage(264, 264, ARGB); + img.loadPixels(); + for (int i = 0; i < img.pixels.length; i++) { + img.pixels[i] = color(0, 90, 102, i % img.width); + } + img.updatePixels(); + image(img, 68, 68); + image(img, 136, 136); + fileName: createImage_ + parameters: + format: + desc: Either RGB, ARGB, ALPHA (grayscale alpha channel) + type: + - int + h: + desc: height in pixels + type: + - int + w: + desc: width in pixels + type: + - int returns: PImage - syntax: createImage(w, h, format) + syntax: + - createImage(w, h, format) type: function createInput: - description: >- - This is a shorthand function for advanced programmers to initialize and 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 you - need 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, as in: `createInput("http://processing.org/")` - - - The name of a file in the sketch's `data` folder - - - The full path to a file to be opened locally (when running as an application) - + description: |- + 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 macOS, 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()`. + examples: + - | + // Load the local file 'data.txt' and initialize a new InputStream + InputStream input = createInput("data.txt"); + + String content = ""; + + try { + int data = input.read(); + while (data != -1) { + content += data; + data = input.read(); + } + } + catch (IOException e) { + e.printStackTrace(); + } + finally { + try { + input.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + } - 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. . . - docUrl: https://processing.org/reference/createInput_.html - name: null + println(content); + fileName: createInput_ parameters: - filename: "String: the name of the file to use as input" + filename: + desc: the name of the file to use as input + type: + - String returns: InputStream - syntax: createInput(filename) + syntax: + - createInput(filename) type: function createOutput: - description: >- - 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. - docUrl: https://processing.org/reference/createOutput_.html - name: null - parameters: - filename: "String: name of the file to open" + description: |- + 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. + fileName: createOutput_ + parameters: + filename: + desc: name of the file to open + type: + - String returns: OutputStream - syntax: createOutput(filename) + syntax: + - createOutput(filename) type: function createReader: - description: >- + description: |- 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. For more information about the `BufferedReader` - class and its methods like `readLine()` and `close` used in the above - example, please consult a Java reference. - + line-by-line as individual `String` objects. This is the complement to + the `createWriter()` function. For more information about the + `BufferedReader` class and its methods like `readLine()` and + `close` used in the above example, please consult a Java + reference. + + 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. + examples: + - | + void setup() { + size(100, 100); + parseFile(); + } - 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. - docUrl: https://processing.org/reference/createReader_.html - name: null + void parseFile() { + // Open the file from the createWriter() example + BufferedReader reader = createReader("positions.txt"); + String line = null; + try { + while ((line = reader.readLine()) != null) { + String[] pieces = split(line, TAB); + int x = int(pieces[0]); + int y = int(pieces[1]); + point(x, y); + } + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + fileName: createReader_ parameters: - filename: "String: name of the file to be opened" + filename: + desc: name of the file to be opened + type: + - String returns: BufferedReader - syntax: createReader(filename) + syntax: + - createReader(filename) type: function createShape: - description: >- - The `createShape()` function is used to define a new shape. Once created, - this shape can be drawn with the `shape()` function. The basic way to use - the function defines new primitive shapes. One of the following parameters - are used as the first parameter: `ELLIPSE`, `RECT`, `ARC`, `TRIANGLE`, - `SPHERE`, `BOX`, `QUAD`, or `LINE`. The parameters for each of these - different shapes are the same as their corresponding functions: `ellipse()`, - `rect()`, `arc()`, `triangle()`, `sphere()`, `box()`, `quad()`, and - `line()`. The first example above clarifies how this works. + description: |- + The `createShape()` function is used to define a new shape. + Once created, this shape can be drawn with the `shape()` + function. The basic way to use the function defines new primitive + shapes. One of the following parameters are used as the first + parameter: `ELLIPSE`, `RECT`, `ARC`, `TRIANGLE`, + `SPHERE`, `BOX`, `QUAD`, or `LINE`. The + parameters for each of these different shapes are the same as their + corresponding functions: `ellipse()`, `rect()`, `arc()`, + `triangle()`, `sphere()`, `box()`, `quad()`, and + `line()`. The first example above clarifies how this works. + + Custom, unique shapes can be made by using `createShape()` without + a parameter. After the shape is started, the drawing attributes and + geometry can be set directly to the shape within the `beginShape()` + and `endShape()` methods. See the second example above for specifics, + and the reference for `beginShape()` for all of its options. + + The `createShape()` function can also be used to make a complex + shape made of other shapes. This is called a "group" and it's created by + using the parameter `GROUP` as the first parameter. See the fourth + example above to see how it works. + + After using `createShape()`, stroke and fill color can be set by + calling methods like `setFill()` and `setStroke()`, as seen + in the examples above. The complete list of methods and fields for the + PShape class are in the Processing Javadoc. + examples: + - | + PShape square; // The PShape object + + void setup() { + size(100, 100); + // Creating the PShape as a square. The + // numeric arguments are similar to rect(). + square = createShape(RECT, 0, 0, 50, 50); + square.setFill(color(0, 0, 255)); + square.setStroke(false); + } + + void draw() { + shape(square, 25, 25); + } + - | + PShape s; // The PShape object + + void setup() { + size(100, 100); + // Creating a custom PShape as a square, by + // specifying a series of vertices. + s = createShape(); + s.beginShape(); + s.fill(0, 0, 255); + s.noStroke(); + s.vertex(0, 0); + s.vertex(0, 50); + s.vertex(50, 50); + s.vertex(50, 0); + s.endShape(CLOSE); + } + void draw() { + shape(s, 25, 25); + } + - | + PShape s; + + void setup() { + size(100, 100, P2D); + s = createShape(); + s.beginShape(TRIANGLE_STRIP); + s.vertex(30, 75); + s.vertex(40, 20); + s.vertex(50, 75); + s.vertex(60, 20); + s.vertex(70, 75); + s.vertex(80, 20); + s.vertex(90, 75); + s.endShape(); + } - Custom, unique shapes can be made by using `createShape()` without a parameter. After the shape is started, the drawing attributes and geometry can be set directly to the shape within the `beginShape()` and `endShape()` methods. See the second example above for specifics, and the reference for `beginShape()` for all of its options. + void draw() { + shape(s, 0, 0); + } + - | + PShape alien, head, body; + void setup() { + size(100, 100); - The `createShape()` function can also be used to make a complex shape made of other shapes. Thi. . . - docUrl: https://processing.org/reference/createShape_.html - name: null - parameters: - kind: "int: either POINT, LINE, TRIANGLE, QUAD, RECT, ELLIPSE, ARC, BOX, SPHERE" - p: "float[]: parameters that match the kind of shape" + // Create the shape group + alien = createShape(GROUP); + + // Make two shapes + ellipseMode(CORNER); + head = createShape(ELLIPSE, -25, 0, 50, 50); + head.setFill(color(255)); + body = createShape(RECT, -25, 45, 50, 40); + body.setFill(color(0)); + + // Add the two "child" shapes to the parent group + alien.addChild(body); + alien.addChild(head); + } + + void draw() { + background(204); + translate(50, 15); + shape(alien); // Draw the group + } + fileName: createShape_ + parameters: + kind: + desc: either POINT, LINE, TRIANGLE, QUAD, RECT, ELLIPSE, ARC, BOX, SPHERE + type: + - int + p: + desc: parameters that match the kind of shape + type: + - float[] returns: PShape - syntax: |- - createShape() - createShape(type) - createShape(kind, p) + syntax: + - createShape() + - createShape(type) + - createShape(kind, p) type: function createWriter: - description: >- - 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. - docUrl: https://processing.org/reference/createWriter_.html - name: null - parameters: - filename: "String: name of the file to be created" - returns: PrintWriter - syntax: createWriter(filename) - type: function -cursor: - description: >- - Sets the cursor to a predefined symbol or an image, or makes it visible if - already hidden. If you are trying to set an image as the cursor, the - recommended size is 16x16 or 32x32 pixels. The values for parameters `x` and - `y` must be less than the dimensions of the image. + description: |- + 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. + examples: + - >+ + PrintWriter output; + + + void setup() { + // Create a new file in the sketch directory + output = createWriter("positions.txt"); + } + + void draw() { + point(mouseX, mouseY); + output.println(mouseX + "\t" + mouseY); // Write the coordinate to the file + } - Setting or hiding the cursor does not generally work with "Present" mode (when running full-screen). + void keyPressed() { + output.flush(); // Writes the remaining data to the file + output.close(); // Finishes the file + exit(); // Stops the program + } - With the P2D and P3D renderers, a generic set of cursors are used because the OpenGL renderer doesn't have access to the default cursor images for each platform (Issue 3791). - docUrl: https://processing.org/reference/cursor_.html - name: null + fileName: createWriter_ parameters: - img: "PImage: any variable of type PImage" - kind: "int: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT" - x: "int: the horizontal active spot of the cursor" - y: "int: the vertical active spot of the cursor" - returns: void - syntax: |- - cursor(kind) - cursor(img) - cursor(img, x, y) - cursor() + filename: + desc: name of the file to be created + type: + - String + returns: PrintWriter + syntax: + - createWriter(filename) + type: function +cursor: + description: |- + Sets the cursor to a predefined symbol or an image, or makes it visible if + already hidden. If you are trying to set an image as the cursor, the + recommended size is 16x16 or 32x32 pixels. The values for parameters + `x` and `y` must be less than the dimensions of the image. + + Setting or hiding the cursor does not generally work with "Present" mode + (when running full-screen). + + With the P2D and P3D renderers, a generic set of cursors are used because + the OpenGL renderer doesn't have access to the default cursor images for + each platform + (Issue + 3791). + examples: + - | + // Move the mouse left and right across the image + // to see the cursor change from a cross to a hand + + void setup() { + size(100, 100); + } + + void draw() { + if (mouseX < 50) { + cursor(CROSS); + } else { + cursor(HAND); + } + } + fileName: cursor_ + parameters: + img: + desc: any variable of type PImage + type: + - PImage + kind: + desc: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT + type: + - int + x: + desc: the horizontal active spot of the cursor + type: + - int + y: + desc: the vertical active spot of the cursor + type: + - int + returns: void + syntax: + - cursor(kind) + - cursor(img) + - cursor(img, x, y) + - cursor() type: function curve: - description: 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). - docUrl: https://processing.org/reference/curve_.html - name: null - parameters: - x1: "float: coordinates for the beginning control point" - x2: "float: coordinates for the first point" - x3: "float: coordinates for the second point" - x4: "float: coordinates for the ending control point" - y1: "float: coordinates for the beginning control point" - y2: "float: coordinates for the first point" - y3: "float: coordinates for the second point" - y4: "float: coordinates for the ending control point" - z1: "float: coordinates for the beginning control point" - z2: "float: coordinates for the first point" - z3: "float: coordinates for the second point" - z4: "float: coordinates for the ending control point" - returns: void - syntax: |- - curve(x1, y1, x2, y2, x3, y3, x4, y4) - curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) + description: |- + 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). + examples: + - |- + size(400, 400); + noFill(); + stroke(255, 102, 0); + curve(20, 104, 20, 104, 292, 96, 292, 244); + stroke(0); + curve(20, 104, 292, 96, 292, 244, 60, 260); + stroke(255, 102, 0); + curve(292, 96, 292, 244, 60, 260, 60, 260); + fileName: curve_ + parameters: + x1: + desc: coordinates for the beginning control point + type: + - float + x2: + desc: coordinates for the first point + type: + - float + x3: + desc: coordinates for the second point + type: + - float + x4: + desc: coordinates for the ending control point + type: + - float + y1: + desc: coordinates for the beginning control point + type: + - float + y2: + desc: coordinates for the first point + type: + - float + y3: + desc: coordinates for the second point + type: + - float + y4: + desc: coordinates for the ending control point + type: + - float + z1: + desc: coordinates for the beginning control point + type: + - float + z2: + desc: coordinates for the first point + type: + - float + z3: + desc: coordinates for the second point + type: + - float + z4: + desc: coordinates for the ending control point + type: + - float + returns: void + syntax: + - curve(x1, y1, x2, y2, x3, y3, x4, y4) + - curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) type: function curveDetail: - description: 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. - docUrl: https://processing.org/reference/curveDetail_.html - name: null + description: |- + 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. + examples: + - |- + void setup(){ + size(400,400,P2D); + } + + void draw(){ + background(204); + curveDetail(1); + drawCurves(-60); + stroke(126); + curveDetail(2); + drawCurves(0); + stroke(255); + curveDetail(4); + drawCurves(60); + noLoop(); + } + + void drawCurves(float y) { + noFill(); + curve( 20, 112+y, 20, 112+y, 292, 104+y, 292, 252+y); + curve( 20, 112+y, 292, 104+y, 292, 252+y, 60, 268+y); + curve(292, 104+y, 292, 252+y, 60, 268+y, 60, 268+y); + } + fileName: curveDetail_ parameters: - detail: "int: resolution of the curves" + detail: + desc: resolution of the curves + type: + - int returns: void - syntax: curveDetail(detail) + syntax: + - curveDetail(detail) type: function curvePoint: - description: Evaluates the curve at point `t` for points `a`, `b`, `c`, `d`. The - parameter `t` may range from 0 (the start of the curve) and 1 (the end of - the curve). `a` and `d` are the control points, and `b` and `c` are points - on the curve. As seen in the example above, this can be used once with the - `x` coordinates and a second time with the `y` coordinates to get the - location of a curve at `t`. - docUrl: https://processing.org/reference/curvePoint_.html - name: null - parameters: - a: "float: coordinate of first control point" - b: "float: coordinate of first point on the curve" - c: "float: coordinate of second point on the curve" - d: "float: coordinate of second control point" - t: "float: value between 0 and 1" + description: |- + Evaluates the curve at point `t` for points `a`, `b`, + `c`, `d`. The parameter `t` may range from 0 (the start of the + curve) and 1 (the end of the curve). `a` and `d` are the control + points, and `b` and `c` are points on the curve. As seen in the + example above, this can be used once with the `x` coordinates and a + second time with the `y` coordinates to get the location of a curve at + `t`. + examples: + - |- + size(400,400); + + noFill(); + curve(20, 104, 20, 104, 292, 96, 292, 244); + curve(20, 104, 292, 96, 292, 244, 60, 260); + + fill(255); + ellipseMode(CENTER); + int steps = 6; + for (int i = 0; i <= steps; i++) { + float t = i / float(steps); + float x = curvePoint(20, 20, 292, 292, t); + float y = curvePoint(104, 104, 96, 244, t); + ellipse(x, y, 10, 10); + x = curvePoint(20, 292, 292, 60, t); + y = curvePoint(104, 96, 244, 260, t); + ellipse(x, y, 10, 10); + } + fileName: curvePoint_ + parameters: + a: + desc: coordinate of first control point + type: + - float + b: + desc: coordinate of first point on the curve + type: + - float + c: + desc: coordinate of second point on the curve + type: + - float + d: + desc: coordinate of second control point + type: + - float + t: + desc: value between 0 and 1 + type: + - float returns: float - syntax: curvePoint(a, b, c, d, t) + syntax: + - curvePoint(a, b, c, d, t) type: function curveTangent: - description: Calculates the tangent of a point on a curve. There's a good - definition of tangent on Wikipedia. - docUrl: https://processing.org/reference/curveTangent_.html - name: null - parameters: - a: "float: coordinate of first control point on the curve" - b: "float: coordinate of first point" - c: "float: coordinate of first point" - d: "float: coordinate of second control point on the curve" - t: "float: value between 0 and 1" + description: |- + Calculates the tangent of a point on a curve. There's a good definition + of tangent on Wikipedia. + examples: + - |- + size(400, 400); + noFill(); + curve(20, 104, 292, 96, 292, 244, 60, 260); + int steps = 6; + for (int i = 0; i <= steps; i++) { + float t = i / float(steps); + float x = curvePoint(20, 292, 292, 60, t); + float y = curvePoint(104, 96, 244, 260, t); + //ellipse(x, y, 20, 20); + float tx = curveTangent(20, 292, 292, 60, t); + float ty = curveTangent(104, 96, 244, 260, t); + float a = atan2(ty, tx); + a -= PI/2.0; + line(x, y, cos(a)*32 + x, sin(a)*32 + y); + } + fileName: curveTangent_ + parameters: + a: + desc: coordinate of first point on the curve + type: + - float + b: + desc: coordinate of first control point + type: + - float + c: + desc: coordinate of second control point + type: + - float + d: + desc: coordinate of second point on the curve + type: + - float + t: + desc: value between 0 and 1 + type: + - float returns: float - syntax: curveTangent(a, b, c, d, t) + syntax: + - curveTangent(a, b, c, d, t) type: function curveTightness: - description: Modifies the quality of forms created with `curve()` and - `curveVertex()`. The parameter `tightness` determines how the curve fits to - the vertex points. The value 0.0 is the default value for `tightness` (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. - docUrl: https://processing.org/reference/curveTightness_.html - name: null + description: >- + Modifies the quality of forms created with `curve()` and + `curveVertex()`. The parameter `tightness` determines how the curve + fits to the vertex points. The value 0.0 is the default value for + `tightness` (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. + examples: + - | + // Move the mouse left and right to see the curve change + + void setup() { + size(100, 100); + noFill(); + } + + void draw() { + background(204); + float t = map(mouseX, 0, width, -5, 5); + curveTightness(t); + beginShape(); + curveVertex(10, 26); + curveVertex(10, 26); + curveVertex(83, 24); + curveVertex(83, 61); + curveVertex(25, 65); + curveVertex(25, 65); + endShape(); + } + fileName: curveTightness_ parameters: - tightness: "float: amount of deformation from the original vertices" + tightness: + desc: amount of deformation from the original vertices + type: + - float returns: void - syntax: curveTightness(tightness) + syntax: + - curveTightness(tightness) type: function curveVertex: - description: 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). - docUrl: https://processing.org/reference/curveVertex_.html - name: null - parameters: - x: "float: the x-coordinate of the vertex" - y: "float: the y-coordinate of the vertex" - z: "float: the z-coordinate of the vertex" - returns: void - syntax: |- - curveVertex(x, y) - curveVertex(x, y, z) + description: |- + 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 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). + examples: + - |- + size(400, 400); + noFill(); + beginShape(); + curveVertex(336, 364); + curveVertex(336, 364); + curveVertex(272, 76); + curveVertex(84, 68); + curveVertex(128, 400); + curveVertex(128, 400); + endShape(); + fileName: curveVertex_ + parameters: + x: + desc: the x-coordinate of the vertex + type: + - float + y: + desc: the y-coordinate of the vertex + type: + - float + z: + desc: the z-coordinate of the vertex + type: + - float + returns: void + syntax: + - curveVertex(x, y) + - curveVertex(x, y, z) type: function day: - description: Processing communicates with the clock on your computer. The - `day()` function returns the current day as a value from 1 - 31. - docUrl: https://processing.org/reference/day_.html - name: null + description: |- + Processing communicates with the clock on your computer. The + `day()` function returns the current day as a value from 1 to 31. + examples: + - | + int d = day(); // Values from 1 - 31 + int m = month(); // Values from 1 - 12 + int y = year(); // 2003, 2004, 2005, etc. + + String s = String.valueOf(d); + text(s, 10, 28); + s = String.valueOf(m); + text(s, 10, 56); + s = String.valueOf(y); + text(s, 10, 84); + fileName: day_ parameters: {} returns: int - syntax: day() + syntax: + - day() + type: function +default: + description: Keyword for defining the default condition of a `switch`. If none + of the case names match the `switch` parameter, the statement(s) after the + `default` syntax are executed. Switch structures don't require a `default`. + examples: + - | + char letter = 'F'; + + switch(letter) { + case 'A': + println("Alpha"); // Does not execute + break; + case 'B': + println("Bravo"); // Does not execute + break; + default: + println("Zulu"); // Prints "Zulu" + break; + } + fileName: default + parameters: + statements: + desc: one or more valid statements to be executed + type: [] + returns: "" + syntax: + - "default: statements" type: function degrees: - description: 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. - docUrl: https://processing.org/reference/degrees_.html - name: null - parameters: - radians: "float: radian value to convert to degrees" + description: |- + 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. + examples: + - | + float rad = PI/4; + float deg = degrees(rad); + println(rad + " radians is " + deg + " degrees"); + fileName: degrees_ + parameters: + radians: + desc: radian value to convert to degrees + type: + - float returns: float - syntax: degrees(radians) + syntax: + - degrees(radians) type: function delay: - description: >- - The `delay()` function halts 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. - + description: |- + 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). + examples: + - | + import processing.serial.*; + + Serial myPort; // The serial port + + void setup() { + printArray(Serial.list()); + myPort = new Serial(this, Serial.list()[0], 9600); + } - 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.) - docUrl: https://processing.org/reference/delay_.html - name: null + void draw() { + while (myPort.available() > 0) { + int inByte = myPort.read(); + println(inByte); + } + delay(100); + } + fileName: delay_ parameters: - napTime: "int: milliseconds to pause before running draw() again" + napTime: + desc: milliseconds to pause before running draw() again + type: + - int returns: void - syntax: delay(napTime) + syntax: + - delay(napTime) type: function directionalLight: - description: "Adds a directional light. Directional light comes from one - direction: it is stronger when hitting a surface squarely, and weaker if it - hits at a gentle angle. After hitting a surface, directional light 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 `v1`, `v2`, and `v3` parameters are interpreted as either RGB or - HSB values, depending on 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 (since the light - would be facing directly upward)." - docUrl: https://processing.org/reference/directionalLight_.html - name: null - parameters: - nx: "float: direction along the x-axis" - ny: "float: direction along the y-axis" - nz: "float: direction along the z-axis" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: directionalLight(v1, v2, v3, nx, ny, nz) + description: >- + 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 + 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). + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + directionalLight(51, 102, 126, -1, 0, 0); + translate(80, 200, 0); + sphere(120); + - |- + size(400, 400, P3D); + background(0); + noStroke(); + directionalLight(51, 102, 126, 0, -1, 0); + translate(320, 200, 0); + sphere(120); + fileName: directionalLight_ + parameters: + nx: + desc: direction along the x-axis + type: + - float + ny: + desc: direction along the y-axis + type: + - float + nz: + desc: direction along the z-axis + type: + - float + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - directionalLight(v1, v2, v3, nx, ny, nz) type: function displayDensity: - description: 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. - docUrl: https://processing.org/reference/displayDensity_.html - name: null - parameters: - display: "int: the display number to check" + description: |- + 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. + examples: + - | + void setup() { + size(100, 100); + pixelDensity(displayDensity()); + noStroke(); + } + + void draw() { + background(0); + ellipse(30, 48, 36, 36); + ellipse(70, 48, 36, 36); + } + fileName: displayDensity_ + parameters: + display: + desc: |- + the display number to check + (1-indexed to match the Preferences dialog box) + type: + - int returns: int - syntax: |- - displayDensity() - displayDensity(display) + syntax: + - displayDensity() + - displayDensity(display) type: function +displayHeight: + description: |- + System variable that stores the height of the computer screen. + For example, if the current screen resolution is 1920x1080, + `displayWidth` is 1920 and `displayHeight` is 1080. + examples: + - | + size(displayWidth, displayHeight); + line(0, 0, width, height); + fileName: displayHeight + type: var +displayWidth: + description: |- + System variable that stores the width of the computer screen. + For example, if the current screen resolution is 1920x1080, + `displayWidth` is 1920 and `displayHeight` is 1080. + examples: + - | + size(displayWidth, displayHeight); + line(0, 0, width, height); + fileName: displayWidth + type: var dist: description: Calculates the distance between two points. - docUrl: https://processing.org/reference/dist_.html - name: null - parameters: - x1: "float: x-coordinate of the first point" - x2: "float: x-coordinate of the second point" - y1: "float: y-coordinate of the first point" - y2: "float: y-coordinate of the second point" - z1: "float: z-coordinate of the first point" - z2: "float: z-coordinate of the second point" + examples: + - | + // Sets the background gray value based on the distance + // of the mouse from the center of the screen + void draw() { + noStroke(); + float d = dist(width/2, height/2, mouseX, mouseY); + float maxDist = dist(0, 0, width/2, height/2); + float gray = map(d, 0, maxDist, 0, 255); + fill(gray); + rect(0, 0, width, height); + } + fileName: dist_ + parameters: + x1: + desc: x-coordinate of the first point + type: + - float + x2: + desc: x-coordinate of the second point + type: + - float + y1: + desc: y-coordinate of the first point + type: + - float + y2: + desc: y-coordinate of the second point + type: + - float + z1: + desc: z-coordinate of the first point + type: + - float + z2: + desc: z-coordinate of the second point + type: + - float returns: float - syntax: |- - dist(x1, y1, x2, y2) - dist(x1, y1, z1, x2, y2, z2) + syntax: + - dist(x1, y1, x2, y2) + - dist(x1, y1, z1, x2, y2, z2) + type: function +double: + description: Datatype for floating-point numbers larger than those that can be + stored in a `float`. A `float` is a 32-bit values that can be as large as + 3.40282347E+38 and as low as -3.40282347E+38. A `double` can be used + similarly to a float, but can have a greater magnitude because it's a 64-bit + number. Processing functions don't use this datatype, so while they work in + the language, you'll usually have to convert to a `float` using the + `(float)` syntax before passing into a function. + examples: + - > + double a; // Declare variable 'a' of type double + + a = 1.5387D; // Assign 'a' the value 1.5387 + + double b = -2.984D; // Declare variable 'b' and assign it the value + -2.984 + + double c = a + b; // Declare variable 'c' and assign it the sum of 'a' + and 'b' + + float f = (float)c; // Converts the value of 'c' from a double to a + float + fileName: double + parameters: + value: + desc: any floating-point value + type: [] + var: + desc: variable name referencing the float + type: [] + returns: "" + syntax: + - double var + - double var = value type: function draw: description: >- - Called directly after `setup()`, the `draw()` function continuously executes - the lines of code contained inside its block until the program is stopped or - `noLoop()` is called. `draw()` is called automatically and should never be - called explicitly. All Processing programs update the screen at the end of - draw(), never earlier. - - - To stop the code inside of `draw()` from running continuously, use `noLoop()`, `redraw()` and `loop()`. If `noLoop()` is used to stop the code in `draw()` from running, then `redraw()` will cause the code inside `draw()` to run a single time, and `loop()` will cause the code inside `draw()` to resume running continuously. - + Called directly after `setup()`, the `draw()` function continuously + executes the lines of code contained inside its block until the program is + stopped or `noLoop()` is called. `draw()` is called automatically + and should never be called explicitly. All Processing programs update the + screen at the end of draw(), never earlier. + + To stop the code inside of `draw()` from running continuously, use + `noLoop()`, `redraw()` and `loop()`. If `noLoop()` is + used to stop the code in `draw()` from running, then `redraw()` + will cause the code inside `draw()` to run a single time, and + `loop()` will cause the code inside `draw()` to resume running + continuously. + + The number of times `draw()` executes in each second may be controlled + with the `frameRate()` function. + + It is common to call `background()` near the beginning of the + `draw()` loop to clear the contents of the window, as shown in the first + example above. Since pixels drawn to the window are cumulative, omitting + `background()` may result in unintended results. + + 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 second example above. + examples: + - | + float yPos = 0.0; + + void setup() { // setup() runs once + size(200, 200); + frameRate(30); + } - The number of times `draw()` executes in each second may be controlled with the `frameRate()` function. + void draw() { // draw() loops forever, until stopped + background(204); + yPos = yPos - 1.0; + if (yPos < 0) { + yPos = height; + } + line(0, yPos, width, yPos); + } + - | + void setup() { + size(200, 200); + } + // Although empty here, draw() is needed so + // the sketch can process user input events + // (mouse presses in this case). + void draw() { } - It is common to call `background()` near the beginning of the `draw()` loop to clear the contents of the window, as shown in the first example above. Since pixels drawn to the window are cumulative, omitting `background()` may result in unin. . . - docUrl: https://processing.org/reference/draw_.html - name: null + void mousePressed() { + line(mouseX, 10, mouseX, 90); + } + fileName: draw_ parameters: {} returns: void - syntax: draw() + syntax: + - draw() type: function ellipse: - description: Draws an ellipse (oval) to the screen. An ellipse with equal width - and height is a circle. By default, the first two parameters set the - location, and the third and fourth parameters set the shape's width and - height. The origin may be changed with the `ellipseMode()` function. - docUrl: https://processing.org/reference/ellipse_.html - name: null - parameters: - a: "float: x-coordinate of the ellipse" - b: "float: y-coordinate of the ellipse" - c: "float: width of the ellipse by default" - d: "float: height of the ellipse by default" - returns: void - syntax: ellipse(a, b, c, d) + description: >- + Draws an ellipse (oval) to the screen. An ellipse with equal width and + height + is a circle. By default, the first two parameters set the location, and the + third and fourth parameters set the shape's width and height. The origin may + be changed with the `ellipseMode()` function. + examples: + - |- + size(400, 400); + ellipse(224, 184, 220, 220); + fileName: ellipse_ + parameters: + a: + desc: x-coordinate of the ellipse + type: + - float + b: + desc: y-coordinate of the ellipse + type: + - float + c: + desc: width of the ellipse by default + type: + - float + d: + desc: height of the ellipse by default + type: + - float + returns: void + syntax: + - ellipse(a, b, c, d) type: function ellipseMode: - description: >- + description: |- Modifies the location from which ellipses are drawn by changing the way in - which parameters given to `ellipse()` are intepreted. - - - The default mode is `ellipseMode(CENTER)`, which interprets the first two parameters of `ellipse()` as the shape's center point, while the third and fourth parameters are its width and height. - - - `ellipseMode(RADIUS)` also uses the first two parameters of `ellipse()` as the shape's center point, but uses the third and fourth parameters to specify half of the shapes's width and height. - - - `ellipseMode(CORNER)` interprets the first two parameters of `ellipse()` as the upper-left corner of the shape, while the third and fourth parameters are its width and height. - - - `ellipseMode(CORNERS)` interprets the first two parameters of `ellipse()` as the location of one corner of the ellipse's bounding box, and the third and fourth parameters as the location of the opposite corner. - - - The parameter must be written in ALL CAPS because Processing is a case-sensitive language. - docUrl: https://processing.org/reference/ellipseMode_.html - name: null - parameters: - mode: "int: either CENTER, RADIUS, CORNER, or CORNERS" - returns: void - syntax: ellipseMode(mode) + which parameters given to `ellipse()` are interpreted. + + The default mode is `ellipseMode(CENTER)`, which interprets the first + two parameters of `ellipse()` as the shape's center point, while the + third and fourth parameters are its width and height. + + `ellipseMode(RADIUS)` also uses the first two parameters of + `ellipse()` as the shape's center point, but uses the third and fourth + parameters to specify half of the shape's width and height. + + `ellipseMode(CORNER)` interprets the first two parameters of + `ellipse()` as the upper-left corner of the shape, while the third and + fourth parameters are its width and height. + + `ellipseMode(CORNERS)` interprets the first two parameters of + `ellipse()` as the location of one corner of the ellipse's bounding box, + and the third and fourth parameters as the location of the opposite + corner. + + The parameter must be written in ALL CAPS because Processing is a + case-sensitive language. + examples: + - |- + size(400, 400); + + ellipseMode(RADIUS); // Set ellipseMode to RADIUS + fill(255); // Set fill to white + ellipse(200, 200, 120, 120); // Draw white ellipse using RADIUS mode + + ellipseMode(CENTER); // Set ellipseMode to CENTER + fill(100); // Set fill to gray + ellipse(200, 200, 120, 120); // Draw gray ellipse using CENTER mode + - |- + size(400, 400); + + ellipseMode(CORNER); // Set ellipseMode is CORNER + fill(255); // Set fill to white + ellipse(100, 100, 200, 200); // Draw white ellipse using CORNER mode + + ellipseMode(CORNERS); // Set ellipseMode to CORNERS + fill(100); // Set fill to gray + ellipse(100, 100, 200, 200); // Draw gray ellipse using CORNERS mode + fileName: ellipseMode_ + parameters: + mode: + desc: either CENTER, RADIUS, CORNER, or CORNERS + type: + - int + returns: void + syntax: + - ellipseMode(mode) + type: function +else: + description: Extends the `if` structure allowing the program to choose between + two or more blocks of code. It specifies a block of code to execute when the + expression in `if` is `false`. + examples: + - |- + size(400, 400); + + for (int i = 20; i < 380; i += 20) { + if (i < 140) { + line(120, i, 320, i); + } else { + line(80, i, 360, i); + } + } + - |- + size(400, 400); + + for (int i = 20; i < 380; i += 20) { + if (i < 140) { + line(120, i, 320, i); + } else if (i < 260) { + line(80, i, 360, i); + } else { + line(0, i, 400, i); + } + } + fileName: else + parameters: + expression: + desc: any valid expression that evaluates to true or false + type: [] + statements: + desc: one or more statements to be executed + type: [] + returns: "" + syntax: + - "if (expression) { " + - " statements " + - "} else { " + - " statements " + - "} " + - "" + - "if (expression) { " + - " statements " + - "} else if (expression) { " + - " statements " + - "} else { " + - " statements " + - "}" type: function emissive: - description: 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. - docUrl: https://processing.org/reference/emissive_.html - name: null - parameters: - gray: "float: value between black and white, by default 0 to 255" - rgb: "int: color to set" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: |- - emissive(rgb) - emissive(gray) - emissive(v1, v2, v3) + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + background(0); + directionalLight(204, 204, 204, .5, 0, -1); + emissive(0, 26, 51); + translate(280, 200, 0); + sphere(120); + fileName: emissive_ + parameters: + gray: + desc: value between black and white, by default 0 to 255 + type: + - float + rgb: + desc: color to set + type: + - int + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - emissive(rgb) + - emissive(gray) + - emissive(v1, v2, v3) type: function endCamera: - description: 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. - docUrl: https://processing.org/reference/endCamera_.html - name: null + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + noFill(); + + beginCamera(); + camera(); + rotateX(-PI/6); + endCamera(); + + translate(200, 200, 0); + rotateY(PI/3); + box(180); + fileName: endCamera_ parameters: {} returns: void - syntax: endCamera() + syntax: + - endCamera() type: function endContour: description: >- - Use the `beginContour()` and `endContour()` function to create negative - shapes within shapes such as the center of the letter 'O'. `beginContour()` - begins recording vertices for the shape and `endContour()` stops recording. - The vertices that define a negative shape must "wind" in the opposite - direction from the exterior shape. First draw vertices for the exterior - shape in clockwise order, then for internal shapes, draw vertices - counterclockwise. - - - These functions can only be used within a `beginShape()`/`endShape()` pair and transformations such as `translate()`, `rotate()`, and `scale()` do not work within a `beginContour()`/`endContour()` pair. It is also not possible to use other shapes, such as `ellipse()` or `rect()` within. - docUrl: https://processing.org/reference/endContour_.html - name: null + Use the `beginContour()` and `endContour()` function to + create negative shapes within shapes such as the center of the + letter "O". `beginContour()` begins recording vertices for + the shape and `endContour()` stops recording. The vertices + that define a negative shape must "wind" in the opposite direction + from the exterior shape. First draw vertices for the exterior shape + in clockwise order, then for internal shapes, draw vertices counterclockwise. + + These functions can only be used within a `beginShape()`/`endShape()` + pair and transformations such as `translate()`, `rotate()`, and + `scale()` do not work within a `beginContour()`/`endContour()` + pair. It is also not possible to use other shapes, such as `ellipse()` + or `rect()` within. + examples: + - |- + size(400, 400); + translate(200, 200); + stroke(255, 0, 0); + beginShape(); + // Exterior part of shape, clockwise winding + vertex(-160, -160); + vertex(160, -160); + vertex(160, 160); + vertex(-160, 160); + // Interior part of shape, counter-clockwise winding + beginContour(); + vertex(-80, -80); + vertex(-80, 80); + vertex(80, 80); + vertex(80, -80); + endContour(); + endShape(CLOSE); + fileName: endContour_ parameters: {} returns: void - syntax: endContour() + syntax: + - endContour() type: function endRaw: - description: Complement to `beginRaw()`; they must always be used together. See - the `beginRaw()` reference for details. - docUrl: https://processing.org/reference/endRaw_.html - name: null + description: |- + Complement to `beginRaw()`; they must always be used together. See + the `beginRaw()` reference for details. + examples: + - | + import processing.pdf.*; + + void setup() { + size(400, 400); + beginRaw(PDF, "raw.pdf"); + } + + void draw() { + line(pmouseX, pmouseY, mouseX, mouseY); + } + + void keyPressed() { + if (key == ' ') { + endRaw(); + exit(); + } + } + fileName: endRaw_ parameters: {} returns: void - syntax: endRaw() + syntax: + - endRaw() type: function endRecord: - description: Stops the recording process started by `beginRecord()` and closes the file. - docUrl: https://processing.org/reference/endRecord_.html - name: null + description: |- + Stops the recording process started by `beginRecord()` and closes + the file. + examples: + - | + import processing.pdf.*; + + void setup() { + size(400, 400); + beginRecord(PDF, "everything.pdf"); + } + + void draw() { + ellipse(mouseX, mouseY, 10, 10); + } + + void mousePressed() { + endRecord(); + exit(); + } + fileName: endRecord_ parameters: {} returns: void - syntax: endRecord() + syntax: + - endRecord() type: function endShape: - description: 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). - docUrl: https://processing.org/reference/endShape_.html - name: null - parameters: - mode: "int: use CLOSE to close the shape" - returns: void - syntax: |- - endShape() - endShape(mode) + description: |- + The `endShape()` function is the companion to `beginShape()` + and may only be called after `beginShape()`. When `endshape()` + is called, all the 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). + examples: + - |- + size(400, 400); + noFill(); + + beginShape(); + vertex(80, 80); + vertex(180, 80); + vertex(180, 320); + endShape(CLOSE); + + beginShape(); + vertex(200, 80); + vertex(300, 80); + vertex(300, 320); + endShape(); + fileName: endShape_ + parameters: + mode: + desc: use CLOSE to close the shape + type: + - int + returns: void + syntax: + - endShape() + - endShape(mode) type: function exit: - description: >- - Quits/stops/exits the program. Programs without a `draw()` function stop - 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). - + description: |- + 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). + examples: + - | + void draw() { + line(mouseX, mouseY, 50, 50); + } - 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). - docUrl: https://processing.org/reference/exit_.html - name: null + void mousePressed() { + exit(); + } + fileName: exit_ parameters: {} returns: void - syntax: exit() + syntax: + - exit() type: function exp: - description: Returns Euler's number e (2.71828...) raised to the power of the - `n` parameter. - docUrl: https://processing.org/reference/exp_.html - name: null - parameters: - n: "float: exponent to raise" + description: |- + Returns Euler's number e (2.71828...) raised to the power of the + `value` parameter. + examples: + - |+ + float v1 = exp(1.0); + println(v1); // Prints "2.7182817" + + fileName: exp_ + parameters: + n: + desc: exponent to raise + type: + - float returns: float - syntax: exp(n) + syntax: + - exp(n) type: function expand: - description: >- + description: |- Increases the size of a one-dimensional 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) - docUrl: https://processing.org/reference/expand_.html - name: null - parameters: - list: "Object, String[], double[], float[], long[], int[], char[], byte[], or - boolean[]: the array to expand" - newSize: "int: new size for the array" + 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) + examples: + - | + int[] data = {0, 1, 3, 4}; + println(data.length); // Prints "4" + data = expand(data); + println(data.length); // Prints "8" + data = expand(data, 512); + println(data.length); // Prints "512" + - | + PImage[] imgs = new PImage[32]; + println(imgs.length); // Prints "32" + imgs = (PImage[]) expand(imgs); + println(imgs.length); // Prints "64" + fileName: expand_ + parameters: + list: + desc: the array to expand + type: + - boolean[] + - byte[] + - char[] + - int[] + - long[] + - float[] + - double[] + - String[] + - Object + newSize: + desc: new size for the array + type: + - int returns: boolean[], byte[], char[], int[], long[], float[], double[], String[], or Object - syntax: |- - expand(list) - expand(list, newSize) + syntax: + - expand(list) + - expand(list, newSize) type: function -fill: +extends: description: >- - 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. + Allows a new class to inherit the methods and data fields (variables and + constants) from an existing class. In code, state the name of the new class, + followed by the keyword `extends` and the name of the base class. The + concept of inheritance is one of the fundamental principles of object + oriented programming. - When using hexadecimal notation to specify a color, use "`#`" or "`0x`" before the values (e.g., `#CCFFAA` or `0xFFCCFFAA`). The `#` syntax uses six digits to specify a color (just as colors are typically 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 define the red, green, and blue components. + Note that in Java, and therefore also Processing, you cannot extend a class + more than once. Instead, see `implements`. + examples: + - | + DrawDot dd1 = new DrawDot(50, 80); + void setup() { + size(200, 200); + } - The value for the "gray" parameter must be less than or equal to the current maximum value as specified by `colorMode()`. The default maximum value is 255. + void draw() { + dd1.display(); + } + class Dot { + int xpos, ypos; + } - To change the color of an image or a texture, use `tint()`. - docUrl: https://processing.org/reference/fill_.html - name: null - parameters: - alpha: "float: opacity of the fill" - gray: "float: number specifying value between white and black" - rgb: "int: color variable or hex value" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: |- - fill(rgb) - fill(rgb, alpha) - fill(gray) - fill(gray, alpha) - fill(v1, v2, v3) - fill(v1, v2, v3, alpha) + class DrawDot extends Dot { + DrawDot(int x, int y) { + xpos = x; + ypos = y; + } + void display() { + ellipse(xpos, ypos, 200, 200); + } + } + fileName: extends + parameters: {} + returns: "" + syntax: [] + type: function +"false": + description: Reserved word representing the logical value "false". Only + variables of type `boolean` may be assigned the value `false`. + examples: + - | + rect(30, 20, 50, 50); + boolean b = false; + if (b == false) { + line(20, 10, 90, 80); // This line is drawn + } else { + line(20, 80, 90, 10); // This line is not drawn + } + fileName: "false" + parameters: {} + returns: "" + syntax: [] + type: function +fill: + description: |- + 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(). + examples: + - |- + size(400, 400); + fill(153); + rect(120, 80, 220, 220); + - |- + size(400, 400); + fill(204, 102, 0); + rect(120, 80, 220, 220); + fileName: fill_ + parameters: + alpha: + desc: opacity of the fill + type: + - float + gray: + desc: number specifying value between white and black + type: + - float + rgb: + desc: color variable or hex value + type: + - int + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - fill(rgb) + - fill(rgb, alpha) + - fill(gray) + - fill(gray, alpha) + - fill(v1, v2, v3) + - fill(v1, v2, v3, alpha) type: function filter: description: >- - Filters the display window using a preset filter or with a custom shader. - Using a shader with `filter()` is much faster than without. Shaders require - the P2D or P3D renderer in size(). - - - The presets options are: - - - THRESHOLD - - Converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The parameter 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. No parameter is used. - - - OPAQUE - - Sets the alpha channel to entirely opaque. No parameter is used. - - - INVERT - - Sets each pixel to its inverse value. No parameter is used. - - - POSTERIZE - - Limits each channel of the image to the number of colors specified as the parameter. The parameter can be set to values between 2 and 255, but results are most noticeable in the lower ranges. - + Filters the image as defined by one of the following modes: + + THRESHOLD + Converts the image to black and white pixels depending on if they + are above or below the threshold defined by the level parameter. + The parameter 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. No parameter is + used. + + OPAQUE + Sets the alpha channel to entirely opaque. No parameter is used. + + INVERT + Sets each pixel to its inverse value. No parameter is used. + + POSTERIZE + Limits each channel of the image to the number of colors specified as the + parameter. The parameter can be set to values between 2 and 255, but results + are most noticeable in the lower ranges. + + BLUR + Executes a Gaussian blur with the level parameter specifying the extent of + the blurring. If no parameter is used, the blur is equivalent to Gaussian + blur of radius 1. Larger values increase the blur. + + ERODE + Reduces the light areas. No parameter is used. + + DILATE + Increases the light areas. No parameter is used. + examples: + - |- + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(THRESHOLD); + - |- + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(GRAY); + - |- + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(INVERT); + - |- + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(POSTERIZE, 4); + - |- + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(BLUR, 6); + - | + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(ERODE); + - | + PImage img; + img = loadImage("flower.jpg"); + image(img, 0, 0); + filter(DILATE); + - |- + PShader blur; + PImage img; + + void setup() { + size(400, 400, P2D); + blur = loadShader("blur.glsl"); + img = loadImage("flower.jpg"); + image(img, 0, 0); + } - BLUR - Executes a Guassian blur with the level parameter specifying the extent of the blurring. If no parameter is used, t. . . - docUrl: https://processing.org/reference/filter_.html - name: null - parameters: - kind: "int: Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or - DILATE" - param: "float: unique for each, see above" - shader: "PShader: the fragment shader to apply" - returns: void - syntax: |- - filter(shader) - filter(kind) - filter(kind, param) + void draw() { + filter(blur); // Blurs more each time through draw() + } + fileName: filter_ + parameters: + kind: + desc: |- + Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, + or DILATE + type: + - int + param: + desc: unique for each, see above + type: + - float + shader: + desc: the fragment shader to apply + type: + - PShader + returns: void + syntax: + - filter(shader) + - filter(kind) + - filter(kind, param) + type: function +final: + description: >- + Keyword used to state that a value, class, or method can't be changed. If + the `final` keyword is used to define a variable, the variable can't be + changed within the program. When used to define a class, a `final` class + cannot be subclassed. When used to define a function or method, a `final` + method can't be overridden by subclasses. + + + This keyword is an essential part of Java programming and is not usually + used with Processing. Consult a Java language reference or tutorial for more + information. + examples: + - | + final float constant = 12.84753; + println(constant); // Prints "12.84753" to the console + constant += 12.84; // ERROR! It's not possible to change a "final" value + fileName: final + parameters: {} + returns: "" + syntax: [] type: function float: description: >- @@ -2047,199 +6307,510 @@ float: return `NaN`. - When an array of `int` or `String` values is passed in, then a floating point array of the same length is returned. - docUrl: https://processing.org/reference/floatconvert_.html - name: null + When an array of `int` or `String` values is passed in, then a floating + point array of the same length is returned. + examples: + - | + int i = 65; + float f = float(i); + println(i + " : " + f); // Prints "65 : 65.0" + fileName: floatconvert_ parameters: {} + syntax: [] type: function floor: - description: Calculates the closest int value that is less than or equal to the - value of the parameter. - docUrl: https://processing.org/reference/floor_.html - name: null - parameters: - n: "float: number to round down" + description: |- + Calculates the closest int value that is less than or equal to the value + of the parameter. + examples: + - | + float x = 2.88; + int a = floor(x); // Sets 'a' to 2 + fileName: floor_ + parameters: + n: + desc: number to round down + type: + - float returns: int - syntax: floor(n) + syntax: + - floor(n) type: function focused: - description: Confirms if a Processing program is "focused," meaning that it is - active and will accept mouse or keyboard input. This variable is "true" if - it is focused and "false" if not. - docUrl: https://processing.org/reference/focused.html - examples: | - if (focused) { // or "if (focused == true)" - ellipse(25, 25, 50, 50); - } else { - line(0, 0, 100, 100); - line(100, 0, 0, 100); - } - name: null - type: var -frameCount: - description: The system variable `frameCount` contains the number of frames that - have been displayed since the program started. Inside `setup()` the value is - 0, after the first iteration of draw it is 1, etc. - docUrl: https://processing.org/reference/frameCount.html - examples: | - void setup() { - frameRate(30); - } - - void draw() { - line(0, 0, width, height); - println(frameCount); - } - name: null + description: |- + 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. + examples: + - | + if (focused) { // or "if (focused == true)" + ellipse(25, 25, 50, 50); + } else { + line(0, 0, 100, 100); + line(100, 0, 0, 100); + } + fileName: focused type: var -frameRate: - description: Specifies the number of frames to be displayed every second. For - example, the function call `frameRate(30)` will attempt to refresh 30 times - a second. If the processor is not fast enough to maintain the specified - rate, the frame rate will not be achieved. Setting the frame rate within - `setup()` is recommended. The default rate is 60 frames per second. - docUrl: https://processing.org/reference/frameRate_.html - name: null - parameters: - fps: "float: number of desired frames per second" - returns: void - syntax: frameRate(fps) - type: function -frustum: +for: description: >- - Sets a perspective matrix as defined by the parameters. + Controls a sequence of repetitions. A basic `for` structure has three parts: + `init`, `test`, and `update`. Each part must be separated by a semicolon + (;). The loop continues until the `test` evaluates to `false`. When a `for` + structure is executed, the following sequence of events occurs: - A frustum is a geometric form: a pyramid with its top cut off. With the viewer's eye at the imaginary top of the pyramid, the six planes of the frustum act as clipping planes when rendering a 3D view. Thus, any form inside the clipping planes is rendered and visible; anything outside those planes is not visible. + 1. The init statement is run. + 2. The test is evaluated to be true or false. - Setting the frustum has the effect of changing the perspective with which the scene is rendered. This can be achieved more simply in many cases by using perspective(). + 3. If the test is true, jump to step 4. If the test is false, jump to step + 6. + 4. Run the statements within the block. - Note that the near value must be greater than zero (as the point of the frustum "pyramid" cannot converge "behind" the viewer). Similarly, the far value must be greater than the near value (as the "far" plane of the frustum must be "farther away" from the viewer than the near plane). + 5. Run the update statement and jump to step 2. + 6. Exit the loop. - Works like glFrustum, except it wipes out the current perspective matrix rather than multiplying itself with it. - docUrl: https://processing.org/reference/frustum_.html - name: null - parameters: - bottom: "float: bottom coordinate of the clipping plane" - far: "float: far component of the clipping plane; must be greater than the near - value" - left: "float: left coordinate of the clipping plane" - near: "float: near component of the clipping plane; must be greater than zero" - right: "float: right coordinate of the clipping plane" - top: "float: top coordinate of the clipping plane" - returns: void - syntax: frustum(left, right, bottom, top, near, far) - type: function -fullScreen: - description: >- - This function is new for Processing 3.0. It opens a sketch using the full - size of the computer's display. This function must be the first line in - `setup()`. The `size()` and `fullScreen()` functions cannot both be used in - the same program, just choose one. + In the first example above, the `for` structure is executed 40 times. In the + init statement, the value i is created and set to zero. i is less than 40, + so the test evaluates as true. At the end of each loop, i is incremented by + one. On the 41st execution, the test is evaluated as false, because i is + then equal to 40, so i < 40 is no longer true. Thus, the loop exits. - When `fullScreen()` is used without a parameter, it draws the sketch to the screen currently selected inside the Preferences window. When it is used with a single parameter, this number defines the screen to display to program on (e.g. 1, 2, 3...). When used with two parameters, the first defines the renderer to use (e.g. P2D) and the second defines the screen. The `SPAN` parameter can be used in place of a screen number to draw the sketch as a full-screen window across all of the attached displays if there are more than one. + A second type of `for` structure makes it easier to iterate over each + element of an array. The last example above shows how it works. Within the + parentheses, first define the datatype of the array, then define a variable + name. This variable name will be assigned to each element of the array in + turn as the `for` moves through the entire array. Finally, after the colon, + define the array name to be used. + examples: + - |- + size(400, 400); + for (int i = 0; i < 160; i = i+1) { + line(120, i, 320, i); + } + - |- + size(400, 400); + for (int i = 0; i < 320; i = i+20) { + line(120, i, 320, i); + } + - |- + size(400, 400); + for (int i = 160; i < 320; i = i+20) { + line(120, i, 320, i); + } + - |- + // Nested for() loops can be used to + // generate two-dimensional patterns + size(400, 400); + + for (int i = 120; i < 320; i = i+20) { + for (int j = 0; j < 320; j = j+20) { + point(i, j); + } + } + fileName: for + parameters: + array: + desc: name of the array to iterate through + type: [] + datatype: + desc: datatype of elements in the array + type: [] + element: + desc: temporary name to use for each element of the array + type: [] + init: + desc: statement executed once when beginning loop + type: [] + statements: + desc: collection of statements executed each time through the loop + type: [] + test: + desc: if the test evaluates to true, the statements execute + type: [] + update: + desc: executes at the end of each iteration + type: [] + returns: "" + syntax: + - "for (init; test; update) { " + - " statements" + - "} " + - "" + - "for (datatype element : array) { " + - " statements" + - "}" + type: function +frameCount: + description: |- + The system variable `frameCount` contains the number o + frames displayed since the program started. Inside `setup()` + the value is 0 and during the first iteration of draw it is 1, etc. + examples: + - | + void setup() { + frameRate(30); + } - Prior to Processing 3.0, a full-screen program was defined with `size(displayWidth, displayHeight)`. - docUrl: https://processing.org/reference/fullScreen_.html - name: null + void draw() { + line(0, 0, width, height); + println(frameCount); + } + fileName: frameCount + type: var +frameRate: + description: |- + Specifies the number of frames to be displayed every second. For example, + the function call `frameRate(30)` will attempt to refresh 30 times a + second. If the processor is not fast enough to maintain the specified rate, + the frame rate will not be achieved. Setting the frame rate within + `setup()` is recommended. The default rate is 60 frames per second. + examples: + - | + void setup() { + frameRate(4); + } + int pos = 0; + void draw() { + background(204); + pos++; + line(pos, 20, pos, 80); + if (pos > width) { + pos = 0; + } + } + fileName: frameRate_ parameters: - display: "int: the screen to run the sketch on (1, 2, 3, etc. or on multiple - screens using SPAN)" - renderer: "String: the renderer to use, e.g. P2D, P3D, JAVA2D (default)" + fps: + desc: number of desired frames per second + type: + - float returns: void - syntax: |- - fullScreen() - fullScreen(display) - fullScreen(renderer) - fullScreen(renderer, display) + syntax: + - frameRate(fps) type: function -get: +frustum: description: >- - 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 additional `w` and `h` parameters. 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()`. + Sets a perspective matrix as defined by the parameters. + A frustum is a geometric form: a pyramid with its top cut off. With the + viewer's eye at the imaginary top of the pyramid, the six planes of the + frustum act as clipping planes when rendering a 3D view. Thus, any form + inside the clipping planes is rendered and visible; anything outside those + planes is not visible. + + Setting the frustum has the effect of changing the perspective with + which the scene is rendered. This can be achieved more simply in many cases + by using perspective(). + + Note that the near value must be greater than zero (as the point of the + frustum "pyramid" cannot converge "behind" the viewer). Similarly, the far + value must be greater than the near value (as the "far" plane of the frustum + must be "farther away" from the viewer than the near plane). + + Works like glFrustum, except it wipes out the current perspective matrix + rather than multiplying itself with it. + examples: + - |- + size(400, 400, P3D); + noFill(); + background(204); + frustum(-40, 0, 0, 40, 40, 800); + rotateY(PI/6); + box(180); + fileName: frustum_ + parameters: + bottom: + desc: bottom coordinate of the clipping plane + type: + - float + far: + desc: |- + far component of the clipping plane; must be greater than the + near value + type: + - float + left: + desc: left coordinate of the clipping plane + type: + - float + near: + desc: near component of the clipping plane; must be greater than zero + type: + - float + right: + desc: right coordinate of the clipping plane + type: + - float + top: + desc: top coordinate of the clipping plane + type: + - float + returns: void + syntax: + - frustum(left, right, bottom, top, near, far) + type: function +fullScreen: + description: |- + This function is new for Processing 3.0. It opens a sketch using the full + size of the computer's display. This function must be the first line in + `setup()`. The `size()` and `fullScreen()` functions cannot + both be used in the same program, just choose one. + + When `fullScreen()` is used without a parameter, it draws the sketch + to the screen currently selected inside the Preferences window. When it is + used with a single parameter, this number defines the screen to display to + program on (e.g. 1, 2, 3...). When used with two parameters, the first + defines the renderer to use (e.g. P2D) and the second defines the screen. + The `SPAN` parameter can be used in place of a screen number to draw + the sketch as a full-screen window across all the attached displays if + there are more than one. + + Prior to Processing 3.0, a full-screen program was defined with + `size(displayWidth, displayHeight)`. + examples: + - | + // Run the code at the full dimensions of the screen currently + // selected inside the Preferences window + + int x = 0; + + void setup() { + fullScreen(); + background(0); + noStroke(); + fill(102); + } + + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + - | + // If more than one screen is attached to the computer, run the + // code at the full dimensions on the screen defined by the + // parameter to fullScreen() + + int x = 0; + + void setup() { + fullScreen(2); + background(0); + noStroke(); + fill(102); + } + + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + - | + // Run full screen using the P2D renderer on screen 2 + + int x = 0; - 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. + void setup() { + fullScreen(P2D, 2); + background(0); + noStroke(); + fill(102); + } + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + - | + // If more than one screen is attached to the computer, run the + // code at the full dimensions across all of the attached screens - If a width and a height are specified, `get(x, y, w, h)` returns a PImage corresponding to the part of the original PImage where the top left pixel is at the `(x, y)` position with a width of `w` a height of `h`. + int x = 0; + void setup() { + fullScreen(P2D, SPAN); + background(0); + noStroke(); + fill(102); + } - Getting the color of a single pixel with `get. . . - docUrl: https://processing.org/reference/get_.html - name: null - parameters: - h: "int: height of pixel rectangle to get" - w: "int: width of pixel rectangle to get" - x: "int: x-coordinate of the pixel" - y: "int: y-coordinate of the pixel" + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + fileName: fullScreen_ + parameters: + display: + desc: the screen to run the sketch on (1, 2, 3, etc. or on multiple screens + using SPAN) + type: + - int + renderer: + desc: the renderer to use, e.g. P2D, P3D, JAVA2D (default) + type: + - String + returns: void + syntax: + - fullScreen() + - fullScreen(display) + - fullScreen(renderer) + - fullScreen(renderer, display) + type: function +get: + description: |- + 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 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. + examples: + - |- + size(400,400); + PImage myImage = loadImage("flower.jpg"); + image(myImage, 0, 0); + PImage c = get(); + image(c, width/2, 0); + - |- + size(400,400); + PImage myImage = loadImage("flower.jpg"); + image(myImage, 0, 0); + color c = get(25, 25); + fill(c); + noStroke(); + rect(100, 100, 200, 200); + fileName: get_ + parameters: + h: + desc: height of pixel rectangle to get + type: + - int + w: + desc: width of pixel rectangle to get + type: + - int + x: + desc: x-coordinate of the pixel + type: + - int + y: + desc: y-coordinate of the pixel + type: + - int returns: int or PImage - syntax: |- - get(x, y) - get(x, y, w, h) - get() + syntax: + - get(x, y) + - get(x, y, w, h) + - get() type: function green: description: >- Extracts the green value from a color, scaled to match current - `colorMode()`. The 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 understand, but it is slower than a technique called bit shifting. When working in `colorMode(RGB, 255)`, you can acheive the same results as `green()` but with greater speed by using the right shift operator (`>>`) with a bit mask. For example, the following two lines of code are equivalent means of getting the green value of the color value `c`: - - - `float g1 = green(c); // Simpler, but slower to calculate - - float g2 = c >> 8 & 0xFF; // Very fast to calculate` - docUrl: https://processing.org/reference/green_.html - name: null - parameters: - rgb: "int: any value of the color datatype" + `colorMode()`. The 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 understand, but it is slower + than a technique called bit shifting. When working in `colorMode(RGB, + 255)`, you can achieve the same results as `green()` but with greater + speed by using the right shift operator (`>>`) with a bit mask. For + example, the following two lines of code are equivalent means of getting the + green value of the color value `c`: + + + ` + float g1 = green(c); // Simpler, but slower to calculate + float g2 = c >> 8 & 0xFF; // Very fast to calculate + ` + examples: + - |- + size(400, 400); + color c = color(20, 75, 200); // Define color 'c' + fill(c); // Use color variable 'c' as fill color + rect(60, 80, 140, 240); // Draw left rectangle + + float greenValue = green(c); // Get green in 'c' + println(greenValue); // Print "75.0" + fill(0, greenValue, 0); // Use 'greenValue' in new fill + rect(200, 80, 140, 240); // Draw right rectangle + fileName: green_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int returns: float - syntax: green(rgb) + syntax: + - green(rgb) type: function height: - description: System variable that 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` defaults to 100 if `size()` is not used in a - program. - docUrl: https://processing.org/reference/height.html - examples: | - noStroke(); - background(0); - rect(40, 0, 20, height); - rect(60, 0, 20, height/2); - name: null + description: |- + 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` defaults to 100 if + `size()` is not used in a program. + examples: + - |- + size(400, 400); + noStroke(); + background(0); + rect(160, 0, 80, height); + rect(240, 0, 80, height/8); + fileName: height type: var hex: - description: >- - Converts an `int`, `byte`, `char`, or `color` to a `String` containing the - equivalent hexadecimal notation. For example, the `color` value produced by - `color(0, 102, 153)` will convert to the `String` value `"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 8 digits will not increase the length of the `String` further. - docUrl: https://processing.org/reference/hex_.html - name: null - parameters: - digits: "int: the number of digits (maximum 8)" - value: "int, char, or byte: the value to convert" + description: |- + Converts an `int`, `byte`, `char`, or `color` to a + `String` containing the equivalent hexadecimal notation. For example, + the `color` value produced by `color(0, 102, 153)` will convert + to the `String` value `"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 8 digits will not + increase the length of the `String` further. + examples: + - | + color c = #ffcc00; + println(c); // Prints "-13312" + println(hex(c)); // Prints "FFFFCC00" + println(hex(c, 6)); // Prints "FFCC00" + - | + color c = color(255, 204, 0); + println(c); // Prints "-13312" + println(hex(c)); // Prints "FFFFCC00" + println(hex(c, 6)); // Prints "FFCC00" + fileName: hex_ + parameters: + digits: + desc: the number of digits (maximum 8) + type: + - int + value: + desc: the value to convert + type: + - byte + - char + - int returns: String - syntax: |- - hex(value) - hex(value, digits) + syntax: + - hex(value) + - hex(value, digits) type: function hint: description: >- @@ -2260,7 +6831,9 @@ hint: `ENABLE_STROKE_PURE` - Fixes a problem with shapes that have a stroke and are rendered using small steps (for instance, using vertex() with points that are close to one another), or are drawn at small sizes. + Fixes a problem with shapes that have a stroke and are rendered using small + steps (for instance, using vertex() with points that are close to one + another), or are drawn at small sizes. @@ -2269,80 +6842,391 @@ hint: `DISABLE_ASYNC_SAVEFRAME` - save() and saveFrame() will not use separate. . . - docUrl: https://processing.org/reference/hint_.html - name: null + 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). + + + `DISABLE_OPENGL_ERRORS` + + Speeds up the P3D renderer setting by not checking for errors while running. + + + `DISABLE_TEXTURE_MIPMAPS` + + Disable generation of texture mipmaps in P2D or P3D. This results in lower + quality - but faster - rendering of texture images when they appear smaller + than their native resolutions (the mipmaps are scaled-down versions of a + texture that make it look better when drawing it at a small size). However, + the difference in performance is fairly minor on recent desktop video cards. + + + + Hints for use with P3D only: + + + `DISABLE_DEPTH_MASK` + + Disables writing into the depth buffer. This means that a shape drawn with + this hint can be hidden by another shape drawn later, irrespective of their + distances to the camera. Note that this is different from disabling the + depth test. The depth test is still applied, as long as the + DISABLE_DEPTH_TEST hint is not called, but the depth values of the objects + are not recorded. This is useful when drawing a semi-transparent 3D object + without depth sorting, in order to avoid visual glitches due the faces of + the object being at different distances from the camera, but still having + the object properly occluded by the rest of the objects in the scene. + + + `ENABLE_DEPTH_SORT` + + Enable primitive z-sorting of triangles and lines in P3D. This can slow + performance considerably, and the algorithm is not yet perfect. + + + `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). When called, 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 will ignore existing shapes on + the screen. + + + `DISABLE_OPTIMIZED_STROKE` + + Forces the P3D renderer to draw each shape (including its strokes) + separately, instead of batching them into larger groups for better + performance. One consequence of this is that 2D items drawn with P3D are + correctly stacked on the screen, depending on the order in which they were + drawn. Otherwise, glitches such as the stroke lines being drawn on top of + the interior of all the shapes will occur. However, this hint can make + rendering substantially slower, so it is recommended to use it only when + drawing a small amount of shapes. For drawing two-dimensional scenes, use + the P2D renderer instead, which doesn't need the hint to properly stack + shapes and their strokes. + + + `ENABLE_STROKE_PERSPECTIVE` + + Enables stroke geometry (lines and points) to be affected by the + perspective, meaning that they will look smaller as they move away from the + camera. + fileName: hint_ parameters: - which: "int: the hint mode to use" - syntax: | - hint(which) + which: + desc: "int: the hint mode to use" + type: [] + returns: void + syntax: + - hint(which) type: function hour: - description: Processing communicates with the clock on your computer. The - `hour()` function returns the current hour as a value from 0 - 23. - docUrl: https://processing.org/reference/hour_.html - name: null + description: |- + Processing communicates with the clock on your computer. The + `hour()` function returns the current hour as a value from 0 to 23. + examples: + - | + void draw() { + background(204); + int s = second(); // Values from 0 - 59 + int m = minute(); // Values from 0 - 59 + int h = hour(); // Values from 0 - 23 + line(s, 0, s, 33); + line(m, 33, m, 66); + line(h, 66, h, 100); + } + fileName: hour_ parameters: {} returns: int - syntax: hour() + syntax: + - hour() type: function hue: description: Extracts the hue value from a color. - docUrl: https://processing.org/reference/hue_.html - name: null - parameters: - rgb: "int: any value of the color datatype" + examples: + - |- + size(400, 400); + noStroke(); + colorMode(HSB, 255); + color c = color(0, 126, 255); + fill(c); + rect(60, 80, 140, 240); + float value = hue(c); // Sets 'value' to "0" + fill(value); + rect(200, 80, 140, 240); + fileName: hue_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int returns: float - syntax: hue(rgb) + syntax: + - hue(rgb) + type: function +if: + description: Allows the program to make a decision about which code to execute. + If the `test` evaluates to `true`, the statements enclosed within the block + are executed and if the `test` evaluates to `false` the statements are not + executed. + examples: + - | + for (int i = 5; i < height; i += 5) { + stroke(255); // Agregamos el color Blanco + if (i < 35) { // When 'i' is less than 35... + stroke(0); //...set the color to black + } + line(30, i, 80, i); + } + - |- + for (int i = 5; i < height; i += 5) { + stroke(255); // Set the color to white + if (i < 35) { // When 'i' is less than 35... + stroke(0); //...set the color to black + } + line(30, i, 80, i); + } + fileName: if + parameters: + statements: + desc: one or more statements to be executed + type: [] + test: + desc: any valid expression that evaluates to true or false + type: [] + returns: "" + syntax: + - "if (test) { " + - " statements " + - "} " type: function image: - description: >- - The `image()` function draws an image to the display window. Images must be - in the sketch's "data" directory to load correctly. Select "Add file..." - from the "Sketch" menu to add the image to the data directory, or just drag - the image file onto the sketch window. Processing currently works with GIF, - JPEG, and PNG images. - + description: |- + The `image()` function draws an image to the display window. Images must + be in the sketch's "data" directory to load correctly. Select "Add file..." + from the "Sketch" menu to add the image to the data directory, or just drag + the image file onto the sketch window. Processing currently works with GIF, + JPEG, and PNG images. + + The `img` parameter specifies the image to display and by default the + `a` and `b` parameters define the location of its upper-left + corner. The image is displayed at its original size unless the `c` and + `d` parameters specify a different size. The `imageMode()` function + can be used to change the way these parameters draw the image. + + The color of an image may be modified with the `tint()` function. This + function will maintain transparency for GIF and PNG images. + examples: + - |- + PImage img; + + void setup() { + size(400,400); + img = loadImage("Toyokawa.jpg"); + } - The `img` parameter specifies the image to display and by default the `a` and `b` parameters define the location of its upper-left corner. The image is displayed at its original size unless the `c` and `d` parameters specify a different size. The `imageMode()` function can be used to change the way these parameters draw the image. + void draw() { + image(img, 0, 0); + } + - |- + PImage img; + void setup() { + size(400,400); + img = loadImage("ginko.jpg"); + } - The color of an image may be modified with the `tint()` function. This function will maintain transparency for GIF and PNG images. - docUrl: https://processing.org/reference/image_.html - name: null - parameters: - a: "float: x-coordinate of the image by default" - b: "float: y-coordinate of the image by default" - c: "float: width to display the image by default" - d: "float: height to display the image by default" - img: "PImage: the image to display" - returns: void - syntax: |- - image(img, a, b) - image(img, a, b, c, d) + void draw() { + image(img, 0, 0); + image(img, 0, 0, width/2, height/2); + } + fileName: image_ + parameters: + a: + desc: x-coordinate of the image by default + type: + - float + b: + desc: y-coordinate of the image by default + type: + - float + c: + desc: width to display the image by default + type: + - float + d: + desc: height to display the image by default + type: + - float + img: + desc: the image to display + type: + - PImage + returns: void + syntax: + - image(img, a, b) + - image(img, a, b, c, d) type: function imageMode: - description: >- + description: |- Modifies the location from which images are drawn by changing the way in - which parameters given to `image()` are intepreted. + which parameters given to `image()` are interpreted. + + The default mode is `imageMode(CORNER)`, which interprets the second and + third parameters of `image()` as the upper-left corner of the image. If + two additional parameters are specified, they are used to set the image's + width and height. + + `imageMode(CORNERS)` interprets the second and third parameters of + `image()` as the location of one corner, and the fourth and fifth + parameters as the opposite corner. + + `imageMode(CENTER)` interprets the second and third parameters of + `image()` as the image's center point. If two additional parameters are + specified, they are used to set the image's width and height. + + The parameter must be written in ALL CAPS because Processing is a + case-sensitive language. + examples: + - |- + PImage img; + + void setup() { + size(400,400); + img = loadImage("Toyokawa.jpg"); + } + + void draw() { + imageMode(CORNER); + image(img, 40, 40, 200, 200); // Draw image using CORNER mode + } + - |- + PImage img; + + void setup() { + size(400,400); + img = loadImage("Toyokawa.jpg"); + } + + void draw() { + imageMode(CORNERS); + image(img, 40, 40, 360, 160); // Draw image using CORNERS mode + } + - |- + PImage img; + + void setup() { + size(400,400); + img = loadImage("Toyokawa.jpg"); + } + + void draw() { + imageMode(CENTER); + image(img, 200, 200, 320, 320); // Draw image using CENTER mode + } + fileName: imageMode_ + parameters: + mode: + desc: either CORNER, CORNERS, or CENTER + type: + - int + returns: void + syntax: + - imageMode(mode) + type: function +implements: + description: >- + Implements an interface or group of interfaces. Interfaces are used to + establish a protocol between classes; they establish the form for a class + (method names, return types, etc.) but no implementation. After + implementation, an interface can be used and extended like any other class. + + + Because Java doesn't allow extending more than one class at a time, you can + create interfaces instead, so specific methods and fields can be found in + the class which implements it. A Thread is an example; it implements the + "Runnable" interface, which means the class has a method called "public void + run()" inside it. + examples: + - | + interface Dot { + void move(); + void display(); + } + + class CircleDot implements Dot { + float x = 50; + float y = 50; + + void move() { + x = x + random(-1, 1); + } + + void display() { + ellipse(x, y, 16, 16); + } + } + + class SquareDot implements Dot { + float x = 50; + float y = 50; + + void move() { + y = y + random(-1, 1); + } + + void display() { + rect(x, y, 16, 16); + } + } + fileName: implements + parameters: {} + returns: "" + syntax: [] + type: function +import: + description: >- + The keyword `import` is used to load a library into a Processing sketch. + + A library is one or more classes that are grouped together to extend the + capabilities of Processing. - The default mode is `imageMode(CORNER)`, which interprets the second and third parameters of `image()` as the upper-left corner of the image. If two additional parameters are specified, they are used to set the image's width and height. + The `*` character is often used at the end of the import line (see the code + example above) + to load all of the related classes at once, without having to reference them + individually. - `imageMode(CORNERS)` interprets the second and third parameters of `image()` as the location of one corner, and the fourth and fifth parameters as the opposite corner. + The import statement will be created for you by selecting a library from the + "Import Library..." - `imageMode(CENTER)` interprets the second and third parameters of `image()` as the image's center point. If two additional parameters are specified, they are used to set the image's width and height. + item in the Sketch menu. + examples: + - | + import processing.pdf.*; + void setup() { + size(1024, 768, PDF); + } - The parameter must be written in ALL CAPS because Processing is a case-sensitive language. - docUrl: https://processing.org/reference/imageMode_.html - name: null + void draw() { + line(0, 0, width, height); + line(0, height, width, 0); + } + fileName: import parameters: - mode: "int: either CORNER, CORNERS, or CENTER" - returns: void - syntax: imageMode(mode) + libraryName: + desc: the name of the library to load (e.g. "processing.pdf.*") + type: [] + returns: "" + syntax: + - import libraryName type: function int: description: >- @@ -2350,2353 +7234,5683 @@ int: `color`, `float`, `int`, or `long`) or String to its integer representation. - When an array of values is passed in, then an `int` array of the same length is returned. - docUrl: https://processing.org/reference/intconvert_.html - name: null + When an array of values is passed in, then an `int` array of the same length + is returned. + examples: + - | + float f = 65.0; + int i = int(f); + println(f + " : " + i); // Prints "65.0 : 65" + + char c = 'E'; + i = int(c); + println(c + " : " + i); // Prints "E : 69" + fileName: intconvert_ parameters: {} + syntax: [] type: function join: - description: 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()`. - docUrl: https://processing.org/reference/join_.html - name: null - parameters: - list: "String[]: array of Strings" - separator: "char: char or String to be placed between each item" + description: |- + 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()`. + examples: + - |+ + String[] animals = new String[3]; + animals[0] = "cat"; + animals[1] = "seal"; + animals[2] = "bear"; + String joinedAnimals = join(animals, " : "); + println(joinedAnimals); // Prints "cat : seal : bear" + + // Joining an array of ints requires first + // converting to an array of Strings + int[] numbers = new int[3]; + numbers[0] = 8; + numbers[1] = 67; + numbers[2] = 5; + String joinedNumbers = join(nf(numbers, 0), ", "); + println(joinedNumbers); // Prints "8, 67, 5" + + fileName: join_ + parameters: + list: + desc: array of Strings + type: + - String[] + separator: + desc: char or String to be placed between each item + type: + - char + - String returns: String - syntax: join(list, separator) + syntax: + - join(list, separator) type: function key: - description: >- - 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 the 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. - - - There are issues with how `keyCode` behaves across different renderers and operating systems. Watch out for unexpected behavior as you switch renderers and operating systems. - docUrl: https://processing.org/reference/key.html - examples: | - // Click on the window to give it focus, - // and press the 'B' key. - - void draw() { - if (keyPressed) { - if (key == 'b' || key == 'B') { - fill(0); + description: |- + 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. + + There are issues with how `keyCode` behaves across different + renderers and operating systems. Watch out for unexpected behavior as + you switch renderers and operating systems. + examples: + - | + // Click on the window to give it focus, + // and press the 'B' key. + + void draw() { + if (keyPressed) { + if (key == 'b' || key == 'B') { + fill(0); + } + } else { + fill(255); } - } else { - fill(255); + rect(25, 25, 50, 50); } - rect(25, 25, 50, 50); - } - name: null + fileName: key type: var keyCode: - description: >- - The variable `keyCode` is used to detect special keys such as the arrow keys - (UP, DOWN, LEFT, and RIGHT) as well as ALT, CONTROL, and SHIFT. + description: |- + 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 can be useful to first check if the key + is coded. This is done with the conditional `if (key == CODED)`, as + shown in the example above. + + The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, + RETURN, ESC, and DELETE) do not require checking to see if the key is + coded; for those keys, you should simply use the `key` variable + directly (and not `keyCode`). If you're making cross-platform + projects, note that the ENTER key is commonly used on PCs and Unix, + while the RETURN key is used on Macs. Make sure your program will work + on all platforms by checking for both ENTER and RETURN. + + For those 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. + + There are issues with how `keyCode` behaves across different + renderers and operating systems. Watch out for unexpected behavior + as you switch renderers and operating systems, and also whenever + you are using keys not mentioned in this reference entry. + + If you are using P2D or P3D as your renderer, use the + NEWT KeyEvent constants. + examples: + - | + color fillVal = color(126); + + void draw() { + fill(fillVal); + rect(25, 25, 50, 50); + } + + void keyPressed() { + if (key == CODED) { + if (keyCode == UP) { + fillVal = 255; + } else if (keyCode == DOWN) { + fillVal = 0; + } + } else { + fillVal = 126; + } + } + fileName: keyCode + type: var +keyPressed: + description: |- + The `keyPressed()` function is called once every time a key is + pressed. The key that was pressed is stored in the `key` variable. - When checking for these keys, it can be useful to first check if the key is coded. This is done with the conditional `if (key == CODED)`, as shown in the example above. + 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 the key is coded; for those keys, you should + simply use the `key` variable directly (and not `keyCode`). If + you're making cross-platform projects, note that the ENTER key is commonly + used on PCs and Unix, while the RETURN key is used on Macs. Make sure your + program will work on all platforms by checking for both ENTER and RETURN. - The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if the key is coded; for those keys, you should simply use the `key` variable directly (and not `keyCode`). If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix, while the RETURN key is used on Macs. Make sure your program will work on all platforms by checking for both ENTER and RETURN. + Because of how operating systems handle key repeats, holding down a key may + cause multiple calls to `keyPressed()`. The rate of repeat is set by + the operating system, and may be configured differently on each computer. - For those 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. + Note that there is a similarly named boolean variable called + `keyPressed`. See its reference page for more information. + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. - There are issues with. . . - docUrl: https://processing.org/reference/keyCode.html - examples: | - color fillVal = color(126); + With the release of macOS Sierra, Apple changed how key repeat works, so + keyPressed may not function as expected. See here + for details of the problem and how to fix it. + examples: + - | + // Click on the image to give it focus, + // and then press any key. - void draw() { - fill(fillVal); - rect(25, 25, 50, 50); - } + int value = 0; - void keyPressed() { - if (key == CODED) { - if (keyCode == UP) { - fillVal = 255; - } else if (keyCode == DOWN) { - fillVal = 0; - } - } else { - fillVal = 126; + void draw() { + fill(value); + rect(25, 25, 50, 50); } - } - name: null - type: var -keyPressed: - description: >- - The boolean system variable `keyPressed` is `true` if any key is pressed and - `false` if no keys are pressed. - - - Note that there is a similarly named function called `keyPressed()`. See its reference page for more information. - docUrl: https://processing.org/reference/keyPressed.html - examples: | - // Click on the image to give it focus, - // and then press any key. - - // Note: The rectangle in this example may - // flicker as the operating system may - // register a long key press as a repetition - // of key presses. - void draw() { - if (keyPressed == true) { - fill(0); - } else { - fill(255); + void keyPressed() { + if (value == 0) { + value = 255; + } else { + value = 0; + } } - rect(25, 25, 50, 50); - } - name: null - type: var + fileName: keyPressed_ + parameters: {} + returns: void + syntax: + - keyPressed() + - keyPressed(event) + type: function keyReleased: - description: >- - 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 `keyCode` for more information. - + description: |- + 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 `keyCode` for more information. + + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - | + // Click on the image to give it focus, + // and then press any key. + + int value = 0; + + void draw() { + fill(value); + rect(25, 25, 50, 50); + } - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/keyReleased_.html - name: null + void keyReleased() { + if (value == 0) { + value = 255; + } else { + value = 0; + } + } + fileName: keyReleased_ parameters: {} returns: void - syntax: |- - keyReleased() - keyReleased(event) + syntax: + - keyReleased() + - keyReleased(event) type: function keyTyped: - description: >- - The `keyTyped()` function is called once every time a key is pressed, but - action keys such as Ctrl, Shift, and Alt are ignored. + description: |- + 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 may + cause multiple calls to `keyTyped()`. The rate of repeat is set by the + operating system, and may be configured differently on each computer. - Because of how operating systems handle key repeats, holding down a key may cause multiple calls to `keyTyped()`. The rate of repeat is set by the operating system, and may be configured differently on each computer. + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - |+ + // Run this program to learn how each of these functions + // relate to the others. + + void draw() { } // Empty draw() needed to keep the program running + + void keyPressed() { + println("pressed " + int(key) + " " + keyCode); + } + + void keyTyped() { + println("typed " + int(key) + " " + keyCode); + } + void keyReleased() { + println("released " + int(key) + " " + keyCode); + } - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/keyTyped_.html - name: null + fileName: keyTyped_ parameters: {} returns: void - syntax: |- - keyTyped() - keyTyped(event) + syntax: + - keyTyped() + - keyTyped(event) type: function launch: - description: >- + description: |- Attempts to open an application or file using your platform's launcher. The - `filename` 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). - - - This function (roughly) emulates what happens when you double-click an application or document in the macOS Finder, the Windows Explorer, or your favorite Linux file manager. If you're trying to run command line functions directly, use the `exec()` function instead (see below). + `filename` 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). + + This function (roughly) emulates what happens when you double-click an + application or document in the macOS Finder, the Windows Explorer, or your + favorite Linux file manager. If you're trying to run command line functions + directly, use the `exec()` function instead (see below). + + 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 and prays that something + useful happens. + + For users familiar with Java, this is not the same as Runtime.exec(), + because the launcher command is prepended. Instead, the + `exec(String[])` function is a shortcut for + Runtime.getRuntime.exec(String[]). The `exec()` function is documented + in the + JavaDoc + in the `PApplet` class. + examples: + - | + void setup() { + size(200, 200); + } + void draw() { + // draw() must be present for mousePressed() to work + } - 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 . . . - docUrl: https://processing.org/reference/launch_.html - name: null + void mousePressed() { + println("Opening Process_4"); + launch("/Applications/Process_4.app"); + } + fileName: launch_ parameters: - args: "String[]: arguments to the launcher, eg. a filename." + args: + desc: arguments to the launcher, e.g. a filename. + type: + - String[] returns: Process - syntax: launch(args) + syntax: + - launch(args) type: function lerp: - description: 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. - docUrl: https://processing.org/reference/lerp_.html - name: null - parameters: - amt: "float: float between 0.0 and 1.0" - start: "float: first value" - stop: "float: second value" + description: |- + 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. + examples: + - |- + size(400, 400); + float a = 80; + float b = 320; + float c = lerp(a, b, .8); + float d = lerp(a, b, .20); + float e = lerp(a, b, .32); + beginShape(POINTS); + vertex(a, 200); + vertex(b, 200); + vertex(c, 200); + vertex(d, 200); + vertex(e, 200); + endShape(); + - |- + size(400, 400); + int x1 = 60; + int y1 = 40; + int x2 = 320; + int y2 = 360; + line(x1, y1, x2, y2); + for (int i = 0; i <= 40; i++) { + float x = lerp(x1, x2, i/40.0) + 40; + float y = lerp(y1, y2, i/40.0); + point(x, y); + } + fileName: lerp_ + parameters: + amt: + desc: float between 0.0 and 1.0 + type: + - float + start: + desc: first value + type: + - float + stop: + desc: second value + type: + - float returns: float - syntax: lerp(start, stop, amt) + syntax: + - lerp(start, stop, amt) type: function lerpColor: - description: >- - Calculates a color between two colors at a specific increment. The `amt` - parameter is the amount to interpolate between the two values where 0.0 is - equal to the first point, 0.1 is very near the first point, 0.5 is halfway - in between, etc. - - - An amount below 0 will be treated as 0. Likewise, amounts above 1 will be capped at 1. This is different from the behavior of lerp(), but necessary because otherwise numbers outside the range will produce strange and unexpected colors. - docUrl: https://processing.org/reference/lerpColor_.html - name: null - parameters: - amt: "float: between 0.0 and 1.0" - c1: "int: interpolate from this color" - c2: "int: interpolate to this color" + description: |- + Calculates a `color` between two colors at a specific increment. The + `amt` parameter is the amount to interpolate between the two values + where 0.0 is equal to the first point, 0.1 is very near the first point, + 0.5 is halfway in between, etc. + An amount below 0 will be treated as 0. Likewise, amounts above 1 will be + capped at 1. This is different from the behavior of `lerp()`, but necessary + because otherwise numbers outside the range will produce strange and + unexpected colors. + examples: + - |- + + size(400,400); + background(51); + stroke(255); + color from = color(204, 102, 0); + color to = color(0, 102, 153); + color interA = lerpColor(from, to, .33); + color interB = lerpColor(from, to, .66); + fill(from); + rect(40, 80, 80, 240); + fill(interA); + rect(120, 80, 80, 240); + fill(interB); + rect(200, 80, 80, 240); + fill(to); + rect(280, 80, 80, 240); + fileName: lerpColor_ + parameters: + amt: + desc: between 0.0 and 1.0 + type: + - float + c1: + desc: interpolate from this color + type: + - int + c2: + desc: interpolate to this color + type: + - int returns: int - syntax: lerpColor(c1, c2, amt) + syntax: + - lerpColor(c1, c2, amt) type: function lightFalloff: description: >- - Sets the falloff rates for point lights, spot lights, and ambient lights. - Like `fill()`, it affects only the elements which are created after it in - the code. The default value is `lightFalloff(1.0, 0.0, 0.0)`, and the - parameters are used to calculate the falloff with the following equation: - - - d = distance from light position to vertex position - - falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * QUADRATIC) - - - Thinking about an ambient light with a falloff can be tricky. If you want a region of your scene to be lit ambiently with one color and another region to be lit ambiently with another color, you could 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. - docUrl: https://processing.org/reference/lightFalloff_.html - name: null - parameters: - constant: "float: constant value or determining falloff" - linear: "float: linear value for determining falloff" - quadratic: "float: quadratic value for determining falloff" - returns: void - syntax: lightFalloff(constant, linear, quadratic) + Sets the falloff rates for point lights, spotlights, and ambient lights. + Like `fill()`, it affects only the elements which are created after it + in the code. The default value is `lightFalloff(1.0, 0.0, 0.0)`, and the + parameters are used to calculate the falloff with the following + equation: + + d = distance from light position to vertex position + falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * QUADRATIC) + + Thinking about an ambient light with a falloff can be tricky. If you want a + region of your scene to be ambient lit with one color and another region to + be ambient lit with another color, you could 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. + examples: + - |- + size(400, 400, P3D); + noStroke(); + background(0); + lightFalloff(1.0, 0.001, 0.0); + pointLight(150, 250, 150, 200, 200, 200); + beginShape(); + vertex(0, 0, 0); + vertex(400, 0, -400); + vertex(400, 400, -400); + vertex(0, 400, 0); + endShape(CLOSE); + fileName: lightFalloff_ + parameters: + constant: + desc: constant value or determining falloff + type: + - float + linear: + desc: linear value for determining falloff + type: + - float + quadratic: + desc: quadratic value for determining falloff + type: + - float + returns: void + syntax: + - lightFalloff(constant, linear, quadratic) type: function lightSpecular: - description: 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 preferred 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. - docUrl: https://processing.org/reference/lightSpecular_.html - name: null - parameters: - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: lightSpecular(v1, v2, v3) + description: |- + 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 preferred 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. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + directionalLight(102, 102, 102, 0, 0, -1); + lightSpecular(204, 204, 204); + directionalLight(102, 102, 102, 0, 1, -1); + lightSpecular(102, 102, 102); + translate(80, 200, 0); + specular(51, 51, 51); + sphere(120); + translate(240, 0, 0); + specular(102, 102, 102); + sphere(120); + fileName: lightSpecular_ + parameters: + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - lightSpecular(v1, v2, v3) type: function lights: - description: 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. - docUrl: https://processing.org/reference/lights_.html - name: null + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + // Sets the default ambient + // and directional light + lights(); + translate(80, 200, 0); + sphere(120); + translate(240, 0, 0); + sphere(120); + - |- + void setup() { + size(400, 400, P3D); + background(0); + noStroke(); + } + + void draw() { + // Include lights() at the beginning + // of draw() to keep them persistent + lights(); + translate(80, 200, 0); + sphere(120); + translate(240, 0, 0); + sphere(120); + } + fileName: lights_ parameters: {} returns: void - syntax: lights() + syntax: + - lights() type: function line: - description: 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. - docUrl: https://processing.org/reference/line_.html - name: null - parameters: - x1: "float: x-coordinate of the first point" - x2: "float: x-coordinate of the second point" - y1: "float: y-coordinate of the first point" - y2: "float: y-coordinate of the second point" - z1: "float: z-coordinate of the first point" - z2: "float: z-coordinate of the second point" - returns: void - syntax: |- - line(x1, y1, x2, y2) - line(x1, y1, z1, x2, y2, z2) + description: |- + 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. + examples: + - |- + size(400, 400); + line(120, 80, 340, 300); + - |- + size(400, 400); + line(120, 80, 340, 80); + stroke(126); + line(340, 80, 340, 300); + stroke(255); + line(340, 300, 120, 300); + - |- + // Drawing lines in 3D requires P3D + // as a parameter to size() + size(400, 400, P3D); + line(120, 80, 0, 340, 80, 60); + stroke(126); + line(340, 80, 60, 340, 300, 0); + stroke(255); + line(340, 300, 0, 120, 300, -200); + fileName: line_ + parameters: + x1: + desc: x-coordinate of the first point + type: + - float + x2: + desc: x-coordinate of the second point + type: + - float + y1: + desc: y-coordinate of the first point + type: + - float + y2: + desc: y-coordinate of the second point + type: + - float + z1: + desc: z-coordinate of the first point + type: + - float + z2: + desc: z-coordinate of the second point + type: + - float + returns: void + syntax: + - line(x1, y1, x2, y2) + - line(x1, y1, z1, x2, y2, z2) type: function loadBytes: - description: >- + description: |- Reads the contents of a file and places it in a byte array. If the name of - the file is used as the parameter, as in the above example, the file must be - loaded in the sketch's "data" directory/folder. - - - Alternatively, the file maybe be loaded from anywhere on the local computer using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows), or the filename parameter can be a URL for a file found on a network. - - - 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. - docUrl: https://processing.org/reference/loadBytes_.html - name: null - parameters: - filename: "String: name of a file in the data folder or a URL." + the file is used as the parameter, as in the above example, the file must + be loaded in the sketch's "data" directory/folder. + + Alternatively, the file maybe be loaded from anywhere on the local computer + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows), or the filename parameter can be a URL for a + file found on a network. + + 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`. + examples: + - | + // Open a file and read its binary data + byte b[] = loadBytes("something.dat"); + + // Print each value, from 0 to 255 + for (int i = 0; i < b.length; i++) { + // Every tenth number, start a new line + if ((i % 10) == 0) { + println(); + } + // bytes are from -128 to 127, this converts to 0 to 255 + int a = b[i] & 0xff; + print(a + " "); + } + // Print a blank line at the end + println(); + fileName: loadBytes_ + parameters: + filename: + desc: name of a file in the data folder or a URL. + type: + - String returns: byte[] - syntax: loadBytes(filename) + syntax: + - loadBytes(filename) type: function loadFont: - description: >- - Loads a .vlw formatted font into a `PFont` object. Create a .vlw font by - selecting "Create Font..." from the Tools menu. This tool creates a texture - for each alphanumeric character and then adds them as a .vlw file to the - current sketch's data folder. Because the letters are defined as textures - (and not vector data) the size at which the fonts are created must be - considered in relation to the size at which they are drawn. For example, - load a 32pt font if the sketch displays the font at 32 pixels or smaller. - Conversely, if a 12pt font is loaded and displayed at 48pts, the letters - will be distorted because the program will be stretching a small graphic to - a large size. - - - 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. It's recommended to load files inside `setup()` - - - To load correctly, fonts must be l. . . - docUrl: https://processing.org/reference/loadFont_.html - name: null - parameters: - filename: "String: name of the font to load" + description: |- + Loads a .vlw formatted font into a `PFont` object. Create a .vlw font + by selecting "Create Font..." from the Tools menu. This tool creates a + texture for each alphanumeric character and then adds them as a .vlw file + to the current sketch's data folder. Because the letters are defined as + textures (and not vector data) the size at which the fonts are created must + be considered in relation to the size at which they are drawn. For example, + load a 32pt font if the sketch displays the font at 32 pixels or smaller. + Conversely, if a 12pt font is loaded and displayed at 48pts, the letters + will be distorted because the program will be stretching a small graphic to + a large size. + + 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. It's recommended to load files + inside `setup()` + + To load correctly, fonts must be located in the "data" folder of the + current sketch. Alternatively, the file maybe be loaded from anywhere on + the local computer using an absolute path (something that starts with / on + Unix and Linux, or a drive letter on Windows), or the filename parameter + can be a URL for a file found on a network. + + 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`. + + Use `createFont()` (instead of `loadFont()`) to enable vector + data to be used with the default renderer setting. This can be helpful when + many font sizes are needed, or when using any renderer based on the default + renderer, such as the PDF library. + examples: + - |- + size(400, 400); + PFont font; + // The font must be located in the sketch's + // "data" directory to load successfully + font = loadFont("LetterGothicStd.otf"); + textFont(font, 128); + text("word", 50, 200); + fileName: loadFont_ + parameters: + filename: + desc: name of the font to load + type: + - String returns: PFont - syntax: loadFont(filename) + syntax: + - loadFont(filename) type: function loadImage: - description: >- - 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. Images cannot be loaded outside `setup()` unless they're inside a function that's called after `setup()` has already run. - - - Alternatively, the file maybe be loaded from anywhere on the local computer using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows), or the filename parameter can be a URL for a file found on a network. + description: |- + 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. Images cannot be loaded outside `setup()` unless + they're inside a function that's called after `setup()` has already + run. + + Alternatively, the file maybe be loaded from anywhere on the local computer + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows), or the filename parameter can be a URL for a + file found on a network. + + 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`. + + The `extension` parameter is used to determine the image type in cases + where the image filename does not end with a proper extension. Specify the + extension as the second parameter to `loadImage()`, as shown in the + third example on this page. Note that CMYK images are not supported. + + Depending on the type of error, a `PImage` object may still be + returned, but the width and height of the image will be set to -1. This + happens if bad image data is returned or cannot be decoded properly. + Sometimes this happens with image URLs that produce a 403 error or that + redirect to a password prompt, because `loadImage()` will attempt to + interpret the HTML as image data. + examples: + - |- + size(400,400); + PImage img; + img = loadImage("shells.jpg"); + image(img, 0, 0); + - |- + PImage img; + + void setup() { + size(400,400); + img = loadImage("shells.jpg"); + } + void draw() { + image(img, 0, 0); + } + - |- + PImage webImg; + + void setup() { + size(400,400); + String url = "https://processing.org/img/processing-web.png"; + // Load image from a web server + webImg = loadImage(url, "png"); + } - 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 wh. . . - docUrl: https://processing.org/reference/loadImage_.html - name: null - parameters: - extension: 'String: type of image to load, for example "png", "gif", "jpg"' - filename: "String: name of file to load, can be .gif, .jpg, .tga, or a handful - of other image types depending on your platform" + void draw() { + background(0); + image(webImg, 0, 0); + } + fileName: loadImage_ + parameters: + extension: + desc: type of image to load, for example "png", "gif", "jpg" + type: + - String + filename: + desc: |- + name of file to load, can be .gif, .jpg, .tga, or a handful of + other image types depending on your platform + type: + - String returns: PImage - syntax: |- - loadImage(filename) - loadImage(filename, extension) + syntax: + - loadImage(filename) + - loadImage(filename, extension) type: function loadJSONArray: - description: >- + description: |- Loads an array of JSON objects from the data folder or a URL, and returns a - `JSONArray`. Per standard JSON syntax, the array must be enclosed in a pair - of hard brackets `[]`, and each object within the array must be separated by - a comma. + `JSONArray`. Per standard JSON syntax, the array must be enclosed in a + pair of hard brackets `[]`, and each object within the array must be + separated by a comma. + + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - | + // The following short JSON file called "data.json" is parsed + // in the code below. It must be in the project's "data" folder. + + /* + [ + { + "id": 0, + "species": "Capra hircus", + "name": "Goat" + }, + { + "id": 1, + "species": "Panthera pardus", + "name": "Leopard" + }, + { + "id": 2, + "species": "Equus zebra", + "name": "Zebra" + } + ] + */ + + JSONArray values; + + void setup() { + + values = loadJSONArray("data.json"); + for (int i = 0; i < values.size(); i++) { - All files loaded and saved by the Processing API use UTF-8 encoding. - docUrl: https://processing.org/reference/loadJSONArray_.html - name: null + JSONObject animal = values.getJSONObject(i); + + int id = animal.getInt("id"); + String species = animal.getString("species"); + String name = animal.getString("name"); + + println(id + ", " + species + ", " + name); + } + } + + // Sketch prints: + // 0, Capra hircus, Goat + // 1, Panthera pardus, Leopard + // 2, Equus zebra, Zebra + fileName: loadJSONArray_ parameters: - filename: "String: name of a file in the data folder or a URL" + filename: + desc: name of a file in the data folder or a URL + type: + - String returns: JSONArray - syntax: |- - loadJSONArray(filename) - loadJSONArray(file) + syntax: + - loadJSONArray(filename) + - loadJSONArray(file) type: function loadJSONObject: description: |- - Loads a JSON from the data folder or a URL, and returns a `JSONObject`. + Loads a JSON from the data folder or a URL, and returns a + `JSONObject`. + + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - | + // The following short JSON file called "data.json" is parsed + // in the code below. It must be in the project's "data" folder. + + /* + { + "id": 0, + "species": "Panthera leo", + "name": "Lion" + } + */ + + JSONObject json; + + void setup() { - All files loaded and saved by the Processing API use UTF-8 encoding. - docUrl: https://processing.org/reference/loadJSONObject_.html - name: null + json = loadJSONObject("data.json"); + + int id = json.getInt("id"); + String species = json.getString("species"); + String name = json.getString("name"); + + println(id + ", " + species + ", " + name); + } + + // Sketch prints: + // 0, Panthera leo, Lion + fileName: loadJSONObject_ parameters: - filename: "String: name of a file in the data folder or a URL" + filename: + desc: name of a file in the data folder or a URL + type: + - String returns: JSONObject - syntax: loadJSONObject(filename) + syntax: + - loadJSONObject(filename) type: function loadPixels: - description: Loads the pixel data of the current display window into the - `pixels[]` array. This function must always be called before reading from or - writing to `pixels[]`. Subsequent changes to the display window will not be - reflected in `pixels` until `loadPixels()` is called again. - docUrl: https://processing.org/reference/loadPixels_.html - name: null + description: |- + Loads the pixel data of the current display window into the `pixels[]` + array. This function must always be called before reading from or writing + to `pixels[]`. Subsequent changes to the display window will not be + reflected in `pixels` until `loadPixels()` is called again. + examples: + - |- + size(400,400); + int halfImage = width*height/2; + PImage myImage = loadImage("mt-fuji.jpg"); + image(myImage, 0, 0); + + loadPixels(); + for (int i = 0; i < halfImage; i++) { + pixels[i+halfImage] = pixels[i]; + } + updatePixels(); + fileName: loadPixels_ parameters: {} returns: void - syntax: loadPixels() + syntax: + - loadPixels() type: function loadShader: - description: >- - Loads a shader into the PShader object. The shader file must be loaded in - the sketch's "data" folder/directory to load correctly. Shaders are - compatible with the P2D and P3D renderers, but not with the default - renderer. - - - Alternatively, the file maybe be loaded from anywhere on the local computer using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows), or the filename parameter can be a URL for a file found on a network. - + description: |- + Loads a shader into the `PShader` object. The shader file must be + loaded in the sketch's "data" folder/directory to load correctly. + Shaders are compatible with the P2D and P3D renderers, but not + with the default renderer. + + Alternatively, the file maybe be loaded from anywhere on the local + computer using an absolute path (something that starts with / on + Unix and Linux, or a drive letter on Windows), or the filename + parameter can be a URL for a file found on a network. + + 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. + examples: + - | + PShader blur; + + void setup() { + size(640, 360, P2D); + // Shaders files must be in the "data" folder to load correctly + blur = loadShader("blur.glsl"); + stroke(0, 102, 153); + rectMode(CENTER); + } - 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. - docUrl: https://processing.org/reference/loadShader_.html - name: null - parameters: - fragFilename: "String: name of fragment shader file" - vertFilename: "String: name of vertex shader file" + void draw() { + filter(blur); + rect(mouseX-75, mouseY, 150, 150); + ellipse(mouseX+75, mouseY, 150, 150); + } + fileName: loadShader_ + parameters: + fragFilename: + desc: name of fragment shader file + type: + - String + vertFilename: + desc: name of vertex shader file + type: + - String returns: PShader - syntax: |- - loadShader(fragFilename) - loadShader(fragFilename, vertFilename) + syntax: + - loadShader(fragFilename) + - loadShader(fragFilename, vertFilename) type: function loadShape: - description: >- - Loads geometry into a variable of type `PShape`. SVG and OBJ files may be - loaded. To load correctly, the file must be located in the data directory of - the current sketch. In most cases, `loadShape()` should be used inside - `setup()` because loading shapes inside `draw()` will reduce the speed of a - sketch. - - - Alternatively, the file maybe be loaded from anywhere on the local computer using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows), or the filename parameter can be a URL for a file found on a network. + description: |- + Loads geometry into a variable of type `PShape`. SVG and OBJ + files may be loaded. To load correctly, the file must be located + in the data directory of the current sketch. In most cases, + `loadShape()` should be used inside `setup()` because + loading shapes inside `draw()` will reduce the speed of a sketch. + + Alternatively, the file maybe be loaded from anywhere on the local + computer using an absolute path (something that starts with / on + Unix and Linux, or a drive letter on Windows), or the filename + parameter can be a URL for a file found on a network. + + 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. + examples: + - |- + + PShape s; + + void setup() { + size(400, 400); + // The file "bot.svg" must be in the data folder + // of the current sketch to load successfully + s = loadShape("bot.svg"); + } + void draw() { + shape(s, 40, 40, 320, 320); + } + - |- + PShape s; + + void setup() { + size(400, 400, P3D); + // The file "bot.obj" must be in the data folder + // of the current sketch to load successfully + s = loadShape("bot.obj"); + } - 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. - docUrl: https://processing.org/reference/loadShape_.html - name: null + void draw() { + background(204); + translate(width/2, height/2); + shape(s, 0, 0); + } + fileName: loadShape_ parameters: - filename: "String: name of file to load, can be .svg or .obj" + filename: + desc: name of file to load, can be .svg or .obj + type: + - String returns: PShape - syntax: loadShape(filename) + syntax: + - loadShape(filename) type: function loadStrings: - description: >- + description: |- Reads the contents of a file and creates a String array of its individual - lines. If the name of the file is used as the parameter, as in the above - example, the file must be loaded in the sketch's "data" directory/folder. + lines. If the name of the file is used as the parameter, as in the above + example, the file must be loaded in the sketch's "data" directory/folder. + + + Alternatively, the file maybe be loaded from anywhere on the local computer + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows), or the filename parameter can be a URL for a + file found on a network. + + 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. + examples: + - | + String[] lines = loadStrings("list.txt"); + println("there are " + lines.length + " lines"); + for (int i = 0 ; i < lines.length; i++) { + println(lines[i]); + } + - | + String[] lines = loadStrings("http://processing.org/about/index.html"); + println("there are " + lines.length + " lines"); + for (int i = 0 ; i < lines.length; i++) { + println(lines[i]); + } + fileName: loadStrings_ + parameters: + filename: + desc: name of the file or url to load + type: + - String + returns: String[] + syntax: + - loadStrings(filename) + - loadStrings(reader) + type: function +loadTable: + description: |- + Reads the contents of a file or URL and creates a Table object with its + values. If a file is specified, it must be located in the sketch's "data" + folder. The filename parameter can also be a URL to a file found online. + The filename must either end in an extension or an extension must be + specified in the `options` parameter. For example, to use + tab-separated data, include "tsv" in the options parameter if the filename + or URL does not end in `.tsv`. Note: If an extension is in both + places, the extension in the `options` is used. + If the file contains a header row, include "header" in the `options` + parameter. If the file does not have a header row, then simply omit the + "header" option. - Alternatively, the file maybe be loaded from anywhere on the local computer using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows), or the filename parameter can be a URL for a file found on a network. + Some CSV files contain newline (CR or LF) characters inside cells. This is + rare, but adding the "newlines" option will handle them properly. (This is + not enabled by default because the parsing code is much slower.) + When specifying multiple options, separate them with commas, as in: + `loadTable("data.csv", "header, tsv")` - 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. + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - | + // The following short CSV file called "mammals.csv" is parsed + // in the code below. It must be in the project's "data" folder. + // + // id,species,name + // 0,Capra hircus,Goat + // 1,Panthera pardus,Leopard + // 2,Equus zebra,Zebra + Table table; - 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 plat. . . - docUrl: https://processing.org/reference/loadStrings_.html - name: null - parameters: - filename: "String: name of the file or url to load" - returns: String[] - syntax: |- - loadStrings(filename) - loadStrings(reader) - type: function -loadTable: - description: >- - Reads the contents of a file or URL and creates an Table object with its - values. If a file is specified, it must be located in the sketch's "data" - folder. The filename parameter can also be a URL to a file found online. The - filename must either end in an extension or an extension must be specified - in the `options` parameter. For example, to use tab-separated data, include - "tsv" in the options parameter if the filename or URL does not end in - `.tsv`. Note: If an extension is in both places, the extension in the - `options` is used. + void setup() { + + table = loadTable("mammals.csv", "header"); + println(table.getRowCount() + " total rows in table"); - If the file contains a header row, include "header" in the `options` parameter. If the file does not have a header row, then simply omit the "header" option. + for (TableRow row : table.rows()) { + int id = row.getInt("id"); + String species = row.getString("species"); + String name = row.getString("name"); - Some CSV files contain newline (CR or LF) characters inside cells. This is rare, but adding the "newlines" option will handle them properly. (This is not enabled by default because the parsing code is much slower.) + println(name + " (" + species + ") has an ID of " + id); + } + } - When specifying multiple options, separate them with commas, as in: `loadTable("data.csv",. . . - docUrl: https://processing.org/reference/loadTable_.html - name: null - parameters: - filename: "String: name of a file in the data folder or a URL." - options: 'String: may contain "header", "tsv", "csv", or "bin" separated by commas' + // Sketch prints: + // 3 total rows in table + // Goat (Capra hircus) has an ID of 0 + // Leopard (Panthera pardus) has an ID of 1 + // Zebra (Equus zebra) has an ID of 2 + fileName: loadTable_ + parameters: + filename: + desc: name of a file in the data folder or a URL. + type: + - String + options: + desc: may contain "header", "tsv", "csv", or "bin" separated by commas + type: + - String returns: Table - syntax: |- - loadTable(filename) - loadTable(filename, options) + syntax: + - loadTable(filename) + - loadTable(filename, options) type: function loadXML: - description: >- - Reads the contents of a file or URL and creates an XML object with its - values. If a file is specified, it must be located in the sketch's "data" - folder. The filename parameter can also be a URL to a file found online. - + description: |- + Reads the contents of a file or URL and creates an XML + object with its values. If a file is specified, it must + be located in the sketch's "data" folder. The filename + parameter can also be a URL to a file found online. + All files loaded and saved by the Processing API use + UTF-8 encoding. If you need to load an XML file that's + not in UTF-8 format, see the + developer's reference for the XML object. + examples: + - | + // The following short XML file called "mammals.xml" is parsed + // in the code below. It must be in the project's "data" folder. + // + // + // + // Goat + // Leopard + // Zebra + // + + XML xml; + + void setup() { + xml = loadXML("mammals.xml"); + XML[] children = xml.getChildren("animal"); + + for (int i = 0; i < children.length; i++) { + int id = children[i].getInt("id"); + String coloring = children[i].getString("species"); + String name = children[i].getContent(); + println(id + ", " + coloring + ", " + name); + } + } - All files loaded and saved by the Processing API use UTF-8 encoding. If you need to load an XML file that's not in UTF-8 format, see the developer's reference for the XML object. - docUrl: https://processing.org/reference/loadXML_.html - name: null + // Sketch prints: + // 0, Capra hircus, Goat + // 1, Panthera pardus, Leopard + // 2, Equus zebra, Zebra + fileName: loadXML_ parameters: - filename: "String: name of a file in the data folder or a URL." + filename: + desc: name of a file in the data folder or a URL. + type: + - String returns: XML - syntax: loadXML(filename) + syntax: + - loadXML(filename) type: function log: - description: Calculates the natural logarithm (the base-e logarithm) of a - number. This function expects the `n` parameter to be a value greater than - 0.0. - docUrl: https://processing.org/reference/log_.html - name: null + description: |- + Calculates the natural logarithm (the base-e logarithm) of a + number. This function expects the values greater than 0.0. + examples: + - | + void setup() { + int i = 12; + println(log(i)); + println(log10(i)); + } + + // Calculates the base-10 logarithm of a number + float log10 (int x) { + return (log(x) / log(10)); + } + fileName: log_ parameters: - n: "float: number greater than 0.0" + n: + desc: number greater than 0.0 + type: + - float returns: float - syntax: log(n) + syntax: + - log(n) + type: function +long: + description: Datatype for large integers. While integers can be as large as + 2,147,483,647 and as low as -2,147,483,648 (stored as 32 bits), a `long` + integer has a minimum value of -9,223,372,036,854,775,808 and a maximum + value of 9,223,372,036,854,775,807 (stored as 64 bits). Use this datatype + when you need a number to have a greater magnitude than can be stored within + an `int`. When assigning literal values that are larger than this magnitude, + it is necessary to also append the qualifier "L" to the number, as shown in + the example above. Processing functions don't use this datatype, so while + they work in the language, you'll usually have to convert to a `int` using + the `(int)` syntax before passing into a function. + examples: + - > + long a; // Declare variable 'a' of type long and assign a large + value: + + //a = 2147483648; // Error: The literal of type int is out of range + + a = 2147483648L; // Instead, add an "L" to the number to mark it as a + long + + + long b = -256; // Declare variable 'b' and assign it the value -256 + + long c = a + b; // Declare variable 'c' and assign it the sum of 'a' and + 'b' + + int i = (int)c; // Converts the value of 'c' from a long to an int + fileName: long + parameters: + value: + desc: any integer value + type: [] + var: + desc: variable name referencing the value + type: [] + returns: "" + syntax: + - long var + - long var = value type: function loop: - description: By default, Processing loops through `draw()` continuously, - executing the code within it. However, the `draw()` loop may be stopped by - calling `noLoop()`. In that case, the `draw()` loop can be resumed with - `loop()`. - docUrl: https://processing.org/reference/loop_.html - name: null + description: |- + By default, Processing loops through `draw()` continuously, executing + the code within it. However, the `draw()` loop may be stopped by calling + `noLoop()`. In that case, the `draw()` loop can be resumed with + `loop()`. + examples: + - | + void setup() { + size(200, 200); + noLoop(); // draw() will not loop + } + + float x = 0; + + void draw() { + background(204); + x = x + .1; + if (x > width) { + x = 0; + } + line(x, 0, x, height); + } + + void mousePressed() { + loop(); // Holding down the mouse activates looping + } + + void mouseReleased() { + noLoop(); // Releasing the mouse stops looping draw() + } + fileName: loop_ parameters: {} returns: void - syntax: loop() + syntax: + - loop() type: function mag: - description: 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 the coordinate 0,0 to its x,y value. Therefore, - `mag()` is a shortcut for writing `dist(0, 0, x, y)`. - docUrl: https://processing.org/reference/mag_.html - name: null - parameters: - a: "float: first value" - b: "float: second value" - c: "float: third value" + description: |- + 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)`. + examples: + - |- + size(400, 400); + + float x1 = 80; + float x2 = 320; + float y1 = 120; + float y2 = 280; + + line(0, 0, x1, y1); + println(mag(x1, y1)); // Prints "144.22205" + line(0, 0, x2, y1); + println(mag(x2, y1)); // Prints "341.76016" + line(0, 0, x1, y2); + println(mag(x1, y2)); // Prints "291.2044" + line(0, 0, x2, y2); + println(mag(x2, y2)); // Prints "425.20584" + fileName: mag_ + parameters: + a: + desc: first value + type: + - float + b: + desc: second value + type: + - float + c: + desc: third value + type: + - float returns: float - syntax: |- - mag(a, b) - mag(a, b, c) + syntax: + - mag(a, b) + - mag(a, b, c) type: function map: - description: >- + description: |- Re-maps a number from one range to another. + In the first example above, the number 25 is converted from a value in the + range of 0 to 100 into a value that ranges from the left edge of the window + (0) to the right edge (width). + + As shown in the second example, numbers outside the range are + not clamped to the minimum and maximum parameters values, + because out-of-range values are often intentional and useful. + examples: + - | + size(200, 200); + float value = 25; + float m = map(value, 0, 100, 0, width); + ellipse(m, 200, 10, 10); + - | + float value = 110; + float m = map(value, 0, 100, -20, -10); + println(m); // Prints "-9.0" + - | + void setup() { + size(200, 200); + noStroke(); + } - In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge (width). - - - As shown in the second example, numbers outside of the range are not clamped to the minimum and maximum parameters values, because out-of-range values are often intentional and useful. - docUrl: https://processing.org/reference/map_.html - name: null - parameters: - start1: "float: lower bound of the value's current range" - start2: "float: lower bound of the value's target range" - stop1: "float: upper bound of the value's current range" - stop2: "float: upper bound of the value's target range" - value: "float: the incoming value to be converted" + void draw() { + background(204); + float x1 = map(mouseX, 0, width, 50, 150); + ellipse(x1, 75, 50, 50); + float x2 = map(mouseX, 0, width, 0, 200); + ellipse(x2, 125, 50, 50); + } + fileName: map_ + parameters: + start1: + desc: lower bound of the value's current range + type: + - float + start2: + desc: lower bound of the value's target range + type: + - float + stop1: + desc: upper bound of the value's current range + type: + - float + stop2: + desc: upper bound of the value's target range + type: + - float + value: + desc: the incoming value to be converted + type: + - float returns: float - syntax: map(value, start1, stop1, start2, stop2) + syntax: + - map(value, start1, stop1, start2, stop2) + type: function +mask: + description: |- + 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. + fileName: mask_ + parameters: + img: + desc: image to use as the mask + type: + - PImage + returns: void + syntax: + - mask(img) type: function match: description: >- This 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. If there are no matches, a null value will be returned. If no groups - are specified in the regular expression, but the sequence matches, an array - of length 1 (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 at all. If the sequence did match, an array is returned. - - - If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Element [0] of a regular expression 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). - + return matching groups (elements found inside parentheses) as a String + array. If there are no matches, a `null` value will be returned. If no groups + are specified in the regular expression, but the sequence matches, an array + of length 1 (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 at all. If the sequence did + match, an array is returned. + + If there are groups (specified by sets of parentheses) in the regular + expression, then the contents of each will be returned in the array. + Element [0] of a regular expression 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. + examples: + - | + String s = "Inside a tag, you will find content."; + String[] m = match(s, "(.*?)"); + println("Found '" + m[1] + "' inside the tag."); + // Prints to the console: + // "Found 'content' inside the tag." + - | + String s1 = "Have you ever heard of a thing called fluoridation. "; + s1 += "Fluoridation of water?"; + String s2 = "Uh? Yes, I-I have heard of that, Jack, yes. Yes."; + + String[] m1 = match(s1, "fluoridation"); + if (m1 != null) { // If not null, then a match was found + // This will print to the console, since a match was found. + println("Found a match in '" + s1 + "'"); + } else { + println("No match found in '" + s1 + "'"); + } - The syntax can be found in the reference for Java's Pattern class. For regular expression syntax, read the Java Tutorial on. . . - docUrl: https://processing.org/reference/match_.html - name: null - parameters: - regexp: "String: the regexp to be used for matching" - str: "String: the String to be searched" + String[] m2 = match(s2, "fluoridation"); + if (m2 != null) { + println("Found a match in '" + s2 + "'"); + } else { + // This will print to the console, since no match was found. + println("No match found in '" + s2 + "'"); + } + fileName: match_ + parameters: + regexp: + desc: the regexp to be used for matching + type: + - String + str: + desc: the String to be searched + type: + - String returns: String[] - syntax: match(str, regexp) + syntax: + - match(str, regexp) type: function matchAll: - description: >- - 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. If there are no matches, a null value will be - returned. If no groups are specified in the regular expression, 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 regular expression, then the contents of each will be returned in the array. Assuming a loop with counter variable i, element [i][0] of a regular expression 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). - + description: |- + 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. If there are no matches, a `null` + value will be returned. If no groups are specified in the regular + expression, 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 regular + expression, then the contents of each will be returned in the array. + Assuming a loop with counter variable i, element [i][0] of a regular + expression 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. + examples: + - | + String s = "Inside tags, you will find multiple< /tag>"; + s += "pieces of content."; + + String[][] m = matchAll(s, "(.*?)"); + for (int i = 0; i < m.length; i++) { + println("Found '" + m[i][1] + "' inside a tag."); + } - The syntax can be found in the reference for Jav. . . - docUrl: https://processing.org/reference/matchAll_.html - name: null - parameters: - regexp: "String: the regexp to be used for matching" - str: "String: the String to be searched" + // Prints to the console: + // "Found 'multiple' inside a tag." + // "Found 'pieces' inside a tag." + // "Found 'content' inside a tag." + fileName: matchAll_ + parameters: + regexp: + desc: the regexp to be used for matching + type: + - String + str: + desc: the String to be searched + type: + - String returns: String[][] - syntax: matchAll(str, regexp) + syntax: + - matchAll(str, regexp) type: function max: - description: Determines the largest value in a sequence of numbers, and then - returns that value. `max()` accepts either two or three `float` or `int` - values as parameters, or an array of any length. - docUrl: https://processing.org/reference/max_.html - name: null - parameters: - a: "float, or int: first number to compare" - b: "float, or int: second number to compare" - c: "float, or int: third number to compare" - list: "float[], or int[]: array of numbers to compare" + description: |- + Determines the largest value in a sequence of numbers, and then returns that + value. `max()` accepts either two or three `float` or `int` + values as parameters, or an array of any length. + examples: + - | + int a = max(5, 9); // Sets 'a' to 9 + int b = max(-4, -12); // Sets 'b' to -4 + float c = max(12.3, 230.24); // Sets 'c' to 230.24 + - | + int[] values = { 9, -4, 362, 21 }; // Create an array of ints + int d = max(values); // Sets 'd' to 362 + fileName: max_ + parameters: + a: + desc: first number to compare + type: + - int + - float + b: + desc: second number to compare + type: + - int + - float + c: + desc: third number to compare + type: + - int + - float + list: + desc: array of numbers to compare + type: + - int[] + - float[] returns: int or float - syntax: |- - max(a, b) - max(a, b, c) - max(list) + syntax: + - max(a, b) + - max(a, b, c) + - max(list) type: function millis: - description: Returns the number of milliseconds (thousandths of a second) since - starting the program. This information is often used for timing events and - animation sequences. - docUrl: https://processing.org/reference/millis_.html - name: null + description: |- + Returns the number of milliseconds (thousandths of a second) since + starting the sketch. This information is often used for timing animation + sequences. + examples: + - | + void draw() { + int m = millis(); + noStroke(); + fill(m % 255); + rect(25, 25, 50, 50); + } + fileName: millis_ parameters: {} returns: int - syntax: millis() + syntax: + - millis() type: function min: - description: Determines the smallest value in a sequence of numbers, and then - returns that value. `min()` accepts either two or three `float` or `int` - values as parameters, or an array of any length. - docUrl: https://processing.org/reference/min_.html - name: null - parameters: - a: "int, or float: first number" - b: "int, or float: second number" - c: "int, or float: third number" - list: "float[], or int[]: array of numbers to compare" + description: >- + Determines the smallest value in a sequence of numbers, and then returns + that + value. `min()` accepts either two or three `float` or `int` + values as parameters, or an array of any length. + examples: + - | + int d = min(5, 9); // Sets 'd' to 5 + int e = min(-4, -12); // Sets 'e' to -12 + float f = min(12.3, 230.24); // Sets 'f' to 12.3 + - | + int[] values = { 5, 1, 2, -3 }; // Create an array of ints + int h = min(values); // Sets 'h' to -3 + fileName: min_ + parameters: + a: + desc: first number + type: + - float + - int + b: + desc: second number + type: + - float + - int + c: + desc: third number + type: + - float + - int + list: + desc: array of numbers to compare + type: + - int[] + - float[] returns: float or int - syntax: |- - min(a, b) - min(a, b, c) - min(list) + syntax: + - min(a, b) + - min(a, b, c) + - min(list) type: function minute: - description: Processing communicates with the clock on your computer. The - `minute()` function returns the current minute as a value from 0 - 59. - docUrl: https://processing.org/reference/minute_.html - name: null + description: |- + Processing communicates with the clock on your computer. The + `minute()` function returns the current minute as a value from 0 to 59. + examples: + - | + void draw() { + background(204); + int s = second(); // Values from 0 - 59 + int m = minute(); // Values from 0 - 59 + int h = hour(); // Values from 0 - 23 + line(s, 0, s, 33); + line(m, 33, m, 66); + line(h, 66, h, 100); + } + fileName: minute_ parameters: {} returns: int - syntax: minute() + syntax: + - minute() type: function modelX: - description: >- - 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. - docUrl: https://processing.org/reference/modelX_.html - name: null - parameters: - x: "float: 3D x-coordinate to be mapped" - y: "float: 3D y-coordinate to be mapped" - z: "float: 3D z-coordinate to be mapped" + description: |- + 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. + examples: + - | + void setup() { + size(500, 500, P3D); + noFill(); + } + + void draw() { + background(0); + + pushMatrix(); + // start at the middle of the screen + translate(width/2, height/2, -200); + // some random rotation to make things interesting + rotateY(1.0); //yrot); + rotateZ(2.0); //zrot); + // rotate in X a little more each frame + rotateX(frameCount / 100.0); + // offset from center + translate(0, 150, 0); + + // draw a white box outline at (0, 0, 0) + stroke(255); + box(50); + + // the box was drawn at (0, 0, 0), store that location + float x = modelX(0, 0, 0); + float y = modelY(0, 0, 0); + float z = modelZ(0, 0, 0); + // clear out all the transformations + popMatrix(); + + // draw another box at the same (x, y, z) coordinate as the other + pushMatrix(); + translate(x, y, z); + stroke(255, 0, 0); + box(50); + popMatrix(); + } + fileName: modelX_ + parameters: + x: + desc: 3D x-coordinate to be mapped + type: + - float + y: + desc: 3D y-coordinate to be mapped + type: + - float + z: + desc: 3D z-coordinate to be mapped + type: + - float returns: float - syntax: modelX(x, y, z) + syntax: + - modelX(x, y, z) type: function modelY: - description: >- - 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. - + description: |- + 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. + examples: + - | + void setup() { + size(500, 500, P3D); + noFill(); + } - 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. - docUrl: https://processing.org/reference/modelY_.html - name: null - parameters: - x: "float: 3D x-coordinate to be mapped" - y: "float: 3D y-coordinate to be mapped" - z: "float: 3D z-coordinate to be mapped" + void draw() { + background(0); + + pushMatrix(); + // start at the middle of the screen + translate(width/2, height/2, -200); + // some random rotation to make things interesting + rotateY(1.0); //yrot); + rotateZ(2.0); //zrot); + // rotate in X a little more each frame + rotateX(frameCount / 100.0); + // offset from center + translate(0, 150, 0); + + // draw a white box outline at (0, 0, 0) + stroke(255); + box(50); + + // the box was drawn at (0, 0, 0), store that location + float x = modelX(0, 0, 0); + float y = modelY(0, 0, 0); + float z = modelZ(0, 0, 0); + // clear out all the transformations + popMatrix(); + + // draw another box at the same (x, y, z) coordinate as the other + pushMatrix(); + translate(x, y, z); + stroke(255, 0, 0); + box(50); + popMatrix(); + } + fileName: modelY_ + parameters: + x: + desc: 3D x-coordinate to be mapped + type: + - float + y: + desc: 3D y-coordinate to be mapped + type: + - float + z: + desc: 3D z-coordinate to be mapped + type: + - float returns: float - syntax: modelY(x, y, z) + syntax: + - modelY(x, y, z) type: function modelZ: - description: >- - 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. - + description: |- + 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. + examples: + - | + void setup() { + size(500, 500, P3D); + noFill(); + } - 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. - docUrl: https://processing.org/reference/modelZ_.html - name: null - parameters: - x: "float: 3D x-coordinate to be mapped" - y: "float: 3D y-coordinate to be mapped" - z: "float: 3D z-coordinate to be mapped" + void draw() { + background(0); + + pushMatrix(); + // start at the middle of the screen + translate(width/2, height/2, -200); + // some random rotation to make things interesting + rotateY(1.0); //yrot); + rotateZ(2.0); //zrot); + // rotate in X a little more each frame + rotateX(frameCount / 100.0); + // offset from center + translate(0, 150, 0); + + // draw a white box outline at (0, 0, 0) + stroke(255); + box(50); + + // the box was drawn at (0, 0, 0), store that location + float x = modelX(0, 0, 0); + float y = modelY(0, 0, 0); + float z = modelZ(0, 0, 0); + // clear out all the transformations + popMatrix(); + + // draw another box at the same (x, y, z) coordinate as the other + pushMatrix(); + translate(x, y, z); + stroke(255, 0, 0); + box(50); + popMatrix(); + } + fileName: modelZ_ + parameters: + x: + desc: 3D x-coordinate to be mapped + type: + - float + y: + desc: 3D y-coordinate to be mapped + type: + - float + z: + desc: 3D z-coordinate to be mapped + type: + - float returns: float - syntax: modelZ(x, y, z) + syntax: + - modelZ(x, y, z) type: function month: - description: Processing communicates with the clock on your computer. The - `month()` function returns the current month as a value from 1 - 12. - docUrl: https://processing.org/reference/month_.html - name: null + description: |- + Processing communicates with the clock on your computer. The + `month()` function returns the current month as a value from 1 to 12. + examples: + - | + int d = day(); // Values from 1 - 31 + int m = month(); // Values from 1 - 12 + int y = year(); // 2003, 2004, 2005, etc. + + String s = String.valueOf(d); + text(s, 10, 28); + s = String.valueOf(m); + text(s, 10, 56); + s = String.valueOf(y); + text(s, 10, 84); + fileName: month_ parameters: {} returns: int - syntax: month() + syntax: + - month() type: function mouseButton: - description: When a mouse button is pressed, the value of the system variable - `mouseButton` is set to either `LEFT`, `RIGHT`, or `CENTER`, depending on - which button is pressed. (If no button is pressed, `mouseButton` may be - reset to `0`. For that reason, it's best to use `mousePressed` first to test - if any button is being pressed, and only then test the value of - `mouseButton`, as shown in the examples above.) - docUrl: https://processing.org/reference/mouseButton.html - examples: | - // Click within the image and press - // the left and right mouse buttons to - // change the value of the rectangle - void draw() { - if (mousePressed && (mouseButton == LEFT)) { - fill(0); - } else if (mousePressed && (mouseButton == RIGHT)) { - fill(255); - } else { - fill(126); + description: |- + When a mouse button is pressed, the value of the system variable + `mouseButton` is set to either `LEFT`, `RIGHT`, or + `CENTER`, depending on which button is pressed. (If no button is + pressed, `mouseButton` may be reset to `0`. For that reason, + it's best to use `mousePressed` first to test if any button is being + pressed, and only then test the value of `mouseButton`, as shown in + the examples above.) + examples: + - | + // Click within the image and press + // the left and right mouse buttons to + // change the value of the rectangle + void draw() { + if (mousePressed && (mouseButton == LEFT)) { + fill(0); + } else if (mousePressed && (mouseButton == RIGHT)) { + fill(255); + } else { + fill(126); + } + rect(25, 25, 50, 50); + } + - | + // Click within the image and press + // the left and right mouse buttons to + // change the value of the rectangle + void draw() { + rect(25, 25, 50, 50); } - rect(25, 25, 50, 50); - } - - - // Click within the image and press - // the left and right mouse buttons to - // change the value of the rectangle - void draw() { - rect(25, 25, 50, 50); - } - void mousePressed() { - if (mouseButton == LEFT) { - fill(0); - } else if (mouseButton == RIGHT) { - fill(255); - } else { - fill(126); + void mousePressed() { + if (mouseButton == LEFT) { + fill(0); + } else if (mouseButton == RIGHT) { + fill(255); + } else { + fill(126); + } } - } - name: null + fileName: mouseButton type: var mouseClicked: - description: >- - The `mouseClicked()` function is called after a mouse button has been - pressed and then released. - + description: |- + The `mouseClicked()` function is called after a mouse button + has been pressed and then released. + + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - | + // Click within the image to change + // the value of the rectangle after + // after the mouse has been clicked + + int value = 0; + + void draw() { + fill(value); + rect(25, 25, 50, 50); + } - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/mouseClicked_.html - name: null + void mouseClicked() { + if (value == 0) { + value = 255; + } else { + value = 0; + } + } + fileName: mouseClicked_ parameters: {} returns: void - syntax: |- - mouseClicked() - mouseClicked(event) + syntax: + - mouseClicked() + - mouseClicked(event) type: function mouseDragged: - description: >- - The `mouseDragged()` function is called once every time the mouse moves - while a mouse button is pressed. (If a button is not being pressed, - `mouseMoved()` is called instead.) - + description: |- + The `mouseDragged()` function is called once every time the mouse + moves while a mouse button is pressed. (If a button is not being + pressed, `mouseMoved()` is called instead.) + + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - | + // Drag (click and hold) your mouse across the + // image to change the value of the rectangle + + int value = 0; + + void draw() { + fill(value); + rect(25, 25, 50, 50); + } - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/mouseDragged_.html - name: null + void mouseDragged() + { + value = value + 5; + if (value > 255) { + value = 0; + } + } + fileName: mouseDragged_ parameters: {} returns: void - syntax: |- - mouseDragged() - mouseDragged(event) + syntax: + - mouseDragged() + - mouseDragged(event) type: function mouseMoved: - description: >- - The `mouseMoved()` function is called every time the mouse moves and a mouse - button is not pressed. (If a button is being pressed, `mouseDragged()` is - called instead.) - + description: |- + The `mouseMoved()` function is called every time the mouse moves and a + mouse button is not pressed. (If a button is being pressed, + `mouseDragged()` is called instead.) + + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - | + // Move the mouse across the image + // to change its value + + int value = 0; + + void draw() { + fill(value); + rect(25, 25, 50, 50); + } - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/mouseMoved_.html - name: null + void mouseMoved() { + value = value + 5; + if (value > 255) { + value = 0; + } + } + fileName: mouseMoved_ parameters: {} returns: void - syntax: |- - mouseMoved() - mouseMoved(event) + syntax: + - mouseMoved() + - mouseMoved(event) type: function mousePressed: - description: >- - 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. + description: |- + 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. - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/mousePressed_.html - name: null + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - | + // Click within the image to change + // the value of the rectangle + + int value = 0; + + void draw() { + fill(value); + rect(25, 25, 50, 50); + } + + void mousePressed() { + if (value == 0) { + value = 255; + } else { + value = 0; + } + } + fileName: mousePressed_ parameters: {} returns: void - syntax: |- - mousePressed() - mousePressed(event) + syntax: + - mousePressed() + - mousePressed(event) type: function mouseReleased: - description: >- + description: |- The `mouseReleased()` function is called every time a mouse button is - released. + released. + Mouse and keyboard events only work when a program has `draw()`. + Without `draw()`, the code is only run once and then stops listening + for events. + examples: + - | + // Click within the image to change + // the value of the rectangle - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/mouseReleased_.html - name: null - parameters: {} - returns: void - syntax: |- - mouseReleased() - mouseReleased(event) - type: function -mouseWheel: - description: >- - The code within the `mouseWheel()` event function is run when the mouse - wheel is moved. (Some mice don't have wheels and this function is only - applicable with mice that have a wheel.) The `getCount()` function used - within `mouseWheel()` returns positive values when the mouse wheel is - rotated down (toward the user), and negative values for the other direction - (up or away from the user). On OS X with "natural" scrolling enabled, the - values are opposite. + int value = 0; + + void draw() { + fill(value); + rect(25, 25, 50, 50); + } + + void mouseReleased() { + if (value == 0) { + value = 255; + } else { + value = 0; + } + } + fileName: mouseReleased_ + parameters: {} + returns: void + syntax: + - mouseReleased() + - mouseReleased(event) + type: function +mouseWheel: + description: |- + The code within the `mouseWheel()` event function + is run when the mouse wheel is moved. (Some mice don't + have wheels and this function is only applicable with + mice that have a wheel.) The `getCount()` function + used within `mouseWheel()` returns positive values + when the mouse wheel is rotated down (toward the user), + and negative values for the other direction (up or away + from the user). On OS X with "natural" scrolling enabled, + the values are opposite. + + Mouse and keyboard events only work when a program has + `draw()`. Without `draw()`, the code is only + run once and then stops listening for events. + examples: + - |+ + void setup() { + size(100, 100); + } + void draw() {} - Mouse and keyboard events only work when a program has `draw()`. Without `draw()`, the code is only run once and then stops listening for events. - docUrl: https://processing.org/reference/mouseWheel_.html - name: null + void mouseWheel(MouseEvent event) { + float e = event.getCount(); + println(e); + } + + fileName: mouseWheel_ parameters: - event: "MouseEvent: the MouseEvent" + event: + desc: the MouseEvent + type: + - MouseEvent returns: void - syntax: mouseWheel(event) + syntax: + - mouseWheel(event) type: function mouseX: - description: >- + description: |- The system variable `mouseX` always contains the current horizontal - coordinate of the mouse. - - - Note that Processing can only track the mouse position when the pointer is over the current window. The default value of `mouseX` is `0`, so `0` will be returned until the mouse moves in front of the sketch window. (This typically happens when a sketch is first run.) Once the mouse moves away from the window, `mouseX` will continue to report its most recent position. - docUrl: https://processing.org/reference/mouseX.html - examples: | - void draw() { - background(204); - line(mouseX, 20, mouseX, 80); - } - name: null + coordinate of the mouse. + + Note that Processing can only track the mouse position when the pointer + is over the current window. The default value of `mouseX` is `0`, + so `0` will be returned until the mouse moves in front of the sketch + window. (This typically happens when a sketch is first run.) Once the + mouse moves away from the window, `mouseX` will continue to report + its most recent position. + examples: + - | + void draw() { + background(204); + line(mouseX, 20, mouseX, 80); + } + fileName: mouseX type: var mouseY: - description: >- - The system variable `mouseY` always contains the current vertical coordinate - of the mouse. + description: |- + The system variable `mouseY` always contains the current + vertical coordinate of the mouse. + + Note that Processing can only track the mouse position when the pointer + is over the current window. The default value of `mouseY` is `0`, + so `0` will be returned until the mouse moves in front of the sketch + window. (This typically happens when a sketch is first run.) Once the + mouse moves away from the window, `mouseY` will continue to report + its most recent position. + examples: + - | + void draw() { + background(204); + line(20, mouseY, 80, mouseY); + } + fileName: mouseY + type: var +new: + description: Creates a "new" object. The keyword `new` is typically used + similarly to the applications in the above example. In this example, a new + object "h1" of the datatype "HLine" is created. On the following line, a new + array of floats called "speeds" is created. + examples: + - |+ + HLine h1 = new HLine(); + float[] speeds = new float[3]; + float ypos; + + void setup() { + size(200, 200); + speeds[0] = 0.1; + speeds[1] = 2.0; + speeds[2] = 0.5; + } + void draw() { + ypos += speeds[int(random(3))]; + if (ypos > width) { + ypos = 0; + } + h1.update(ypos); + } - Note that Processing can only track the mouse position when the pointer is over the current window. The default value of `mouseY` is `0`, so `0` will be returned until the mouse moves in front of the sketch window. (This typically happens when a sketch is first run.) Once the mouse moves away from the window, `mouseY` will continue to report its most recent position. - docUrl: https://processing.org/reference/mouseY.html - examples: | - void draw() { - background(204); - line(20, mouseY, 80, mouseY); - } - name: null - type: var + class HLine { + void update(float y) { + line(0, y, width, y); + } + } + + fileName: new + parameters: {} + returns: "" + syntax: [] + type: function nf: - description: "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` and `right` parameters should always be positive - integers. The `left` parameter should be positive or 0. If it is zero, only - the right side is formatted.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." - docUrl: https://processing.org/reference/nf_.html - name: null - parameters: - digits: "int: number of digits to pad with zero" - left: "int: number of digits to the left of the decimal point" - num: "float, or int: the number to format" - nums: "float[], or int[]: the numbers to format" - right: "int: number of digits to the right of the decimal point" + description: |- + 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` and `right` parameters should always be + positive integers. The `left` parameter should be positive or 0. If it + is zero, only the right side is formatted. + + 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. + examples: + - | + int a=200, b=40, c=90; + String sa = nf(a, 10); + println(sa); // Prints "0000000200" + String sb = nf(b, 5); + println(sb); // Prints "00040" + String sc = nf(c, 3); + println(sc); // Prints "090" + + float d = 200.94, e = 40.2, f = 9.012; + String sd = nf(d, 10, 4); + println(sd); // Prints "0000000200.9400" + String se = nf(e, 5, 3); + println(se); // Prints "00040.200" + String sf = nf(f, 3, 5); + println(sf); // Prints "009.01200" + + String sf2 = nf(f, 0, 5); + println(sf2); // Prints "9.01200" + String sf3 = nf(f, 0, 2); + println(sf3); // Prints "9.01" + fileName: nf_ + parameters: + digits: + desc: number of digits to pad with zero + type: + - int + left: + desc: number of digits to the left of the decimal point + type: + - int + num: + desc: the number to format + type: + - int + - float + nums: + desc: the numbers to format + type: + - int[] + - float[] + right: + desc: number of digits to the right of the decimal point + type: + - int returns: String[] - syntax: |- - nf(num) - nf(nums) - nf(nums, digits) - nf(num, digits) - nf(nums, left, right) - nf(num, left, right) + syntax: + - nf(num) + - nf(nums) + - nf(nums, digits) + - nf(num, digits) + - nf(nums, left, right) + - nf(num, left, right) type: function nfc: - description: >- - Utility function for formatting numbers into strings and placing appropriate - commas to mark units of 1000. There are four versions: one for formatting - ints, one for formatting an array of ints, one for formatting floats, and - one for formatting an array of floats. - - - The value for the `right` 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. - docUrl: https://processing.org/reference/nfc_.html - name: null - parameters: - num: "float, or int: the number to format" - nums: "float[], or int[]: the numbers to format" - right: "int: number of digits to the right of the decimal point" + description: |- + Utility function for formatting numbers into strings and placing + appropriate commas to mark units of 1000. There are four versions: one for + formatting ints, one for formatting an array of ints, one for formatting + floats, and one for formatting an array of floats. + + The value for the `right` parameter should always be a positive + integer. + + For a non-US locale, this will insert periods instead of commas, + or whatever is appropriate for that region. + examples: + - |+ + int i = 500000; + String si = nfc(i); + println(si); // Prints "500,000" + float f = 42525.34343; + String fi = nfc(f, 2); + println(fi); // Prints "42,525.34" + + - |+ + int[] i = { 500000, 4000 }; + String[] si = nfc(i); + println(si); // Prints "500,000 4,000" + float[] f = { 42525.34343, 3.14159 }; + String[] fi = nfc(f, 2); + println(fi); // Prints "42,525.34 3.14" + + fileName: nfc_ + parameters: + num: + desc: the number to format + type: + - int + - float + nums: + desc: the numbers to format + type: + - int[] + - float[] + right: + desc: number of digits to the right of the decimal point + type: + - int returns: String[] - syntax: |- - nfc(nums) - nfc(num) - nfc(nums, right) - nfc(num, right) + syntax: + - nfc(nums) + - nfc(num) + - nfc(nums, right) + - nfc(num, right) type: function nfp: - description: '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.' - docUrl: https://processing.org/reference/nfp_.html - name: null - parameters: - digits: "int: number of digits to pad with zeroes" - left: "int: the number of digits to the left of the decimal point" - num: "float, or int: the number to format" - nums: "float[], or int[]: the numbers to format" - right: "int: the number of digits to the right of the decimal point" + description: |- + 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. + examples: + - | + int a=200, b=-40, c=90; + String sa = nfp(a, 10); + println(sa); // Prints "+0000000200" + String sb = nfp(b, 5); + println(sb); // Prints "-00040" + String sc = nfp(c, 3); + println(sc); // Prints "+090" + + float d = -200.94, e = 40.2, f = -9.012; + String sd = nfp(d, 10, 4); + println(sd); // Prints "-0000000200.9400" + String se = nfp(e, 5, 3); + println(se); // Prints "+00040.200" + String sf = nfp(f, 3, 5); + println(sf); // Prints "-009.01200" + fileName: nfp_ + parameters: + digits: + desc: number of digits to pad with zeroes + type: + - int + left: + desc: the number of digits to the left of the decimal point + type: + - int + num: + desc: the number to format + type: + - int + - float + nums: + desc: the numbers to format + type: + - int[] + - float[] + right: + desc: the number of digits to the right of the decimal point + type: + - int returns: String or String[] - syntax: |- - nfp(num, digits) - nfp(nums, digits) - nfp(nums, left, right) - nfp(num, left, right) + syntax: + - nfp(num, digits) + - nfp(nums, digits) + - nfp(nums, left, right) + - nfp(num, left, right) type: function nfs: - description: "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." - docUrl: https://processing.org/reference/nfs_.html - name: null - parameters: - digits: "int: number of digits to pad with zeroes" - left: "int: the number of digits to the left of the decimal point" - num: "float, or int: the number to format" - nums: "float[], or int[]: the numbers to format" - right: "int: the number of digits to the right of the decimal point" + description: |- + 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. + examples: + - | + int a=200, b=-40, c=90; + String sa = nfs(a, 10); + println(sa); // Prints " 0000000200" + String sb = nfs(b, 5); + println(sb); // Prints "-00040" + String sc = nfs(c, 3); + println(sc); // Prints " 090" + + float d = -200.94, e = 40.2, f = -9.012; + String sd = nfs(d, 10, 4); + println(sd); // Prints "-0000000200.9400" + String se = nfs(e, 5, 3); + println(se); // Prints " 00040.200" + String sf = nfs(f, 3, 5); + println(sf); // Prints "-009.01200" + fileName: nfs_ + parameters: + digits: + desc: number of digits to pad with zeroes + type: + - int + left: + desc: the number of digits to the left of the decimal point + type: + - int + num: + desc: the number to format + type: + - int + - float + nums: + desc: the numbers to format + type: + - int[] + - float[] + right: + desc: the number of digits to the right of the decimal point + type: + - int returns: String or String[] - syntax: |- - nfs(num, digits) - nfs(nums, digits) - nfs(nums, left, right) - nfs(num, left, right) + syntax: + - nfs(num, digits) + - nfs(nums, digits) + - nfs(nums, left, right) + - nfs(num, left, right) type: function noClip: description: Disables the clipping previously started by the `clip()` function. - docUrl: https://processing.org/reference/noClip_.html - name: null + examples: + - | + void setup() { + size(200, 200); + imageMode(CENTER); + } + + void draw() { + background(204); + if (mousePressed) { + clip(mouseX, mouseY, 100, 100); + } else { + noClip(); + } + line(0, 0, width, height); + line(0, height, width, 0); + } + fileName: noClip_ parameters: {} returns: void - syntax: noClip() + syntax: + - noClip() type: function noCursor: - description: Hides the cursor from view. Will not work when running the program - in a web browser or in full screen (Present) mode. - docUrl: https://processing.org/reference/noCursor_.html - name: null + description: |- + Hides the cursor from view. Will not work when running the program in a + web browser or when running in full screen (Present) mode. + examples: + - | + // Press the mouse to hide the cursor + void draw() + { + if (mousePressed == true) { + noCursor(); + } else { + cursor(HAND); + } + } + fileName: noCursor_ parameters: {} returns: void - syntax: noCursor() + syntax: + - noCursor() type: function noFill: - description: Disables filling geometry. If both `noStroke()` and `noFill()` are - called, nothing will be drawn to the screen. - docUrl: https://processing.org/reference/noFill_.html - name: null + description: |- + Disables filling geometry. If both `noStroke()` and `noFill()` + are called, nothing will be drawn to the screen. + examples: + - |- + size(400, 400); + float x1 = 80; + rect(60, 40, 220, 220); + noFill(); + rect(120, 80, 220, 220); + fileName: noFill_ parameters: {} returns: void - syntax: noFill() + syntax: + - noFill() type: function noLights: - description: 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. - docUrl: https://processing.org/reference/noLights_.html - name: null + description: |- + 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. + fileName: noLights_ parameters: {} returns: void - syntax: noLights() + syntax: + - noLights() type: function noLoop: - description: >- - Stops Processing from continuously executing the code within `draw()`. If - `loop()` is called, the code in `draw()` begins to run continuously again. - If using `noLoop()` in `setup()`, it should be the last line inside the - block. + description: |- + 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. + examples: + - | + void setup() { + size(200, 200); + noLoop(); + } + + void draw() { + line(10, 10, 190, 190); + } + - | + void setup() { + size(200, 200); + } + + float x = 0.0; + + void draw() { + background(204); + x = x + 0.1; + if (x > width) { + x = 0; + } + line(x, 0, x, height); + } + + void mousePressed() { + noLoop(); + } + void mouseReleased() { + loop(); + } + - | + boolean someMode = false; - 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. + void setup() { + noLoop(); + } + void draw() { + if (someMode) { + // do something + } + } - 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. - docUrl: https://processing.org/reference/noLoop_.html - name: null + void mousePressed() { + someMode = true; + redraw(); // or loop() + } + fileName: noLoop_ parameters: {} returns: void - syntax: noLoop() + syntax: + - noLoop() type: function noSmooth: - description: Draws all geometry and fonts with jagged (aliased) edges and images - with hard edges between the pixels when enlarged rather than interpolating - pixels. Note that `smooth()` is active by default, so it is necessary to - call `noSmooth()` to disable smoothing of geometry, fonts, and images. Since - the release of Processing 3.0, the `noSmooth()` function can only be run - once for each sketch, either at the top of a sketch without a `setup()`, or - after the `size()` function when used in a sketch with `setup()`. See the - examples above for both scenarios. - docUrl: https://processing.org/reference/noSmooth_.html - name: null + description: |- + Draws all geometry and fonts with jagged (aliased) + edges and images with hard edges between the pixels + when enlarged rather than interpolating pixels. Note + that `smooth()` is active by default, so it is necessary + to call `noSmooth()` to disable smoothing of geometry, + fonts, and images. Since the release of Processing 3.0, + the `noSmooth()` function can only be run once for each + sketch, either at the top of a sketch without a `setup()`, + or after the `size()` function when used in a sketch with + `setup()`. See the examples above for both scenarios. + examples: + - |- + size(400, 400); + noSmooth(); + noStroke(); + background(0); + ellipse(120, 192, 144, 144); + ellipse(280, 192, 144, 144); + fileName: noSmooth_ parameters: {} returns: void - syntax: noSmooth() + syntax: + - noSmooth() type: function noStroke: - description: Disables drawing the stroke (outline). If both `noStroke()` and - `noFill()` are called, nothing will be drawn to the screen. - docUrl: https://processing.org/reference/noStroke_.html - name: null + description: |- + Disables drawing the stroke (outline). If both `noStroke()` and + `noFill()` are called, nothing will be drawn to the screen. + examples: + - |- + size(400, 400); + noStroke(); + rect(120, 80, 220, 220); + fileName: noStroke_ parameters: {} returns: void - syntax: noStroke() + syntax: + - noStroke() type: function noTint: - description: Removes the current fill value for displaying images and reverts to - displaying images with their original hues. - docUrl: https://processing.org/reference/noTint_.html - name: null + description: |- + Removes the current fill value for displaying images and reverts to + displaying images with their original hues. + examples: + - |- + size(400,400); + PImage img; + img = loadImage("yuya-onsen.jpg"); + tint(0, 153, 204); // Tint blue + image(img, 0, 0); + noTint(); // Disable tint + image(img, 200, 0); + fileName: noTint_ parameters: {} returns: void - syntax: noTint() + syntax: + - noTint() type: function noise: - description: >- + description: |- Returns the Perlin noise value at specified coordinates. Perlin noise is a - random sequence generator producing a more natural, harmonic succession of - numbers than that of the standard `random()` function. It was developed by - Ken Perlin in the 1980s and has been used in graphical applications to - generate procedural textures, shapes, terrains, and other seemingly organic - forms. - - - In contrast to the `random()` function, Perlin noise is defined in an infinite n-dimensional space, in which 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 first example above. The 2nd and 3rd dimensions can also be interpreted as time. - - - The actual noise structure is similar to that of an audio signal, in respect to t. . . - docUrl: https://processing.org/reference/noise_.html - name: null - parameters: - x: "float: x-coordinate in noise space" - y: "float: y-coordinate in noise space" - z: "float: z-coordinate in noise space" + random sequence generator producing a more natural, harmonic succession of + numbers than that of the standard `random()` function. It was + developed by Ken Perlin in the 1980s and has been used in graphical + applications to generate procedural textures, shapes, terrains, and other + seemingly organic forms. + + In contrast to the `random()` function, Perlin noise is defined in an + infinite n-dimensional space, in which 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 first example above. The 2nd and 3rd dimensions can + also be interpreted as time. + + The actual noise structure is similar to that of 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 is important (such as when + using `noise()` within a loop). As a general rule, the smaller the + difference between coordinates, the smoother the resulting noise sequence. + Steps of 0.005-0.03 work best for most applications, but this will differ + depending on use. + + There have been debates over the accuracy of the implementation of noise in + Processing. For clarification, it's an implementation of "classic Perlin + noise" from 1983, and not the newer "simplex noise" method from 2001. + examples: + - | + float xoff = 0.0; + + void draw() { + background(204); + xoff = xoff + .01; + float n = noise(xoff) * width; + line(n, 0, n, height); + } + - | + float noiseScale = 0.02; + + void draw() { + background(0); + for (int x=0; x < width; x++) { + float noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale); + stroke(noiseVal*255); + line(x, mouseY+noiseVal*80, x, height); + } + } + fileName: noise_ + parameters: + x: + desc: x-coordinate in noise space + type: + - float + y: + desc: y-coordinate in noise space + type: + - float + z: + desc: z-coordinate in noise space + type: + - float returns: float - syntax: |- - noise(x) - noise(x, y) - noise(x, y, z) + syntax: + - noise(x) + - noise(x, y) + - noise(x, y, z) type: function noiseDetail: - description: >- + description: |- 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 overall 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 first octave. This falloff amount can be changed by adding an additional function parameter. For example, a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. While any number between 0.0 and 1.0 is valid, note that values greater than 0.5 may result in `noise()` returning values greater than 1.0. - - - By changing these parameters, the signal created by the `noise()` function can be adapted to fit very specific needs and characteristics. - docUrl: https://processing.org/reference/noiseDetail_.html - name: null + 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 overall 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 first + octave. This falloff amount can be changed by adding a function parameter. + For example, a falloff factor of 0.75 means each octave will now + have 75% impact (25% less) of the previous lower octave. While any number + between 0.0 and 1.0 is valid, note that values greater than 0.5 may result + in `noise()` returning values greater than 1.0. + + By changing these parameters, the signal created by the `noise()` + function can be adapted to fit very specific needs and characteristics. + examples: + - | + float noiseVal; + float noiseScale=0.02; + + void draw() { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width/2; x++) { + noiseDetail(3,0.5); + noiseVal = noise((mouseX+x) * noiseScale, (mouseY+y) * noiseScale); + stroke(noiseVal*255); + point(x,y); + noiseDetail(8,0.65); + noiseVal = noise((mouseX + x + width/2) * noiseScale, + (mouseY + y) * noiseScale); + stroke(noiseVal * 255); + point(x + width/2, y); + } + } + } + fileName: noiseDetail_ parameters: - falloff: "float: falloff factor for each octave" - lod: "int: number of octaves to be used by the noise" + falloff: + desc: falloff factor for each octave + type: + - float + lod: + desc: number of octaves to be used by the noise + type: + - int returns: void - syntax: |- - noiseDetail(lod) - noiseDetail(lod, falloff) + syntax: + - noiseDetail(lod) + - noiseDetail(lod, falloff) type: function noiseSeed: - description: Sets the seed value for `noise()`. By default, `noise()` produces - different results each time the program is run. Set the `seed` parameter to - a constant to return the same pseudo-random numbers each time the software - is run. - docUrl: https://processing.org/reference/noiseSeed_.html - name: null + description: |- + 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. + examples: + - | + float xoff = 0.0; + + void setup() { + noiseSeed(0); + stroke(0, 10); + } + + void draw() { + xoff = xoff + .01; + float n = noise(xoff) * width; + line(n, 0, n, height); + } + fileName: noiseSeed_ parameters: - seed: "int: seed value" + seed: + desc: seed value + type: + - int returns: void - syntax: noiseSeed(seed) + syntax: + - noiseSeed(seed) type: function norm: - description: >- + description: |- Normalizes a number from another range into a value between 0 and 1. - Identical to `map(value, low, high, 0, 1)`. - - - Numbers outside of the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. (See the second example above.) - docUrl: https://processing.org/reference/norm_.html - name: null - parameters: - start: "float: lower bound of the value's current range" - stop: "float: upper bound of the value's current range" - value: "float: the incoming value to be converted" + 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. (See the second + example above.) + examples: + - | + float value = 20; + float n = norm(value, 0, 50); + println(n); // Prints "0.4" + - | + float value = -10; + float n = norm(value, 0, 100); + println(n); // Prints "-0.1" + fileName: norm_ + parameters: + start: + desc: lower bound of the value's current range + type: + - float + stop: + desc: upper bound of the value's current range + type: + - float + value: + desc: the incoming value to be converted + type: + - float returns: float - syntax: norm(value, start, stop) + syntax: + - norm(value, start, stop) type: function normal: - description: Sets the current normal vector. Used for drawing three dimensional - shapes and surfaces, `normal()` specifies a vector perpendicular to a - shape's surface which, in turn, 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. - docUrl: https://processing.org/reference/normal_.html - name: null - parameters: - nx: "float: x direction" - ny: "float: y direction" - nz: "float: z direction" - returns: void - syntax: normal(nx, ny, nz) + description: |- + Sets the current normal vector. Used for drawing three-dimensional + shapes and surfaces, `normal()` specifies a vector perpendicular + to a shape's surface which, in turn, 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. + examples: + - |- + size(400, 400, P3D); + noStroke(); + background(0); + pointLight(150, 250, 150, 40, 120, 200); + beginShape(); + normal(0, 0, 4); + vertex(80, 80, -40); + vertex(320, 80, 40); + vertex(320, 320, -40); + vertex(80, 320, 40); + endShape(CLOSE); + fileName: normal_ + parameters: + nx: + desc: x direction + type: + - float + ny: + desc: y direction + type: + - float + nz: + desc: z direction + type: + - float + returns: void + syntax: + - normal(nx, ny, nz) + type: function +"null": + description: Special value used to signify the target is not a valid data + element. In Processing, you may run across the keyword `null` when trying to + access data which is not there. + examples: + - | + String content = "It is a beautiful day."; + String[] results; // Declare empty String array + + results = match(content, "orange"); + // The match statement above will fail to find + // the word "orange" in the String 'content', so + // it will return a null value to 'results'. + + if (results == null) { + println("Value of 'results' is null."); // This line is printed + } else { + println("Value of 'results' is not null!"); // This line is not printed + } + fileName: "null" + parameters: {} + returns: "" + syntax: [] type: function ortho: - description: "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(-width/2, width/2, -height/2, height/2)." - docUrl: https://processing.org/reference/ortho_.html - name: null - parameters: - bottom: "float: bottom plane of the clipping volume" - far: "float: maximum distance from the origin away from the viewer" - left: "float: left plane of the clipping volume" - near: "float: maximum distance from the origin to the viewer" - right: "float: right plane of the clipping volume" - top: "float: top plane of the clipping volume" - returns: void - syntax: |- - ortho() - ortho(left, right, bottom, top) - ortho(left, right, bottom, top, near, far) + description: >- + 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(-width/2, width/2, -height/2, height/2)`. + examples: + - |- + size(400, 400, P3D); + pixelDensity(2); + noFill(); + ortho(-width/2, width/2, -height/2, height/2); // Same as ortho() + translate(width/2, height/2, 0); + rotateX(-PI/6); + rotateY(PI/3); + box(180); + fileName: ortho_ + parameters: + bottom: + desc: bottom plane of the clipping volume + type: + - float + far: + desc: maximum distance from the origin away from the viewer + type: + - float + left: + desc: left plane of the clipping volume + type: + - float + near: + desc: maximum distance from the origin to the viewer + type: + - float + right: + desc: right plane of the clipping volume + type: + - float + top: + desc: top plane of the clipping volume + type: + - float + returns: void + syntax: + - ortho() + - ortho(left, right, bottom, top) + - ortho(left, right, bottom, top, near, far) type: function parseJSONArray: - description: >- - Takes a `String`, parses its contents, and returns a `JSONArray`. If the - `String` does not contain `JSONArray` data or cannot be parsed, a `null` - value is returned. - + description: |- + Takes a `String`, parses its contents, and returns a `JSONArray`. + If the `String` does not contain `JSONArray` data or cannot be + parsed, a `null` value is returned. + + `parseJSONArray()` is most useful when pulling data dynamically, such as + from third-party APIs. Normally, API results would be saved to a + `String`, and then can be converted to a structured `JSONArray` + using `parseJSONArray()`. Be sure to check if `null` is returned + before performing operations on the new `JSONArray` in case the + `String` content could not be parsed. + + If your data already exists as a `JSON` file in the data folder, it is + simpler to use `loadJSONArray()`. + examples: + - >2 + String data = "[ \"Capra hircus\", \"Panthera pardus\", \"Equus zebra\" + ]"; + + void setup() { + JSONArray json = parseJSONArray(data); + if (json == null) { + println("JSONArray could not be parsed"); + } else { + String species = json.getString(1); + println(species); + } + } - `parseJSONArray()` is most useful when pulling data dynamically, such as from third-party APIs. Normally, API results would be saved to a `String`, and then can be converted to a structured `JSONArray` using `parseJSONArray()`. Be sure to check if `null` is returned before performing operations on the new `JSONArray` in case the `String` content could not be parsed. + // Sketch prints: - If your data already exists as a `JSON` file in the data folder, it is simpler to use `loadJSONArray()`. - docUrl: https://processing.org/reference/parseJSONArray_.html - name: null + // Panthera pardus + fileName: parseJSONArray_ parameters: - input: "String: String to parse as a JSONArray" + input: + desc: String to parse as a JSONArray + type: + - String returns: JSONArray - syntax: parseJSONArray(input) + syntax: + - parseJSONArray(input) type: function parseJSONObject: - description: >- - Takes a `String`, parses its contents, and returns a `JSONObject`. If the - `String` does not contain `JSONObject` data or cannot be parsed, a `null` - value is returned. - + description: |- + Takes a `String`, parses its contents, and returns a + `JSONObject`. If the `String` does not contain `JSONObject` + data or cannot be parsed, a `null` value is returned. + + `parseJSONObject()` is most useful when pulling data dynamically, such + as from third-party APIs. Normally, API results would be saved to a + `String`, and then can be converted to a structured `JSONObject` + using `parseJSONObject()`. Be sure to check if `null` is returned + before performing operations on the new `JSONObject` in case the + `String` content could not be parsed. + + If your data already exists as a `JSON` file in the data folder, it is + simpler to use `loadJSONObject()`. + examples: + - > + String data = "{ \"id\": 0, \"species\": \"Panthera leo\", \"name\": + \"Lion\"}"; + + + void setup() { + JSONObject json = parseJSONObject(data); + if (json == null) { + println("JSONObject could not be parsed"); + } else { + String species = json.getString("species"); + println(species); + } + } - `parseJSONObject()` is most useful when pulling data dynamically, such as from third-party APIs. Normally, API results would be saved to a `String`, and then can be converted to a structured `JSONObject` using `parseJSONObject()`. Be sure to check if `null` is returned before performing operations on the new `JSONObject` in case the `String` content could not be parsed. + // Sketch prints: - If your data already exists as a `JSON` file in the data folder, it is simpler to use `loadJSONObject()`. - docUrl: https://processing.org/reference/parseJSONObject_.html - name: null + // Panthera leo + fileName: parseJSONObject_ parameters: - input: "String: String to parse as a JSONObject" + input: + desc: String to parse as a JSONObject + type: + - String returns: JSONObject - syntax: parseJSONObject(input) + syntax: + - parseJSONObject(input) type: function parseXML: - description: >- - Takes a String, parses its contents, and returns an XML object. If the - String does not contain XML data or cannot be parsed, a null value is - returned. - - - `parseXML()` is most useful when pulling data dynamically, such as from third-party APIs. Normally, API results would be saved to a String, and then can be converted to a structured XML object using `parseXML()`. Be sure to check if null is returned before performing operations on the new XML object, in case the String content could not be parsed. - + description: |- + Takes a String, parses its contents, and returns an XML object. If the + String does not contain XML data or cannot be parsed, a `null` value is + returned. + + `parseXML()` is most useful when pulling data dynamically, such as + from third-party APIs. Normally, API results would be saved to a String, + and then can be converted to a structured XML object using + `parseXML()`. Be sure to check if `null` is returned before performing + operations on the new XML object, in case the String content could not be + parsed. + + If your data already exists as an XML file in the data folder, it is + simpler to use `loadXML()`. + examples: + - | + String data = "Goat"; + + void setup() { + XML xml = parseXML(data); + if (xml == null) { + println("XML could not be parsed."); + } else { + XML firstChild = xml.getChild("animal"); + println(firstChild.getContent()); + } + } - If your data already exists as an XML file in the data folder, it is simpler to use `loadXML()`. - docUrl: https://processing.org/reference/parseXML_.html - name: null + // Sketch prints: + // Goat + fileName: parseXML_ parameters: - xmlString: "String: the content to be parsed as XML" + xmlString: + desc: the content to be parsed as XML + type: + - String returns: XML - syntax: |- - parseXML(xmlString) - parseXML(xmlString, options) + syntax: + - parseXML(xmlString) + - parseXML(xmlString, options) type: function perspective: - description: "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));" - docUrl: https://processing.org/reference/perspective_.html - name: null - parameters: - aspect: "float: ratio of width to height" - fovy: "float: field-of-view angle (in radians) for vertical direction" - zFar: "float: z-position of farthest clipping plane" - zNear: "float: z-position of nearest clipping plane" - returns: void - syntax: |- - perspective() - perspective(fovy, aspect, zNear, zFar) + description: |- + 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))` + examples: + - |- + // Re-creates the default perspective + size(400, 400, P3D); + noFill(); + float fov = PI/3.0; + float cameraZ = (height/2.0) / tan(fov/2.0); + perspective(fov, float(width)/float(height), + cameraZ/10.0, cameraZ*10.0); + translate(200, 200, 0); + rotateX(-PI/6); + rotateY(PI/3); + box(180); + fileName: perspective_ + parameters: + aspect: + desc: ratio of width to height + type: + - float + fovy: + desc: field-of-view angle (in radians) for vertical direction + type: + - float + zFar: + desc: z-position of the farthest clipping plane + type: + - float + zNear: + desc: z-position of nearest clipping plane + type: + - float + returns: void + syntax: + - perspective() + - perspective(fovy, aspect, zNear, zFar) type: function pixelDensity: - description: >- - This function is new with Processing 3.0. It makes it possible for - Processing to render using all of the pixels on high resolutions screens - like Apple Retina displays and Windows High-DPI displays. This function can - only be run once within a program and it must be used right after `size()` - in a program without a `setup()` and used within `setup()` when a program - has one. The `pixelDensity()` should only be used with hardcoded numbers - (in almost all cases this number will be 2) or in combination with - `displayDensity()` as in the third example above. - - - When the pixel density is set to more than 1, it changes all of the pixel operations including the way `get()`, `set()`, `blend()`, `copy()`, and `updatePixels()` all work. See the reference for `pixelWidth` and `pixelHeight` for more information. + description: |- + This function makes it possible to render using all the pixels + on high resolutions screens like Apple Retina and Windows HiDPI. + This function can only be run once within a program, and must + be called right after `size()` in a program without a + `setup()` function, or within `setup()` if present. + + `pixelDensity()` should only be used with hardcoded + numbers (in almost all cases this number will be 2) + or in combination with `displayDensity()` as in the + third example above. + + When the pixel density is set to more than 1, it changes the + pixel operations including the way `get()`, `set()`, + `blend()`, `copy()`, and `updatePixels()` + all work. See the reference for `pixelWidth` and + pixelHeight for more information. + + To use variables as the arguments to `pixelDensity()` + function, place the `pixelDensity()` function within + the `settings()` function. There is more information + about this on the `settings()` reference page. + examples: + - | + size(100, 100); + pixelDensity(2); + noStroke(); + background(0); + ellipse(30, 48, 36, 36); + ellipse(70, 48, 36, 36); + - | + void setup() { + size(100, 100); + pixelDensity(2); + noStroke(); + } + void draw() { + background(0); + ellipse(30, 48, 36, 36); + ellipse(70, 48, 36, 36); + } + - | + void setup() { + size(100, 100); + // Pulling the display's density dynamically + pixelDensity(displayDensity()); + noStroke(); + } - To use variables as the arguments to `pixelDensity()` function, place the `pixelDensity()` function within the `settings()` function. There is more information about this on the `settings()` re. . . - docUrl: https://processing.org/reference/pixelDensity_.html - name: null + void draw() { + background(0); + ellipse(30, 48, 36, 36); + ellipse(70, 48, 36, 36); + } + fileName: pixelDensity_ parameters: - density: "int: 1 or 2" + density: + desc: 1 or 2 + type: + - int returns: void - syntax: pixelDensity(density) + syntax: + - pixelDensity(density) type: function pixelHeight: - description: 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`. - docUrl: https://processing.org/reference/pixelHeight.html - examples: | - void setup() { - size(600, 400); - pixelDensity(2); - println(width, height); - println(pixelWidth, pixelHeight); - } - - - void setup() { - size(600, 400); - pixelDensity(2); // Double the pixel density - println(width, height); - println(pixelWidth, pixelHeight); - } + description: |- + 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`. + examples: + - | + void setup() { + size(600, 400); + pixelDensity(2); + println(width, height); + println(pixelWidth, pixelHeight); + } + - | + void setup() { + size(600, 400); + pixelDensity(2); // Double the pixel density + println(width, height); + println(pixelWidth, pixelHeight); + } - void draw() { - loadPixels(); - // Fill all the pixels to blue with using - // pixelWidth and pixelHeight - for (int i = 0; i < pixelWidth * pixelHeight; i++) { - pixels[i] = color(0, 0, 255); - } - // Fill one quarter of the pixels to yellow - // because the pixel density is set to 2 in setup() - // and 'width' and 'height' don't reflect the pixel - // dimensions of the sketch - for (int i = 0; i < width * height; i++) { - pixels[i] = color(255, 255, 0); + void draw() { + loadPixels(); + // Fill all the pixels to blue with using + // pixelWidth and pixelHeight + for (int i = 0; i < pixelWidth * pixelHeight; i++) { + pixels[i] = color(0, 0, 255); + } + // Fill one quarter of the pixels to yellow + // because the pixel density is set to 2 in setup() + // and 'width' and 'height' don't reflect the pixel + // dimensions of the sketch + for (int i = 0; i < width * height; i++) { + pixels[i] = color(255, 255, 0); + } + updatePixels(); + noLoop(); } - updatePixels(); - noLoop(); - } - name: null + fileName: pixelHeight type: var pixelWidth: - description: 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`. - docUrl: https://processing.org/reference/pixelWidth.html - examples: | - void setup() { - size(600, 400); - pixelDensity(2); - println(width, height); - println(pixelWidth, pixelHeight); - } - - - void setup() { - size(600, 400); - pixelDensity(2); // Double the pixel density - println(width, height); - println(pixelWidth, pixelHeight); - } + description: |- + 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`. + examples: + - | + void setup() { + size(600, 400); + pixelDensity(2); + println(width, height); + println(pixelWidth, pixelHeight); + } + - | + void setup() { + size(600, 400); + pixelDensity(2); // Double the pixel density + println(width, height); + println(pixelWidth, pixelHeight); + } - void draw() { + void draw() { + loadPixels(); + // Fill all the pixels to blue with using + // pixelWidth and pixelHeight + for (int i = 0; i < pixelWidth * pixelHeight; i++) { + pixels[i] = color(0, 0, 255); + } + // Fill one quarter of the pixels to yellow + // because the pixel density is set to 2 in setup() + // and 'width' and 'height' don't reflect the pixel + // dimensions of the sketch + for (int i = 0; i < width * height; i++) { + pixels[i] = color(255, 255, 0); + } + updatePixels(); + noLoop(); + } + fileName: pixelWidth + type: var +pixels[]: + description: >- + The `pixels[]` array contains the values for all the pixels in the + display window. These values are of the color datatype. This array is + defined by the size of the display window. For example, if the window is + 100 x 100 pixels, there will be 10,000 values and if the window is + 200 x 300 pixels, there will be 60,000 values. When the pixel density is + set to higher than 1 with the `pixelDensity()` function, these values + will change. See the reference for `pixelWidth` or `pixelHeight` + for more information. + + Before accessing this array, the data must be loaded with the `loadPixels()` + function. Failure to do so may result in a NullPointerException. Subsequent + changes to the display window will not be reflected in `pixels` until + `loadPixels()` is called again. After `pixels` has been modified, + the `updatePixels()` function must be run to update the content of the + display window. + examples: + - |- + size(400, 400); + color pink = color(255, 102, 204); loadPixels(); - // Fill all the pixels to blue with using - // pixelWidth and pixelHeight - for (int i = 0; i < pixelWidth * pixelHeight; i++) { - pixels[i] = color(0, 0, 255); - } - // Fill one quarter of the pixels to yellow - // because the pixel density is set to 2 in setup() - // and 'width' and 'height' don't reflect the pixel - // dimensions of the sketch - for (int i = 0; i < width * height; i++) { - pixels[i] = color(255, 255, 0); + for (int i = 0; i < (width*height/2)-width/2; i++) { + pixels[i] = pink; } updatePixels(); - noLoop(); - } - name: null + fileName: pixels type: var pmouseX: description: >- - 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 when referenced inside of `draw()` and inside of mouse events like `mousePressed()` and `mouseMoved()`. Inside `draw()`, `pmouseX` and `pmouseY` update only once per frame (once per trip through the `draw()` loop). But inside mouse events, they update each time the event is called. If these values weren't updated immediately during mouse events, then the mouse position would be read only once per frame, resulting in slight delays and choppy interaction. If the mouse variables were always updated multiple times per frame, then something like `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()`. - - If you want values relative to the previous frame, use `pmouseX` and `pmouseY` inside `draw()`. . . . - docUrl: https://processing.org/reference/pmouseX.html - examples: | - // Move the mouse quickly to see the difference - // between the current and previous position - void draw() { - background(204); - line(mouseX, 20, pmouseX, 80); - println(mouseX + " : " + pmouseX); - } - name: null + 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 + when referenced inside of `draw()` and inside of mouse events like + `mousePressed()` and `mouseMoved()`. Inside `draw()`, + `pmouseX` and `pmouseY` update only once per frame (once per trip + through the `draw()` loop). But inside mouse events, they update each + time the event is called. If these values weren't updated immediately during + events, then the mouse position would be read only once per frame, resulting + in slight delays and choppy interaction. If the mouse variables were always + updated multiple times per frame, then something like `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()`. + If you want values relative to the previous frame, use `pmouseX` and + `pmouseY` inside `draw()`. If you want continuous response, use + `pmouseX` and `pmouseY` inside the mouse event functions. + examples: + - | + // Move the mouse quickly to see the difference + // between the current and previous position + void draw() { + background(204); + line(mouseX, 20, pmouseX, 80); + println(mouseX + " : " + pmouseX); + } + fileName: pmouseX type: var pmouseY: - description: >- - The system variable `pmouseY` always contains the vertical position of the - mouse in the frame previous to the current frame. - - - For more detail on how `pmouseY` is updated inside of mouse events and `draw()`, see the reference for `pmouseX`. - docUrl: https://processing.org/reference/pmouseY.html - examples: | - // Move the mouse quickly to see the difference - // between the current and previous position - void draw() { - background(204); - line(20, mouseY, 80, pmouseY); - println(mouseY + " : " + pmouseY); - } - name: null + description: |- + 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`. + examples: + - | + // Move the mouse quickly to see the difference + // between the current and previous position + void draw() { + background(204); + line(20, mouseY, 80, pmouseY); + println(mouseY + " : " + pmouseY); + } + fileName: pmouseY type: var point: description: >- 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. - - - Use `stroke()` to set the color of a `point()`. - - - Point appears round with the default `strokeCap(ROUND)` and square with `strokeCap(PROJECT)`. Points are invisible with `strokeCap(SQUARE)` (no cap). - - - Using point() with strokeWeight(1) or smaller may draw nothing to the screen, depending on the graphics settings of the computer. Workarounds include setting the pixel using `set() or drawing the point using either `circle()` or `square()`. - - ` - docUrl: https://processing.org/reference/point_.html - name: null - parameters: - x: "float: x-coordinate of the point" - y: "float: y-coordinate of the point" - z: "float: z-coordinate of the point" - returns: void - syntax: |- - point(x, y) - point(x, y, z) + 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. + + + Use `stroke()` to set the color of a `point()`. + + Point appears round with the default `strokeCap(ROUND)` and square with + `strokeCap(PROJECT)`. Points are invisible with `strokeCap(SQUARE)` + (no cap). + + Using point() with strokeWeight(1) or smaller may draw nothing to the screen, + depending on the graphics settings of the computer. Workarounds include + setting the pixel using `set() or drawing the point using either + `circle()` or `square()`. + examples: + - |- + size(400, 400); + noSmooth(); + point(120, 80); + point(340, 80); + point(340, 300); + point(120, 300); + - |- + size(400, 400, P3D); + noSmooth(); + point(120, 80, -200); + point(340, 80, -200); + point(340, 300, -200); + point(120, 300, -200); + fileName: point_ + parameters: + x: + desc: x-coordinate of the point + type: + - float + y: + desc: y-coordinate of the point + type: + - float + z: + desc: z-coordinate of the point + type: + - float + returns: void + syntax: + - point(x, y) + - point(x, y, z) type: function pointLight: - description: 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 `v1`, `v2`, and `v3` parameters are interpreted as - either RGB or HSB values, depending on the current color mode. The `x`, `y`, - and `z` parameters set the position of the light. - docUrl: https://processing.org/reference/pointLight_.html - name: null - parameters: - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - x: "float: x-coordinate of the light" - y: "float: y-coordinate of the light" - z: "float: z-coordinate of the light" - returns: void - syntax: pointLight(v1, v2, v3, x, y, z) + description: >- + 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 `v1`, `v2`, and `v3` parameters are interpreted + as either RGB or HSB values, depending on the current color mode. The + `x`, `y`, and `z` parameters set the position of the light. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + pointLight(51, 102, 126, 140, 160, 144); + translate(320, 200, 0); + sphere(120); + fileName: pointLight_ + parameters: + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + x: + desc: x-coordinate of the light + type: + - float + y: + desc: y-coordinate of the light + type: + - float + z: + desc: z-coordinate of the light + type: + - float + returns: void + syntax: + - pointLight(v1, v2, v3, x, y, z) type: function pop: - description: >- - The `pop()` function restores the previous drawing style settings and - transformations after `push()` has changed them. Note that these functions - are always used together. They allow you to change the style and - transformation settings and later return to what you had. When a new state - is started with push(), it builds on the current style and transform - information. - - - `push()` stores information related to the current transformation state and style settings controlled by the following functions: `rotate()`, `translate()`, `scale()`, `fill()`, `stroke()`, `tint()`, `strokeWeight()`, `strokeCap()`, `strokeJoin()`, `imageMode()`, `rectMode()`, `ellipseMode()`, `colorMode()`, `textAlign()`, `textFont()`, `textMode()`, `textSize()`, `textLeading()`. - - - The `push()` and `pop()` functions were added with Processing 3.5. They can be used in place of `pushMatrix()`, `popMatrix()`, `pushStyles()`, and `popStyles()`. The difference is that push() and pop() control both the transformations (rotate, sca. . . - docUrl: https://processing.org/reference/pop_.html - name: null + description: |- + The `pop()` function restores the previous drawing style + settings and transformations after `push()` has changed them. + Note that these functions are always used together. They allow + you to change the style and transformation settings and later + return to what you had. When a new state is started with push(), + it builds on the current style and transform information. + + + `push()` stores information related to the current + transformation state and style settings controlled by the + following functions: `rotate()`, `translate()`, + `scale()`, `fill()`, `stroke()`, `tint()`, + `strokeWeight()`, `strokeCap()`, `strokeJoin()`, + `imageMode()`, `rectMode()`, `ellipseMode()`, + `colorMode()`, `textAlign()`, `textFont()`, + `textMode()`, `textSize()`, `textLeading()`. + + The `push()` and `pop()` functions were added with + Processing 3.5. They can be used in place of `pushMatrix()`, + `popMatrix()`, `pushStyles()`, and `popStyles()`. + The difference is that push() and pop() control both the + transformations (rotate, scale, translate) and the drawing styles + at the same time. + examples: + - |- + fill(255); + rect(0, 0, 200, 200); // White rectangle + + push(); + translate(80, 70); + fill(0); + rect(0, 0, 200, 200); // Black rectangle + pop(); // Restore original settings + + fill(100); + rect(40, 40, 200, 200); // Gray rectangle + - |- + ellipse(0, 200, 133, 133); // Left circle + + push(); + strokeWeight(40); + fill(204, 153, 0); + ellipse(200, 200, 133, 133); // Middle circle + pop(); // Restore original settings + + ellipse(400, 200, 133, 133); // Right circle + fileName: pop_ parameters: {} returns: void - syntax: pop() + syntax: + - pop() type: function popMatrix: - description: 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. - docUrl: https://processing.org/reference/popMatrix_.html - name: null + description: |- + 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 conjunction with the other transformation functions and may be + embedded to control the scope of the transformations. + examples: + - |- + size(400, 400); + + fill(255); + rect(0, 0, 200, 200); // White rectangle + + pushMatrix(); + translate(120, 80); + fill(0); + rect(0, 0, 200, 200); // Black rectangle + popMatrix(); + + fill(100); + rect(60, 40, 200, 200); // Gray rectangle + fileName: popMatrix_ parameters: {} returns: void - syntax: popMatrix() + syntax: + - popMatrix() type: function popStyle: - description: 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.) - docUrl: https://processing.org/reference/popStyle_.html - name: null + description: |- + 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.) + examples: + - |- + size(400, 400); + + ellipse(0, 200, 132, 132); // Left circle + + pushStyle(); // Start a new style + strokeWeight(40); + fill(204, 153, 0); + ellipse(200, 200, 132, 132); // Middle circle + popStyle(); // Restore original style + + ellipse(400, 200, 132, 132); // Right circle + - |- + size(400, 400); + + ellipse(0, 200, 132, 132); // Left circle + + pushStyle(); // Start a new style + strokeWeight(40); + fill(204, 153, 0); + ellipse(132, 200, 132, 132); // Left-middle circle + + pushStyle(); // Start another new style + stroke(0, 102, 153); + ellipse(264, 200, 132, 132); // Right-middle circle + popStyle(); // Restore the previous style + + popStyle(); // Restore original style + + ellipse(400, 200, 132, 132); // Right circle + fileName: popStyle_ parameters: {} returns: void - syntax: popStyle() + syntax: + - popStyle() type: function pow: - description: Facilitates exponential expressions. The `pow()` function is an - efficient way of multiplying numbers by themselves (or their reciprocals) 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. - docUrl: https://processing.org/reference/pow_.html - name: null - parameters: - e: "float: power by which to raise the base" - n: "float: base of the exponential expression" + description: |- + 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. + examples: + - | + float a = pow( 1, 3); // Sets 'a' to 1*1*1 = 1 + float b = pow( 3, 5); // Sets 'b' to 3*3*3*3*3 = 243 + float c = pow( 3,-5); // Sets 'c' to 1 / 3*3*3*3*3 = 1 / 243 = .0041 + float d = pow(-3, 5); // Sets 'd' to -3*-3*-3*-3*-3 = -243 + fileName: pow_ + parameters: + e: + desc: power by which to raise the base + type: + - float + n: + desc: base of the exponential expression + type: + - float returns: float - syntax: pow(n, e) + syntax: + - pow(n, e) type: function print: description: >- - The `print()` function writes to the console area, the black rectangle at - the bottom of the Processing environment. This function 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. More than one parameter can be passed into the - function by separating them with commas. Alternatively, individual elements - can be separated with quotes ("") and joined with the addition operator (+). - - - 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. - - - Note that the console is relatively slow. It works well for occasional messages, but does not support high-speed, real-time output (such as at 60 frames pe. . . - docUrl: https://processing.org/reference/print_.html - name: null - parameters: - variables: "Object[]: list of data, separated by commas" - what: "String, float, char, boolean, or byte: data to print to console" - returns: void - syntax: |- - print(what) - print(variables) + The `print()` function writes to the console area, the black rectangle + at the bottom of the Processing environment. This function 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. More than one parameter can be passed into the + function by separating them with commas. Alternatively, individual elements + can be separated with quotes ("") and joined with the addition operator + (+). + + 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. + + Note that the console is relatively slow. It works well for occasional + messages, but does not support high-speed, real-time output (such as at 60 + frames per second). It should also be noted, that a print() within a for loop + can sometimes lock up the program, and cause the sketch to freeze. + examples: + - | + String s = "The size is "; + int w = 1920; + int h = 1080; + print(s); + print(w, "x", h); + + // This program writes to the console: + // The size is 1920 x 1080 + - | + print("begin- "); + float f = 0.3; + int i = 1024; + print("f is " + f + " and i is " + 1024); + String s = " -end"; + println(s); + + // This program writes to the console: + // "begin- f is 0.3 and i is 1024 -end" + fileName: print_ + parameters: + variables: + desc: list of data, separated by commas + type: + - Object[] + what: + desc: data to print to console + type: + - byte + - boolean + - char + - int + - float + - String + returns: void + syntax: + - print(what) + - print(variables) type: function printArray: - description: >- - The `printArray()` function writes array data to the text area of the - Processing environment's console. A new line is put between each element of - the array. This function can only print one dimensional arrays. - - - Note that the console is relatively slow. It works well for occasional messages, but does not support high-speed, real-time output (such as at 60 frames per second). - docUrl: https://processing.org/reference/printArray_.html - name: null - parameters: - what: "Object: one-dimensional array" - returns: void - syntax: printArray(what) + description: |- + The `printArray()` function writes array data to the text + area of the Processing environment's console. A new line + is put between each element of the array. This function + can only print one dimensional arrays. + Note that the console is relatively slow. It works well + for occasional messages, but does not support high-speed, + real-time output (such as at 60 frames per second). + examples: + - | + float[] f = { 0.3, 0.4, 0.5 }; + printArray(f); + + // The above code prints: + // [0] 0.3 + // [1] 0.4 + // [2] 0.5 + fileName: printArray_ + parameters: + what: + desc: one-dimensional array + type: + - Object + returns: void + syntax: + - printArray(what) type: function printCamera: - description: Prints the current camera matrix to the Console (the text window at - the bottom of Processing). - docUrl: https://processing.org/reference/printCamera_.html - name: null + description: |- + Prints the current camera matrix to the Console (the text window at the + bottom of Processing). + examples: + - | + size(100, 100, P3D); + printCamera(); + + // The program above prints this data: + // 01.0000 00.0000 00.0000 -50.0000 + // 00.0000 01.0000 00.0000 -50.0000 + // 00.0000 00.0000 01.0000 -86.6025 + // 00.0000 00.0000 00.0000 01.0000 + fileName: printCamera_ parameters: {} returns: void - syntax: printCamera() + syntax: + - printCamera() type: function printMatrix: - description: Prints the current matrix to the Console (the text window at the - bottom of Processing). - docUrl: https://processing.org/reference/printMatrix_.html - name: null + description: |- + Prints the current matrix to the Console (the text window at the bottom + of Processing). + examples: + - | + size(100, 100, P3D); + printMatrix(); + // Prints: + // 01.0000 00.0000 00.0000 -50.0000 + // 00.0000 01.0000 00.0000 -50.0000 + // 00.0000 00.0000 01.0000 -86.6025 + // 00.0000 00.0000 00.0000 01.0000 + + resetMatrix(); + printMatrix(); + // Prints: + // 1.0000 0.0000 0.0000 0.0000 + // 0.0000 1.0000 0.0000 0.0000 + // 0.0000 0.0000 1.0000 0.0000 + // 0.0000 0.0000 0.0000 1.0000 + fileName: printMatrix_ parameters: {} returns: void - syntax: printMatrix() + syntax: + - printMatrix() type: function printProjection: - description: Prints the current projection matrix to the Console (the text - window at the bottom of Processing). - docUrl: https://processing.org/reference/printProjection_.html - name: null + description: |- + Prints the current projection matrix to the Console (the text window at + the bottom of Processing). + examples: + - | + size(100, 100, P3D); + printProjection(); + + // The program above prints this data: + // 01.7321 00.0000 00.0000 00.0000 + // 00.0000 -01.7321 00.0000 00.0000 + // 00.0000 00.0000 -01.0202 -17.4955 + // 00.0000 00.0000 -01.0000 00.0000 + fileName: printProjection_ parameters: {} returns: void - syntax: printProjection() + syntax: + - printProjection() type: function println: + description: |- + The `println()` function writes to the console area, the black + rectangle at the bottom of the Processing environment. This function is + often helpful for looking at the data a program is producing. Each call to + this function creates a new line of output. More than one parameter can be + passed into the function by separating them with commas. Alternatively, + individual elements can be separated with quotes ("") and joined with the + addition operator (+). + + Before Processing 2.1, `println()` was used to write array data to the + console. Now, use `printArray()` to write array data to the + console. + + Note that the console is relatively slow. It works well for occasional + messages, but does not support high-speed, real-time output (such as at 60 + frames per second). It should also be noted, that a println() within a for + loop can sometimes lock up the program, and cause the sketch to freeze. + examples: + - | + String s = "The size is "; + int w = 1920; + int h = 1080; + println(s); + println(w, "x", h); + + // This program writes to the console: + // The size is + // 1920 x 1080 + - | + print("begin- "); + float f = 0.3; + int i = 1024; + print("f is " + f + " and i is " + 1024); + String s = " -end"; + println(s); + + // This program writes to the console: + // "begin- f is 0.3 and i is 1024 -end" + fileName: println_ + parameters: + variables: + desc: list of data, separated by commas + type: + - Object[] + what: + desc: data to print to console + type: + - byte + - boolean + - char + - int + - float + - String + - Object + returns: void + syntax: + - println() + - println(what) + - println(variables) + type: function +private: + description: >- + This keyword is used to disallow other classes access to the fields and + methods within a class. The `private` keyword is used before a field or + method that you want to be available only within the class. In Processing, + all fields and methods are public unless otherwise specified by the + `private` keyword. + + + This keyword is an essential part of Java programming and is not usually + used with Processing. Consult a Java language reference or tutorial for more + information. + fileName: private + parameters: {} + syntax: [] + type: function +public: description: >- - The `println()` function writes to the console area, the black rectangle at - the bottom of the Processing environment. This function is often helpful for - looking at the data a program is producing. Each call to this function - creates a new line of output. More than one parameter can be passed into the - function by separating them with commas. Alternatively, individual elements - can be separated with quotes ("") and joined with the addition operator (+). - - - Before Processing 2.1, `println()` was used to write array data to the console. Now, use `printArray()` to write array data to the console. + Keyword used to provide other classes access the fields and methods within a + class. The `public` keyword is used before a field or method that you want + to make available. In Processing, all fields and methods are public unless + otherwise specified by the `private` keyword. - Note that the console is relatively slow. It works well for occasional messages, but does not support high-speed, real-time output (such as at 60 frames per second). It should also be noted, that a println() within a for loop can sometimes lock up the program, and cause the sketch to freeze. - docUrl: https://processing.org/reference/println_.html - name: null - parameters: - variables: "Object[]: list of data, separated by commas" - what: "Object, String, float, char, boolean, or byte: data to print to console" - returns: void - syntax: |- - println() - println(what) - println(variables) + This keyword is an essential part of Java programming and is not usually + used with Processing. Consult a Java language reference or tutorial for more + information. + fileName: public + parameters: {} + returns: "" + syntax: [] type: function push: - description: >- - The `push()` function saves the current drawing style settings and - transformations, while `pop()` restores these settings. Note that these - functions are always used together. They allow you to change the style and - transformation settings and later return to what you had. When a new state - is started with push(), it builds on the current style and transform - information. - - - `push()` stores information related to the current transformation state and style settings controlled by the following functions: `rotate()`, `translate()`, `scale()`, `fill()`, `stroke()`, `tint()`, `strokeWeight()`, `strokeCap()`, `strokeJoin()`, `imageMode()`, `rectMode()`, `ellipseMode()`, `colorMode()`, `textAlign()`, `textFont()`, `textMode()`, `textSize()`, `textLeading()`. - - - The `push()` and `pop()` functions were added with Processing 3.5. They can be used in place of `pushMatrix()`, `popMatrix()`, `pushStyles()`, and `popStyles()`. The difference is that push() and pop() control both the transformations (rotate,. . . - docUrl: https://processing.org/reference/push_.html - name: null + description: |- + The `push()` function saves the current drawing style + settings and transformations, while `pop()` restores these + settings. Note that these functions are always used together. + They allow you to change the style and transformation settings + and later return to what you had. When a new state is started + with push(), it builds on the current style and transform + information. + + `push()` stores information related to the current + transformation state and style settings controlled by the + following functions: `rotate()`, `translate()`, + `scale()`, `fill()`, `stroke()`, `tint()`, + `strokeWeight()`, `strokeCap()`, `strokeJoin()`, + `imageMode()`, `rectMode()`, `ellipseMode()`, + `colorMode()`, `textAlign()`, `textFont()`, + `textMode()`, `textSize()`, `textLeading()`. + + The `push()` and `pop()` functions were added with + Processing 3.5. They can be used in place of `pushMatrix()`, + `popMatrix()`, `pushStyles()`, and `popStyles()`. + The difference is that push() and pop() control both the + transformations (rotate, scale, translate) and the drawing styles + at the same time. + examples: + - |- + fill(255); + rect(0, 0, 200, 200); // White rectangle + + push(); + translate(80, 70); + fill(0); + rect(0, 0, 200, 200); // Black rectangle + pop(); // Restore original settings + + fill(100); + rect(40, 40, 200, 200); // Gray rectangle + - |- + ellipse(0, 200, 133, 133); // Left circle + + push(); + strokeWeight(40); + fill(204, 153, 0); + ellipse(200, 200, 133, 133); // Middle circle + pop(); // Restore original settings + + ellipse(400, 200, 133, 133); // Right circle + fileName: push_ parameters: {} returns: void - syntax: push() + syntax: + - push() type: function pushMatrix: - description: 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. - docUrl: https://processing.org/reference/pushMatrix_.html - name: null + description: |- + 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 conjunction with + the other transformation functions and may be embedded to control the + scope of the transformations. + examples: + - |- + size(400, 400); + + fill(255); + rect(0, 0, 200, 200); // White rectangle + + pushMatrix(); + translate(120, 80); + fill(0); + rect(0, 0, 200, 200); // Black rectangle + popMatrix(); + + fill(100); + rect(60, 40, 200, 200); // Gray rectangle + fileName: pushMatrix_ parameters: {} returns: void - syntax: pushMatrix() + syntax: + - pushMatrix() type: function pushStyle: description: >- - 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() - docUrl: https://processing.org/reference/pushStyle_.html - name: null + 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()` + examples: + - |- + size(400, 400); + + ellipse(0, 200, 132, 132); // Left circle + + pushStyle(); // Start a new style + strokeWeight(40); + fill(204, 153, 0); + ellipse(200, 200, 132, 132); // Middle circle + popStyle(); // Restore original style + + ellipse(400, 200, 132, 132); // Right circle + - |- + size(400, 400); + + ellipse(0, 200, 132, 132); // Left circle + + pushStyle(); // Start a new style + strokeWeight(40); + fill(204, 153, 0); + ellipse(132, 200, 132, 132); // Left-middle circle + + pushStyle(); // Start another new style + stroke(0, 102, 153); + ellipse(264, 200, 132, 132); // Right-middle circle + popStyle(); // Restore the previous style + + popStyle(); // Restore original style + + ellipse(400, 200, 132, 132); // Right circle + fileName: pushStyle_ parameters: {} returns: void - syntax: pushStyle() + syntax: + - pushStyle() type: function quad: - description: 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. - docUrl: https://processing.org/reference/quad_.html - name: null - parameters: - x1: "float: x-coordinate of the first corner" - x2: "float: x-coordinate of the second corner" - x3: "float: x-coordinate of the third corner" - x4: "float: x-coordinate of the fourth corner" - y1: "float: y-coordinate of the first corner" - y2: "float: y-coordinate of the second corner" - y3: "float: y-coordinate of the third corner" - y4: "float: y-coordinate of the fourth corner" - returns: void - syntax: quad(x1, y1, x2, y2, x3, y3, x4, y4) + description: |- + 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. + examples: + - |- + size(400, 400); + quad(152, 124, 344, 80, 276, 252, 120, 304); + fileName: quad_ + parameters: + x1: + desc: x-coordinate of the first corner + type: + - float + x2: + desc: x-coordinate of the second corner + type: + - float + x3: + desc: x-coordinate of the third corner + type: + - float + x4: + desc: x-coordinate of the fourth corner + type: + - float + y1: + desc: y-coordinate of the first corner + type: + - float + y2: + desc: y-coordinate of the second corner + type: + - float + y3: + desc: y-coordinate of the third corner + type: + - float + y4: + desc: y-coordinate of the fourth corner + type: + - float + returns: void + syntax: + - quad(x1, y1, x2, y2, x3, y3, x4, y4) type: function quadraticVertex: - description: Specifies vertex coordinates for quadratic Bezier curves. Each call - to `quadraticVertex()` defines the position of one control point and one - anchor point of a Bezier curve, adding a new segment to a line or shape. The - first time `quadraticVertex()` 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). - docUrl: https://processing.org/reference/quadraticVertex_.html - name: null - parameters: - cx: "float: the x-coordinate of the control point" - cy: "float: the y-coordinate of the control point" - cz: "float: the z-coordinate of the control point" - x3: "float: the x-coordinate of the anchor point" - y3: "float: the y-coordinate of the anchor point" - z3: "float: the z-coordinate of the anchor point" - returns: void - syntax: |- - quadraticVertex(cx, cy, x3, y3) - quadraticVertex(cx, cy, cz, x3, y3, z3) + description: |- + Specifies vertex coordinates for quadratic Bézier curves. Each call + to `quadraticVertex()` defines the position of one control + point and one anchor point of a Bézier curve, adding a new segment + to a line or shape. The first time `quadraticVertex()` 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). + examples: + - |- + size(400, 400); + noFill(); + strokeWeight(16); + beginShape(); + vertex(80, 80); + quadraticVertex(320, 80, 200, 200); + endShape(); + - |- + size(400, 400); + noFill(); + strokeWeight(16); + beginShape(); + vertex(80, 80); + quadraticVertex(320, 80, 200, 200); + quadraticVertex(80, 320, 320, 320); + vertex(320, 240); + endShape(); + fileName: quadraticVertex_ + parameters: + cx: + desc: the x-coordinate of the control point + type: + - float + cy: + desc: the y-coordinate of the control point + type: + - float + cz: + desc: the z-coordinate of the control point + type: + - float + x3: + desc: the x-coordinate of the anchor point + type: + - float + y3: + desc: the y-coordinate of the anchor point + type: + - float + z3: + desc: the z-coordinate of the anchor point + type: + - float + returns: void + syntax: + - quadraticVertex(cx, cy, x3, y3) + - quadraticVertex(cx, cy, cz, x3, y3, z3) type: function radians: - description: 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. - docUrl: https://processing.org/reference/radians_.html - name: null - parameters: - degrees: "float: degree value to convert to radians" + description: |- + 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. + examples: + - | + float deg = 45.0; + float rad = radians(deg); + println(deg + " degrees is " + rad + " radians"); + fileName: radians_ + parameters: + degrees: + desc: degree value to convert to radians + type: + - float returns: float - syntax: radians(degrees) + syntax: + - radians(degrees) type: function random: - description: >- - Generates random numbers. Each time the `random()` function is called, it - returns an unexpected value within the specified range. If only one - parameter is passed to the function, it will return a float between zero and - the value of the `high` parameter. For example, `random(5)` returns values - between 0 and 5 (starting at zero, and up to, but not including, 5). - - - If two parameters are specified, the function will return a float with a value between the two values. For example, `random(-5, 10.2)` returns values starting at -5 and up to (but not including) 10.2. To convert a floating-point random number to an integer, use the `int()` function. - docUrl: https://processing.org/reference/random_.html - name: null - parameters: - high: "float: upper limit" - low: "float: lower limit" + description: |- + Generates random numbers. Each time the `random()` function is called, + it returns an unexpected value within the specified range. If only one + parameter is passed to the function, it will return a float between zero + and the value of the `high` parameter. For example, `random(5)` + returns values between 0 and 5 (starting at zero, and up to, but not + including, 5). + + If two parameters are specified, the function will return a float with a + value between the two values. For example, `random(-5, 10.2)` returns + values starting at -5 and up to (but not including) 10.2. To convert a + floating-point random number to an integer, use the `int()` function. + examples: + - | + for (int i = 0; i < 100; i++) { + float r = random(50); + stroke(r*5); + line(50, i, 50+r, i); + } + - | + for (int i = 0; i < 100; i++) { + float r = random(-50, 50); + println(r); + } + - | + // Get a random element from an array + String[] words = { "apple", "bear", "cat", "dog" }; + int index = int(random(words.length)); // Same as int(random(4)) + println(words[index]); // Prints one of the four words + fileName: random_ + parameters: + high: + desc: upper limit + type: + - float + low: + desc: lower limit + type: + - float returns: float - syntax: |- - random(high) - random(low, high) + syntax: + - random(high) + - random(low, high) type: function randomGaussian: - description: 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. - docUrl: https://processing.org/reference/randomGaussian_.html - name: null + description: |- + 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. + examples: + - |- + size(400, 400); + for (int y = 0; y < 400; y++) { + float x = randomGaussian() * 60; + line(200, y, 200 + x, y); + } + - |- + float[] distribution = new float[360]; + + void setup() { + size(400, 400); + for (int i = 0; i < distribution.length; i++) { + distribution[i] = int(randomGaussian() * 60); + } + } + + void draw() { + background(204); + + translate(width/2, width/2); + + for (int i = 0; i < distribution.length; i++) { + rotate(TWO_PI/distribution.length); + stroke(0); + float dist = abs(distribution[i]); + line(0, 0, dist, 0); + } + } + fileName: randomGaussian_ parameters: {} returns: float - syntax: randomGaussian() + syntax: + - randomGaussian() type: function randomSeed: - description: Sets the seed value for `random()`. By default, `random()` produces - different results each time the program is run. Set the `seed` parameter to - a constant to return the same pseudo-random numbers each time the software - is run. - docUrl: https://processing.org/reference/randomSeed_.html - name: null + description: |- + Sets the seed value for `random()`. By default, `random()` + produces different results each time the program is run. Set the `seed` + parameter to a constant to return the same pseudo-random numbers each time + the software is run. + examples: + - |+ + randomSeed(0); + for (int i=0; i < 100; i++) { + float r = random(0, 255); + stroke(r); + line(i, 0, i, 100); + } + + fileName: randomSeed_ parameters: - seed: "int: seed value" + seed: + desc: seed value + type: + - int returns: void - syntax: randomSeed(seed) + syntax: + - randomSeed(seed) type: function rect: description: >- 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. The way these parameters are interpreted, however, may be - changed with the `rectMode()` function. - - - To draw a rounded rectangle, add a fifth parameter, which is used as the radius value for all four corners. - - - To use a different radius value for each corner, include eight parameters. When using eight parameters, the latter four set the radius of the arc at each corner separately, starting with the top-left corner and moving clockwise around the rectangle. - docUrl: https://processing.org/reference/rect_.html - name: null - parameters: - a: "float: x-coordinate of the rectangle by default" - b: "float: y-coordinate of the rectangle by default" - bl: "float: radius for bottom-left corner" - br: "float: radius for bottom-right corner" - c: "float: width of the rectangle by default" - d: "float: height of the rectangle by default" - r: "float: radii for all four corners" - tl: "float: radius for top-left corner" - tr: "float: radius for top-right corner" - returns: void - syntax: |- - rect(a, b, c, d) - rect(a, b, c, d, r) - rect(a, b, c, d, tl, tr, br, bl) + 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. The way these parameters are interpreted, however, may be + changed with the `rectMode()` function. + + To draw a rounded rectangle, add a fifth parameter, which is used as the + radius value for all four corners. + + To use a different radius value for each corner, include eight parameters. + When using eight parameters, the latter four set the radius of the arc at + each corner separately, starting with the top-left corner and moving + clockwise around the rectangle. + examples: + - | + size(400, 400); + rect(120, 80, 220, 220); + - |- + size(400, 400); + rect(120, 80, 220, 220, 28); + - |- + size(400, 400); + rect(120, 80, 220, 220, 12, 24, 48, 72); + fileName: rect_ + parameters: + a: + desc: x-coordinate of the rectangle by default + type: + - float + b: + desc: y-coordinate of the rectangle by default + type: + - float + bl: + desc: radius for bottom-left corner + type: + - float + br: + desc: radius for bottom-right corner + type: + - float + c: + desc: width of the rectangle by default + type: + - float + d: + desc: height of the rectangle by default + type: + - float + r: + desc: radii for all four corners + type: + - float + tl: + desc: radius for top-left corner + type: + - float + tr: + desc: radius for top-right corner + type: + - float + returns: void + syntax: + - rect(a, b, c, d) + - rect(a, b, c, d, r) + - rect(a, b, c, d, tl, tr, br, bl) type: function rectMode: - description: >- + description: |- Modifies the location from which rectangles are drawn by changing the way in - which parameters given to `rect()` are intepreted. + which parameters given to `rect()` are interpreted. + + The default mode is `rectMode(CORNER)`, which interprets the first two + parameters of `rect()` as the upper-left corner of the shape, while the + third and fourth parameters are its width and height. + + `rectMode(CORNERS)` interprets the first two parameters of `rect()` + as the location of one corner, and the third and fourth parameters as the + location of the opposite corner. + + `rectMode(CENTER)` interprets the first two parameters of `rect()` + as the shape's center point, while the third and fourth parameters are its + width and height. + + `rectMode(RADIUS)` also uses the first two parameters of `rect()` + as the shape's center point, but uses the third and fourth parameters to + specify half of the shape's width and height. + + The parameter must be written in ALL CAPS because Processing is a + case-sensitive language. + examples: + - |- + size(400, 400); + rectMode(CORNER); // Default rectMode is CORNER + fill(255); // Set fill to white + rect(100, 100, 200, 200); // Draw white rect using CORNER mode + + rectMode(CORNERS); // Set rectMode to CORNERS + fill(100); // Set fill to gray + rect(100, 100, 200, 200); // Draw gray rect using CORNERS mode + - |- + size(400, 400); + rectMode(RADIUS); // Set rectMode to RADIUS + fill(255); // Set fill to white + rect(200, 200, 120, 120); // Draw white rect using RADIUS mode + + rectMode(CENTER); // Set rectMode to CENTER + fill(100); // Set fill to gray + rect(200, 200, 120, 120); // Draw gray rect using CENTER mode + fileName: rectMode_ + parameters: + mode: + desc: either CORNER, CORNERS, CENTER, or RADIUS + type: + - int + returns: void + syntax: + - rectMode(mode) + type: function +red: + description: >- + Extracts the red value from a color, scaled to match current + `colorMode()`. The 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 understand, but it is slower + than a technique called bit shifting. When working in `colorMode(RGB, + 255)`, you can achieve the same results as `red()` but with greater + speed by using the right shift operator (`>>`) with a bit mask. For + example, the following two lines of code are equivalent means of getting the + red value of the color value `c`: + + + ` + float r1 = red(c); // Simpler, but slower to calculate + float r2 = c >> 16 & 0xFF; // Very fast to calculate + ` + examples: + - |- + size(400, 400); + + color c = color(255, 204, 0); // Define color 'c' + fill(c); // Use color variable 'c' as fill color + rect(60, 80, 140, 240); // Draw left rectangle + + float redValue = red(c); // Get red in 'c' + println(redValue); // Print "255.0" + fill(redValue, 0, 0); // Use 'redValue' in new fill + rect(200, 80, 140, 240); // Draw right rectangle + fileName: red_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int + returns: float + syntax: + - red(rgb) + type: function +redraw: + description: >- + 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. - The default mode is `rectMode(CORNER)`, which interprets the first two parameters of `rect()` as the upper-left corner of the shape, while the third and fourth parameters are its width and height. + In 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). + The `redraw()` function does not work properly when called inside + `draw()`. To enable/disable animations, use `loop()` and + `noLoop()`. + examples: + - | + float x = 0; - `rectMode(CORNERS)` interprets the first two parameters of `rect()` as the location of one corner, and the third and fourth parameters as the location of the opposite corner. + void setup() { + size(200, 200); + noLoop(); + } + void draw() { + background(204); + line(x, 0, x, height); + } - `rectMode(CENTER)` interprets the first two parameters of `rect()` as the shape's center point, while the third and fourth parameters are its width and height. - - - `rectMode(RADIUS)` also uses the first two parameters of `rect()` as the shape's center point, but uses the third and fourth parameters to specify half of the shapes's width and height. - - - The parameter must be written in ALL CAPS because Processing is a case-sensitive language. - docUrl: https://processing.org/reference/rectMode_.html - name: null - parameters: - mode: "int: either CORNER, CORNERS, CENTER, or RADIUS" - returns: void - syntax: rectMode(mode) - type: function -red: - description: >- - Extracts the red value from a color, scaled to match current `colorMode()`. - The 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 understand, but it is slower than a technique called bit shifting. When working in `colorMode(RGB, 255)`, you can acheive the same results as `red()` but with greater speed by using the right shift operator (`>>`) with a bit mask. For example, the following two lines of code are equivalent means of getting the red value of the color value `c`: - - - `float r1 = red(c); // Simpler, but slower to calculate - - float r2 = c >> 16 & 0xFF; // Very fast to calculate` - docUrl: https://processing.org/reference/red_.html - name: null - parameters: - rgb: "int: any value of the color datatype" - returns: float - syntax: red(rgb) - type: function -redraw: - description: >- - 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. - - - In 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). - - - The `redraw()` function does not work properly when called inside `draw()`. To enable/disable animations, use `loop()` and `noLoop()`. - docUrl: https://processing.org/reference/redraw_.html - name: null + void mousePressed() { + x += 1; + redraw(); + } + fileName: redraw_ parameters: {} returns: void - syntax: redraw() + syntax: + - redraw() type: function requestImage: - description: >- + description: |- This function loads images on a separate thread so that your sketch doesn't - 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. - + freeze while images load during `setup()`. While the image is loading, + its width and height will be 0. If an error occurs while loading the image, + its width and height will be set to -1. You'll know when the image has + loaded properly because its `width` and `height` will be greater + than 0. Asynchronous image loading (particularly when downloading from a + server) can dramatically improve performance. + + The `extension` parameter is used to determine the image type in cases + where the image filename does not end with a proper extension. Specify the + extension as the second parameter to `requestImage()`. + examples: + - | + PImage bigImage; + + void setup() { + bigImage = requestImage("something.jpg"); + } - The `extension` parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to `requestImage()`. - docUrl: https://processing.org/reference/requestImage_.html - name: null - parameters: - extension: 'String: the type of image to load, for example "png", "gif", "jpg"' - filename: "String: name of the file to load, can be .gif, .jpg, .tga, or a - handful of other image types depending on your platform" + void draw() { + if (bigImage.width == 0) { + // Image is not yet loaded + } else if (bigImage.width == -1) { + // This means an error occurred during image loading + } else { + // Image is ready to go, draw it + image(bigImage, 0, 0); + } + } + fileName: requestImage_ + parameters: + extension: + desc: the type of image to load, for example "png", "gif", "jpg" + type: + - String + filename: + desc: |- + name of the file to load, can be .gif, .jpg, .tga, or a handful of + other image types depending on your platform + type: + - String returns: PImage - syntax: |- - requestImage(filename) - requestImage(filename, extension) + syntax: + - requestImage(filename) + - requestImage(filename, extension) type: function resetMatrix: - description: Replaces the current matrix with the identity matrix. The - equivalent function in OpenGL is `glLoadIdentity()`. - docUrl: https://processing.org/reference/resetMatrix_.html - name: null + description: |- + Replaces the current matrix with the identity matrix. + The equivalent function in OpenGL is `glLoadIdentity()`. + examples: + - |- + size(400, 400, P3D); + noFill(); + box(320); + printMatrix(); + // Prints: + // 001.0000 000.0000 000.0000 -200.0000 + // 000.0000 001.0000 000.0000 -200.0000 + // 000.0000 000.0000 001.0000 -346.4102 + // 000.0000 000.0000 000.0000 001.0000 + + resetMatrix(); + box(320); + printMatrix(); + // Prints: + // 1.0000 0.0000 0.0000 0.0000 + // 0.0000 1.0000 0.0000 0.0000 + // 0.0000 0.0000 1.0000 0.0000 + // 0.0000 0.0000 0.0000 1.0000 + fileName: resetMatrix_ parameters: {} returns: void - syntax: resetMatrix() + syntax: + - resetMatrix() type: function resetShader: - description: Restores the default shaders. Code that runs after `resetShader()` - will not be affected by previously defined shaders. - docUrl: https://processing.org/reference/resetShader_.html - name: null + description: |- + Restores the default shaders. Code that runs after `resetShader()` + will not be affected by previously defined shaders. + examples: + - | + PShader edges; + PImage img; + + void setup() { + size(640, 360, P2D); + img = loadImage("leaves.jpg"); + edges = loadShader("edges.glsl"); + } + + void draw() { + shader(edges); + image(img, 0, 0); + resetShader(); + image(img, width/2, 0); + } + fileName: resetShader_ parameters: - kind: "int: type of shader, either POINTS, LINES, or TRIANGLES" + kind: + desc: type of shader, either POINTS, LINES, or TRIANGLES + type: + - int returns: void - syntax: |- - resetShader() - resetShader(kind) + syntax: + - resetShader() + - resetShader(kind) + type: function +return: + description: >- + Keyword used to indicate the value to return from a function. The value + being returned must be the same datatype as defined in the function + declaration. Functions declared with `void` can't return values and + shouldn't include a return value. + + + The keyword `return` may also be used to break out of a function, thus not + allowing the program to the remaining statements. (See the third example + above.) + examples: + - | + int val = 30; + + void draw() { + int t = timestwo(val); + println(t); + } + + // The first 'int' in the function declaration + // specifies the type of data to be returned. + int timestwo(int dVal) { + dVal = dVal * 2; + return dVal; // Returns an int of 60, in this case + } + - | + int[] vals = {10, 20, 30}; + + void draw() { + int[] t = timestwo(vals); + println(t); + noLoop(); + } + + int[] timestwo(int[] dVals) { + for (int i = 0; i < dVals.length; i++) { + dVals[i] = dVals[i] * 2; + } + return dVals; // Returns an array of 3 ints: 20, 40, 60 + } + - | + void draw() { + background(204); + line(0, 0, width, height); + if (mousePressed) { + return; // Break out of draw(), skipping the line statement below + } + line(0, height, width, 0); // Executed only if mouse is not pressed + } + fileName: return + parameters: + function: + desc: the function that is being defined + type: [] + statements: + desc: any valid statements + type: [] + type: + desc: boolean, byte, char, int, float, String, boolean[], byte[], char[], int[], + float[], or String[] + type: [] + value: + desc: must be the same datatype as the "type" parameter + type: [] + returns: "" + syntax: + - type function { + - " statements" + - " return value" + - "}" type: function reverse: description: Reverses the order of an array. - docUrl: https://processing.org/reference/reverse_.html - name: null - parameters: - list: "Object, String[], float[], int[], char[], byte[], or boolean[]: - booleans[], bytes[], chars[], ints[], floats[], or Strings[]" + examples: + - | + String sa[] = { "OH", "NY", "MA", "CA"}; + sa = reverse(sa); + println(sa); + // Prints updated array contents to the console: + // [0] "CA" + // [1] "MA" + // [2] "NY" + // [3] "OH" + fileName: reverse_ + parameters: + list: + desc: booleans[], bytes[], chars[], ints[], floats[], or Strings[] + type: + - boolean[] + - byte[] + - char[] + - int[] + - float[] + - String[] + - Object returns: boolean[], byte[], char[], int[], float[], String[], or Object - syntax: reverse(list) + syntax: + - reverse(list) type: function rotate: - description: >- - Rotates the amount specified by the `angle` parameter. Angles must be - specified in radians (values from `0` to `TWO_PI`), or they can be converted - from degrees to radians with the `radians()` function. - - The coordinates are always rotated around their relative position to the origin. Positive numbers rotate objects in a clockwise direction and negative numbers rotate in the couterclockwise direction. Transformations apply to everything that happens afterward, and subsequent calls to the function compound the effect. For example, calling `rotate(PI/2.0)` once and then calling `rotate(PI/2.0)` a second time is the same as a single `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 `pushMatrix()` and `popMatrix()`. - docUrl: https://processing.org/reference/rotate_.html - name: null - parameters: - angle: "float: angle of rotation specified in radians" - returns: void - syntax: rotate(angle) + description: |- + 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 transformations 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()`. + examples: + - | + size(400, 400); + translate(width/2, height/2); + rotate(PI/3.0); + rect(-104, -104, 208, 208); + fileName: rotate_ + parameters: + angle: + desc: angle of rotation specified in radians + type: + - float + returns: void + syntax: + - rotate(angle) type: function rotateX: - description: Rotates 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 from degrees to radians with the `radians()` function. - Coordinates are always rotated around their relative position to the origin. - Positive numbers rotate in a clockwise direction and negative numbers rotate - 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 run 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. - docUrl: https://processing.org/reference/rotateX_.html - name: null - parameters: - angle: "float: angle of rotation specified in radians" - returns: void - syntax: rotateX(angle) + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + translate(width/2, height/2); + rotateX(PI/3.0); + rect(-104, -104, 208, 208); + - |- + size(400, 400, P3D); + translate(width/2, height/2); + rotateX(radians(60)); + rect(-104, -104, 208, 208); + fileName: rotateX_ + parameters: + angle: + desc: angle of rotation specified in radians + type: + - float + returns: void + syntax: + - rotateX(angle) type: function rotateY: - description: Rotates 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 from degrees to radians with the `radians()` function. - Coordinates are always rotated around their relative position to the origin. - Positive numbers rotate in a clockwise direction and negative numbers rotate - 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 run 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. - docUrl: https://processing.org/reference/rotateY_.html - name: null - parameters: - angle: "float: angle of rotation specified in radians" - returns: void - syntax: rotateY(angle) + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + translate(width/2, height/2); + rotateY(PI/3.0); + rect(-104, -104, 208, 208); + - |- + size(400, 400, P3D); + translate(width/2, height/2); + rotateY(radians(60)); + rect(-104, -104, 208, 208); + fileName: rotateY_ + parameters: + angle: + desc: angle of rotation specified in radians + type: + - float + returns: void + syntax: + - rotateY(angle) type: function rotateZ: - description: Rotates 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 from degrees to radians with the `radians()` function. - Coordinates are always rotated around their relative position to the origin. - Positive numbers rotate in a clockwise direction and negative numbers rotate - 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 run 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. - docUrl: https://processing.org/reference/rotateZ_.html - name: null - parameters: - angle: "float: angle of rotation specified in radians" - returns: void - syntax: rotateZ(angle) + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + translate(width/2, height/2); + rotateZ(PI/3.0); + rect(-104, -104, 208, 208); + - |- + size(400, 400, P3D); + translate(width/2, height/2); + rotateZ(radians(60)); + rect(-104, -104, 208, 208); + fileName: rotateZ_ + parameters: + angle: + desc: angle of rotation specified in radians + type: + - float + returns: void + syntax: + - rotateZ(angle) type: function round: - description: Calculates the integer closest to the `n` parameter. For example, - `round(133.8)` returns the value 134. - docUrl: https://processing.org/reference/round_.html - name: null + description: |- + Calculates the integer closest to the `n` parameter. For example, + `round(133.8)` returns the value 134. + examples: + - |+ + float x = 9.2; + int rx = round(x); // Sets 'rx' to 9 + + float y = 9.5; + int ry = round(y); // Sets 'ry' to 10 + + float z = 9.9; + int rz = round(z); // Sets 'rz' to 10 + + fileName: round_ parameters: - n: "float: number to round" + n: + desc: number to round + type: + - float returns: int - syntax: round(n) + syntax: + - round(n) type: function saturation: description: Extracts the saturation value from a color. - docUrl: https://processing.org/reference/saturation_.html - name: null - parameters: - rgb: "int: any value of the color datatype" + examples: + - |- + size(400, 400); + noStroke(); + colorMode(HSB, 255); + color c = color(0, 126, 255); + fill(c); + rect(60, 80, 140, 240); + float value = saturation(c); // Sets 'value' to 504 + fill(value); + rect(200, 80, 140, 240); + fileName: saturation_ + parameters: + rgb: + desc: any value of the color datatype + type: + - int returns: float - syntax: saturation(rgb) + syntax: + - saturation(rgb) type: function save: - description: >- + description: |- Saves an image from the display window. 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. Alternatively, the - files can be saved to any location on the computer by using an absolute path - (something that starts with / on Unix and Linux, or a drive letter on - Windows). - - - All images saved from the main drawing window will be opaque. To save images without a background, use `createGraphics()`. - docUrl: https://processing.org/reference/save_.html - name: null - parameters: - filename: "String: any sequence of letters and numbers" - returns: void - syntax: save(filename) + 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. + Alternatively, the files can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). + + All images saved from the main drawing window will be opaque. To save + images without a background, use `createGraphics()`. + examples: + - | + line(20, 20, 80, 80); + // Saves a TIFF file named "diagonal.tif" + save("diagonal.tif"); + // Saves a TARGA file named "cross.tga" + line(80, 20, 20, 80); + save("cross.tga"); + fileName: save_ + parameters: + filename: + desc: any sequence of letters and numbers + type: + - String + returns: void + syntax: + - save(filename) type: function saveBytes: - description: As the opposite of `loadBytes()`, this function 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. Alternatively, the files can be saved - to any location on the computer by using an absolute path (something that - starts with / on Unix and Linux, or a drive letter on Windows). - docUrl: https://processing.org/reference/saveBytes_.html - name: null - parameters: - data: "byte[]: array of bytes to be written" - filename: "String: name of the file to write to" - returns: void - syntax: saveBytes(filename, data) + description: |- + As the opposite of `loadBytes()`, this function 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. Alternatively, the files can be saved to + any location on the computer by using an absolute path (something that + starts with / on Unix and Linux, or a drive letter on Windows). + examples: + - | + byte[] nums = { 0, 34, 5, 127, 52}; + + // Writes the bytes to a file + saveBytes("numbers.dat", nums); + fileName: saveBytes_ + parameters: + data: + desc: array of bytes to be written + type: + - byte[] + filename: + desc: name of the file to write to + type: + - String + returns: void + syntax: + - saveBytes(filename, data) type: function saveFrame: - description: >- + description: |- 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()`. Use the Movie Maker program in the - Tools menu to combine these images to a movie. - - - If `saveFrame()` is used without parameters, it will save files as screen-0000.tif, screen-0001.tif, and so on. You can specify the name of the sequence with the `filename` parameter, including hash marks (####), which will be replaced by the current `frameCount` value. (The number of hash marks is used to determine how many digits to include in the file names.) Append a file extension, to indicate the file format to be used: either TIFF (.tif), TARGA (.tga), JPEG (.jpg), or PNG (.png). Image files are saved to the sketch's folder, which may be opened by selecting "Show Sketch Folder" from the "Sketch" menu. - - - Alternatively, the files can be saved to any loc. . . - docUrl: https://processing.org/reference/saveFrame_.html - name: null + 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()`. Use the Movie Maker program + in the Tools menu to combine these images to a movie. + + If `saveFrame()` is used without parameters, it will save files as + screen-0000.tif, screen-0001.tif, and so on. You can specify the name of + the sequence with the `filename` parameter, including hash marks + (####), which will be replaced by the current `frameCount` value. (The + number of hash marks is used to determine how many digits to include in the + file names.) Append a file extension, to indicate the file format to be + used: either TIFF (.tif), TARGA (.tga), JPEG (.jpg), or PNG (.png). Image + files are saved to the sketch's folder, which may be opened by selecting + "Show Sketch Folder" from the "Sketch" menu. + + Alternatively, the files can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). + + All images saved from the main drawing window will be opaque. To save + images without a background, use `createGraphics()`. + examples: + - | + int x = 0; + void draw() { + background(204); + if (x < 100) { + line(x, 0, x, 100); + x = x + 1; + } else { + noLoop(); + } + // Saves each frame as screen-0001.tif, screen-0002.tif, etc. + saveFrame(); + } + - | + int x = 0; + void draw() { + background(204); + if (x < 100) { + line(x, 0, x, 100); + x = x + 1; + } else { + noLoop(); + } + // Saves each frame as line-000001.png, line-000002.png, etc. + saveFrame("line-######.png"); + } + fileName: saveFrame_ parameters: - filename: 'String: any sequence of letters or numbers that ends with either - ".tif", ".tga", ".jpg", or ".png"' + filename: + desc: |- + any sequence of letters or numbers that ends with either ".tif", + ".tga", ".jpg", or ".png" + type: + - String returns: void - syntax: |- - saveFrame() - saveFrame(filename) + syntax: + - saveFrame() + - saveFrame(filename) type: function saveJSONArray: - description: >- - Writes the contents of a `JSONArray` object to a file. By default, this file - is saved to the sketch's folder. This folder is opened by selecting "Show - Sketch Folder" from the "Sketch" menu. + description: |- + Writes the contents of a `JSONArray` object to a file. By default, + this file is saved to the sketch's folder. This folder is opened by + selecting "Show Sketch Folder" from the "Sketch" menu. + Alternatively, the file can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). - Alternatively, the file can be saved to any location on the computer by using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows). + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - | + String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" }; + String[] names = { "Goat", "Leopard", "Zebra" }; + JSONArray values; - All files loaded and saved by the Processing API use UTF-8 encoding. - docUrl: https://processing.org/reference/saveJSONArray_.html - name: null - parameters: - filename: "String: the name of the file to save to" - json: "JSONArray: the JSONArray to save" - options: 'String: "compact" and "indent=N", replace N with the number of spaces' + void setup() { + + values = new JSONArray(); + + for (int i = 0; i < species.length; i++) { + + JSONObject animal = new JSONObject(); + + animal.setInt("id", i); + animal.setString("species", species[i]); + animal.setString("name", names[i]); + + values.setJSONObject(i, animal); + } + + saveJSONArray(values, "data/new.json"); + } + + // Sketch saves the following to a file called "new.json": + // [ + // { + // "id": 0, + // "species": "Capra hircus", + // "name": "Goat" + // }, + // { + // "id": 1, + // "species": "Panthera pardus", + // "name": "Leopard" + // }, + // { + // "id": 2, + // "species": "Equus zebra", + // "name": "Zebra" + // } + // ] + fileName: saveJSONArray_ + parameters: + filename: + desc: the name of the file to save to + type: + - String + json: + desc: the JSONArray to save + type: + - JSONArray + options: + desc: '"compact" and "indent=N", replace N with the number of spaces' + type: + - String returns: boolean - syntax: |- - saveJSONArray(json, filename) - saveJSONArray(json, filename, options) + syntax: + - saveJSONArray(json, filename) + - saveJSONArray(json, filename, options) type: function saveJSONObject: - description: >- - Writes the contents of a `JSONObject` object to a file. By default, this - file is saved to the sketch's folder. This folder is opened by selecting - "Show Sketch Folder" from the "Sketch" menu. + description: |- + Writes the contents of a `JSONObject` object to a file. By default, + this file is saved to the sketch's folder. This folder is opened by + selecting "Show Sketch Folder" from the "Sketch" menu. + Alternatively, the file can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). - Alternatively, the file can be saved to any location on the computer by using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows). + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - | + JSONObject json; + void setup() { - All files loaded and saved by the Processing API use UTF-8 encoding. - docUrl: https://processing.org/reference/saveJSONObject_.html - name: null - parameters: - filename: "String: the name of the file to save to" - json: "JSONObject: the JSONObject to save" - options: 'String: "compact" and "indent=N", replace N with the number of spaces' + json = new JSONObject(); + + json.setInt("id", 0); + json.setString("species", "Panthera leo"); + json.setString("name", "Lion"); + + saveJSONObject(json, "data/new.json"); + } + + // Sketch saves the following to a file called "new.json": + // { + // "id": 0, + // "species": "Panthera leo", + // "name": "Lion" + // } + fileName: saveJSONObject_ + parameters: + filename: + desc: the name of the file to save to + type: + - String + json: + desc: the JSONObject to save + type: + - JSONObject + options: + desc: '"compact" and "indent=N", replace N with the number of spaces' + type: + - String returns: boolean - syntax: |- - saveJSONObject(json, filename) - saveJSONObject(json, filename, options) + syntax: + - saveJSONObject(json, filename) + - saveJSONObject(json, filename, options) type: function saveStream: - description: >- + description: |- 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). - - The `target` parameter can be either a String specifying a file name, or, for greater control over the file location, a `File` object. (Note that, unlike some other functions, this will not automatically compress or uncompress gzip files.) - docUrl: https://processing.org/reference/saveStream_.html - name: null - parameters: - source: "String: location to read from (a filename, path, or URL)" - target: "File, or String: name of the file to write to" + basically `saveBytes(blah, loadBytes())`, but done more efficiently + (and with less confusing syntax). + + The `target` parameter can be either a String specifying a file name, + or, for greater control over the file location, a `File` object. (Note + that, unlike some other functions, this will not automatically compress or + uncompress gzip files.) + fileName: saveStream_ + parameters: + source: + desc: location to read from (a filename, path, or URL) + type: + - String + target: + desc: name of the file to write to + type: + - String + - File returns: boolean or void - syntax: saveStream(target, source) + syntax: + - saveStream(target, source) type: function saveStrings: - description: >- + description: |- Writes an array of Strings to a file, one line per String. By default, this - file is saved to the sketch's folder. This folder is opened by selecting - "Show Sketch Folder" from the "Sketch" menu. + file is saved to the sketch's folder. This folder is opened by selecting + "Show Sketch Folder" from the "Sketch" menu. + + Alternatively, the file can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). + + Starting with Processing 1.0, all files loaded and saved by the Processing + API use UTF-8 encoding. In earlier releases, the default encoding for your + platform was used, which causes problems when files are moved to other + platforms. + examples: + - | + String words = "apple bear cat dog"; + String[] list = split(words, ' '); + + // Writes the strings to a file, each on a separate line + saveStrings("nouns.txt", list); + fileName: saveStrings_ + parameters: + data: + desc: string array to be written + type: + - String[] + filename: + desc: filename for output + type: + - String + returns: void + syntax: + - saveStrings(filename, data) + type: function +saveTable: + description: |- + Writes the contents of a Table object to a file. By default, this file is + saved to the sketch's folder. This folder is opened by selecting "Show + Sketch Folder" from the "Sketch" menu. + Alternatively, the file can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). - Alternatively, the file can be saved to any location on the computer by using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows). + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - | + Table table; + void setup() { - Starting with Processing 1.0, all files loaded and saved by the Processing API use UTF-8 encoding. In earlier releases, the default encoding for your platform was used, which causes problems when files are moved to other platforms. - docUrl: https://processing.org/reference/saveStrings_.html - name: null - parameters: - data: "String[]: string array to be written" - filename: "String: filename for output" - returns: void - syntax: saveStrings(filename, data) - type: function -saveTable: - description: >- - Writes the contents of a Table object to a file. By default, this file is - saved to the sketch's folder. This folder is opened by selecting "Show - Sketch Folder" from the "Sketch" menu. + table = new Table(); + table.addColumn("id"); + table.addColumn("species"); + table.addColumn("name"); - Alternatively, the file can be saved to any location on the computer by using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows). + TableRow newRow = table.addRow(); + newRow.setInt("id", table.getRowCount() - 1); + newRow.setString("species", "Panthera leo"); + newRow.setString("name", "Lion"); + saveTable(table, "data/new.csv"); + } - All files loaded and saved by the Processing API use UTF-8 encoding. - docUrl: https://processing.org/reference/saveTable_.html - name: null - parameters: - filename: "String: the filename to which the Table should be saved" - options: 'String: can be one of "tsv", "csv", "bin", or "html"' - table: "Table: the Table object to save to a file" + // Sketch saves the following to a file called "new.csv": + // id,species,name + // 0,Panthera leo,Lion + fileName: saveTable_ + parameters: + filename: + desc: the filename to which the Table should be saved + type: + - String + options: + desc: can be one of "tsv", "csv", "bin", or "html" + type: + - String + table: + desc: the Table object to save to a file + type: + - Table returns: boolean - syntax: |- - saveTable(table, filename) - saveTable(table, filename, options) + syntax: + - saveTable(table, filename) + - saveTable(table, filename, options) type: function saveXML: - description: >- + description: |- Writes the contents of an XML object to a file. By default, this file is - saved to the sketch's folder. This folder is opened by selecting "Show - Sketch Folder" from the "Sketch" menu. - - - Alternatively, the file can be saved to any location on the computer by using an absolute path (something that starts with / on Unix and Linux, or a drive letter on Windows). - + saved to the sketch's folder. This folder is opened by selecting "Show + Sketch Folder" from the "Sketch" menu. + + Alternatively, the file can be saved to any location on the computer by + using an absolute path (something that starts with / on Unix and Linux, or + a drive letter on Windows). + + All files loaded and saved by the Processing API use UTF-8 encoding. + examples: + - |- + // The following short XML file called "mammals.xml" is parsed + // in the code below. It must be in the project's "data" folder. + // + // + // + // Goat + // Leopard + // Zebra + // + + XML xml; + + void setup() { + xml = loadXML("mammals.xml"); + XML firstChild = xml.getChild("animal"); + xml.removeChild(firstChild); + saveXML(xml, "subset.xml"); + } - All files loaded and saved by the Processing API use UTF-8 encoding. - docUrl: https://processing.org/reference/saveXML_.html - name: null - parameters: - filename: "String: name of the file to write to" - xml: "XML: the XML object to save to disk" + // Sketch saves the following to a file called "subset.xml": + // + // + // Leopard + // Zebra + // + fileName: saveXML_ + parameters: + filename: + desc: name of the file to write to + type: + - String + xml: + desc: the XML object to save to disk + type: + - XML returns: boolean - syntax: saveXML(xml, filename) + syntax: + - saveXML(xml, filename) type: function scale: - description: >- + description: |- 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 function with the `z` parameter requires using P3D as a parameter for `size()`, as shown in the third example above. This function can be further controlled with `pushMatrix()` and `popMatrix()`. - docUrl: https://processing.org/reference/scale_.html - name: null - parameters: - s: "float: percentage to scale the object" - x: "float: percentage to scale the object in the x-axis" - y: "float: percentage to scale the object in the y-axis" - z: "float: percentage to scale the object in the z-axis" - returns: void - syntax: |- - scale(s) - scale(x, y) - scale(x, y, z) + 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 function with the `z` parameter + requires using P3D as a parameter for `size()`, as shown in the third + example above. This function can be further controlled with + `pushMatrix()` and `popMatrix()`. + examples: + - |- + size(400, 400); + rect(120, 80, 200, 200); + scale(0.5); + rect(120, 80, 200, 200); + - |- + size(400, 400); + rect(120, 80, 200, 200); + scale(0.5, 1.3); + rect(120, 80, 200, 200); + - |- + // Scaling in 3D requires P3D + // as a parameter to size() + size(400, 400, P3D); + noFill(); + translate(width/2+48, height/2); + box(80, 80, 80); + scale(2.5, 2.5, 2.5); + box(80, 80, 80); + fileName: scale_ + parameters: + s: + desc: percentage to scale the object + type: + - float + x: + desc: percentage to scale the object in the x-axis + type: + - float + y: + desc: percentage to scale the object in the y-axis + type: + - float + z: + desc: percentage to scale the object in the z-axis + type: + - float + returns: void + syntax: + - scale(s) + - scale(x, y) + - scale(x, y, z) type: function screenX: - description: Takes a three-dimensional X, Y, Z position and returns the X value - for where it will appear on a (two-dimensional) screen. - docUrl: https://processing.org/reference/screenX_.html - name: null - parameters: - x: "float: 3D x-coordinate to be mapped" - y: "float: 3D y-coordinate to be mapped" - z: "float: 3D z-coordinate to be mapped" + description: |- + Takes a three-dimensional X, Y, Z position and returns the X value for + where it will appear on a (two-dimensional) screen. + examples: + - | + void setup() { + size(100, 100, P3D); + } + + void draw() { + background(204); + + float x = mouseX; + float y = mouseY; + float z = -100; + + // Draw "X" at z = -100 + stroke(255); + line(x-10, y-10, z, x+10, y+10, z); + line(x+10, y-10, z, x-10, y+10, z); + + // Draw gray line at z = 0 and same + // x value. Notice the parallax + stroke(102); + line(x, 0, 0, x, height, 0); + + // Draw black line at z = 0 to match + // the x value element drawn at z = -100 + stroke(0); + float theX = screenX(x, y, z); + line(theX, 0, 0, theX, height, 0); + } + fileName: screenX_ + parameters: + x: + desc: 3D x-coordinate to be mapped + type: + - float + y: + desc: 3D y-coordinate to be mapped + type: + - float + z: + desc: 3D z-coordinate to be mapped + type: + - float returns: float - syntax: |- - screenX(x, y) - screenX(x, y, z) + syntax: + - screenX(x, y) + - screenX(x, y, z) type: function screenY: - description: Takes a three-dimensional X, Y, Z position and returns the Y value - for where it will appear on a (two-dimensional) screen. - docUrl: https://processing.org/reference/screenY_.html - name: null - parameters: - x: "float: 3D x-coordinate to be mapped" - y: "float: 3D y-coordinate to be mapped" - z: "float: 3D z-coordinate to be mapped" + description: |- + Takes a three-dimensional X, Y, Z position and returns the Y value for + where it will appear on a (two-dimensional) screen. + examples: + - | + void setup() { + size(100, 100, P3D); + } + + void draw() { + background(204); + + float x = mouseX; + float y = mouseY; + float z = -100; + + // Draw "X" at z = -100 + stroke(255); + line(x-10, y-10, z, x+10, y+10, z); + line(x+10, y-10, z, x-10, y+10, z); + + // Draw gray line at z = 0 and same + // y value. Notice the parallax + stroke(102); + line(0, y, 0, width, y, 0); + + // Draw black line at z = 0 to match + // the y value element drawn at z = -100 + stroke(0); + float theY = screenY(x, y, z); + line(0, theY, 0, width, theY, 0); + } + fileName: screenY_ + parameters: + x: + desc: 3D x-coordinate to be mapped + type: + - float + y: + desc: 3D y-coordinate to be mapped + type: + - float + z: + desc: 3D z-coordinate to be mapped + type: + - float returns: float - syntax: |- - screenY(x, y) - screenY(x, y, z) + syntax: + - screenY(x, y) + - screenY(x, y, z) type: function screenZ: - description: Takes a three-dimensional X, Y, Z position and returns the Z value - for where it will appear on a (two-dimensional) screen. - docUrl: https://processing.org/reference/screenZ_.html - name: null - parameters: - x: "float: 3D x-coordinate to be mapped" - y: "float: 3D y-coordinate to be mapped" - z: "float: 3D z-coordinate to be mapped" + description: |- + Takes a three-dimensional X, Y, Z position and returns the Z value for + where it will appear on a (two-dimensional) screen. + fileName: screenZ_ + parameters: + x: + desc: 3D x-coordinate to be mapped + type: + - float + y: + desc: 3D y-coordinate to be mapped + type: + - float + z: + desc: 3D z-coordinate to be mapped + type: + - float returns: float - syntax: screenZ(x, y, z) + syntax: + - screenZ(x, y, z) type: function second: - description: Processing communicates with the clock on your computer. The - `second()` function returns the current second as a value from 0 - 59. - docUrl: https://processing.org/reference/second_.html - name: null + description: |- + Processing communicates with the clock on your computer. The + `second()` function returns the current second as a value from 0 to 59. + examples: + - | + void draw() { + background(204); + int s = second(); // Values from 0 - 59 + int m = minute(); // Values from 0 - 59 + int h = hour(); // Values from 0 - 23 + line(s, 0, s, 33); + line(m, 33, m, 66); + line(h, 66, h, 100); + } + fileName: second_ parameters: {} returns: int - syntax: second() + syntax: + - second() type: function selectFolder: - description: Opens a platform-specific file chooser dialog to select a folder. - After the selection is made, the selection 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. - docUrl: https://processing.org/reference/selectFolder_.html - name: null - parameters: - callback: "String: name of the method to be called when the selection is made" - prompt: "String: message to the user" - returns: void - syntax: >- - selectFolder(prompt, callback) - - selectFolder(prompt, callback, file) - - selectFolder(prompt, callback, file, callbackObject) - - selectFolder(prompt, callbackMethod, defaultSelection, callbackObject, parentFrame) + description: |- + Opens a platform-specific file chooser dialog to select a folder. + After the selection is made, the selection 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. + examples: + - | + void setup() { + selectFolder("Select a folder to process:", "folderSelected"); + } - selectFolder(prompt, callbackMethod, defaultSelection, callbackObject, parentFrame, sketch) + void folderSelected(File selection) { + if (selection == null) { + println("Window was closed or the user hit cancel."); + } else { + println("User selected " + selection.getAbsolutePath()); + } + } + fileName: selectFolder_ + parameters: + callback: + desc: name of the method to be called when the selection is made + type: + - String + prompt: + desc: message to the user + type: + - String + returns: void + syntax: + - selectFolder(prompt, callback) + - selectFolder(prompt, callback, file) + - selectFolder(prompt, callback, file, callbackObject) type: function selectInput: - description: Opens 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. - docUrl: https://processing.org/reference/selectInput_.html - name: null - parameters: - callback: "String: name of the method to be called when the selection is made" - prompt: "String: message to the user" - returns: void - syntax: |- - selectInput(prompt, callback) - selectInput(prompt, callback, file) - selectInput(prompt, callback, file, callbackObject) - selectInput(prompt, callbackMethod, file, callbackObject, parent, sketch) - selectInput(prompt, callbackMethod, file, callbackObject, parent) + description: >- + 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. + examples: + - | + 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 " + selection.getAbsolutePath()); + } + } + fileName: selectInput_ + parameters: + callback: + desc: name of the method to be called when the selection is made + type: + - String + prompt: + desc: message to the user + type: + - String + returns: void + syntax: + - selectInput(prompt, callback) + - selectInput(prompt, callback, file) + - selectInput(prompt, callback, file, callbackObject) type: function selectOutput: - description: Opens a platform-specific file chooser dialog to select a file for - output. 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. - docUrl: https://processing.org/reference/selectOutput_.html - name: null - parameters: - callback: "String: name of the method to be called when the selection is made" - prompt: "String: message to the user" - returns: void - syntax: |- - selectOutput(prompt, callback) - selectOutput(prompt, callback, file) - selectOutput(prompt, callback, file, callbackObject) - selectOutput(prompt, callbackMethod, file, callbackObject, parent) - selectOutput(prompt, callbackMethod, file, callbackObject, parent, sketch) - type: function -set: description: >- - Changes the color of any pixel, or writes an image directly to the display - window. - - - The `x` and `y` parameters specify the pixel to change and the `c` parameter specifies the color value. The `c` parameter is interpreted according to the current color mode. (The default color mode 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()`. - + Opens a platform-specific file chooser dialog to select a file for output. + 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. + examples: + - | + void setup() { + selectOutput("Select a file to write to:", "fileSelected"); + } - 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. - docUrl: https://processing.org/reference/set_.html - name: null - parameters: - c: "int: any value of the color datatype" - img: "PImage: image to copy into the original image" - x: "int: x-coordinate of the pixel" - y: "int: y-coordinate of the pixel" - returns: void - syntax: |- - set(x, y, c) - set(x, y, img) + void fileSelected(File selection) { + if (selection == null) { + println("Window was closed or the user hit cancel."); + } else { + println("User selected " + selection.getAbsolutePath()); + } + } + fileName: selectOutput_ + parameters: + callback: + desc: name of the method to be called when the selection is made + type: + - String + prompt: + desc: message to the user + type: + - String + returns: void + syntax: + - selectOutput(prompt, callback) + - selectOutput(prompt, callback, file) + - selectOutput(prompt, callback, file, callbackObject) + type: function +set: + description: |- + 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. + examples: + - | + size(400,400); + color black = color(0); + set(120, 80, black); + set(340, 80, black); + set(340, 300, black); + set(120, 300, black); + - |- + size(400,400); + + for (int i = 120; i < width-60; i++) { + for (int j = 80; j < height-100; j++) { + color c = color(j, i, 0); + set(i, j, c); + } + } + - |- + size(400,400); + PImage myImage = loadImage("flower.jpg"); + set(0, 0, myImage); + line(0, 0, width, height); + line(0, height, width, 0); + fileName: set_ + parameters: + c: + desc: any value of the color datatype + type: + - int + img: + desc: image to copy into the original image + type: + - PImage + x: + desc: x-coordinate of the pixel + type: + - int + y: + desc: y-coordinate of the pixel + type: + - int + returns: void + syntax: + - set(x, y, c) + - set(x, y, img) type: function setLocation: description: >- @@ -4705,13 +12919,31 @@ setLocation: There are more features of PSurface documented in the Processing JavaDoc. - docUrl: https://processing.org/reference/setLocation_.html - name: null + examples: + - | + void setup() { + size(200, 200); + surface.setTitle("Hello World!"); + surface.setResizable(true); + surface.setLocation(100, 100); + } + + void draw() { + background(204); + line(0, 0, width, height); + line(width, 0, 0, height); + } + fileName: setLocation_ parameters: - x: "int: x-coordinate of the surface" - y: "int: y-coordinate of the surface" - syntax: | - surface.setLocation(x, y) + x: + desc: "int: x-coordinate of the surface" + type: [] + y: + desc: "int: y-coordinate of the surface" + type: [] + returns: void + syntax: + - surface.setLocation(x, y) type: function setResizable: description: >- @@ -4721,12 +12953,28 @@ setResizable: There are more features of PSurface documented in the Processing JavaDoc. - docUrl: https://processing.org/reference/setResizable_.html - name: null + examples: + - | + void setup() { + size(200, 200); + surface.setTitle("Hello World!"); + surface.setResizable(true); + surface.setLocation(100, 100); + } + + void draw() { + background(204); + line(0, 0, width, height); + line(width, 0, 0, height); + } + fileName: setResizable_ parameters: - resizable: "boolean: true to make the surface resizable" - syntax: | - surface.setResizable(resizable) + resizable: + desc: "boolean: true to make the surface resizable" + type: [] + returns: void + syntax: + - surface.setResizable(resizable) type: function setTitle: description: >- @@ -4735,433 +12983,1216 @@ setTitle: There are more features of PSurface documented in the Processing JavaDoc. - docUrl: https://processing.org/reference/setTitle_.html - name: null + examples: + - | + void setup() { + size(200, 200); + surface.setTitle("Hello World!"); + surface.setResizable(true); + surface.setLocation(100, 100); + } + + void draw() { + background(204); + line(0, 0, width, height); + line(width, 0, 0, height); + } + fileName: setTitle_ parameters: - title: "String: name of the window" - syntax: | - surface.setTitle(title) + title: + desc: "String: name of the window" + type: [] + returns: void + syntax: + - surface.setTitle(title) type: function settings: - description: >- - The `settings()` function is new with Processing 3.0. It's not needed in - most sketches. It's only useful when it's absolutely necessary to define the - parameters to `size()` with a variable. Alternately, the `settings()` - function is necessary when using Processing code outside of the Processing - Development Environment (PDE). For example, when using the Eclipse code - editor, it's necessary to use `settings()` to define the `size()` and - `smooth()` values for a sketch.. - - The `settings()` method runs before the sketch has been set up, so other Processing functions cannot be used at that point. For instance, do not use loadImage() inside settings(). The settings() method runs "passively" to set a few variables, compared to the `setup()` command that call commands in the Processing API. - docUrl: https://processing.org/reference/settings_.html - name: null + description: |- + The `settings()` function is new with Processing 3.0. + It's not needed in most sketches. It's only useful when it's + absolutely necessary to define the parameters to `size()` + with a variable. Alternately, the `settings()` function + is necessary when using Processing code outside the + Processing Development Environment (PDE). For example, when + using the Eclipse code editor, it's necessary to use + `settings()` to define the `size()` and + `smooth()` values for a sketch.`. + + The `settings()` method runs before the sketch has been + set up, so other Processing functions cannot be used at that + point. For instance, do not use loadImage() inside settings(). + The settings() method runs "passively" to set a few variables, + compared to the `setup()` command that call commands in + the Processing API. + examples: + - | + // Run code at full screen using the default renderer + + int x = 0; + + void settings() { + fullScreen(); + } + + void setup() { + background(0); + noStroke(); + fill(102); + } + + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + - | + // Run code at full screen using the P2D renderer + // on screen 2 of a multiple monitor hardware setup + + int x = 0; + + void settings() { + fullScreen(P2D, 2); + } + + void setup() { + background(0); + noStroke(); + fill(102); + } + + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + - | + // Run code at full screen using the P2D renderer + // across all screens on a multiple monitor setup + + int x = 0; + + void settings() { + fullScreen(P2D, SPAN); + } + + void setup() { + background(0); + noStroke(); + fill(102); + } + + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + - | + int w = 200; + int h = 200; + int x = 0; + + void settings() { + size(w, h); + } + + void setup() { + background(0); + noStroke(); + fill(102); + } + + void draw() { + rect(x, 10, 1, 180); + x = x + 2; + } + fileName: settings_ parameters: {} returns: void - syntax: settings() + syntax: + - settings() type: function setup: description: >- - The `setup()` function is run once, when the program starts. It's used to - define initial enviroment properties such as screen size 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. - - - If the sketch is a different dimension than the default, the `size()` function or `fullScreen()` function must be the first line in `setup()`. + The `setup()` function is run once, when the program starts. It's used + to define initial environment properties such as screen size 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. + + If the sketch is a different dimension than the default, the `size()` + function or `fullScreen()` function must be the first line in + `setup()`. + + Note: Variables declared within `setup()` are not accessible within + other functions, including `draw()`. + examples: + - | + int x = 0; + + void setup() { + size(200, 200); + background(0); + noStroke(); + fill(102); + } + void draw() { + rect(x, 10, 2, 80); + x = x + 1; + } + - | + int x = 0; + + void setup() { + fullScreen(); + background(0); + noStroke(); + fill(102); + } - Note: Variables declared within `setup()` are not accessible within other functions, including `draw()`. - docUrl: https://processing.org/reference/setup_.html - name: null + void draw() { + rect(x, height*0.2, 1, height*0.6); + x = x + 2; + } + fileName: setup_ parameters: {} returns: void - syntax: setup() + syntax: + - setup() type: function shader: - description: Applies the shader specified by the parameters. It's compatible - with the P2D and P3D renderers, but not with the default renderer. - docUrl: https://processing.org/reference/shader_.html - name: null + description: |- + Applies the shader specified by the parameters. It's compatible with + the P2D and P3D renderers, but not with the default renderer. + examples: + - | + PShader edges; + PImage img; + + void setup() { + size(640, 360, P2D); + img = loadImage("leaves.jpg"); + edges = loadShader("edges.glsl"); + } + + void draw() { + shader(edges); + image(img, 0, 0); + } + fileName: shader_ parameters: - kind: "int: type of shader, either POINTS, LINES, or TRIANGLES" - shader: "PShader: name of shader file" + kind: + desc: type of shader, either POINTS, LINES, or TRIANGLES + type: + - int + shader: + desc: name of shader file + type: + - PShader returns: void - syntax: |- - shader(shader) - shader(shader, kind) + syntax: + - shader(shader) + - shader(shader, kind) type: function shape: - description: Draws shapes to the display window. 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, OBJ, and - custom-created shapes. The `shape` parameter specifies the shape to display - and the coordinate parameters define the location of the shape from its - upper-left corner. The shape is displayed at its original size unless the - `c` and `d` parameters specify a different size. The `shapeMode()` function - can be used to change the way these parameters are interpreted. - docUrl: https://processing.org/reference/shape_.html - name: null - parameters: - a: "float: x-coordinate of the shape" - b: "float: y-coordinate of the shape" - c: "float: width to display the shape" - d: "float: height to display the shape" - shape: "PShape: the shape to display" - x: "float: x-coordinate of the shape" - y: "float: y-coordinate of the shape" - returns: void - syntax: |- - shape(shape) - shape(shape, x, y) - shape(shape, a, b, c, d) + description: |- + Draws shapes to the display window. 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, OBJ, and custom-created + shapes. The `shape` parameter specifies the shape to display and the + coordinate parameters define the location of the shape from its upper-left + corner. The shape is displayed at its original size unless the `c` and + `d` parameters specify a different size. The `shapeMode()` function + can be used to change the way these parameters are interpreted. + examples: + - |- + PShape s; + + void setup() { + size(400,400); + s = loadShape("bot.svg"); + } + + void draw() { + shape(s, 40, 40, 320, 320); + } + fileName: shape_ + parameters: + a: + desc: x-coordinate of the shape + type: + - float + b: + desc: y-coordinate of the shape + type: + - float + c: + desc: width to display the shape + type: + - float + d: + desc: height to display the shape + type: + - float + shape: + desc: the shape to display + type: + - PShape + x: + desc: x-coordinate of the shape + type: + - float + y: + desc: y-coordinate of the shape + type: + - float + returns: void + syntax: + - shape(shape) + - shape(shape, x, y) + - shape(shape, a, b, c, d) type: function shapeMode: - description: 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. - docUrl: https://processing.org/reference/shapeMode_.html - name: null - parameters: - mode: "int: either CORNER, CORNERS, CENTER" - returns: void - syntax: shapeMode(mode) + description: |- + 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. + examples: + - |- + + PShape bot; + + void setup() { + size(400, 400); + bot = loadShape("bot.svg"); + } + + void draw() { + shapeMode(CENTER); + shape(bot, 140, 140, 200, 200); + shapeMode(CORNER); + shape(bot, 140, 140, 200, 200); + } + fileName: shapeMode_ + parameters: + mode: + desc: either CORNER, CORNERS, CENTER + type: + - int + returns: void + syntax: + - shapeMode(mode) type: function shearX: - description: >- - 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. - docUrl: https://processing.org/reference/shearX_.html - name: null - parameters: - angle: "float: angle of shear specified in radians" - returns: void - syntax: shearX(angle) + description: |- + 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. + examples: + - |- + size(400, 400); + translate(width/4, height/4); + shearX(PI/4.0); + rect(0, 0, 120, 120); + fileName: shearX_ + parameters: + angle: + desc: angle of shear specified in radians + type: + - float + returns: void + syntax: + - shearX(angle) type: function shearY: - description: >- - 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. - docUrl: https://processing.org/reference/shearY_.html - name: null - parameters: - angle: "float: angle of shear specified in radians" - returns: void - syntax: shearY(angle) + description: |- + 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. + examples: + - |- + size(400, 400); + translate(width/4, height/4); + shearY(PI/4.0); + rect(0, 0, 120, 120); + fileName: shearY_ + parameters: + angle: + desc: angle of shear specified in radians + type: + - float + returns: void + syntax: + - shearY(angle) type: function shininess: - description: 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. - docUrl: https://processing.org/reference/shininess_.html - name: null - parameters: - shine: "float: degree of shininess" - returns: void - syntax: shininess(shine) + description: |- + 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. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + background(0); + fill(0, 51, 102); + ambientLight(102, 102, 102); + lightSpecular(204, 204, 204); + directionalLight(102, 102, 102, 0, 0, -1); + specular(255, 255, 255); + translate(120, 200, 0); + shininess(1.0); + sphere(80); // Left sphere + translate(160, 0, 0); + shininess(5.0); + sphere(80); // Right sphere + fileName: shininess_ + parameters: + shine: + desc: degree of shininess + type: + - float + returns: void + syntax: + - shininess(shine) type: function shorten: - description: >- - Decreases a one-dimensional 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) - docUrl: https://processing.org/reference/shorten_.html - name: null - parameters: - list: "Object, String[], float[], int[], char[], byte[], or boolean[]: array to - shorten" + description: |- + 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). + examples: + - | + String[] sa1 = { "OH ", "NY ", "CA "}; + String[] sa2 = shorten(sa1); + println(sa1); // 'sa1' still contains OH, NY, CA + println(sa2); // 'sa2' now contains OH, NY + fileName: shorten_ + parameters: + list: + desc: array to shorten + type: + - boolean[] + - byte[] + - char[] + - int[] + - float[] + - String[] + - Object returns: boolean[], byte[], char[], int[], float[], String[], or Object - syntax: shorten(list) + syntax: + - shorten(list) type: function sin: - description: 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. - docUrl: https://processing.org/reference/sin_.html - name: null + description: |- + 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. + examples: + - |- + size(400, 400); + float a = 0.0; + float inc = TWO_PI/25.0; + + for (int i = 0; i < 400; i=i+16) { + line(i, 200, i, 200+sin(a)*160.0); + a = a + inc; + } + fileName: sin_ parameters: - angle: "float: an angle in radians" + angle: + desc: an angle in radians + type: + - float returns: float - syntax: sin(angle) + syntax: + - sin(angle) type: function size: description: >- Defines the dimension of the display window width and height in units of - pixels. In a program that has the `setup()` function, the `size()` function - must be the first line of code inside `setup()`, and the `setup()` function - must appear in the code tab with the same name as your sketch folder. - - - The built-in variables `width` and `height` are set by the parameters passed to this function. For example, running `size(640, 480)` will assign 640 to the `width` variable and 480 to the height `variable`. If `size()` is not used, the window will be given a default size of 100 x 100 pixels. - - - The `size()` function can only be used once inside a sketch, and it cannot be used for resizing. - - - As of Processing 3, to run a sketch at the full dimensions of a screen, use the `fullScreen()` function, rather than the older way of using `size(displayWidth, displayHeight)`. - + pixels. In a program that has the `setup()` function, the + `size()` function must be the first line of code inside + `setup()`, and the `setup()` function must appear in the code tab + with the same name as your sketch folder. + + The built-in variables `width` and `height` are set by the + parameters passed to this function. For example, running `size(640, + 480)` will assign 640 to the `width` variable and 480 to the height + `variable`. If `size()` is not used, the window will be given a + default size of 100 x 100 pixels. + + The `size()` function can only be used once inside a sketch, and it + cannot be used for resizing. Use `windowResize()` instead. + + To run a sketch that fills the screen, use the `fullScreen()` function, + rather than using `size(displayWidth, displayHeight)`. + + The `renderer` parameter selects which rendering engine to use. For + example, if you will be drawing 3D shapes, use `P3D`. The default + renderer is slower for some situations (for instance large or + high-resolution displays) but generally has higher quality than the + other renderers for 2D drawing. + + In addition to the default renderer, other renderers are: + + `P2D` (Processing 2D): 2D graphics renderer that makes use of + OpenGL-compatible graphics hardware. + + `P3D` (Processing 3D): 3D graphics renderer that makes use of + OpenGL-compatible graphics hardware. + + `FX2D` (JavaFX 2D): A 2D renderer that uses JavaFX, which may be + faster for some applications, but has some compatibility quirks. + Use \u201cManage Libraries\u201d to download and install the JavaFX library. + + `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. + + `SVG`: The SVG renderer draws 2D graphics directly to an SVG file. + This is great for importing into other vector programs or using for + digital fabrication. It is not as feature-complete as other renderers. + Like PDF, you must first use Import Library → SVG Export to + make use the SVG library. + + As of Processing 3.0, to use variables as the parameters to `size()` + function, place the `size()` function within the `settings()` + function (instead of `setup()`). There is more information about this + on the `settings()` reference page. + + 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 800 x 600 could support `size(1600, 300)`, since that is 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. + + The minimum width and height is around 100 pixels in each direction. This + is the smallest that is supported across Windows, macOS, and Linux. We + enforce the minimum size so that sketches will run identically on different + machines. + examples: + - |- + + size(200, 100); + background(153); + line(0, 0, width, height); + - |- + void setup() { + size(320, 240); + } - The maximum width and height is limited by your operating system, and is usually the width and height of your actual screen. On some m. . . - docUrl: https://processing.org/reference/size_.html - name: null - parameters: - height: "int: height of the display window in units of pixels" - width: "int: width of the display window in units of pixels" - returns: void - syntax: |- - size(width, height) - size(width, height, renderer) + void draw() { + background(153); + line(0, 0, width, height); + } + - |- + + size(150, 200, P3D); // Specify P3D renderer + background(153); + + // With P3D, we can use z (depth) values... + line(0, 0, 0, width, height, -100); + line(width, 0, 0, width, height, -100); + line(0, height, 0, width, height, -100); + + //...and 3D-specific functions, like box() + translate(width/2, height/2); + rotateX(PI/6); + rotateY(PI/6); + box(35); + fileName: size_ + parameters: + height: + desc: height of the display window in units of pixels + type: + - int + width: + desc: width of the display window in units of pixels + type: + - int + returns: void + syntax: + - size(width, height) + - size(width, height, renderer) type: function smooth: - description: >- - Draws all geometry with smooth (anti-aliased) edges. This behavior is the - default, so `smooth()` only needs to be used when a program needs to set the - smoothing in a different way. The `level` parameter increases the amount of - smoothness. This is the level of over sampling applied to the graphics - buffer. - - - With the P2D and P3D renderers, `smooth(2)` is the default, this is called "2x anti-aliasing." The code `smooth(4)` is used for 4x anti-aliasing and `smooth(8)` is specified for "8x anti-aliasing." The maximum anti-aliasing level is determined by the hardware of the machine that is running the software, so `smooth(4)` and `smooth(8)` will not work with every computer. + description: |- + Draws all geometry with smooth (anti-aliased) edges. + This behavior is the default, so `smooth()` only needs + to be used when a program needs to set the smoothing + in a different way. The level parameter increases + the amount of smoothness. This is the level of over + sampling applied to the graphics buffer. + + With the P2D and P3D renderers, `smooth(2)` is the + default, this is called "2x anti-aliasing." The code + `smooth(4)` is used for 4x anti-aliasing and `smooth(8)` + is specified for "8x anti-aliasing." The maximum + anti-aliasing level is determined by the hardware of + the machine that is running the software, so `smooth(4)` + and `smooth(8)` will not work with every computer. + + The default renderer uses `smooth(3)` by default. This + is bicubic smoothing. The other option for the default + renderer is `smooth(2)`, which is bilinear smoothing. + + With Processing 3.0, `smooth()` is handled differently + than in earlier releases. In 2.x and earlier, it was possible + to use `smooth()` and `noSmooth()` to turn on + and off antialiasing within a sketch. Now, because of + how the software has changed, `smooth()` can only be set + once within a sketch. It can be used either at the top + of a sketch without a `setup()`, or after the `size()` + function when used in a sketch with `setup()`. The + `noSmooth()` function also follows the same rules. + + When `smooth()` is used with a PGraphics object, it should + be run right after the object is created with + `createGraphics()`, as shown in the Reference in the third + example. + examples: + - | + + void setup() { + size(400, 400); + smooth(2); + noStroke(); + } + void draw() { + background(0); + ellipse(120, 192, 144, 144); + ellipse(280, 192, 144, 144); + } + - |- + int x = 0; - The default renderer uses `smooth(3)` by default. This is bicubic smoothing. The other option for the default renderer is `smooth(2)`, which is bilinear smoothing. + void setup() { + fullScreen(P2D, SPAN); + smooth(4); + } + void draw() { + background(0); + ellipse(x, height/2, height/4, height/4); + x += 1; + } + - |- + PGraphics pg; + int x = 0; + + void setup() { + fullScreen(P2D); + pg = createGraphics(width, height, P2D); + pg.smooth(4); + } - With Processing 3.0, `smooth()` is different than before. It was common to use `smooth()` and `noSmooth()` to turn on and off antialiasing within a sketch. . . . - docUrl: https://processing.org/reference/smooth_.html - name: null + void draw() { + pg.beginDraw(); + pg.background(0); + pg.ellipse(x, height/2, height/4, height/4); + pg.endDraw(); + image(pg, 0, 0); + x += 1; + } + fileName: smooth_ parameters: - level: "int: either 2, 3, 4, or 8 depending on the renderer" + level: + desc: either 2, 3, 4, or 8 depending on the renderer + type: + - int returns: void - syntax: smooth(level) + syntax: + - smooth(level) type: function sort: - description: Sorts an array of numbers from smallest to largest, or 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 - `count` is set to 5, only the first 5 elements in the array will be sorted. - docUrl: https://processing.org/reference/sort_.html - name: null - parameters: - count: "int: number of elements to sort, starting from 0" - list: "String[], float[], int[], char[], or byte[]: array to sort" + description: |- + Sorts an array of numbers from smallest to largest, or 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 + `count` is set to 5, only the first 5 elements in the array will be + sorted. + examples: + - | + float[] a = { 3.4, 3.6, 2, 0, 7.1 }; + a = sort(a); + println(a); + // Prints the contents of the sorted array: + // [0] 0.0 + // [1] 2.0 + // [2] 3.4 + // [3] 3.6 + // [4] 7.1 + - | + String[] s = { "deer", "elephant", "bear", "aardvark", "cat" }; + s = sort(s); + println(s); + // Prints the contents of the sorted array: + // [0] "aardvark" + // [1] "bear" + // [2] "cat" + // [3] "deer" + // [4] "elephant" + - | + String[] s = { "deer", "elephant", "bear", "aardvark", "cat" }; + s = sort(s, 3); + println(s); + // Prints the contents of the array, with the first 3 elements sorted: + // [0] "bear" + // [1] "deer" + // [2] "elephant" + // [3] "aardvark" + // [4] "cat" + fileName: sort_ + parameters: + count: + desc: number of elements to sort, starting from 0 + type: + - int + list: + desc: array to sort + type: + - byte[] + - char[] + - int[] + - float[] + - String[] returns: byte[], char[], int[], float[], or String[] - syntax: |- - sort(list) - sort(list, count) + syntax: + - sort(list) + - sort(list, count) type: function specular: - description: Sets the specular color of the materials used for shapes drawn to - the screen, which sets the color of highlights. Specular refers to light - which bounces off a surface in a preferred 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. - docUrl: https://processing.org/reference/specular_.html - name: null - parameters: - gray: "float: value between black and white, by default 0 to 255" - rgb: "int: color to set" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: |- - specular(rgb) - specular(gray) - specular(v1, v2, v3) + description: |- + Sets the specular color of the materials used for shapes drawn to the + screen, which sets the color of highlights. Specular refers to light + which bounces off a surface in a preferred 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. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + background(0); + fill(0, 51, 102); + lightSpecular(255, 255, 255); + directionalLight(204, 204, 204, 0, 0, -1); + translate(80, 200, 0); + specular(255, 255, 255); + sphere(120); + translate(240, 0, 0); + specular(204, 102, 0); + sphere(120); + fileName: specular_ + parameters: + gray: + desc: value between black and white, by default 0 to 255 + type: + - float + rgb: + desc: color to set + type: + - int + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - specular(rgb) + - specular(gray) + - specular(v1, v2, v3) type: function sphere: description: A sphere is a hollow ball made from tessellated triangles. - docUrl: https://processing.org/reference/sphere_.html - name: null - parameters: - r: "float: the radius of the sphere" - returns: void - syntax: sphere(r) + examples: + - |- + size(400, 400, P3D); + noStroke(); + lights(); + translate(232, 192, 0); + sphere(112); + fileName: sphere_ + parameters: + r: + desc: the radius of the sphere + type: + - float + returns: void + syntax: + - sphere(r) type: function sphereDetail: - description: 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. - docUrl: https://processing.org/reference/sphereDetail_.html - name: null - parameters: - res: "int: number of segments (minimum 3) used per full circle revolution" - ures: "int: number of segments used longitudinally per full circle revolutoin" - vres: "int: number of segments used latitudinally from top to bottom" - returns: void - syntax: |- - sphereDetail(res) - sphereDetail(ures, vres) + description: |- + 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. + examples: + - | + void setup() { + size(100, 100, P3D); + } + + void draw() { + background(200); + stroke(255, 50); + translate(50, 50, 0); + rotateX(mouseY * 0.05); + rotateY(mouseX * 0.05); + fill(mouseX * 2, 0, 160); + sphereDetail(mouseX / 4); + sphere(40); + } + fileName: sphereDetail_ + parameters: + res: + desc: number of segments (minimum 3) used per full circle revolution + type: + - int + ures: + desc: number of segments used longitudinally per full circle revolution + type: + - int + vres: + desc: number of segments used latitudinally from top to bottom + type: + - int + returns: void + syntax: + - sphereDetail(res) + - sphereDetail(ures, vres) type: function splice: - description: >- + description: |- Inserts a value or an array of values into an existing array. The first two - parameters must be arrays of the same datatype. The first parameter - specifies the initial array to be modified, and the second parameter defines - the data to be inserted. The third parameter is an index value which - specifies the array position from which to insert data. (Remember that array - index numbering starts at zero, so the first position is 0, the second - position is 1, and so on.) - - - When splicing 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) - docUrl: https://processing.org/reference/splice_.html - name: null - parameters: - index: "int: position in the array from which to insert data" - list: "Object, String[], float[], int[], char[], byte[], or boolean[]: array to - splice into" - value: "Object, String[], String, float[], float, int[], int, char[], char, - byte[], byte, boolean[], or boolean: value to be spliced in" + parameters must be arrays of the same datatype. The first parameter + specifies the initial array to be modified, and the second parameter + defines the data to be inserted. The third parameter is an index value + which specifies the array position from which to insert data. (Remember + that array index numbering starts at zero, so the first position is 0, the + second position is 1, and so on.) + + When splicing 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) + examples: + - | + String[] a = { "OH", "NY", "CA" }; + a = splice(a, "KY", 1); // Splice one value into an array + println(a); + // Prints the following array contents to the console: + // [0] "OH" + // [1] "KY" + // [2] "NY" + // [3] "CA" + + println(); // Prints a blank line + + String[] b = { "VA", "CO", "IL" }; + a = splice(a, b, 2); // Splice one array of values into another + println(a); + // Prints the following array contents to the console: + // [0] "OH" + // [1] "KY" + // [2] "VA" + // [3] "CO" + // [4] "IL" + // [5] "NY" + // [6] "CA" + fileName: splice_ + parameters: + index: + desc: position in the array from which to insert data + type: + - int + list: + desc: array to splice into + type: + - boolean[] + - byte[] + - char[] + - int[] + - float[] + - String[] + - Object + value: + desc: value to be spliced in + type: + - boolean + - boolean[] + - byte + - byte[] + - char + - char[] + - int + - int[] + - float + - float[] + - String + - String[] + - Object returns: boolean[], byte[], char[], int[], float[], String[], or Object - syntax: splice(list, value, index) + syntax: + - splice(list, value, index) type: function split: - description: >- - The `split()` function breaks a String into pieces using a character or - string as the delimiter. 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 a float[] or int[] array using the datatype conversion functions `int()` and `float()`. (See the second 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. - - - This function uses regular expressions to determine how the `delim` parameter divides the `str` parameter. Therefore, if you use characters such parentheses and brackets that are used with regular expressions as a part of the `delim` parameter, you'll need to put two blackslashes (\) in front of the character (see example above). You can read more about regular expressions and esc. . . - docUrl: https://processing.org/reference/split_.html - name: null - parameters: - delim: "char: the character or String used to separate the data" - value: "String: the String to be split" + description: |- + The `split()` function breaks a String into pieces using a character + or string as the delimiter. 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 a + float[] or int[] array using the datatype conversion functions `int()` + and `float()`. (See the second 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. + + This function uses regular expressions to determine how the `delim` + parameter divides the `str` parameter. Therefore, if you use + characters such parentheses and brackets that are used with regular + expressions as a part of the `delim` parameter, you'll need to put two + backslashes (\\\\) in front of the character (see example above). You can + read more about + regular + expressions and + escape + characters on Wikipedia. --> + examples: + - | + String men = "Chernenko,Andropov,Brezhnev"; + String[] list = split(men, ','); + // list[0] is now "Chernenko", list[1] is "Andropov"... + - | + String numbers = "8 67 5 309"; + int[] nums = int(split(numbers, ' ')); + // nums[0] is now 8, nums[1] is now 67... + - | + String men = "Chernenko ] Andropov ] Brezhnev"; + String[] list = split(men, " ] "); + // list[0] is now "Chernenko", list[1] is "Andropov"... + fileName: split_ + parameters: + delim: + desc: the character or String used to separate the data + type: + - char + - String + value: + desc: the String to be split + type: + - String returns: String[] - syntax: split(value, delim) + syntax: + - split(value, delim) type: function splitTokens: - description: >- - The `splitTokens()` function splits a String at one or many character - delimiters or "tokens." The `delim` parameter specifies the character or - characters to be used as a boundary. - - - If no `delim` characters are specified, any whitespace character is used to split. Whitespace characters include tab (\t), line feed ( - - - ), carriage return (\r), form feed (\f), and space. - - - After using this function to parse incoming data, it is common to convert the data from Strings to integers or floats by using the datatype conversion functions `int()` and `float()`. - docUrl: https://processing.org/reference/splitTokens_.html - name: null - parameters: - delim: "String: list of individual characters that will be used as separators" - value: "String: the String to be split" + description: |- + The `splitTokens()` function splits a `String` at one or many character + delimiters or "tokens". The `delim` parameter specifies the character + or characters to be used as a boundary. + + If no `delim` characters are specified, any whitespace character is + used to split. Whitespace characters include tab (\t), line feed + (\n), carriage return (\r), form feed (\f), and space. + + After using this function to parse incoming data, it is common to convert + the data from Strings to integers or floats by using the datatype + conversion functions `int()` and `float()`. + examples: + - | + String t = "a b"; + String[] q = splitTokens(t); + println(q[0]); // Prints "a" + println(q[1]); // Prints "b" + - | + // Despite the bad formatting, the data is parsed correctly. + // The ", " as delimiter means to break whenever a comma *or* + // a space is found in the String. Unlike the split() function, + // multiple adjacent delimiters are treated as a single break. + String s = "a, b c ,,d "; + String[] q = splitTokens(s, ", "); + println(q.length + " values found"); // Prints "4 values found" + println(q[0]); // Prints "a" + println(q[1]); // Prints "b" + println(q[2]); // Prints "c" + println(q[3]); // Prints "d" + fileName: splitTokens_ + parameters: + delim: + desc: list of individual characters that will be used as separators + type: + - String + value: + desc: the String to be split + type: + - String returns: String[] - syntax: |- - splitTokens(value) - splitTokens(value, delim) + syntax: + - splitTokens(value) + - splitTokens(value, delim) type: function spotLight: - description: 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 `v1`, `v2`, and `v3` parameters are interpreted as - either RGB or HSB values, depending on the current color mode. The `x`, `y`, - and `z` parameters specify the position of the light and `nx`, `ny`, `nz` - specify the direction of light. The `angle` parameter affects angle of the - spotlight cone, while `concentration` sets the bias of light focusing toward - the center of that cone. - docUrl: https://processing.org/reference/spotLight_.html - name: null - parameters: - angle: "float: angle of the spotlight cone" - concentration: "float: exponent determining the center bias of the cone" - nx: "float: direction along the x axis" - ny: "float: direction along the y axis" - nz: "float: direction along the z axis" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - x: "float: x-coordinate of the light" - y: "float: y-coordinate of the light" - z: "float: z-coordinate of the light" - returns: void - syntax: spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration) + description: >- + Adds a spotlight. 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 `v1`, `v2`, and `v3` parameters are interpreted + as either RGB or HSB values, depending on the current color mode. The + `x`, `y`, and `z` parameters specify the position of the light + and `nx`, `ny`, `nz` specify the direction of light. The + `angle` parameter affects angle of the spotlight cone, while + `concentration` sets the bias of light focusing toward the center of + that cone. + examples: + - |- + size(400, 400, P3D); + background(0); + noStroke(); + spotLight(51, 102, 126, 320, 80, 160, -1, 0, 0, PI/2, 2); + translate(80, 200, 0); + sphere(120); + - |- + size(400, 400, P3D); + int concentration = 600; // Try 1 -> 10000 + background(0); + noStroke(); + spotLight(51, 102, 126, 200, 200, 1600, + 0, 0, -1, PI/16, concentration); + translate(320, 200, 0); + sphere(120); + fileName: spotLight_ + parameters: + angle: + desc: angle of the spotlight cone + type: + - float + concentration: + desc: exponent determining the center bias of the cone + type: + - float + nx: + desc: direction along the x-axis + type: + - float + ny: + desc: direction along the y-axis + type: + - float + nz: + desc: direction along the z-axis + type: + - float + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: |- + green or saturation value (depending on current color + mode) + type: + - float + v3: + desc: |- + blue or brightness value (depending on current color + mode) + type: + - float + x: + desc: x-coordinate of the light + type: + - float + y: + desc: y-coordinate of the light + type: + - float + z: + desc: z-coordinate of the light + type: + - float + returns: void + syntax: + - spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration) type: function sq: - description: 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. - docUrl: https://processing.org/reference/sq_.html - name: null - parameters: - n: "float: number to square" + description: |- + 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.` + examples: + - |- + size(400, 400); + noStroke(); + float a = sq(4); // Sets 'a' to 16 + float b = sq(-10); // Sets 'b' to 100 + float c = sq(18); // Sets 'c' to 324 + rect(0, 100, a, 40); + rect(0, 180, b, 40); + rect(0, 260, c, 40); + fileName: sq_ + parameters: + n: + desc: number to square + type: + - float returns: float - syntax: sq(n) + syntax: + - sq(n) type: function sqrt: - description: 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. - docUrl: https://processing.org/reference/sqrt_.html - name: null - parameters: - n: "float: non-negative number" + description: |- + 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. + examples: + - |- + size(400, 400); + noStroke(); + float a = sqrt(104976); // Sets 'a' to 324 + float b = sqrt(10000); // Sets 'b' to 100 + float c = sqrt(256); // Sets 'c' to 16 + rect(0, 100, a, 40); + rect(0, 180, b, 40); + rect(0, 260, c, 40); + fileName: sqrt_ + parameters: + n: + desc: non-negative number + type: + - float returns: float - syntax: sqrt(n) + syntax: + - sqrt(n) type: function square: - description: Draws a square to the screen. A square is a four-sided shape with - every angle at ninety degrees and each side is the same length. By default, - the first two parameters set the location of the upper-left corner, the - third sets the width and height. The way these parameters are interpreted, - however, may be changed with the `rectMode()` function. - docUrl: https://processing.org/reference/square_.html - name: null - parameters: - extent: "float: width and height of the rectangle by default" - x: "float: x-coordinate of the rectangle by default" - y: "float: y-coordinate of the rectangle by default" - returns: void - syntax: square(x, y, extent) + description: |- + Draws a square to the screen. A square is a four-sided shape with + every angle at ninety degrees and each side is the same length. + By default, the first two parameters set the location of the + upper-left corner, the third sets the width and height. The way + these parameters are interpreted, however, may be changed with the + `rectMode()` function. + examples: + - square(120, 100, 220); + fileName: square_ + parameters: + extent: + desc: width and height of the rectangle by default + type: + - float + x: + desc: x-coordinate of the rectangle by default + type: + - float + y: + desc: y-coordinate of the rectangle by default + type: + - float + returns: void + syntax: + - square(x, y, extent) + type: function +static: + description: >- + Keyword used to define a variable as a "class variable" and a method as a + "class method." When a variable is declared with the `static` keyword, all + instances of that class share the same variable. When a class is defined + with the `static` keyword, it's methods can be used without making an + instance of the class. The above examples demonstrate each of these uses. + + + This keyword is an essential part of Java programming and is not usually + used with Processing. Consult a Java language reference or tutorial for more + information. + examples: + - | + void setup() { + MiniClass mc1 = new MiniClass(); + MiniClass mc2 = new MiniClass(); + println( mc1.y ); // Prints "10" to the console + MiniClass.y += 10; // The 'y' variable is shared by 'mc1' and 'mc2' + println( mc1.y ); // Prints "20" to the console + println( mc2.y ); // Prints "20" to the console + } + + static class MiniClass { + static int y = 10; // Class variable + } + - | + void setup() { + println(MiniClass.add(3, 4)); // Prints "7" to the console + } + + static class MiniClass { + static int add(int x, int y) { + return(x + y); + } + } + fileName: static + parameters: {} + returns: "" + syntax: [] type: function str: description: >- @@ -5172,510 +14203,1675 @@ str: `str(true)` will return `"true"`. - When an array of values is passed in, then a `String` array of the same length is returned. - docUrl: https://processing.org/reference/strconvert_.html - name: null + When an array of values is passed in, then a `String` array of the same + length is returned. + examples: + - | + boolean b = false; + byte y = -28; + char c = 'R'; + float f = -32.6; + int i = 1024; + + String sb = str(b); + String sy = str(y); + String sc = str(c); + String sf = str(f); + String si = str(i); + + sb = sb + sy + sc + sf + si; + + println(sb); // Prints 'false-28R-32.61024' + fileName: strconvert_ parameters: {} + syntax: [] type: function stroke: - description: >- + description: |- 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` or `0xFFCCFFAA`). The `#` syntax uses six digits to specify a color (just as colors are typically 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 define the red, green, and blue components. - - The value for the gray parameter must be less than or equal to the current maximum value as specified by `colorMode()`. The default maximum value is 255. - - When drawing in 2D with the default renderer, you may need `hint(ENABLE_STROKE_PURE)` to improve drawing quality (at the expense. . . - docUrl: https://processing.org/reference/stroke_.html - name: null - parameters: - alpha: "float: opacity of the stroke" - gray: "float: specifies a value between white and black" - rgb: "int: color value in hexadecimal notation" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" - returns: void - syntax: |- - stroke(rgb) - stroke(rgb, alpha) - stroke(gray) - stroke(gray, alpha) - stroke(v1, v2, v3) - stroke(v1, v2, v3, alpha) + 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` or `0xFFCCFFAA`). + The `#` syntax uses six digits to specify a color (just as colors are + typically 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 define the red, green, and blue components. + + The value for the gray parameter must be less than or equal to the current + maximum value as specified by `colorMode()`. The default maximum value + is 255. + + When drawing in 2D with the default renderer, you may need + `hint(ENABLE_STROKE_PURE)` to improve drawing quality (at the expense of + performance). See the hint() documentation for more details. + examples: + - |- + size(400, 400); + stroke(153); + rect(120, 80, 220, 220); + - |- + size(400, 400); + stroke(204, 102, 0); + rect(120, 80, 220, 220); + fileName: stroke_ + parameters: + alpha: + desc: opacity of the stroke + type: + - float + gray: + desc: specifies a value between white and black + type: + - float + rgb: + desc: color value in hexadecimal notation + type: + - int + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - stroke(rgb) + - stroke(rgb, alpha) + - stroke(gray) + - stroke(gray, alpha) + - stroke(v1, v2, v3) + - stroke(v1, v2, v3, alpha) type: function strokeCap: - description: >- + description: |- Sets the style for rendering line endings. These ends are either squared, - extended, or rounded, each of which specified with the corresponding - parameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND. - - - To make `point()` appear square, use `strokeCap(PROJECT)`. Using `strokeCap(SQUARE)` (no cap) causes points to become invisible. - docUrl: https://processing.org/reference/strokeCap_.html - name: null - parameters: - cap: "int: either SQUARE, PROJECT, or ROUND" - returns: void - syntax: strokeCap(cap) + extended, or rounded, each of which specified with the corresponding + parameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND. + + To make `point()` appear square, use `strokeCap(PROJECT)`. Using + `strokeCap(SQUARE)` (no cap) causes points to become invisible. + examples: + - |- + size(400, 400); + strokeWeight(48.0); + strokeCap(ROUND); + line(80, 120, 320, 120); + strokeCap(SQUARE); + line(80, 200, 320, 200); + strokeCap(PROJECT); + line(80, 280, 320, 280); + fileName: strokeCap_ + parameters: + cap: + desc: either SQUARE, PROJECT, or ROUND + type: + - int + returns: void + syntax: + - strokeCap(cap) type: function strokeJoin: - description: 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. - docUrl: https://processing.org/reference/strokeJoin_.html - name: null - parameters: - join: "int: either MITER, BEVEL, ROUND" - returns: void - syntax: strokeJoin(join) + description: |- + 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. + examples: + - |- + size(400, 400); + noFill(); + strokeWeight(40.0); + strokeJoin(MITER); + beginShape(); + vertex(140, 80); + vertex(260, 200); + vertex(140, 320); + endShape(); + - |- + size(400, 400); + noFill(); + strokeWeight(40.0); + strokeJoin(BEVEL); + beginShape(); + vertex(140, 80); + vertex(260, 200); + vertex(140, 320); + endShape(); + - |- + size(400, 400); + noFill(); + strokeWeight(40.0); + strokeJoin(ROUND); + beginShape(); + vertex(140, 80); + vertex(260, 200); + vertex(140, 320); + endShape(); + fileName: strokeJoin_ + parameters: + join: + desc: either MITER, BEVEL, ROUND + type: + - int + returns: void + syntax: + - strokeJoin(join) type: function strokeWeight: description: >- Sets the width of the stroke used for lines, points, and the border around - shapes. All widths are set in units of pixels. - - - Using point() with strokeWeight(1) or smaller may draw nothing to the screen, depending on the graphics settings of the computer. Workarounds include setting the pixel using `set() or drawing the point using either `circle()` or `square()`. - - ` - docUrl: https://processing.org/reference/strokeWeight_.html - name: null - parameters: - weight: "float: the weight (in pixels) of the stroke" - returns: void - syntax: strokeWeight(weight) + shapes. All widths are set in units of pixels. + + Using point() with strokeWeight(1) or smaller may draw nothing to the screen, + depending on the graphics settings of the computer. Workarounds include + setting the pixel using `set() or drawing the point using either + `circle()` or `square()`. + examples: + - |- + size(400, 400); + strokeWeight(4); // Default + line(80, 80, 320, 80); + strokeWeight(16); // Thicker + line(80, 160, 320, 160); + strokeWeight(40); // Beastly + line(80, 280, 320, 280); + fileName: strokeWeight_ + parameters: + weight: + desc: the weight (in pixels) of the stroke + type: + - float + returns: void + syntax: + - strokeWeight(weight) type: function subset: - description: >- - Extracts an array of elements from an existing array. The `list` parameter - defines the array from which the elements will be copied, and the `start` - and `count` parameters specify which elements to extract. If no `count` is - given, elements will be extracted from the `start` to the end of the array. - When specifying the `start`, remember that 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) - docUrl: https://processing.org/reference/subset_.html - name: null - parameters: - count: "int: number of values to extract" - list: "Object, String[], double[], float[], long[], int[], char[], byte[], or - boolean[]: array to extract from" - start: "int: position to begin" + description: |- + Extracts an array of elements from an existing array. The `list` + parameter defines the array from which the elements will be copied, and the + `start` and `count` parameters specify which elements to extract. + If no `count` is given, elements will be extracted from the + `start` to the end of the array. When specifying the `start`, + remember that 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) + examples: + - | + String[] sa1 = { "OH", "NY", "CA", "VA", "CO", "IL" }; + String[] sa2 = subset(sa1, 1); + println(sa2); + // Prints the following array contents to the console: + // [0] "NY" + // [1] "CA" + // [2] "VA" + // [3] "CO" + // [4] "IL" + println(); + String[] sa3 = subset(sa1, 2, 3); + println(sa3); + // Prints the following array contents to the console: + // [0] "CA" + // [1] "VA" + // [2] "CO" + fileName: subset_ + parameters: + count: + desc: number of values to extract + type: + - int + list: + desc: array to extract from + type: + - boolean[] + - Object + - byte[] + - char[] + - int[] + - long[] + - float[] + - double[] + - String[] + start: + desc: position to begin + type: + - int returns: boolean[], byte[], char[], int[], long[], float[], double[], String[], or Object - syntax: |- - subset(list, start) - subset(list, start, count) + syntax: + - subset(list, start) + - subset(list, start, count) + type: function +super: + description: Keyword used to reference the superclass of a subclass. + examples: + - |+ + // This example is a code fragment; + // it will not compile on its own. + + // Create the DragDrop subclass from + // the Button class. Button becomes + // the superclass of DragDrop. + class DragDrop extends Button { + int xoff, yoff; + DragDrop(int x, int y) { + // Runs the superclass' constructor + super(x, y); + } + void press(int mx, int my) { + // Runs the superclass' press() method + super.press(); + xoff = mx; + yoff = my; + } + } + + fileName: super + parameters: {} + returns: "" + syntax: [] + type: function +switch: + description: Works like an `if else` structure, but `switch` is more convenient + when you need to select between three or more alternatives. Program controls + jumps to the case with the same value as the expression. All remaining + statements in the switch are executed unless redirected by a `break`. Only + primitive datatypes which can convert to an integer (byte, char, and int) + may be used as the `expression` parameter. The default is optional. + examples: + - | + int num = 1; + + switch(num) { + case 0: + println("Zero"); // Does not execute + break; + case 1: + println("One"); // Prints "One" + break; + } + - | + char letter = 'N'; + + switch(letter) { + case 'A': + println("Alpha"); // Does not execute + break; + case 'B': + println("Bravo"); // Does not execute + break; + default: // Default executes if the case names + println("None"); // don't match the switch parameter + break; + } + - | + // Removing a "break" enables testing + // for more than one value at once + + char letter = 'b'; + + switch(letter) { + case 'a': + case 'A': + println("Alpha"); // Does not execute + break; + case 'b': + case 'B': + println("Bravo"); // Prints "Bravo" + break; + } + fileName: switch + parameters: + expression: + desc: byte, char, or int + type: [] + name: + desc: byte, char, or int + type: [] + statements: + desc: one or more statements to be executed + type: [] + returns: "" + syntax: + - switch(expression) + - "{" + - " case name: " + - " statements " + - " case name: // Optional" + - ' statements // "' + - ' default: // "' + - ' statements // "' + - "}" type: function tan: - description: 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`. - docUrl: https://processing.org/reference/tan_.html - name: null - parameters: - angle: "float: an angle in radians" + description: |- + 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`. + examples: + - |- + size(400, 400); + + float a = 0.0; + float inc = TWO_PI/50.0; + + for (int i = 0; i <= 400; i = i+8) { + line(i, 200, i, 200+tan(a)*8.0); + a = a + inc; + } + fileName: tan_ + parameters: + angle: + desc: an angle in radians + type: + - float returns: float - syntax: tan(angle) + syntax: + - tan(angle) type: function text: - description: >- + description: |- Draws text to the screen. Displays the information specified in the first - parameter on the screen in the position specified by the additional - parameters. A default font will be used unless a font is set with the - `textFont()` function and a default size will be used unless a font is set - with `textSize()`. 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. When these parameters are specified, they are interpreted based on the current `rectMode()` setting. Text that does not fit completely within the rectangle specified will not be drawn to the screen. - - - Note that Processing now lets you call `text()` without first specifying a PFont with `textFont()`. In that case, a generic sans-serif font will be used instead. (See the third exam. . . - docUrl: https://processing.org/reference/text_.html - name: null - parameters: - c: "char: the alphanumeric character to be displayed" - chars: "char[]: the alphanumberic symbols to be displayed" - num: "int, or float: the numeric value to be displayed" - start: "int: array index at which to start writing characters" - stop: "int: array index at which to stop writing characters" - x: "float: x-coordinate of text" - x1: "float: by default, the x-coordinate of text, see rectMode() for more info" - x2: "float: by default, the width of the text box, see rectMode() for more info" - y: "float: y-coordinate of text" - y1: "float: by default, the y-coordinate of text, see rectMode() for more info" - y2: "float: by default, the height of the text box, see rectMode() for more - info" - z: "float: z-coordinate of text" - returns: void - syntax: |- - text(c, x, y) - text(c, x, y, z) - text(str, x, y) - text(chars, start, stop, x, y) - text(str, x, y, z) - text(chars, start, stop, x, y, z) - text(str, x1, y1, x2, y2) - text(num, x, y) - text(num, x, y, z) + parameter on the screen in the position specified by the additional + parameters. A default font will be used unless a font is set with the + `textFont()` function and a default size will be used unless a font is + set with `textSize()`. 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. When these parameters are + specified, they are interpreted based on the current `rectMode()` + setting. Text that does not fit completely within the rectangle specified + will not be drawn to the screen. + + Note that Processing now lets you call `text()` without first specifying + a PFont with `textFont()`. In that case, a generic sans-serif font will + be used instead. (See the third example above.) + examples: + - |- + size(400, 400); + textSize(128); + text("word", 40, 120); + fill(0, 408, 612); + text("word", 40, 240); + fill(0, 408, 612, 204); + text("word", 40, 360); + - |- + size(400, 400, P3D); + textSize(128); + fill(0, 408, 612, 816); + text("word", 48, 180, -120); // Specify a z-axis value + text("word", 48, 240); // Default depth, no z-value specified + - |- + size(400, 400); + String s = "The quick brown fox jumps over the lazy dog."; + fill(200); + text(s, 40, 40, 280, 320); // Text wraps within text box + fileName: text_ + parameters: + c: + desc: the alphanumeric character to be displayed + type: + - char + chars: + desc: the alphanumeric symbols to be displayed + type: + - char[] + num: + desc: the numeric value to be displayed + type: + - float + - int + start: + desc: array index at which to start writing characters + type: + - int + stop: + desc: array index at which to stop writing characters + type: + - int + x: + desc: x-coordinate of text + type: + - float + x1: + desc: by default, the x-coordinate of text, see rectMode() for more info + type: + - float + x2: + desc: by default, the width of the text box, see rectMode() for more info + type: + - float + y: + desc: y-coordinate of text + type: + - float + y1: + desc: by default, the y-coordinate of text, see rectMode() for more info + type: + - float + y2: + desc: by default, the height of the text box, see rectMode() for more info + type: + - float + z: + desc: z-coordinate of text + type: + - float + returns: void + syntax: + - text(c, x, y) + - text(c, x, y, z) + - text(str, x, y) + - text(chars, start, stop, x, y) + - text(str, x, y, z) + - text(chars, start, stop, x, y, z) + - text(str, x1, y1, x2, y2) + - text(num, x, y) + - text(num, x, y, z) type: function textAlign: description: >- 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. - - 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 c. . . - docUrl: https://processing.org/reference/textAlign_.html - name: null - parameters: - alignX: "int: horizontal alignment, either LEFT, CENTER, or RIGHT" - alignY: "int: vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE" - returns: void - syntax: |- - textAlign(alignX) - textAlign(alignX, alignY) + and + RIGHT set the display characteristics of the letters in relation to the + values for the `x` and `y` parameters of the `text()` + function. + + 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. + examples: + - |- + size(400, 400); + background(0); + textSize(64); + textAlign(RIGHT); + text("ABCD", 200, 120); + textAlign(CENTER); + text("EFGH", 200, 200); + textAlign(LEFT); + text("IJKL", 200, 280); + - |- + size(400, 400); + background(0); + stroke(153); + textSize(44); + textAlign(CENTER, BOTTOM); + line(0, 120, width, 120); + text("CENTER,BOTTOM", 200, 120); + textAlign(CENTER, CENTER); + line(0, 200, width, 200); + text("CENTER,CENTER", 200, 200); + textAlign(CENTER, TOP); + line(0, 280, width, 280); + text("CENTER,TOP", 200, 280); + fileName: textAlign_ + parameters: + alignX: + desc: horizontal alignment, either LEFT, CENTER, or RIGHT + type: + - int + alignY: + desc: vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE + type: + - int + returns: void + syntax: + - textAlign(alignX) + - textAlign(alignX, alignY) type: function textAscent: - description: Returns ascent of the current font at its current size. This - information is useful for determining the height of the font above the - baseline. - docUrl: https://processing.org/reference/textAscent_.html - name: null + description: |- + Returns ascent of the current font at its current size. This information is + useful for determining the height of the font above the baseline. + examples: + - |- + size(400, 400); + float base = height * 0.75; + float scalar = 0.8; // Different for each font + + textSize(128); // Set initial text size + float a = textAscent() * scalar; // Calc ascent + line(0, base-a, width, base-a); + text("dp", 0, base); // Draw text on baseline + + textSize(256); // Increase text size + a = textAscent() * scalar; // Recalc ascent + line(160, base-a, width, base-a); + text("dp", 160, base); // Draw text on baseline + fileName: textAscent_ parameters: {} returns: float - syntax: textAscent() + syntax: + - textAscent() type: function textDescent: - description: Returns descent of the current font at its current size. This - information is useful for determining the height of the font below the - baseline. - docUrl: https://processing.org/reference/textDescent_.html - name: null + description: |- + Returns descent of the current font at its current size. This information is + useful for determining the height of the font below the baseline. + examples: + - |- + size(400, 400); + float base = height * 0.75; + float scalar = 0.8; // Different for each font + + textSize(128); // Set initial text size + textSize(128); // Set initial text size + float a = textDescent() * scalar; // Calc ascent + line(0, base+a, width, base+a); + text("dp", 0, base); // Draw text on baseline + + textSize(256); // Increase text size + a = textDescent() * scalar; // Recalc ascent + line(160, base+a, width, base+a); + text("dp", 160, base); // Draw text on baseline + fileName: textDescent_ parameters: {} returns: float - syntax: textDescent() + syntax: + - textDescent() type: function textFont: description: >- - Sets the current font that will be drawn with the `text()` function. Fonts - must be created for Processing with `createFont()` or loaded with - `loadFont()` before they can be used. The font set through `textFont()` will - be used in all subsequent calls to the `text()` function. If no `size` - parameter is specified, the font size defaults to the original size (the - size in which it was created with the "Create Font..." tool) overriding any - previous calls to `textFont()` or `textSize()`. - When fonts are rendered as an image texture (as is the case with the P2D and P3D renderers as well as with `loadFont()` and vlw files), you should create fonts at the sizes that will be used most commonly. Using `textFont()` without the size parameter will result in the cleanest type. - docUrl: https://processing.org/reference/textFont_.html - name: null - parameters: - size: "float: the size of the letters in units of pixels" - which: "PFont: any variable of the type PFont" - returns: void - syntax: |- - textFont(which) - textFont(which, size) + Sets the current font that will be drawn with the `text()` function. + Fonts must be created for Processing with `createFont()` or loaded with + `loadFont()` before they can be used. The font set through + `textFont()` will be used in all subsequent calls to the `text()` + function. If no `size` parameter is specified, the font size defaults to + the original size (the size in which it was created with the "Create Font..." + tool) overriding any previous calls to `textFont()` or + `textSize()`. + + When fonts are rendered as an image texture (as is the case with the P2D and + P3D renderers as well as with `loadFont()` and vlw files), you should + create fonts at the sizes that will be used most commonly. Using + `textFont()` without the size parameter will result in the cleanest + type. + examples: + - |- + size(400,400); + PFont mono; + // The font "andalemo.ttf" must be located in the + // current sketch's "data" directory to load successfully + mono = createFont("andalemo.ttf", 128); + background(0); + textFont(mono); + text("word", 48, 240); + fileName: textFont_ + parameters: + size: + desc: the size of the letters in units of pixels + type: + - float + which: + desc: any variable of the type PFont + type: + - PFont + returns: void + syntax: + - textFont(which) + - textFont(which, size) type: function textLeading: - description: Sets the spacing between lines of text in units of pixels. This - setting will be used in all subsequent calls to the `text()` - function. Note, however, that the leading is reset by `textSize()`. For - example, if the leading is set to 20 with `textLeading(20)`, then if - `textSize(48)` is run at a later point, the leading will be reset to the - default for the text size of 48. - docUrl: https://processing.org/reference/textLeading_.html - name: null + description: >- + Sets the spacing between lines of text in units of pixels. This setting will + be used in all subsequent calls to the `text()` function. Note, however, + that the leading is reset by `textSize()`. For example, if the leading + is set to 20 with `textLeading(20)`, then if `textSize(48)` is run + at a later point, the leading will be reset to the default for the text size + of 48. + examples: + - |- + size(400, 400); + + // Text to display. The "\n" is a "new line" character + String lines = "L1\nL2\nL3"; + textSize(48); + fill(0); // Set fill to black + + textLeading(40); // Set leading to 40 + text(lines, 40, 100); + + textLeading(80); // Set leading to 80 + text(lines, 160, 100); + + textLeading(120); // Set leading to 120 + text(lines, 280, 100); + fileName: textLeading_ parameters: - leading: "float: the size in pixels for spacing between lines" + leading: + desc: the size in pixels for spacing between lines + type: + - float returns: void - syntax: textLeading(leading) + syntax: + - textLeading(leading) type: function textMode: - description: >- + description: |- Sets the way text draws to the screen, either as texture maps or as vector - geometry. The default `textMode(MODEL)`, uses textures to render the fonts. - The `textMode(SHAPE)` mode draws text using 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. - + geometry. The default `textMode(MODEL)`, uses textures to render the + fonts. The `textMode(SHAPE)` mode draws text using 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()`. + examples: + - | + import processing.pdf.*; + + void setup() { + size(500, 500, PDF, "TypeDemo.pdf"); + textMode(SHAPE); + textSize(180); + } - 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()`. - docUrl: https://processing.org/reference/textMode_.html - name: null + void draw() { + text("ABC", 75, 350); + exit(); // Quit the program + } + fileName: textMode_ parameters: - mode: "int: either MODEL or SHAPE" + mode: + desc: either MODEL or SHAPE + type: + - int returns: void - syntax: textMode(mode) + syntax: + - textMode(mode) type: function textSize: - description: 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. - docUrl: https://processing.org/reference/textSize_.html - name: null - parameters: - size: "float: the size of the letters in units of pixels" - returns: void - syntax: textSize(size) + description: |- + 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. + examples: + - |- + size(400, 400); + background(0); + fill(255); + textSize(104); + text("WORD", 40, 200); + textSize(56); + text("WORD", 40, 280); + fileName: textSize_ + parameters: + size: + desc: the size of the letters in units of pixels + type: + - float + returns: void + syntax: + - textSize(size) type: function textWidth: description: Calculates and returns the width of any character or text string. - docUrl: https://processing.org/reference/textWidth_.html - name: null - parameters: - c: "char: the character to measure" - str: "String: the String of characters to measure" + examples: + - |- + size(400, 400); + textSize(112); + + char c = 'T'; + float cw = textWidth(c); + text(c, 0, 160); + line(cw, 0, cw, 200); + + String s = "Tokyo"; + float sw = textWidth(s); + text(s, 0, 340); + line(sw, 200, sw, 400); + fileName: textWidth_ + parameters: + c: + desc: the character to measure + type: + - char + str: + desc: the String of characters to measure + type: + - String returns: float - syntax: |- - textWidth(c) - textWidth(str) + syntax: + - textWidth(c) + - textWidth(str) type: function texture: - description: >- - 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()`. This function only works with the P2D and P3D renderers. - - - 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. - docUrl: https://processing.org/reference/texture_.html - name: null - parameters: - image: "PImage: reference to a PImage object" - returns: void - syntax: texture(image) + description: |- + 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()`. This function only works with the P2D and P3D + renderers. + + 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. + examples: + - |- + size(400, 400, P3D); + noStroke(); + PImage img = loadImage("shells.jpg"); + textureMode(NORMAL); + beginShape(); + texture(img); + vertex(40, 80, 0, 0); + vertex(320, 20, 1, 0); + vertex(380, 360, 1, 1); + vertex(160, 380, 0, 1); + endShape(); + fileName: texture_ + parameters: + image: + desc: reference to a PImage object + type: + - PImage + returns: void + syntax: + - texture(image) type: function textureMode: - description: >- - Sets the coordinate space for texture mapping. The default mode is `IMAGE`, - which refers to the actual coordinates of the image. `NORMAL` refers to a - normalized space of values ranging from 0 to 1. This function only works - with the P2D and P3D renderers. - - - With `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) (100, 0) (100,200) (0,200). The same mapping in `NORMAL` is (0,0) (1,0) (1,1) (0,1). - docUrl: https://processing.org/reference/textureMode_.html - name: null - parameters: - mode: "int: either IMAGE or NORMAL" - returns: void - syntax: textureMode(mode) + description: |- + Sets the coordinate space for texture mapping. The default mode is + `IMAGE`, which refers to the actual coordinates of the image. + `NORMAL` refers to a normalized space of values ranging from 0 to 1. + This function only works with the P2D and P3D renderers. + + With `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) (100, 0) (100,200) + (0,200). The same mapping in `NORMAL` is (0,0) (1,0) (1,1) (0,1). + examples: + - |- + size(400, 400, P3D); + noStroke(); + PImage img = loadImage("shells.jpg"); + beginShape(); + texture(img); + vertex(40, 80, 0, 0); + vertex(320, 20, 1, 0); + vertex(380, 360, 1, 1); + vertex(160, 380, 0, 1); + endShape(); + - |- + size(400, 400, P3D); + noStroke(); + PImage img = loadImage("shells.jpg"); + textureMode(IMAGE); + beginShape(); + texture(img); + vertex(40, 80, 0, 0); + vertex(320, 20, 400, 0); + vertex(380, 360, 400, 400); + vertex(160, 380, 0, 400); + endShape(); + fileName: textureMode_ + parameters: + mode: + desc: either IMAGE or NORMAL + type: + - int + returns: void + syntax: + - textureMode(mode) type: function textureWrap: - description: Defines if textures repeat or draw once within a texture map. The - two parameters are CLAMP (the default behavior) and REPEAT. This function - only works with the P2D and P3D renderers. - docUrl: https://processing.org/reference/textureWrap_.html - name: null - parameters: - wrap: "int: Either CLAMP (default) or REPEAT" - returns: void - syntax: textureWrap(wrap) - type: function -thread: - description: >- - Processing sketches follow a specific sequence of steps: `setup()` first, - followed by `draw()` over and over and over again in a loop. A thread is - also a series of steps with a beginning, a middle, and an end. A Processing - sketch is a single thread, often referred to as the "Animation" thread. - Other threads' sequences, however, can run independently of the main - animation loop. In fact, you can launch any number of threads at one time, - and they will all run concurrently. - - - You cannot draw to the screen from a function called by `thread()`. Because it runs independently, the code will not be synchronized to the animation thread, causing strange or at least inconsistent results. Use `thread()` to load files or do other tasks that take time. When the task is finished, set a variable that indicates the task is complete, and check that from inside your `draw()` method. + description: |- + Defines if textures repeat or draw once within a texture map. + The two parameters are CLAMP (the default behavior) and REPEAT. + This function only works with the P2D and P3D renderers. + examples: + - | + PImage img; + + void setup() { + size(300, 300, P2D); + img = loadImage("berlin-1.jpg"); + textureMode(NORMAL); + } + void draw() { + background(0); + translate(width/2, height/2); + rotate(map(mouseX, 0, width, -PI, PI)); + if (mousePressed) { + textureWrap(REPEAT); + } else { + textureWrap(CLAMP); + } + beginShape(); + texture(img); + vertex(-100, -100, 0, 0); + vertex(100, -100, 2, 0); + vertex(100, 100, 2, 2); + vertex(-100, 100, 0, 2); + endShape(); + } + fileName: textureWrap_ + parameters: + wrap: + desc: Either CLAMP (default) or REPEAT + type: + - int + returns: void + syntax: + - textureWrap(wrap) + type: function +this: + description: >- + Refers to the current object (i.e., "this object"), which will change + depending on the context in which `this` is referenced. In Processing, it's + most common to use `this` to pass a reference from the current object into + one of the libraries. + + + The keyword `this` can also be used to reference an object's own method from + within itself, but such usage is typically not necessary. For example, if + you are calling the `filter()` method of a `PImage` object named `tree` from + another object, you would write `tree.filter()`. To call this method inside + the PImage object itself, one could simply write `filter()` or, more + explicitly, `this.filter()`. The additional level of specificity in + `this.filter()` is not necessary, as it is always implied. + examples: + - |+ + float ypos = 50; + + void setup() { + size(100, 100); + noLoop(); + } - Processing uses threads quite often, such as with library functions like `captureEvent()` and `movieEvent()`. These functio. . . - docUrl: https://processing.org/reference/thread_.html - name: null - parameters: - name: "String: name of the function to be executed in a separate thread" - returns: void - syntax: thread(name) - type: function -tint: - description: >- - Sets the fill value for displaying images. Images can be tinted to specified - colors or made transparent by including an alpha value. + void draw() { + line(0, 0, 100, ypos); + // "this" references the Processing sketch, + // and is not necessary in this case + this.ypos = 100; + line(0, 0, 100, ypos); + } + - |+ + import processing.video.*; + Movie myMovie; - To apply transparency to an image without affecting its color, use white as the tint color and specify an alpha value. For instance, `tint(255, 128)` will make an image 50% transparent (assuming the default alpha range of 0-255, which can be changed with `colorMode()`). + void setup() { + size(200, 200); + background(0); + // "this" references the Processing sketch + myMovie = new Movie(this, "totoro.mov"); + myMovie.loop(); + } + void draw() { + if (myMovie.available()) { + myMovie.read(); + } + image(myMovie, 0, 0); + } - When using hexadecimal notation to specify a color, use "`#`" or "`0x`" before the values (e.g., `#CCFFAA` or `0xFFCCFFAA`). The `#` syntax uses six digits to specify a color (just as colors are typically 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 define the red, green, and blue components. + fileName: this + parameters: {} + returns: "" + syntax: [] + type: function +thread: + description: |- + Processing sketches follow a specific sequence of steps: `setup()` + first, followed by `draw()` over and over and over again in a loop. A + thread is also a series of steps with a beginning, a middle, and an end. A + Processing sketch is a single thread, often referred to as the "Animation" + thread. Other threads' sequences, however, can run independently of the + main animation loop. In fact, you can launch any number of threads at one + time, and they will all run concurrently. + + You cannot draw to the screen from a function called by `thread()`. + Because it runs independently, the code will not be synchronized to the + animation thread, causing strange or at least inconsistent results. Use + `thread()` to load files or do other tasks that take time. When the + task is finished, set a variable that indicates the task is complete, and + check that from inside your `draw()` method. + + Processing uses threads quite often, such as with library functions like + `captureEvent()` and `movieEvent()`. These functions are + triggered by a different thread running behind the scenes, and they alert + Processing whenever they have something to report. This is useful when you + need to perform a task that takes too long and would slow down the main + animation's frame rate, such as grabbing data from the network. If a + separate thread gets stuck or has an error, the entire program won't grind + to a halt, since the error only stops that individual thread. + + Writing your own thread can be a complex endeavor that involves extending + the Java Thread + class. However, the `thread()` method is a quick and dirty way to + implement a simple thread in Processing. By passing in a `String` that + matches the name of a function declared elsewhere in the sketch, Processing + will execute that function in a separate thread. + examples: + - | + String time = ""; + + void setup() { + size(100, 100); + } + void draw() { + background(0); + // Every 30 frames request new data + if (frameCount % 30 == 0) { + thread("requestData"); + } + text(time, 10, 50); + } - The value for the gray parameter must be less than or equal to the current maximum value as specified by `colorMode()`. Th. . . - docUrl: https://processing.org/reference/tint_.html - name: null + // This happens as a separate thread and can take as long as it wants + void requestData() { + JSONObject json = loadJSONObject("http://time.jsontest.com/"); + time = json.getString("time"); + } + fileName: thread_ parameters: - alpha: "float: opacity of the image" - gray: "float: specifies a value between white and black" - rgb: "int: color value in hexadecimal notation" - v1: "float: red or hue value (depending on current color mode)" - v2: "float: green or saturation value (depending on current color mode)" - v3: "float: blue or brightness value (depending on current color mode)" + name: + desc: name of the function to be executed in a separate thread + type: + - String returns: void - syntax: |- - tint(rgb) - tint(rgb, alpha) - tint(gray) - tint(gray, alpha) - tint(v1, v2, v3) - tint(v1, v2, v3, alpha) + syntax: + - thread(name) + type: function +tint: + description: |- + Sets the fill value for displaying images. Images can be tinted to specified + colors or made transparent by including an alpha value. + + To apply transparency to an image without affecting its color, use white as + the tint color and specify an alpha value. For instance, `tint(255, + 128)` will make an image 50% transparent (assuming the default alpha range + of 0-255, which can be changed with `colorMode()`). + + When using hexadecimal notation to specify a color, use "`#`" or + "`0x`" before the values (e.g., `#CCFFAA` or `0xFFCCFFAA`). + The `#` syntax uses six digits to specify a color (just as colors are + typically 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 define the red, green, and blue components. + + The value for the gray parameter 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. + examples: + - | + size(400,400); + PImage img; + img = loadImage("yuya-onsen.jpg"); + image(img, 0, 0); + tint(0, 153, 204); // Tint blue + image(img, width/2, 0); + - | + size(400,400); + PImage img; + img = loadImage("yuya-onsen.jpg"); + image(img, 0, 0); + tint(0, 153, 204, 126); // Tint blue and set transparency + image(img, width/2, 0); + - | + size(400,400); + PImage img; + img = loadImage("yuya-onsen.jpg"); + image(img, 0, 0); + tint(255, 126); // Apply transparency without changing color + image(img, width/2, 0); + fileName: tint_ + parameters: + alpha: + desc: opacity of the image + type: + - float + gray: + desc: specifies a value between white and black + type: + - float + rgb: + desc: color value in hexadecimal notation + type: + - int + v1: + desc: red or hue value (depending on current color mode) + type: + - float + v2: + desc: green or saturation value (depending on current color mode) + type: + - float + v3: + desc: blue or brightness value (depending on current color mode) + type: + - float + returns: void + syntax: + - tint(rgb) + - tint(rgb, alpha) + - tint(gray) + - tint(gray, alpha) + - tint(v1, v2, v3) + - tint(v1, v2, v3, alpha) type: function translate: description: >- - 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 are cumulative and 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 using `pushMatrix()` and `popMatrix()`. - docUrl: https://processing.org/reference/translate_.html - name: null - parameters: - x: "float: left/right translation" - y: "float: up/down translation" - z: "float: forward/backward translation" - returns: void - syntax: |- - translate(x, y) - translate(x, y, z) + 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 are cumulative and 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 using `pushMatrix()` and + `popMatrix()`. + examples: + - |- + size(400, 400); + translate(120, 80); + rect(0, 0, 220, 220); + - |- + // Translating in 3D requires P3D + // as the parameter to size() + size(400, 400, P3D); + // Translate 30 across, 20 down, and + // 50 back, or "away" from the screen. + translate(120, 80, -200); + rect(0, 0, 220, 220); + - |- + size(400, 400); + rect(0, 0, 220, 220); // Draw rect at original 0,0 + translate(120, 80); + rect(0, 0, 220, 220); // Draw rect at new 0,0 + translate(56, 56); + rect(0, 0, 220, 220); // Draw rect at new 0,0 + fileName: translate_ + parameters: + x: + desc: left/right translation + type: + - float + y: + desc: up/down translation + type: + - float + z: + desc: forward/backward translation + type: + - float + returns: void + syntax: + - translate(x, y) + - translate(x, y, z) type: function triangle: - description: 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. - docUrl: https://processing.org/reference/triangle_.html - name: null - parameters: - x1: "float: x-coordinate of the first point" - x2: "float: x-coordinate of the second point" - x3: "float: x-coordinate of the third point" - y1: "float: y-coordinate of the first point" - y2: "float: y-coordinate of the second point" - y3: "float: y-coordinate of the third point" - returns: void - syntax: triangle(x1, y1, x2, y2, x3, y3) + description: |- + 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. + examples: + - |- + size(400, 400); + triangle(120, 300, 232, 80, 344, 300); + fileName: triangle_ + parameters: + x1: + desc: x-coordinate of the first point + type: + - float + x2: + desc: x-coordinate of the second point + type: + - float + x3: + desc: x-coordinate of the third point + type: + - float + y1: + desc: y-coordinate of the first point + type: + - float + y2: + desc: y-coordinate of the second point + type: + - float + y3: + desc: y-coordinate of the third point + type: + - float + returns: void + syntax: + - triangle(x1, y1, x2, y2, x3, y3) type: function trim: - description: 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. - docUrl: https://processing.org/reference/trim_.html - name: null - parameters: - array: "String[]: a String array" - str: "String: any string" + description: |- + 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" (U+00A0) + character and the zero width no-break space (U+FEFF) character. + examples: + - | + Table table; + + void setup() { + + table = new Table(); + + table.addColumn("name"); + table.addColumn("type"); + + TableRow newRow = table.addRow(); + newRow.setString("name", " Lion"); + newRow.setString("type", "Mammal"); + + newRow = table.addRow(); + newRow.setString("name", "Snake "); + newRow.setString("type", "Reptile"); + + newRow = table.addRow(); + newRow.setString("name", " Mosquito "); + newRow.setString("type", "Insect"); + + println(table.getStringColumn("name")); + + table.trim(); + + println(table.getStringColumn("name")); + } + + // Sketch prints: + // [0] " Lion" + // [1] "Snake " + // [2] " Mosquito " + // [0] "Lion" + // [1] "Snake" + // [2] "Mosquito" + - | + String s1 = " Somerville MA "; + println(s1); // Prints " Somerville MA " + String s2 = trim(s1); + println(s2); // Prints "Somerville MA" + + String[] a1 = { " inconsistent ", " spacing" }; // Note spaces + String[] a2 = trim(a1); + printArray(a2); + // Prints the following array contents to the console: + // [0] "inconsistent" + // [1] "spacing" + fileName: trim_ + parameters: + array: + desc: a String array + type: + - String[] + str: + desc: any string + type: + - String returns: String or String[] - syntax: |- - trim(str) - trim(array) + syntax: + - trim(str) + - trim(array) + type: function +"true": + description: Reserved word representing the logical value "true". Only variables + of type `boolean` may be assigned the value `true`. + examples: + - | + rect(30, 20, 50, 50); + boolean b = true; + if (b == true) { + line(20, 10, 90, 80); // This line is drawn + } else { + line(20, 80, 90, 10); // This line is not drawn + } + fileName: "true" + parameters: {} + returns: "" + syntax: [] + type: function +try: + description: The `try` keyword is used with `catch` to handle exceptions. Sun's + Java documentation defines an exception as "an event, which occurs during + the execution of a program, that disrupts the normal flow of the program's + instructions." This could be, for example, an error while a file is read. + examples: + - | + BufferedReader reader; + String line; + + void setup() { + // Open the file from the createWriter() example + reader = createReader("positions.txt"); + } + + void draw() { + try { + line = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + line = null; + } + if (line == null) { + // Stop reading because of an error or file is empty + noLoop(); + } else { + String[] pieces = split(line, TAB); + int x = int(pieces[0]); + int y = int(pieces[1]); + point(x, y); + } + } + fileName: try + parameters: + catchStatements: + desc: code that handles the exception + type: [] + exception: + desc: the Java exception that was thrown + type: [] + tryStatements: + desc: if this code throws an exception, then the code in "catch" is run + type: [] + returns: "" + syntax: + - try { + - " tryStatements" + - "} catch (exception) {" + - " catchStatements" + - "} " type: function unbinary: - description: Converts a `String` representation of a binary number to its - equivalent integer value. For example, `unbinary("00001000")` will return - `8`. - docUrl: https://processing.org/reference/unbinary_.html - name: null - parameters: - value: "String: String to convert to an integer" + description: |- + Converts a `String` representation of a binary number to its equivalent + integer value. For example, `unbinary("00001000")` will return + `8`. + examples: + - | + String s1 = "00010000"; + String s2 = "00001000"; + String s3 = "00000100"; + println(unbinary(s1)); // Prints "16" + println(unbinary(s2)); // Prints "8" + println(unbinary(s3)); // Prints "4" + fileName: unbinary_ + parameters: + value: + desc: String to convert to an integer + type: + - String returns: int - syntax: unbinary(value) + syntax: + - unbinary(value) type: function unhex: - description: Converts a `String` representation of a hexadecimal number to its - equivalent integer value. - docUrl: https://processing.org/reference/unhex_.html - name: null - parameters: - value: "String: String to convert to an integer" + description: |- + Converts a `String` representation of a hexadecimal number to its + equivalent integer value. + examples: + - | + String hs = "FF006699"; + int hi = unhex(hs); + fill(hi); + rect(30, 20, 55, 55); + fileName: unhex_ + parameters: + value: + desc: String to convert to an integer + type: + - String returns: int - syntax: unhex(value) + syntax: + - unhex(value) type: function updatePixels: - description: 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()` — updating is only - necessary to apply changes. - docUrl: https://processing.org/reference/updatePixels_.html - name: null + description: |- + 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()` — updating is + only necessary to apply changes. + examples: + - |- + size(400,400); + PImage img = loadImage("mt-fuji.jpg"); + image(img, 0, 0); + int halfImage = img.width * img.height/2; + loadPixels(); + for (int i = 0; i < halfImage; i++) { + pixels[i+halfImage] = pixels[i]; + } + updatePixels(); + fileName: updatePixels_ parameters: {} returns: void - syntax: updatePixels() + syntax: + - updatePixels() type: function vertex: description: >- - 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. It is used exclusively within the `beginShape()` and - `endShape()` functions. - - - Drawing a vertex in 3D using the `z` parameter requires the P3D parameter in combination with size, as shown in the above example. + 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. It is used exclusively within the + `beginShape()` and `endShape()` functions. + + 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 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()`. + examples: + - |- + size(400, 400); + beginShape(POINTS); + vertex(120, 80); + vertex(340, 80); + vertex(340, 300); + vertex(120, 300); + endShape(); + - |- + // Drawing vertices in 3D requires P3D + // as a parameter to size() + size(400, 400, P3D); + beginShape(POINTS); + vertex(120, 80, -200); + vertex(340, 80, -200); + vertex(340, 300, -200); + vertex(120, 300, -200); + endShape(); + - |- + size(400, 400, P3D); + PImage img = loadImage("laDefense.jpg"); + noStroke(); + beginShape(); + texture(img); + // "laDefense.jpg" is 100x100 pixels in size so + // the values 0 and 400 are used for the + // parameters "u" and "v" to map it directly + // to the vertex points + vertex(40, 80, 0, 0); + vertex(320, 20, 100, 0); + vertex(380, 360, 100, 100); + vertex(160, 380, 0, 100); + endShape(); + fileName: vertex_ + parameters: + u: + desc: horizontal coordinate for the texture mapping + type: + - float + v: + desc: vertical coordinate for the texture mapping + type: + - float + - float[] + x: + desc: x-coordinate of the vertex + type: + - float + y: + desc: y-coordinate of the vertex + type: + - float + z: + desc: z-coordinate of the vertex + type: + - float + returns: void + syntax: + - vertex(x, y) + - vertex(x, y, z) + - vertex(v) + - vertex(x, y, u, v) + - vertex(x, y, z, u, v) + type: function +void: + description: Keyword used to indicate that a function returns no value. Each + function must either return a value of a specific datatype or use the + keyword `void` to specify it returns nothing. + examples: + - | + void setup() { // setup() does not return a value + size(200, 200); + } + void draw() { // draw() does not return a value + line(10, 100, 190, 100); + drawCircle(); + } - This function is also used to map a texture onto 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()`. - docUrl: https://processing.org/reference/vertex_.html - name: null - parameters: - u: "float: horizontal coordinate for the texture mapping" - v: "float: vertical coordinate for the texture mapping" - x: "float: x-coordinate of the vertex" - y: "float: y-coordinate of the vertex" - z: "float: z-coordinate of the vertex" - returns: void - syntax: |- - vertex(x, y) - vertex(x, y, z) - vertex(v) - vertex(x, y, u, v) - vertex(x, y, z, u, v) + void drawCircle() { // This function also does not return a value + ellipse(30, 30, 50, 50); + } + fileName: void + parameters: + function: + desc: any function that is being defined or implemented + type: [] + statements: + desc: any valid statements + type: [] + returns: "" + syntax: + - void function { + - " statements" + - "}" + type: function +while: + description: >- + Controls a sequence of repetitions. The `while` structure executes a series + of statements continuously while the `expression` is `true`. The expression + must be updated during the repetitions or the program will never "break out" + of `while`. + + This function can be dangerous because the code inside the `while` loop will + not finish until the expression inside `while` becomes false. It will lock + out all other code from running (e.g., mouse and keyboard events will not be + updated). Be careful — if used incorrectly, this can lock up your code + (and sometimes even the Processing environment itself). + examples: + - |- + size(400, 400); + int i = 0; + while (i < 320) { + line(120, i, 320, i); + i = i + 20; + } + fileName: while + parameters: + expression: + desc: a valid expression + type: [] + statements: + desc: one or more statements + type: [] + returns: "" + syntax: + - while (expression) { + - " statements" + - "}" type: function width: - description: System variable that 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` defaults to 100 if `size()` is not used in a - program. - docUrl: https://processing.org/reference/width.html - examples: | - noStroke(); - background(0); - rect(0, 40, width, 20); - rect(0, 60, width/2, 20); - name: null + description: |- + 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` defaults to 100 if + `size()` is not used in a program. + examples: + - |- + size(400, 400); + noStroke(); + background(0); + rect(0, 160, width, 80); + rect(0, 240, width/2, 80); + fileName: width type: var +windowMove: + description: |- + The `windowMove()` function defines the position of the Processing + sketch in relation to the upper-left corner of the computer screen. + fileName: windowMove_ + parameters: + x: + desc: x-coordinate of the window + type: + - int + y: + desc: y-coordinate of the window + type: + - int + returns: void + syntax: + - windowMove(x, y) + type: function +windowMoved: + description: Called when the window is moved. + fileName: windowMoved_ + parameters: {} + returns: void + syntax: + - windowMoved() + type: function +windowRatio: + description: |- + Scale the sketch as if it fit this specific width and height. + This will also scale the `mouseX` and `mouseY` variables (as well as + `pmouseX` and `pmouseY`). Note that it will not have an effect on + MouseEvent objects (i.e. `event.getX()` and `event.getY()`) because + their exact behavior may interact strangely with other libraries. + fileName: windowRatio_ + parameters: + high: + desc: height of the sketch + type: + - int + wide: + desc: width of the sketch + type: + - int + returns: void + syntax: + - windowRatio(wide, high) + type: function +windowResizable: + description: |- + By default, Processing sketches can't be resized. When + `surface.setResizable(true)` is used within a sketch, + the window can be resized while it's running. + fileName: windowResizable_ + parameters: + resizable: + desc: true to make the window resizable + type: + - boolean + returns: void + syntax: + - windowResizable(resizable) + type: function +windowResize: + description: The `windowWidth()` function defines the width of the sketch window + fileName: windowResize_ + parameters: + newHeight: + desc: height of the window + type: + - int + newWidth: + desc: width of the window + type: + - int + returns: void + syntax: + - windowResize(newWidth, newHeight) + type: function +windowResized: + description: Called every time the sketch window is resized. + fileName: windowResized_ + parameters: {} + returns: void + syntax: + - windowResized() + type: function +windowTitle: + description: The `windowTitle()` function defines the title to appear at the top + of the sketch window + fileName: windowTitle_ + parameters: + title: + desc: name of the window + type: + - String + returns: void + syntax: + - windowTitle(title) + type: function year: - description: Processing communicates with the clock on your computer. The - `year()` function returns the current year as an integer (2003, 2004, 2005, - etc). - docUrl: https://processing.org/reference/year_.html - name: null + description: |- + Processing communicates with the clock on your computer. The + `year()` function returns the current year as an integer (2003, + 2004, 2005, etc). + examples: + - | + int d = day(); // Values from 1 - 31 + int m = month(); // Values from 1 - 12 + int y = year(); // 2003, 2004, 2005, etc. + + String s = String.valueOf(d); + text(s, 10, 28); + s = String.valueOf(m); + text(s, 10, 56); + s = String.valueOf(y); + text(s, 10, 84); + fileName: year_ parameters: {} returns: int - syntax: year() + syntax: + - year() type: function diff --git a/package.json b/package.json index 613fb7e..201443f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "processing-vscode", - "version": "3.0.0-beta.0", + "version": "3.0.0", "private": true, "description": "Processing Language Support for VSCode", "license": "MIT", @@ -12,16 +12,18 @@ "bugs": "https://github.com/Luke-zhang-04/processing-vscode/issues", "main": "./processing-vscode.js", "engines": { - "vscode": "^1.48.0" + "vscode": "^1.78.0" }, - "type": "module", + "type": "commonjs", "scripts": { - "build": "rollup -c rollup.config.js", - "deploy": "vsce publish", + "build": "rollup -c rollup.config.mjs", + "deploy": "vsce publish --no-dependencies", + "deploy:local": "pnpm package && code --install-extension processing-vscode.vsix --force", "format": "prettier . --write && eslint --ext ts --fix --cache", "lint": "eslint --ext ts src --max-warnings 0 --cache", + "package": "vsce package --no-dependencies -o processing-vscode.vsix", "test": "jest --config jest.config.mjs", - "vscode:prepublish": "rollup -c rollup.config.js" + "vscode:prepublish": "rollup -c rollup.config.mjs" }, "keywords": [ "processing", @@ -42,6 +44,7 @@ "@types/vscode": "~1.78.0", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", + "dotenv": "^16.4.5", "eslint": "^8.57.0", "eslint-plugin-prefer-arrow": "^1.2.3", "glob": "^10.3.12", @@ -50,7 +53,7 @@ "prettier": "^3.2.5", "prettier-plugin-jsdoc": "^1.3.0", "prettier-plugin-package": "^1.4.0", - "rollup": "^4.17.1", + "rollup": "^4.17.2", "rollup-plugin-progress": "^1.1.2", "ts-jest": "^29.1.2", "tslib": "^2.6.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 16b497e..cfd2e78 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,10 +10,10 @@ importers: devDependencies: '@rollup/plugin-node-resolve': specifier: ^15.2.3 - version: 15.2.3(rollup@4.17.1) + version: 15.2.3(rollup@4.17.2) '@rollup/plugin-typescript': specifier: ^11.1.6 - version: 11.1.6(rollup@4.17.1)(tslib@2.6.2)(typescript@5.4.5) + version: 11.1.6(rollup@4.17.2)(tslib@2.6.2)(typescript@5.4.5) '@types/glob': specifier: ^8.1.0 version: 8.1.0 @@ -35,6 +35,9 @@ importers: '@typescript-eslint/parser': specifier: ^7.8.0 version: 7.8.0(eslint@8.57.0)(typescript@5.4.5) + dotenv: + specifier: ^16.4.5 + version: 16.4.5 eslint: specifier: ^8.57.0 version: 8.57.0 @@ -60,8 +63,8 @@ importers: specifier: ^1.4.0 version: 1.4.0(prettier@3.2.5) rollup: - specifier: ^4.17.1 - version: 4.17.1 + specifier: ^4.17.2 + version: 4.17.2 rollup-plugin-progress: specifier: ^1.1.2 version: 1.1.2 @@ -85,7 +88,7 @@ importers: dependencies: '@rollup/pluginutils': specifier: ^5.1.0 - version: 5.1.0(rollup@4.17.1) + version: 5.1.0(rollup@4.17.2) js-yaml: specifier: ^4.1.0 version: 4.1.0 @@ -94,8 +97,8 @@ importers: specifier: ^4.0.1 version: 4.0.1 rollup: - specifier: ^4.17.1 - version: 4.17.1 + specifier: ^4.17.2 + version: 4.17.2 typescript: specifier: ~5.4.5 version: 5.4.5 @@ -797,7 +800,7 @@ packages: dev: true optional: true - /@rollup/plugin-node-resolve@15.2.3(rollup@4.17.1): + /@rollup/plugin-node-resolve@15.2.3(rollup@4.17.2): resolution: {integrity: sha512-j/lym8nf5E21LwBT4Df1VD6hRO2L2iwUeUmP7litikRsVp1H6NWx20NEp0Y7su+7XGc476GnXXc4kFeZNGmaSQ==} engines: {node: '>=14.0.0'} peerDependencies: @@ -806,16 +809,16 @@ packages: rollup: optional: true dependencies: - '@rollup/pluginutils': 5.1.0(rollup@4.17.1) + '@rollup/pluginutils': 5.1.0(rollup@4.17.2) '@types/resolve': 1.20.2 deepmerge: 4.3.1 is-builtin-module: 3.2.1 is-module: 1.0.0 resolve: 1.22.8 - rollup: 4.17.1 + rollup: 4.17.2 dev: true - /@rollup/plugin-typescript@11.1.6(rollup@4.17.1)(tslib@2.6.2)(typescript@5.4.5): + /@rollup/plugin-typescript@11.1.6(rollup@4.17.2)(tslib@2.6.2)(typescript@5.4.5): resolution: {integrity: sha512-R92yOmIACgYdJ7dJ97p4K69I8gg6IEHt8M7dUBxN3W6nrO8uUxX5ixl0yU/N3aZTi8WhPuICvOHXQvF6FaykAA==} engines: {node: '>=14.0.0'} peerDependencies: @@ -828,14 +831,14 @@ packages: tslib: optional: true dependencies: - '@rollup/pluginutils': 5.1.0(rollup@4.17.1) + '@rollup/pluginutils': 5.1.0(rollup@4.17.2) resolve: 1.22.8 - rollup: 4.17.1 + rollup: 4.17.2 tslib: 2.6.2 typescript: 5.4.5 dev: true - /@rollup/pluginutils@5.1.0(rollup@4.17.1): + /@rollup/pluginutils@5.1.0(rollup@4.17.2): resolution: {integrity: sha512-XTIWOPPcpvyKI6L1NHo0lFlCyznUEyPmPY1mc3KpPVDYulHSTvyeLNVW00QTLIAFNhR3kYnJTQHeGqU4M3n09g==} engines: {node: '>=14.0.0'} peerDependencies: @@ -847,115 +850,115 @@ packages: '@types/estree': 1.0.5 estree-walker: 2.0.2 picomatch: 2.3.1 - rollup: 4.17.1 + rollup: 4.17.2 - /@rollup/rollup-android-arm-eabi@4.17.1: - resolution: {integrity: sha512-P6Wg856Ou/DLpR+O0ZLneNmrv7QpqBg+hK4wE05ijbC/t349BRfMfx+UFj5Ha3fCFopIa6iSZlpdaB4agkWp2Q==} + /@rollup/rollup-android-arm-eabi@4.17.2: + resolution: {integrity: sha512-NM0jFxY8bB8QLkoKxIQeObCaDlJKewVlIEkuyYKm5An1tdVZ966w2+MPQ2l8LBZLjR+SgyV+nRkTIunzOYBMLQ==} cpu: [arm] os: [android] requiresBuild: true optional: true - /@rollup/rollup-android-arm64@4.17.1: - resolution: {integrity: sha512-piwZDjuW2WiHr05djVdUkrG5JbjnGbtx8BXQchYCMfib/nhjzWoiScelZ+s5IJI7lecrwSxHCzW026MWBL+oJQ==} + /@rollup/rollup-android-arm64@4.17.2: + resolution: {integrity: sha512-yeX/Usk7daNIVwkq2uGoq2BYJKZY1JfyLTaHO/jaiSwi/lsf8fTFoQW/n6IdAsx5tx+iotu2zCJwz8MxI6D/Bw==} cpu: [arm64] os: [android] requiresBuild: true optional: true - /@rollup/rollup-darwin-arm64@4.17.1: - resolution: {integrity: sha512-LsZXXIsN5Q460cKDT4Y+bzoPDhBmO5DTr7wP80d+2EnYlxSgkwdPfE3hbE+Fk8dtya+8092N9srjBTJ0di8RIA==} + /@rollup/rollup-darwin-arm64@4.17.2: + resolution: {integrity: sha512-kcMLpE6uCwls023+kknm71ug7MZOrtXo+y5p/tsg6jltpDtgQY1Eq5sGfHcQfb+lfuKwhBmEURDga9N0ol4YPw==} cpu: [arm64] os: [darwin] requiresBuild: true optional: true - /@rollup/rollup-darwin-x64@4.17.1: - resolution: {integrity: sha512-S7TYNQpWXB9APkxu/SLmYHezWwCoZRA9QLgrDeml+SR2A1LLPD2DBUdUlvmCF7FUpRMKvbeeWky+iizQj65Etw==} + /@rollup/rollup-darwin-x64@4.17.2: + resolution: {integrity: sha512-AtKwD0VEx0zWkL0ZjixEkp5tbNLzX+FCqGG1SvOu993HnSz4qDI6S4kGzubrEJAljpVkhRSlg5bzpV//E6ysTQ==} cpu: [x64] os: [darwin] requiresBuild: true optional: true - /@rollup/rollup-linux-arm-gnueabihf@4.17.1: - resolution: {integrity: sha512-Lq2JR5a5jsA5um2ZoLiXXEaOagnVyCpCW7xvlcqHC7y46tLwTEgUSTM3a2TfmmTMmdqv+jknUioWXlmxYxE9Yw==} + /@rollup/rollup-linux-arm-gnueabihf@4.17.2: + resolution: {integrity: sha512-3reX2fUHqN7sffBNqmEyMQVj/CKhIHZd4y631duy0hZqI8Qoqf6lTtmAKvJFYa6bhU95B1D0WgzHkmTg33In0A==} cpu: [arm] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-arm-musleabihf@4.17.1: - resolution: {integrity: sha512-9BfzwyPNV0IizQoR+5HTNBGkh1KXE8BqU0DBkqMngmyFW7BfuIZyMjQ0s6igJEiPSBvT3ZcnIFohZ19OqjhDPg==} + /@rollup/rollup-linux-arm-musleabihf@4.17.2: + resolution: {integrity: sha512-uSqpsp91mheRgw96xtyAGP9FW5ChctTFEoXP0r5FAzj/3ZRv3Uxjtc7taRQSaQM/q85KEKjKsZuiZM3GyUivRg==} cpu: [arm] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-arm64-gnu@4.17.1: - resolution: {integrity: sha512-e2uWaoxo/rtzA52OifrTSXTvJhAXb0XeRkz4CdHBK2KtxrFmuU/uNd544Ogkpu938BzEfvmWs8NZ8Axhw33FDw==} + /@rollup/rollup-linux-arm64-gnu@4.17.2: + resolution: {integrity: sha512-EMMPHkiCRtE8Wdk3Qhtciq6BndLtstqZIroHiiGzB3C5LDJmIZcSzVtLRbwuXuUft1Cnv+9fxuDtDxz3k3EW2A==} cpu: [arm64] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-arm64-musl@4.17.1: - resolution: {integrity: sha512-ekggix/Bc/d/60H1Mi4YeYb/7dbal1kEDZ6sIFVAE8pUSx7PiWeEh+NWbL7bGu0X68BBIkgF3ibRJe1oFTksQQ==} + /@rollup/rollup-linux-arm64-musl@4.17.2: + resolution: {integrity: sha512-NMPylUUZ1i0z/xJUIx6VUhISZDRT+uTWpBcjdv0/zkp7b/bQDF+NfnfdzuTiB1G6HTodgoFa93hp0O1xl+/UbA==} cpu: [arm64] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-powerpc64le-gnu@4.17.1: - resolution: {integrity: sha512-UGV0dUo/xCv4pkr/C8KY7XLFwBNnvladt8q+VmdKrw/3RUd3rD0TptwjisvE2TTnnlENtuY4/PZuoOYRiGp8Gw==} + /@rollup/rollup-linux-powerpc64le-gnu@4.17.2: + resolution: {integrity: sha512-T19My13y8uYXPw/L/k0JYaX1fJKFT/PWdXiHr8mTbXWxjVF1t+8Xl31DgBBvEKclw+1b00Chg0hxE2O7bTG7GQ==} cpu: [ppc64] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-riscv64-gnu@4.17.1: - resolution: {integrity: sha512-gEYmYYHaehdvX46mwXrU49vD6Euf1Bxhq9pPb82cbUU9UT2NV+RSckQ5tKWOnNXZixKsy8/cPGtiUWqzPuAcXQ==} + /@rollup/rollup-linux-riscv64-gnu@4.17.2: + resolution: {integrity: sha512-BOaNfthf3X3fOWAB+IJ9kxTgPmMqPPH5f5k2DcCsRrBIbWnaJCgX2ll77dV1TdSy9SaXTR5iDXRL8n7AnoP5cg==} cpu: [riscv64] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-s390x-gnu@4.17.1: - resolution: {integrity: sha512-xeae5pMAxHFp6yX5vajInG2toST5lsCTrckSRUFwNgzYqnUjNBcQyqk1bXUxX5yhjWFl2Mnz3F8vQjl+2FRIcw==} + /@rollup/rollup-linux-s390x-gnu@4.17.2: + resolution: {integrity: sha512-W0UP/x7bnn3xN2eYMql2T/+wpASLE5SjObXILTMPUBDB/Fg/FxC+gX4nvCfPBCbNhz51C+HcqQp2qQ4u25ok6g==} cpu: [s390x] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-x64-gnu@4.17.1: - resolution: {integrity: sha512-AsdnINQoDWfKpBzCPqQWxSPdAWzSgnYbrJYtn6W0H2E9It5bZss99PiLA8CgmDRfvKygt20UpZ3xkhFlIfX9zQ==} + /@rollup/rollup-linux-x64-gnu@4.17.2: + resolution: {integrity: sha512-Hy7pLwByUOuyaFC6mAr7m+oMC+V7qyifzs/nW2OJfC8H4hbCzOX07Ov0VFk/zP3kBsELWNFi7rJtgbKYsav9QQ==} cpu: [x64] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-linux-x64-musl@4.17.1: - resolution: {integrity: sha512-KoB4fyKXTR+wYENkIG3fFF+5G6N4GFvzYx8Jax8BR4vmddtuqSb5oQmYu2Uu067vT/Fod7gxeQYKupm8gAcMSQ==} + /@rollup/rollup-linux-x64-musl@4.17.2: + resolution: {integrity: sha512-h1+yTWeYbRdAyJ/jMiVw0l6fOOm/0D1vNLui9iPuqgRGnXA0u21gAqOyB5iHjlM9MMfNOm9RHCQ7zLIzT0x11Q==} cpu: [x64] os: [linux] requiresBuild: true optional: true - /@rollup/rollup-win32-arm64-msvc@4.17.1: - resolution: {integrity: sha512-J0d3NVNf7wBL9t4blCNat+d0PYqAx8wOoY+/9Q5cujnafbX7BmtYk3XvzkqLmFECaWvXGLuHmKj/wrILUinmQg==} + /@rollup/rollup-win32-arm64-msvc@4.17.2: + resolution: {integrity: sha512-tmdtXMfKAjy5+IQsVtDiCfqbynAQE/TQRpWdVataHmhMb9DCoJxp9vLcCBjEQWMiUYxO1QprH/HbY9ragCEFLA==} cpu: [arm64] os: [win32] requiresBuild: true optional: true - /@rollup/rollup-win32-ia32-msvc@4.17.1: - resolution: {integrity: sha512-xjgkWUwlq7IbgJSIxvl516FJ2iuC/7ttjsAxSPpC9kkI5iQQFHKyEN5BjbhvJ/IXIZ3yIBcW5QDlWAyrA+TFag==} + /@rollup/rollup-win32-ia32-msvc@4.17.2: + resolution: {integrity: sha512-7II/QCSTAHuE5vdZaQEwJq2ZACkBpQDOmQsE6D6XUbnBHW8IAhm4eTufL6msLJorzrHDFv3CF8oCA/hSIRuZeQ==} cpu: [ia32] os: [win32] requiresBuild: true optional: true - /@rollup/rollup-win32-x64-msvc@4.17.1: - resolution: {integrity: sha512-0QbCkfk6cnnVKWqqlC0cUrrUMDMfu5ffvYMTUHf+qMN2uAb3MKP31LPcwiMXBNsvoFGs/kYdFOsuLmvppCopXA==} + /@rollup/rollup-win32-x64-msvc@4.17.2: + resolution: {integrity: sha512-TGGO7v7qOq4CYmSBVEYpI1Y5xDuCEnbVC5Vth8mOsW0gDSzxNrVERPc790IGHsrT2dQSimgMr9Ub3Y1Jci5/8w==} cpu: [x64] os: [win32] requiresBuild: true @@ -1841,6 +1844,11 @@ packages: domhandler: 5.0.3 dev: true + /dotenv@16.4.5: + resolution: {integrity: sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==} + engines: {node: '>=12'} + dev: true + /eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} dev: true @@ -3783,29 +3791,29 @@ packages: chalk: 2.4.2 dev: true - /rollup@4.17.1: - resolution: {integrity: sha512-0gG94inrUtg25sB2V/pApwiv1lUb0bQ25FPNuzO89Baa+B+c0ccaaBKM5zkZV/12pUUdH+lWCSm9wmHqyocuVQ==} + /rollup@4.17.2: + resolution: {integrity: sha512-/9ClTJPByC0U4zNLowV1tMBe8yMEAxewtR3cUNX5BoEpGH3dQEWpJLr6CLp0fPdYRF/fzVOgvDb1zXuakwF5kQ==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true dependencies: '@types/estree': 1.0.5 optionalDependencies: - '@rollup/rollup-android-arm-eabi': 4.17.1 - '@rollup/rollup-android-arm64': 4.17.1 - '@rollup/rollup-darwin-arm64': 4.17.1 - '@rollup/rollup-darwin-x64': 4.17.1 - '@rollup/rollup-linux-arm-gnueabihf': 4.17.1 - '@rollup/rollup-linux-arm-musleabihf': 4.17.1 - '@rollup/rollup-linux-arm64-gnu': 4.17.1 - '@rollup/rollup-linux-arm64-musl': 4.17.1 - '@rollup/rollup-linux-powerpc64le-gnu': 4.17.1 - '@rollup/rollup-linux-riscv64-gnu': 4.17.1 - '@rollup/rollup-linux-s390x-gnu': 4.17.1 - '@rollup/rollup-linux-x64-gnu': 4.17.1 - '@rollup/rollup-linux-x64-musl': 4.17.1 - '@rollup/rollup-win32-arm64-msvc': 4.17.1 - '@rollup/rollup-win32-ia32-msvc': 4.17.1 - '@rollup/rollup-win32-x64-msvc': 4.17.1 + '@rollup/rollup-android-arm-eabi': 4.17.2 + '@rollup/rollup-android-arm64': 4.17.2 + '@rollup/rollup-darwin-arm64': 4.17.2 + '@rollup/rollup-darwin-x64': 4.17.2 + '@rollup/rollup-linux-arm-gnueabihf': 4.17.2 + '@rollup/rollup-linux-arm-musleabihf': 4.17.2 + '@rollup/rollup-linux-arm64-gnu': 4.17.2 + '@rollup/rollup-linux-arm64-musl': 4.17.2 + '@rollup/rollup-linux-powerpc64le-gnu': 4.17.2 + '@rollup/rollup-linux-riscv64-gnu': 4.17.2 + '@rollup/rollup-linux-s390x-gnu': 4.17.2 + '@rollup/rollup-linux-x64-gnu': 4.17.2 + '@rollup/rollup-linux-x64-musl': 4.17.2 + '@rollup/rollup-win32-arm64-msvc': 4.17.2 + '@rollup/rollup-win32-ia32-msvc': 4.17.2 + '@rollup/rollup-win32-x64-msvc': 4.17.2 fsevents: 2.3.3 /run-parallel@1.2.0: diff --git a/rollup.config.js b/rollup.config.mjs similarity index 98% rename from rollup.config.js rename to rollup.config.mjs index a8f55cd..667994f 100644 --- a/rollup.config.js +++ b/rollup.config.mjs @@ -8,7 +8,7 @@ const banner = `/** * https://github.com/Luke-zhang-04/processing-vscode * * @license MIT - * @version 3.0.0-beta.0 + * @version 3.0.0 * @preserve * @copyright (C) 2016 - 2020 Tobiah Zarlez, 2021-2024 Luke Zhang * @@ -34,11 +34,11 @@ const config = { }, plugins: [ progress(), - typescript(), yaml(), resolve({ resolveOnly: [/^(?!vscode)$/], }), + typescript(), ], } diff --git a/rollup/plugins/package.json b/rollup/plugins/package.json index ec0af66..a41aff8 100644 --- a/rollup/plugins/package.json +++ b/rollup/plugins/package.json @@ -13,7 +13,7 @@ }, "devDependencies": { "@types/js-yaml": "^4.0.1", - "rollup": "^4.17.1", + "rollup": "^4.17.2", "typescript": "~5.4.5" }, "types": "./lib/index.d.ts" diff --git a/scripts/checkDocs.mjs b/scripts/checkDocs.mjs index 6393aa0..b130ad4 100755 --- a/scripts/checkDocs.mjs +++ b/scripts/checkDocs.mjs @@ -1,8 +1,6 @@ #!/bin/node -/** - * @file Checks If documentation data is up to date - */ +/** @file Checks If documentation data is up to date */ import crypto from "crypto" import {dirname} from "path" @@ -17,12 +15,13 @@ export const hash = (algo, contents, format = "hex") => const __dirname = dirname(fileURLToPath(import.meta.url)) const newDocs = await getDocs() -const newDocsString = `# THIS IS AN AUTOGENERATED FILE; DO NOT EDIT DIRECTLY\n\n${yaml.stringify( - newDocs, - { - sortMapEntries: true, - }, -)}`.trim() +const newDocsString = `# THIS IS AN AUTOGENERATED FILE; DO NOT EDIT DIRECTLY +# All documentation is by the Processing Foundation (https://processing.org/reference/strokeJoin_.html) +# and licensed under CC BY-NC-SA 4.0 Deed (https://creativecommons.org/licenses/by-nc-sa/4.0/) + +${yaml.stringify(newDocs, { + sortMapEntries: true, +})}`.trim() const oldDocsString = ( await fs.readFile(`${__dirname}/../data/documentation-data.yml`, "utf-8") diff --git a/scripts/helpers/fetchDocs.mjs b/scripts/helpers/fetchDocs.mjs index 6595e59..7afd270 100644 --- a/scripts/helpers/fetchDocs.mjs +++ b/scripts/helpers/fetchDocs.mjs @@ -1,37 +1,58 @@ #!/bin/node +import "dotenv/config" import fetch from "node-fetch" +const repoName = "processing/processing-website" +const docDir = "content/references/translations/en/processing" +const exampleDir = "content/references/examples/processing" +const ghAccessToken = process.env.GH_ACCESS_TOKEN +const constants = ["HALF_PI", "PI", "QUARTER_PI", "TAU", "TWO_PI"] +let requestCount = 0 + +/** @returns {Promise} */ +const getGithubDir = async (path) => { + const response = await fetch(`https://api.github.com/repos/${repoName}/contents/${path}`, { + headers: { + Authorization: ghAccessToken ? `Bearer ${ghAccessToken}` : undefined, + }, + }) + + requestCount++ + + if (!response.ok) { + throw new Error(`Error ${response.status} - ${await response.text()}`) + } + + return await response.json() +} + +/** @type {{[name: string]: import("./types").APIDirItem}} */ +const examples = Object.fromEntries( + (await getGithubDir(exampleDir)).map((item) => [item.name, item]), +) /** - * Gets all the links to Processing builtins + * @param {string} docFilename + * @returns {Promise} */ -const getDocLinks = async () => { - const response = await fetch(docsUrl) +const getExamples = async (docFilename) => { + const exampleDir = await getGithubDir(examples[docFilename].path) - if (response.status !== 200) { - console.log(`Response for all links returned status ${response.status}.`) - console.log(response) + return await Promise.all( + exampleDir + .filter(({download_url}) => download_url.endsWith(".pde")) + .map(async (example) => { + const response = await fetch(example.download_url) - return - } + if (!response.ok) { + throw new Error(`Error ${response.status} - ${await response.text()}`) + } - const {window} = new JSDOM(await response.text()) // Fetch docs and parse as document - const {document} = window - const references = Array.from(document.querySelectorAll("div.category a")) // All reference items - - return { - functionLinks: references // Function doc links - .filter(({innerHTML}) => /[A-z]\(\)/u.test(innerHTML)) - .map((item) => item.getAttribute("href").trim()), - variableLinks: references // Variable doc links - .filter(({innerHTML}) => variables.includes(innerHTML)) - .map((item) => item.getAttribute("href").trim()), - classLinks: references // Class doc links - .filter(({innerHTML}) => classes.includes(innerHTML)) - .map((item) => item.getAttribute("href").trim()), - } + return (await response.text()).replace(/\r/gu, "") + }), + ) } /** @@ -52,299 +73,147 @@ const escapeHTML = (html) => /** * Gets the documentation for a single link * - * @param {string} link - Link to get doc from - * @returns {Promise} + * @param {string} docFilename - Filename of doc entry without .json ending + * @param {import("./types").VariableDoc} variable + * @returns {Promise<[name: string, data: import("../../src/types").DocumentationVariable]>} */ -const documentVariable = async (link) => { - const documentation = { - docUrl: `${docsUrl}/${link}`, - type: constants.includes(link) ? "const" : "var", - } +const documentVariable = async (docFilename, variable) => { + const doc = { + fileName: docFilename, + description: escapeHTML(variable.description), - const response = await fetch(`${docsUrl}/${link}`) - - if (!response.ok) { - console.log(`Response for ${link} returned status ${response.status}.`) - console.log(response) - - return + type: constants.includes(variable.name) ? "const" : "var", } - const {window} = new JSDOM(await response.text()) // Parse webpage - const {document} = window - - for (const item of Array.from(document.querySelectorAll(".content table tr"))) { - const header = item.querySelector("th") - - if (!header) { - continue - } - - const {innerHTML} = header // Get the header for each table item - - const property = (() => { - if (["Description", "Examples", "Name"].includes(innerHTML)) { - return innerHTML.toLowerCase() - } - })() - - if (property) { - if (property === "description") { - const description = escapeHTML(item.querySelector("td").innerHTML).replace( - /\\n/gu, - "\n\n", - ) - - documentation.description = - description.length > 1000 ? description.slice(0, 1000) + ". . ." : description - } else if (property === "examples") { - documentation[property] = escapeHTML(item.querySelector("td").innerHTML).replace( - /`/giu, - "", - ) - } else { - documentation[property] = escapeHTML(item.querySelector("td").innerHTML) - } - } + if (docFilename in examples) { + doc.examples = await getExamples(docFilename) } - return documentation + return [variable.name, doc] } /** * Gets the documentation for a single link * - * @param {string} link - Link to get doc from - * @returns {Promise} + * @param {string} docFilename - Filename of doc entry without .json ending + * @param {import("./types").FunctionDoc} func + * @returns {Promise<[name: string, data: import("../../src/types").DocumentationFunction]>} */ -const documentFunction = async (link) => { - const documentation = { - docUrl: `${docsUrl}/${link}`, - parameters: {}, +const documentFunction = async (docFilename, func) => { + const doc = { + fileName: docFilename, + parameters: Object.fromEntries( + func.parameters?.map((param) => [ + param.name, + { + type: param.type, + desc: escapeHTML(param.description), + }, + ]) ?? [], + ), + syntax: func.syntax.map((item) => item.replace(/\r/gu, "")), + description: escapeHTML(func.description), + returns: func.returns, type: "function", } - const response = await fetch(`${docsUrl}/${link}`) - - if (!response.ok) { - console.log(`Response for ${link} returned status ${response.status}.`) - console.log(response) - - return + if (docFilename in examples) { + doc.examples = await getExamples(docFilename) } - const {window} = new JSDOM(await response.text()) - const {document} = window - - for (const item of Array.from(document.querySelectorAll(".content table tr"))) { - const header = item.querySelector("th") - - if (!header) { - continue - } - - const {innerHTML} = header - - const property = (() => { - if (["Description", "Syntax", "Returns", "Parameters", "Name"].includes(innerHTML)) { - return innerHTML.toLowerCase() - } - })() - - if (property) { - if (property === "parameters") { - Array.from(item.querySelectorAll("td table tr")).forEach((item) => { - documentation.parameters[item.querySelector("th").innerHTML] = escapeHTML( - item.querySelector("td").innerHTML, - ) - }) - } else if (property === "syntax") { - documentation.syntax = escapeHTML(item.querySelector("td").innerHTML).replace( - /`/gu, - "", - ) - } else if (property === "description") { - const description = escapeHTML(item.querySelector("td").innerHTML).replace( - /\\n/gu, - "\n\n", - ) - - documentation.description = - description.length > 1000 ? description.slice(0, 1000) + ". . ." : description - } else { - documentation[property] = escapeHTML(item.querySelector("td").innerHTML) - } - } - } - - return documentation + return [func.name.replace(/\(\)$/u, ""), doc] } /** * Gets the documentation for a single link * - * @param {string} link - Link to get doc from - * @returns {Promise} + * @param {string} docFilename - Filename of doc entry without .json ending + * @param {import("./types").ClassDoc} cls + * @returns {Promise<[name: string, data: import("../../src/types").DocumentationClass]>} */ -const documentClass = async (link) => { - const documentation = { - docUrl: `${docsUrl}/${link}`, - parameters: {}, - methods: {}, - fields: {}, +const documentClass = async (docFilename, cls) => { + const doc = { + fileName: docFilename, + parameters: Object.fromEntries( + cls.parameters?.map((param) => [ + param.name, + { + type: param.type, + desc: escapeHTML(param.description), + }, + ]) ?? [], + ), + methods: Object.fromEntries( + cls.methods?.map((method) => [ + method.name.replace(/\(\)$/u, ""), + {anchor: method.anchor, desc: escapeHTML(method.desc)}, + ]) ?? [], + ), + fields: Object.fromEntries( + cls.classFields?.map((field) => [ + field.name, + {anchor: field.anchor, desc: escapeHTML(field.desc)}, + ]) ?? [], + ), + syntax: cls.constructors.map((syntax) => escapeHTML(syntax.replace(/\r/gu, ""))), + description: escapeHTML(cls.description), type: "class", } - const response = await fetch(`${docsUrl}/${link}`) - - if (!response.ok) { - // If response wasn't ok, return - console.log(`Response for ${link} returned status ${response.status}.`) - console.log(response) - - return - } - - const {window} = new JSDOM(await response.text()) // Parse the page - const {document} = window - - for (const item of Array.from(document.querySelectorAll(".content table tr"))) { - const header = item.querySelector("th") - - if (!header) { - continue - } - - const {innerHTML} = header - - const property = (() => { - if (["Description", "Constructor", "Parameters", "Name"].includes(innerHTML)) { - return innerHTML.toLowerCase() - } - })() - - if (property) { - if (property === "parameters") { - Array.from(item.querySelectorAll("td table tr")).forEach((item) => { - documentation.parameters[item.querySelector("th").innerHTML] = escapeHTML( - item.querySelector("td").innerHTML, - ) - }) - } else if (property === "constructor") { - documentation.syntax = escapeHTML(item.querySelector("td").innerHTML).replace( - /`/gu, - "", - ) - } else if (property === "description") { - const description = escapeHTML(item.querySelector("td").innerHTML).replace( - /\\n/gu, - "\n\n", - ) - - documentation.description = - description.length > 1000 ? description.slice(0, 1000) + ". . ." : description - } else { - documentation[property] = escapeHTML(item.querySelector("td").innerHTML) - } - } + if (docFilename in examples) { + doc.examples = await getExamples(docFilename) } - return documentation + return [cls.name, doc] } -/** - * Gets the documentation for the links in `links` - * - * @param {{ - * functionLinks: string[] - * variableLinks: string[] - * classLinks: string[] - * }} links - * - Links go get documenttion from - */ -const documentLinks = async ({classLinks, functionLinks, variableLinks}) => { - /** - * All documentation (final object dumped to JSON) - * - * @type {import("../../src/types").Documentation} - */ - const documentation = {} - - const fetchPromises = [] // Get documentation asynchronously - - console.log(` Getting documentation for ${functionLinks.length} functions`) - for (const link of functionLinks) { - // Document functions - const job = (async () => { - const doc = await documentFunction(link) - - if (doc) { - documentation[doc.name.replace(/\(\)/gu, "")] = { - ...doc, - name: undefined, - } - } - })() - - fetchPromises.push(job) - } - - console.log(` Getting documentation for ${classLinks.length} classes`) - for (const link of classLinks) { - // Document classes - const job = (async () => { - const doc = await documentClass(link) - - if (doc) { - documentation[doc.name.replace(/\(\)/gu, "")] = { - ...doc, - name: undefined, - } - } - })() - - fetchPromises.push(job) - } - - console.log(` Getting documentation for ${variableLinks.length} variables`) - for (const link of variableLinks) { - // Document variables - const job = (async () => { - const doc = await documentVariable(link) - - if (doc) { - documentation[doc.name.replace(/\(\)/gu, "")] = { - ...doc, - name: undefined, - } - } - })() - - fetchPromises.push(job) - } - - await Promise.all(fetchPromises) - - return documentation -} - -/** - * @returns Documentation from https://processing.org/reference - */ +/** @returns Documentation from https://processing.org/reference */ export const getDocs = async () => { - const links = await getDocLinks() - - if (!links) { - return - } - - console.log( - `Got doc links for ${ - links.functionLinks.length + links.classLinks.length + links.variableLinks.length - } items`, + const links = await getGithubDir(docDir) + + console.log(`Got doc links for ${links.length} items`) + + const docs = Object.fromEntries( + ( + await Promise.all( + links.map(async (link) => { + const response = await fetch(link.download_url) + + if (!response.ok) { + throw new Error(`ERROR ${response.status} - ${await response.text()}`) + } + + const data = await response.json() + const name = link.name.replace(/\.json$/u, "") + + try { + if (/\(([A-z]| )+\)$/u.test(data.name)) { + console.warn(`Skipping link ${data.name}`) + + return undefined + } + + switch (data.type) { + case "other": + return await documentVariable(name, data) + case "function": + return await documentFunction(name, data) + case "class": + return await documentClass(name, data) + default: + console.warn(`Skipping link type ${data.type}: ${link.name}`) + + return undefined + } + } catch (err) { + throw new Error(`"${data.name}" ${err.toString()}`) + } + }), + ) + ).filter((item) => item !== undefined), ) - const docs = await documentLinks(links) + console.log(`Done with ${requestCount} requests.`) return docs } diff --git a/scripts/helpers/types.d.ts b/scripts/helpers/types.d.ts new file mode 100644 index 0000000..6847da2 --- /dev/null +++ b/scripts/helpers/types.d.ts @@ -0,0 +1,73 @@ +export interface APIDirItem { + name: string + path: string + sha: string + size: number + url: string + html_url: string + git_url: string + download_url: string + type: string + /* eslint-disable-next-line @typescript-eslint/naming-convention */ + _links: { + self: string + git: string + html: string + } +} + +interface Parameter { + name: string + description: string + type: string[] +} + +interface ClassMember { + anchor: string + name: string + desc: string +} + +interface BaseType { + brief: string + related: string[] + name: string + description: string + category: string + subcategory: string + type: string + examples?: string[] +} + +export interface ClassDoc extends BaseType { + constructors: string[] + classFields: ClassMember[] + methods: ClassMember[] + type: "class" + classanchor: string + parameters: Parameter[] + + csspath?: string + isLibrary?: "true" +} + +export interface MethodDoc extends BaseType { + syntax: string[] + returns: string + type: "method" + classanchor: string + parameters: Parameter[] +} + +export interface VariableDoc extends BaseType { + type: "other" +} + +export interface FunctionDoc extends BaseType { + syntax: string[] + returns: string + type: "function" + parameters: Parameter[] +} + +export type DocType = ClassDoc | MethodDoc | VariableDoc | FunctionDoc diff --git a/scripts/writeDocs.mjs b/scripts/writeDocs.mjs index fff53f2..d8b0390 100755 --- a/scripts/writeDocs.mjs +++ b/scripts/writeDocs.mjs @@ -1,7 +1,7 @@ #!/bin/node /** - * @file gets Documentation from https://processing.org/reference and dumps it into + * @file Gets Documentation from https://processing.org/reference and dumps it into * `src/documentation-data.json` with some bootleg webscraping */ @@ -17,8 +17,12 @@ const docs = await getDocs() await fs.writeFile( `${__dirname}/../data/documentation-data.yml`, - `# THIS IS AN AUTOGENERATED FILE; DO NOT EDIT DIRECTLY\n\n${yaml.stringify(docs, { - sortMapEntries: true, - })}`, + `# THIS IS AN AUTOGENERATED FILE; DO NOT EDIT DIRECTLY +# All documentation is by the Processing Foundation (https://processing.org/reference/strokeJoin_.html) +# and licensed under CC BY-NC-SA 4.0 Deed (https://creativecommons.org/licenses/by-nc-sa/4.0/) + +${yaml.stringify(docs, { + sortMapEntries: true, +})}`, "utf8", ) diff --git a/src/commands/run.ts b/src/commands/run.ts index bb29f53..06abd8b 100644 --- a/src/commands/run.ts +++ b/src/commands/run.ts @@ -36,7 +36,7 @@ class RunManager { return mode } - if (/\.pde$/u.test(editor.document.fileName)) { + if (editor.document.fileName.endsWith(".pde")) { return "java" } else if (editor.document.languageId === "python") { return "py" @@ -55,7 +55,8 @@ class RunManager { } /** - * This monstrosity searches for an existing terminal if it exists or creates a new one and returns it. + * This monstrosity searches for an existing terminal if it exists or creates a new one and + * returns it. * * @param terminalName - Key of terminal in class * @param terminalDisplayName - Display name of terminal diff --git a/src/documentation.ts b/src/documentation.ts index 46a812b..ff5e376 100644 --- a/src/documentation.ts +++ b/src/documentation.ts @@ -4,6 +4,7 @@ import type { DocumentationFunction, DocumentationVariable, } from "./types" +import {Urls} from "./utils/search" import documentation from "./documentation-data.yml" import vscode from "vscode" @@ -45,65 +46,67 @@ const getHoveredItem = (line: string, position: number): string | undefined => { return line.slice(itemStart, itemEnd) } +/** + * @example + * + * ```ts + * console.log("bruh") + * ``` + */ const documentVariable = ( info: DocumentationVariable, item: keyof typeof documentation, ): vscode.Hover => new vscode.Hover([ - info.examples - ? `\`\`\`js -${info.type} ${item} -\`\`\` -\`\`\`java -// Examples -${info.examples} -\`\`\`` - : `\`\`\`js + `\`\`\`js ${info.type} ${item} \`\`\``, `${info.examples ? "" : `${item}\n\n`}${info.description} -*@see* — [${info.docUrl}](${info.docUrl}) +*@see* — [${Urls.ProcessingorgDocs}/${info.fileName}.html](${Urls.ProcessingorgDocs}/${info.fileName}.html) `, + ...(info.examples?.map((example) => `*@example*\n\`\`\`java\n${example}\n\`\`\``) ?? []), ]) const documentFuntion = ( info: DocumentationFunction, item: keyof typeof documentation, ): vscode.Hover => { - const params = Object.entries(info.parameters).map(([name, desc]) => { - const typeDefs = desc.indexOf(":") + const params = Object.entries(info.parameters).map(([name, {type: types, desc}]) => { + const type = types.join(" | ") - if (typeDefs === -1) { + if (types.length === 0) { return `*@param* \`${name}\` — ${desc}` } - const formattedDesc = `\`${desc.slice(0, typeDefs)}\`${desc.slice(typeDefs)}` - - return `*@param* \`${name}\` — ${formattedDesc}` + return `*@param* \`${name}\` — \`${type}\`: ${desc}` }) const {returns} = info - // Prepare yourself return new vscode.Hover([ - ...(info.syntax + ...(info.syntax.length > 0 ? [ `\`\`\`js ${info.type} ${item} \`\`\` \`\`\`java -${info.syntax} +${info.syntax.join("\n")} \`\`\``, ] - : []), - `${info.syntax ? "" : `${item}\n\n`}${info.description} + : [ + `\`\`\`js +${info.type} ${item} +\`\`\``, + ]), + `${info.syntax.length > 0 ? "" : `${item}\n\n`}${info.description} -*@see* — [${info.docUrl}](${info.docUrl}) +*@see* — [${Urls.ProcessingorgDocs}/${info.fileName}.html](${Urls.ProcessingorgDocs}/${info.fileName}.html) ${params.join("\n\n")} ${returns ? `*@returns* \`${returns}\`` : ""} `, + ...(info.examples?.map((example) => `*@example*\n\`\`\`java\n${example}\n\`\`\``) ?? []), ]) } @@ -111,36 +114,40 @@ const documentClass = ( info: DocumentationClass, item: keyof typeof documentation, ): vscode.Hover => { - const params = Object.entries(info.parameters).map(([name, desc]) => { - const typeDefs = desc.indexOf(":") + const params = Object.entries(info.parameters).map(([name, {type: types, desc}]) => { + const type = types.join(" | ") - if (typeDefs === -1) { + console.log(info.fileName, {type, types}) + + if (types.length === 0) { return `*@param* \`${name}\` — ${desc}` } - const formattedDesc = `\`${desc.slice(0, typeDefs)}\`${desc.slice(typeDefs)}` - - return `*@param* \`${name}\` — ${formattedDesc}` + return `*@param* \`${name}\` — \`${type}\`: ${desc}` }) - // Prepare yourself return new vscode.Hover([ - ...(info.syntax + ...(info.syntax.length > 0 ? [ `\`\`\`js ${info.type} ${item} \`\`\` \`\`\`java -${info.syntax} +${info.syntax.join("\n")} \`\`\``, ] - : []), - `${info.syntax ? "" : `${item}\n\n`}${info.description} + : [ + `\`\`\`js +${info.type} ${item} +\`\`\``, + ]), + `${info.syntax.length > 0 ? "" : `${item}\n\n`}${info.description} -*@see* — [${info.docUrl}](${info.docUrl}) +*@see* — [${Urls.ProcessingorgDocs}/${info.fileName}.html](${Urls.ProcessingorgDocs}/${info.fileName}.html) ${params.join("\n\n")} `, + ...(info.examples?.map((example) => `*@example*\n\`\`\`java\n${example}\n\`\`\``) ?? []), ]) } diff --git a/src/index.ts b/src/index.ts index 8653334..f35c35c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ /** * Processing-vscode - Processing Language Support for VSCode * - * @version 3.0.0-beta.0 + * @version 3.0.0 * @copyright (C) 2016 - 2020 Tobiah Zarlez, 2021-2024 Luke Zhang */ diff --git a/src/types.d.ts b/src/types.d.ts index d20f160..b268eb8 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -1,24 +1,28 @@ export interface DocumentationClass { description: string - syntax: string - parameters: {[key: string]: string} - docUrl: string + examples?: string[] + syntax: string[] + parameters: {[name: string]: {type: string[]; desc: string}} + methods: {[name: string]: {anchor: string; desc: string}} + fields: {[name: string]: {anchor: string; desc: string}} + fileName: string type: "class" } export interface DocumentationFunction { description: string - syntax: string - parameters: {[key: string]: string} + examples?: string[] + syntax: string[] + parameters: {[name: string]: {type: string[]; desc: string}} returns: string - docUrl: string + fileName: string type: "function" } export interface DocumentationVariable { description: string - examples?: string - docUrl: string + examples?: string[] + fileName: string type: "var" | "const" } diff --git a/src/utils/escapePath.ts b/src/utils/escapePath.ts index debb3a4..5a60bf9 100644 --- a/src/utils/escapePath.ts +++ b/src/utils/escapePath.ts @@ -1,4 +1,6 @@ -export const escapeExecutablePath = (pathName: string): string => { +/* eslint-disable prefer-arrow/prefer-arrow-functions */ // Problem with circular dependencies + +export function escapeExecutablePath(pathName: string): string { if (!/ /gu.test(pathName)) { return pathName } @@ -16,3 +18,5 @@ export const escapeExecutablePath = (pathName: string): string => { return pathName.replace(/(? } else { const {processingDocs, searchEngine} = searchConfig const searchUrl = ((): string => { - let directDocUrl: string | undefined + let docFilename: string | undefined if (searchBase === "docs") { const { @@ -46,9 +46,9 @@ export const openURL = async (searchBase?: string, url?: string): Promise // Look for entry directly in documentation data (processingDocs === "auto" || processingDocs === "processing.org") && languageId === "pde" && - (directDocUrl = (documentation as Documentation)[url]?.docUrl) !== undefined + (docFilename = (documentation as Documentation)[url]?.fileName) !== undefined ) { - return directDocUrl + return `${Urls.ProcessingorgDocs}/${docFilename}.html` } else if (searchEngine === "DuckDuckGo") { // Search Engine == "google" if (processingDocs === "p5js.org") { diff --git a/tsconfig.json b/tsconfig.json index 8008b68..0ddc977 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,7 @@ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "ES2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ + "target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "module": "ESNext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ // "lib": [], /* Specify library files to be included in the compilation. */ "allowJs": true, /* Allow javascript files to be compiled. */ @@ -70,6 +70,7 @@ "noUncheckedIndexedAccess": true, }, "include": [ - "src" + "src", + "./scripts/helpers/types.d.ts" ] }