From b7b8bc84c08600ccf71687e274fcdca50c03a0fc Mon Sep 17 00:00:00 2001 From: shiffman Date: Sun, 17 Dec 2023 15:36:01 +0000 Subject: [PATCH] Notion - Update docs --- content/00_4_acknowledgments.html | 4 ++-- content/00_5_introduction.html | 26 ++++++++++---------- content/02_forces.html | 2 +- content/03_oscillation.html | 4 ++-- content/04_particles.html | 22 ++++++++--------- content/05_steering.html | 40 ++++++++++++++++++++----------- content/06_libraries.html | 10 ++++---- content/07_ca.html | 6 ++--- content/08_fractals.html | 2 +- content/09_ga.html | 2 +- content/10_nn.html | 6 ++--- content/11_nn_ga.html | 5 ++-- content/xx_2_image_credits.html | 28 +++++++++++----------- 13 files changed, 84 insertions(+), 73 deletions(-) diff --git a/content/00_4_acknowledgments.html b/content/00_4_acknowledgments.html index 72c52a5e..1cd8cfbc 100644 --- a/content/00_4_acknowledgments.html +++ b/content/00_4_acknowledgments.html @@ -15,8 +15,8 @@

Acknowledgments

The students of ITP and IMA, too numerous to mention, have been an amazing source of feedback throughout this process. Much of the material in this book comes from my course of the same title, which I’ve now taught 17 times. I have stacks of draft printouts of the book with notes scrawled in the margins, as well as a vast archive of student emails with corrections, comments, and generous words of encouragement.

I would like to spotlight several students who worked as graduate associates on the Nature of Code materials. Through their work with the ITP/IMA Equitable Syllabus project, Chaski No and Briana Jones provided extraordinary research support that expanded the book’s concepts and references. As the graduate assistant for the inaugural undergraduate version of the Nature of Code class, Gracy Whelihan offered invaluable support and feedback, and always reminded me of the wonder of random numbers.

Jason Gao and Stuti Mohgaonkar worked on the build systems for the book materials, inventing new workflows for writing and editing. Elias Jarzombek also warrants a mention for his advice and technical support, stemming from the Code of Music book project.

-

After graduating, Jason Gao continued to develop and design the Nature of Code website. If you head to https://natureofcode.com right now, you will see the fruits of his many talents: a full version of the book that seamlessly integrates with the p5.js web editor. It’s a realization far beyond my initial vision.

-

The interior of the book was meticulously designed by Tuan Huang. Tuan began developing layout ideas while taking the Nature of Code class in the spring of 2023. After graduating, Tuan further refined the design, working to develop a consistent visual language across the many elements of the book. Her minimal and elegant aesthetics greatly enhanced the book’s visual appeal and accessibility. A special thanks also to the OpenMoji project—the open source emoji and icon project (Creative Commons license CC BY-SA 4.0)—for providing a delightful and comprehensive set of emojis used throughout this book for various elements.

+

After graduating, Jason Gao continued to develop the Nature of Code website. If you head there now, you will see the fruits of his many talents: a full version of the book that seamlessly integrates with the p5.js web editor. It’s a realization far beyond my initial vision.

+

The interior of the book along with the website was meticulously designed by Tuan Huang. Tuan began developing layout ideas while taking the Nature of Code class in the spring of 2023. After graduating, Tuan further refined the design, working to develop a consistent visual language across the many elements of the book. Her minimal and elegant aesthetics greatly enhanced the book’s visual appeal and accessibility. A special thanks also to the OpenMoji project—the open source emoji and icon project (Creative Commons license CC BY-SA 4.0)—for providing a delightful and comprehensive set of emojis used throughout this book for various elements.

I’m also indebted to the energetic and supportive creative coding community and the Processing Foundation. I wouldn’t be writing this book if it weren’t for Casey Reas and Ben Fry, who created Processing in 2001 and co-founded the Processing Foundation. They’ve dedicated over 20 years to building and maintaining the software and its community. I’ve learned half of what I know simply from reading through the Processing source code and documentation; the elegant simplicity of the Processing language, website, and IDE is the original source of inspiration for all my teaching and work.

Lauren Lee McCarthy, the creator of p5.js, planted the seed that made everything possible for transforming the book into JavaScript. She’s a tireless champion for inclusion and access in open source, and her approach to community building has been profoundly inspiring to me. Cassie Tarakajian invented the p5.js web editor, a heroic undertaking that has made it possible to collect and organize all the example code in the book.

My heartfelt thanks extends to the other current and former members (along with Casey, Ben, and Lauren) of the Processing board of directors: Dorothy Santos, Kate Hollenbach, Xin Xin, and Johanna Hedva. A special acknowledgment to the project leads, staff, and alumni of the foundation, who have each played a pivotal role in shaping and propelling the community and its projects: Andres Colubri, Charles Reinhardt, evelyn masso, Jesse C Thompson, Jonathan Feinberg, Moira Turner, Qianqian Ye, Rachel Lim, Raphaël de Courville, Saber Khan, Suhyun (Sonia) Choi, Toni Pizza, Tsige Tafesse, and Xiaowei R. Wang.

diff --git a/content/00_5_introduction.html b/content/00_5_introduction.html index 28299334..9fa14130 100644 --- a/content/00_5_introduction.html +++ b/content/00_5_introduction.html @@ -12,16 +12,16 @@

A Word About p5.js

The p5.js library is a reimagining of the Processing creative coding environment for the modern web. I’m using it in this book for a number of reasons. For one, it’s an environment that I’m very familiar with. While the original Processing built on top of Java is my first love and still what I turn to when trying out a new idea, p5.js is what I now use for teaching many of my programming classes. It’s free, open source, and well suited to beginners, and because it’s JavaScript, everything runs right there in the web browser itself—no installation required.

For me, however, Processing and p5.js are first and foremost a community of people, not coding libraries or frameworks. Those people have generously dedicated countless hours to making and sharing the software. I’ve written this book for that community and for anyone and everyone who loves to explore their curiosity and play through code.

All that said, nothing that this book’s content strictly to p5.js—or Processing, for that matter. This book could have been written with “vanilla” JavaScript or Java, or with any number of other open source creative coding environments like openFrameworks, Cinder, and so on. It’s my hope that after I’ve completed this book, I’ll be able to release versions of the examples that run in other environments. If anyone is interested in helping to port the examples, please feel free to contact me (daniel@natureofcode.com). Go on, you know you want to port The Nature of Code to PHP!

-

All the examples in this book have been tested with p5.js version 1.8.0, but for the most part they should also work with earlier versions. I’ll be keeping them up-to-date with the latest version. The most recent code can always be found on this book’s website, https://natureofcode.com (and its associated GitHub repository).

+

All the examples in this book have been tested with p5.js version 1.8.0, but for the most part they should also work with earlier versions. I’ll be keeping them up-to-date with the latest version. The most recent code can always be found on this book’s website and its associated GitHub repository.

What Do You Need to Know?

The prerequisites for understanding the material in this book could be stated as “one semester of programming instruction with p5.js, Processing, or any other creative coding environment.” That said, there’s no reason you couldn’t read this book having learned programming with a different language or development environment.

-

If you’ve never written any code before, while you could read the book for the concepts and inspiration, you’ll likely struggle with the code because I’m assuming knowledge of the fundamentals: variables, conditionals, loops, functions, objects, and arrays. If these concepts are new to you, my “Code! Programming with p5.js” or “Introduction to Creative Coding with Processing 4” video courses on YouTube (found on the “Tracks” page of the Coding Train website, https://thecodingtrain.com/tracks) provide the fundamentals of what you need to know.

-

If you’re an experienced programmer but haven’t worked with p5.js, you can probably pick it up by checking out the p5.js documentation (https://p5js.org), poking through the examples, and reading through the library’s “Get Started” page (https://p5js.org/get-started/).

-

I should also point out that experience with object-oriented programming is fairly critical. I’ll review some of the basics in Chapter 0, but if classes and objects are unfamiliar to you, I suggest watching my p5.js or Processing object-oriented video tutorials, both also available at the Coding Train (https://thecodingtrain.com/oop).

+

If you’ve never written any code before, while you could read the book for the concepts and inspiration, you’ll likely struggle with the code because I’m assuming knowledge of the fundamentals: variables, conditionals, loops, functions, objects, and arrays. If these concepts are new to you, my “Code! Programming with p5.js” or “Introduction to Creative Coding with Processing 4” video courses provide the fundamentals of what you need to know.

+

If you’re an experienced programmer but haven’t worked with p5.js, you can probably pick it up by checking out the p5.js documentation, poking through the examples, and reading through the library’s “Get Started” page.

+

I should also point out that experience with object-oriented programming is fairly critical. I’ll review some of the basics in Chapter 0, but if classes and objects are unfamiliar to you, I suggest watching my p5.js or Processing object-oriented video tutorials, both also available at the Coding Train.

How Are You Reading This Book?

Are you reading this book on a Kindle? Printed paper? On your laptop in PDF form? On a tablet showing an animated HTML5 version? Are you strapped to a chair, absorbing the content directly into your brain via a series of electrodes, tubes, and cartridges?

My dream has always been to write this book in one single format (in this case, a collection of Notion documents) and then, after pressing a magic button (npm run build), out comes the book in any and all formats you might want—PDF, HTML5, printed hard copy, Kindle, and so on. This was largely made possible by the Magic Book project, an open source framework for self-publishing originally developed at ITP by Rune Madsen and Steve Klise. Everything has been designed and styled using CSS—no manual typesetting or layout.

-

The reality of putting this book together isn’t quite so clean as that, and the story of how it happened is long. If you’re interested in learning more, make sure to read the book’s acknowledgments, and then go hire the people I’ve thanked to help you publish a book! Also, I’ll include more details in the associated GitHub repository at https://github.com/nature-of-code.

+

The reality of putting this book together isn’t quite so clean as that, and the story of how it happened is long. If you’re interested in learning more, make sure to read the book’s acknowledgments, and then go hire the people I’ve thanked to help you publish a book! I’ll also include more details in the associated GitHub repository.

The bottom line is that no matter what format you’re reading in, the material is all the same. The only difference will be in how you experience the code examples—more on that in “How to Read the Code” on page XX.

The Coding Train Connection

Personally, I still love an assembled amalgamation of cellulose pulp, meticulously bound together with a resilient spine, upon which pigmented compounds have been artfully deployed to convey words and ideas. Yet, ever since 2012, when I impulsively recorded my very first video lesson about programming in my office at ITP, I’ve discovered the tremendous value and joy in conveying ideas and lessons through moving pictures.

@@ -29,7 +29,7 @@

The Coding Train Connection

If video learning is your style, I’m also working on an accompanying set of video tutorials that follow the exact same material as this book. I made a whole bunch 10 years ago with Processing, and more recently I started publishing a series of updated ones with p5.js. At the time of this writing, I’m about halfway through Chapter 5.

Additional Resources

There’s also an abundance of exceptional educational material teaching simulation and generative algorithms that I did not write or record. I always recommend that you explore various perspectives and voices when attempting to learn something new. It’s possible that what I’ve written might not click with you, and even hearing me repeat the same information in video form, regardless of how much mugging I do for the camera, won’t help. Sometimes what’s best is someone else you can relate to writing or saying or demonstrating the same concepts in different words with a different style. To this end, I’m including an “Additional Resources” section on this book’s website. If you create your own materials or have any recommendations for inclusion, please get in touch!

-

Two quick recommendations I have right now are The Computational Beauty of Nature by Gary William Flake (MIT Press, 1998)—it’s where I originally learned a lot of the ideas for this book—and the superbly organized online resource “That Creative Code Page” by Taru Muhonen and Raphaël de Courville (https://thatcreativecode.page).

+

Two quick recommendations I have right now are The Computational Beauty of Nature by Gary William Flake (MIT Press, 1998)—it’s where I originally learned a lot of the ideas for this book—and the superbly organized online resource “That Creative Code Page” by Taru Muhonen and Raphaël de Courville.

The “Story” of This Book

If you glance over the book’s table of contents, you’ll notice 12 chapters (0–11!), each one covering a different topic. And in one sense, this book is just that—a survey of a dozen concepts and associated code examples. Nevertheless, in putting together the material, I always imagined something of a linear narrative. Before you begin reading, I’d like to walk you through this story.

Part 1: Inanimate Objects

@@ -133,11 +133,11 @@

Example #.#: Example Title

}

The examples are numbered sequentially within each chapter to help you find the corresponding code online. In the printed version of the book, you’ll see a screenshot right below the example title. The online version has the running sketch embedded right there on the page. For animated examples (which are almost all of them), the screenshots will often show a “trail” of motion. This effect was achieved by adding transparency to the background(255, 10) function, though the accompanying code won’t include that enhancement.

Below the example, you’ll find the code, but it’s not always the complete code. Since many examples are quite long and span multiple files, I make my best effort to include a snippet that highlights the main aspects of the example or whatever new components are being introduced that weren’t already discussed earlier in the section.

-

You can find the full version of the code on the book’s website. There, you can interact with, modify, and experiment with the code in the p5.js Web Editor. Additionally, everything is included in the book’s GitHub repository. Here are the full URLs to access all the materials:

+

You can find the full version of the code on the book’s website. There, you can interact with, modify, and experiment with the code in the p5.js Web Editor. Additionally, everything is included in the book’s GitHub repository. Here are links for all of the materials:

Notice that I’ve used comments in the example to address what’s happening in the code. These comments float next to the code (though the appearance may vary depending on where you’re reading the book). The background highlighting groups the comments with their corresponding lines of code.

Complete Snippets

@@ -198,7 +198,7 @@

The Ecosystem Project

As much as I’d like to pretend you could learn everything by curling up in a comfy chair and reading some prose, to learn programming, you’re really going to have to do some programming. The exercises scattered throughout each chapter are a start, but you might find it helpful to also keep in mind a more substantial project idea (or two) that you can develop as you go from chapter to chapter. In fact, when teaching my Nature of Code course at ITP, I’ve often found that students enjoy building a single project, step by step, week by week, over the course of the semester.

At the end of each chapter, you’ll find a series of prompts for one such project—exercises that build on each other, one topic at a time. This project is based on the following scenario. You’ve been asked by a science museum to develop the software for a new exhibit, the Digital Ecosystem, a world of animated, procedural creatures that live in a computer simulation for visitors to enjoy as they enter the museum. I don’t mean to suggest that this is a particularly innovative or creative concept. Rather, I’ll use this example Ecosystem Project idea as a literal representation of the content in the book, demonstrating how the elements can fit together in a single program. I encourage you to develop your own idea, one that’s perhaps more abstract and nontraditional.

Getting Help and Submitting Feedback

-

Coding can be tough and frustrating, and the ideas in this book aren’t always straightforward. You don’t have to go it alone. There’s probably someone else reading right now who would love to co-organize a study group or a book club where you can meet, chat, and share your struggles and successes. If you don’t find a local community for traveling this journey together, what about an online one? Two places I’d suggest are the official Processing forums (https://discourse.processing.org) and the Coding Train Discord server (https://thecodingtrain.com/discord).

-

I consider the online version of this book a living document and welcome your feedback. For all things book related, please visit the Nature of Code website: https://natureofcode.com. The raw source text of the book and all the illustrations are on GitHub at https://github.com/nature-of-code. Please leave feedback and submit corrections by using GitHub issues.

-

More important, I want to see what you make! You can share your ideas by submitting to the passenger showcase on the Coding Train website, or in the channels on the aforementioned Discord. A hello in a YouTube comment is always welcome (although to be honest, it’s often best not to read the comments on YouTube), and feel free to tag me on whatever platform the future of social media has to offer—whichever one is the friendliest and least toxic! I want to enjoy all the bloops that swim in your ecosystem. Whether they leap triumphantly over a wave of creativity or make a tiny splash in a pond of learning, let’s bask in the ripples they send through the nature of coding!

+

Coding can be tough and frustrating, and the ideas in this book aren’t always straightforward. You don’t have to go it alone. There’s probably someone else reading right now who would love to co-organize a study group or a book club where you can meet, chat, and share your struggles and successes. If you don’t find a local community for traveling this journey together, what about an online one? Two places I’d suggest are the official Processing forums and the Coding Train Discord server.

+

I consider the online version of this book a living document and welcome your feedback. For all things book related, please visit the Nature of Code website. The raw source text of the book and all the illustrations are on GitHub. Please leave feedback and submit corrections by using GitHub issues.

+

More important, I want to see what you make! You can share your ideas by submitting to the passenger showcase on the Coding Train website, or in the channels on the aforementioned Discord. A hello in a YouTube comment is always welcome (although to be honest, it’s often best not to read the comments on YouTube), and feel free to tag me on whatever platform the future of social media has to offer—whichever one is the friendliest and least toxic! I want to enjoy all the bloops that swim in your ecosystem. Whether they leap triumphantly over a wave of creativity or make a tiny splash in a pond of learning, let’s bask in the ripples they send through the nature of coding!

\ No newline at end of file diff --git a/content/02_forces.html b/content/02_forces.html index 3e7cbc90..76a5b75e 100644 --- a/content/02_forces.html +++ b/content/02_forces.html @@ -1072,7 +1072,7 @@

Exercise 2.15

Exercise 2.16

-

Can you arrange the bodies of the n-body simulation to orbit the center of the canvas in a pattern that resembles a spiral galaxy? You may need to include an additional large body in the center to hold everything together. A solution is offered in my “Mutual Attraction” video in the Nature of Code series on the Coding Train (https://www.thecodingtrain.com/nbody).

+

Can you arrange the bodies of the n-body simulation to orbit the center of the canvas in a pattern that resembles a spiral galaxy? You may need to include an additional large body in the center to hold everything together. A solution is offered in my “Mutual Attraction” video in the Nature of Code series on the Coding Train.

diff --git a/content/03_oscillation.html b/content/03_oscillation.html index db0da936..7f89ac2c 100644 --- a/content/03_oscillation.html +++ b/content/03_oscillation.html @@ -52,7 +52,7 @@

What Is Pi?

angleMode(DEGREES); rotate(angle); -

While degrees can be useful, for the purposes of this book, I’ll be working with radians because they’re the standard unit of measurement across many programming languages and graphics environments. If they‘re new to you, this is a good opportunity to practice! Additionally, if you aren’t familiar with the way rotation is implemented in p5.js, I recommend watching my Coding Train video series on transformations in p5.js (https://thecodingtrain.com/transformations).

+

While degrees can be useful, for the purposes of this book, I’ll be working with radians because they’re the standard unit of measurement across many programming languages and graphics environments. If they‘re new to you, this is a good opportunity to practice! Additionally, if you aren’t familiar with the way rotation is implemented in p5.js, I recommend watching my Coding Train video series on transformations in p5.js.

Exercise 3.1

Rotate a baton-like object around its center by using translate() and rotate().

@@ -1058,7 +1058,7 @@

Example 3.11: Swinging Pendulum

On the book’s website, this example has additional code to allow the user to grab the pendulum and swing it with the mouse.

Exercise 3.15

-

String together a series of pendulums so that the bob of one is the pivot point of another. Note that doing this may produce intriguing results but will be wildly inaccurate physically. Simulating an actual double pendulum requires sophisticated equations. You can read about them in the Wolfram Research article on double pendulums (https://scienceworld.wolfram.com/physics/DoublePendulum.html) or watch my video on coding a double pendulum (Coding Train Challenge #93) at https://thecodingtrain.com/doublependulum.

+

String together a series of pendulums so that the bob of one is the pivot point of another. Note that doing this may produce intriguing results but will be wildly inaccurate physically. Simulating an actual double pendulum requires sophisticated equations. You can read about them in the Wolfram Research article on double pendulums or watch my video on coding a double pendulum.

diff --git a/content/04_particles.html b/content/04_particles.html index fed8e9fc..54e85b66 100644 --- a/content/04_particles.html +++ b/content/04_particles.html @@ -179,7 +179,7 @@

Exercise 4.2

Add angular velocity (rotation) to the particle, and design a particle that isn’t a circle so its rotation is visible.

An Array of Particles

-

Now that I have a class to describe a single particle, it’s time for the next big step: how can I keep track of many particles, without knowing in advance exactly how many I might have at any given time? The answer is the JavaScript array, a data structure that stores an arbitrarily long list of values. In JavaScript, an array is actually an object created from the Array class, and so it comes with many built-in methods. These methods supply all the functionality I need for maintaining a list of Particle objects, including adding particles, removing particles, or otherwise manipulating them. For a refresher on arrays, see the JavaScript array documentation on the MDN Web Docs website (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).

+

Now that I have a class to describe a single particle, it’s time for the next big step: how can I keep track of many particles, without knowing in advance exactly how many I might have at any given time? The answer is the JavaScript array, a data structure that stores an arbitrarily long list of values. In JavaScript, an array is actually an object created from the Array class, and so it comes with many built-in methods. These methods supply all the functionality I need for maintaining a list of Particle objects, including adding particles, removing particles, or otherwise manipulating them. For a refresher on arrays, see the JavaScript array documentation on the MDN Web Docs website.

As I bring arrays into the picture, I’ll use a solution to Exercise 4.1 and assume a Particle.run() method that manages all of an individual particle’s functionality. While this approach also has some cons, it will keep the subsequent code examples more concise. To begin, I’ll use a for loop in setup() to populate an array with particles, then use another for loop in draw() to run each particle:

let total = 10;
 // Start with an empty array.
@@ -302,7 +302,7 @@ 

An Array of Particles

// Keep particles that are not dead! return !particle.isDead(); });
-

This is more commonly written using JavaScript’s arrow notation. (To learn more, check out my Coding Train video tutorial on higher-order functions and arrow notation at https://thecodingtrain.com/hof.)

+

This is more commonly written using JavaScript’s arrow notation. To learn more, you can watch my Coding Train video tutorial on higher-order functions and arrow notation.

  particles = particles.filter(particle => !particle.isDead());

For the purposes of this book, I’m going to stick with the splice() method, but I encourage you to explore writing your code with higher-order functions and arrow notation.

@@ -444,7 +444,7 @@

A System of Emitters

Consider this scenario: you start with a blank screen (Figure 4.2). 

-
+
Figure 4.2: Starting with a blank screen

You click the mouse and generate a particle system at the mouse’s position (Figure 4.3).

@@ -454,9 +454,9 @@

A System of Emitters

You keep clicking the mouse. Each time, another particle system springs up where you clicked (Figure 4.4).

-
+
Figure 4.4: Adding more particle systems
-

How to do this? In Example 4.3, I stored a single reference to an Emitter object in the variable emitter:

+

How to do this? In Example 4.3, I stored a single reference to an Emitter object in the variable emitter:

let emitter;
 
 function setup() {
@@ -521,7 +521,7 @@ 

Inheritance and Polymorphism

class WackyConfetti { }
-

This is a nice solution: create three classes to describe the different kinds of confetti that are part of your particle system. The Emitter constructor could then have some code to pick randomly from the three classes when filling the array (note that this probabilistic method is the same one I employed in the random walk examples in Chapter 0):

+

This is a nice solution: create three classes to describe the different kinds of confetti that are part of your particle system. The Emitter constructor could then have some code to pick randomly from the three classes when filling the array (note that this probabilistic method is the same one I employed in the random walk examples in Chapter 0):

class Emitter {
   constructor(num) {
     this.particles = [];
@@ -618,7 +618,7 @@ 

Inheritance Basics

} } -//{!1} The Dog class is the child (or subclass), indicated by the code “extends Animal”. +//{!1} The Dog class is the child (or subclass), indicated by the code extends Animal. class Dog extends Animal { constructor() { // super() executes code found in the parent class. @@ -746,7 +746,7 @@

Polymorphism Basics

}

This is polymorphism (from the Greek polymorphos meaning “many forms”) in action. Although all the animals are grouped together in an array and processed in a single for loop, JavaScript can identify their true types and invoke the appropriate eat() method for each one. It’s that simple!

Particles with Inheritance and Polymorphism

-

Now that I’ve covered the theory and syntax behind inheritance and polymorphism, I’m ready to write a working example of them in p5.js, based on my Particle class. First, take another look at a basic Particle implementation, adapted from Example 4.1:

+

Now that I’ve covered the theory and syntax behind inheritance and polymorphism, I’m ready to write a working example of them in p5.js, based on my Particle class. First, take another look at a basic Particle implementation, adapted from Example 4.1:

class Particle {
   constructor(x, y) {
     this.acceleration = createVector(0, 0);
@@ -797,7 +797,7 @@ 

Particles with Inheritance } }

Let’s make this a bit more sophisticated. Say I want to have each Confetti particle rotate as it flies through the air. One option is to model angular velocity and acceleration, as described in Chapter 3. For ease, however, I’ll implement something less formal.

-

I know a particle has an x-position somewhere between 0 and the width of the canvas. What if I said that when the particle’s x-position is 0, its rotation should be 0; when its x-position is equal to the width, its rotation should be equal to 4\pi? Does this ring a bell? As discussed in Chapter 0, whenever a value has one range that you want to map to another range, you can use the map() function:

+

I know a particle has an x-position somewhere between 0 and the width of the canvas. What if I said that when the particle’s x-position is 0, its rotation should be 0; when its x-position is equal to the width, its rotation should be equal to 4\pi? Does this ring a bell? As discussed in Chapter 0, whenever a value has one range that you want to map to another range, you can use the map() function:

let angle = map(this.position.x, 0, width, 0, TWO_PI * 2);

Here’s how this code fits into the show() method:

  show() {
@@ -971,7 +971,7 @@ 

Example 4.6: A Particle System }

While this example demonstrates a hardcoded gravity force, it’s worth considering how other forces from previous chapters, such as wind or drag, could come into play. You could also experiment with varying how and when forces are applied. Instead of a force acting on particles continuously every frame, what if a force kicked in only under certain conditions or at specific moments? A lot of room here remains for creativity and interactivity in the way you design your particle systems!

Particle Systems with Repellers

-

What if I want to take my code one step further and add a Repeller object—the inverse of the Attractor object covered in Chapter 2—that pushes any particles away that get too close? This requires a bit more sophistication than uniformly applying the gravity force, because the force the repeller exerts on a particular particle is unique and must be calculated separately for each particle (see Figure 4.3).

+

What if I want to take my code one step further and add a Repeller object—the inverse of the Attractor object covered in Chapter 2—that pushes any particles away that get too close? This requires a bit more sophistication than uniformly applying the gravity force, because the force the repeller exerts on a particular particle is unique and must be calculated separately for each particle (see Figure 4.3).

Figure 4.3: A gravity force where vectors are all identical (left) and a repeller force where all vectors point in different directions (right)
Figure 4.3: A gravity force where vectors are all identical (left) and a repeller force where all vectors point in different directions (right)
@@ -1265,7 +1265,7 @@

Example 4.9: Additive Blending

// Enable the WebGL renderer. createCanvas(640, 240, WEBGL); } -

Typically, the WebGL renderer is necessary only if you’re drawing 3D shapes in your p5.js sketch. However, even for 2D sketches, the WebGL renderer can be useful in some cases—depending on your computer’s hardware and the specific details of your sketch, it can significantly improve drawing performance. A particle system (especially one with additive blending enabled) is exactly one of these scenarios where many more particles can be drawn without slowing the sketch in WEBGL mode. Keep in mind that WEBGL mode changes the origin point for drawing, making (0,0) the center of the canvas rather than the top-left corner. WEBGL mode also changes the way some functions behave, and it may alter the quality of the rendering. Additionally, some older devices or browsers don’t support WebGL, though such instances are rare. You can learn more in the WebGL videos at the Coding Train website (https://thecodingtrain.com/webgl).

+

Typically, the WebGL renderer is necessary only if you’re drawing 3D shapes in your p5.js sketch. However, even for 2D sketches, the WebGL renderer can be useful in some cases—depending on your computer’s hardware and the specific details of your sketch, it can significantly improve drawing performance. A particle system (especially one with additive blending enabled) is exactly one of these scenarios where many more particles can be drawn without slowing the sketch in WEBGL mode. Keep in mind that WEBGL mode changes the origin point for drawing, making (0,0) the center of the canvas rather than the top-left corner. WEBGL mode also changes the way some functions behave, and it may alter the quality of the rendering. Additionally, some older devices or browsers don’t support WebGL, though such instances are rare. You can learn more in the WebGL videos at the Coding Train website.

Exercise 4.13

In Example 4.9, three particles are added with a for loop each time through draw() to create a more layered effect. A better solution would be to modify the addParticle() method to accept an argument—for example, addParticle(3), to determine the number of particles to add. Fill in the new method definition here. How might it default to one particle if no value is provided?

diff --git a/content/05_steering.html b/content/05_steering.html index 759e002f..2bff060d 100644 --- a/content/05_steering.html +++ b/content/05_steering.html @@ -23,7 +23,10 @@

Forces from Within

The switch from inanimate objects to autonomous agents is a significant conceptual leap, but the codebase will barely change. The desire for an autonomous agent to move is just another force, like the force of gravity or the force of the wind. It’s just that now the force is coming from within.

Here are three key components of autonomous agents to keep in mind as I build this chapter’s examples:

    -
  • An autonomous agent has a limited ability to perceive its environment. It makes sense that a living, breathing being should be aware of its environment. However, this awareness doesn’t refer to just the external environment but also to the agent’s internal state—its position, velocity, and potentially other properties or even simulated emotions. Throughout the chapter, I’ll explore ways agents can take their own state into account when making decisions. I’ll also cover programming techniques for objects to store references to other objects and therefore “perceive” their surroundings. It’s important to consider the word limited here. Are you designing an all-knowing circle that flies around a canvas, aware of everything else in that canvas? Or are you creating a shape that can examine other shapes only within 15 pixels of itself? Of course, there’s no right answer to this question; it all depends on what you want. I’ll explore several possibilities throughout this chapter, but in general, limitations are good for creating a simulation that feels more “natural.” An insect, for example, may be aware of only the sights and smells that immediately surround it. To model a real-world creature, you could study the exact science of these limitations. Luckily, I can just make stuff up and try it out.
  • +
  • + An autonomous agent has a limited ability to perceive its environment. It makes sense that a living, breathing being should be aware of its environment. However, this awareness doesn’t refer to just the external environment but also to the agent’s internal state—its position, velocity, and potentially other properties or even simulated emotions. Throughout the chapter, I’ll explore ways agents can take their own state into account when making decisions. I’ll also cover programming techniques for objects to store references to other objects and therefore “perceive” their surroundings. + It’s important to consider the word limited here. Are you designing an all-knowing circle that flies around a canvas, aware of everything else in that canvas? Or are you creating a shape that can examine other shapes only within 15 pixels of itself? Of course, there’s no right answer to this question; it all depends on what you want. I’ll explore several possibilities throughout this chapter, but in general, limitations are good for creating a simulation that feels more “natural.” An insect, for example, may be aware of only the sights and smells that immediately surround it. To model a real-world creature, you could study the exact science of these limitations. Luckily, I can just make stuff up and try it out. +
  • An autonomous agent processes the information from its environment and calculates an action. This will be the easy part, as the action is a force. The environment might tell the agent that there’s a big, scary-looking shark swimming right at it, and the action will be a powerful force in the opposite direction.
  • An autonomous agent has no leader. This third principle is something I care a little less about, depending on the context. For example, if you’re designing a system for which it makes sense to have a leader barking commands at various entities, then that’s what you’ll want to implement. Nevertheless, many of the chapter’s examples will have no leader for an important reason: toward the end of this chapter, I’ll examine group behaviors and look at designing collections of autonomous agents that exhibit the properties of complex systems. These are intelligent and structured group dynamics that emerge not from a leader, but from the local interactions of the elements themselves.
@@ -79,7 +82,7 @@

The Steering Force

Figure 5.3: The magnitude of the vehicle’s desired velocity is max speed.
Figure 5.3: The magnitude of the vehicle’s desired velocity is max speed.
-

The concept of maximum speed was introduced in Chapter 1 to ensure that a mover’s speed remained within a reasonable range. However, I didn’t always use it in the subsequent chapters. In Chapter 2, other forces such as friction and drag kept the speed in check, while in Chapter 3, oscillation was caused by opposing forces that kept the speed limited. In this chapter, maximum speed is a key parameter for controlling the behavior of a steering agent, so I’ll include it in all the examples.

+

The concept of maximum speed was introduced in Chapter 1 to ensure that a mover’s speed remained within a reasonable range. However, I didn’t always use it in the subsequent chapters. In Chapter 2, other forces such as friction and drag kept the speed in check, while in Chapter 3, oscillation was caused by opposing forces that kept the speed limited. In this chapter, maximum speed is a key parameter for controlling the behavior of a steering agent, so I’ll include it in all the examples.

While I encourage you to consider how other forces such as friction and drag could be combined with steering behaviors, I’m going to focus only on steering forces for the time being. As such, I can include the concept of maximum speed as a limiting factor in the force calculation. First, I need to add a property to the Vehicle class setting the maximum speed:

class Vehicle {
@@ -212,7 +215,7 @@ 

Exercise 5.1

Exercise 5.2

-

Implement a seeking behavior with a moving target, often referred to as pursuit. In this case, your desired vector won’t point toward the object’s current position, but rather its future position as extrapolated from its current velocity. You’ll see this ability for a vehicle to “predict the future” in later examples. The solution is covered in the “Pursue and Evade” video on the Coding Train website (https://thecodingtrain.com/pursuit).

+

Implement a seeking behavior with a moving target, often referred to as pursuit. In this case, your desired vector won’t point toward the object’s current position, but rather its future position as extrapolated from its current velocity. You’ll see this ability for a vehicle to “predict the future” in later examples. The solution is covered in the “Pursue and Evade” video on the Coding Train website.

@@ -385,7 +388,7 @@

Flow Fields

Figure 5.13: A 2D grid full of unit vectors pointing in random directions

Reynolds’s own flow-field example involves the vehicle looking ahead to its future position and following the vector at that spot. For simplicity’s sake, however, I’ll instead have the vehicle follow the vector at its current position.

-

Before I can write the additional code for the Vehicle class to follow a flow field, I first need a class that describes the flow field. Since a flow field is essentially a grid of vectors, a 2D array is a convenient data structure to represent it, as I can reference each element with two indices, the cell’s column and row in the grid. (If you aren’t familiar with 2D arrays, I suggest reviewing my video tutorial on “2D Arrays in JavaScript” at the Coding Train website (https://thecodingtrain.com/2d-array).

+

Before I can write the additional code for the Vehicle class to follow a flow field, I first need a class that describes the flow field. Since a flow field is essentially a grid of vectors, a 2D array is a convenient data structure to represent it, as I can reference each element with two indices, the cell’s column and row in the grid. (If you aren’t familiar with 2D arrays, I suggest reviewing my video tutorial on “2D Arrays in JavaScript” at the Coding Train website.

class FlowField {
   constructor() {
     // Resolution of the grid relative to the canvas width and height in pixels
@@ -650,10 +653,13 @@ 

Simple Path Following

I’m also going to consider a path to have a radius. If the path is a road, the radius is the road’s width. With a smaller radius, vehicles have to follow the path more closely; a wider radius allows them to stray a bit more to either side of the path.

Now I’ll put this into a class.

-
-
-
-
+
+

Example 5.5: Creating a Path Object

+
+
+
+
+
class Path {
   constructor() {
     // A path has a radius, indicating its width.
@@ -839,10 +845,13 @@ 

Path Following with Multiple Segm

If you have a point and an infinitely long line, you’ll always have a normal point that touches the line. But if you have a point and a finite line segment, you won’t necessarily find a normal that’s on the line segment. If this happens for any of the segments, I can disqualify those normals. Once I’m left with just those normals that are on the path (only two in Figure 5.31), I pick the one that’s shortest.

To write the code for this, I’ll expand the Path class to have an array of points (rather than just the start and end).

-
-
-
-
+
+

Example 5.7: Path Made of Multiple Line Segments

+
+
+
+
+
 class Path {
   constructor() {
     this.radius = 20;
@@ -949,7 +958,10 @@ 

Complex Systems

Beyond these core principles, three additional qualities of complex systems will help frame the discussion, as well as provide guidelines for features to include in a software simulation. It’s important to acknowledge that this is a fuzzy set of characteristics, and not all complex systems have all of them:

    -
  • Nonlinearity: This aspect of complex systems is often casually referred to as the butterfly effect, coined by mathematician and meteorologist Edward Norton Lorenz, a pioneer in the study of chaos theory. In 1961, Lorenz was running a computer weather simulation for the second time and, perhaps to save a little time, typed in a starting value of 0.506 instead of 0.506127. The end result was completely different from the first result of the simulation. Stated more evocatively, the theory is that a single butterfly flapping its wings on the other side of the world could cause a massive weather shift and ruin your weekend at the beach. It‘s called nonlinear because there isn’t a linear relationship between a change in initial conditions and a change in outcome. A small change in initial conditions can have a massive effect on the outcome. Nonlinear systems are a superset of chaotic systems. In Chapter 7, you’ll see how even in a system of many 0s and 1s, if you change just one bit, the result will be completely different.
  • +
  • + Nonlinearity: This aspect of complex systems is often casually referred to as the butterfly effect, coined by mathematician and meteorologist Edward Norton Lorenz, a pioneer in the study of chaos theory. In 1961, Lorenz was running a computer weather simulation for the second time and, perhaps to save a little time, typed in a starting value of 0.506 instead of 0.506127. The end result was completely different from the first result of the simulation. + Stated more evocatively, the theory is that a single butterfly flapping its wings on the other side of the world could cause a massive weather shift and ruin your weekend at the beach. It‘s called nonlinear because there isn’t a linear relationship between a change in initial conditions and a change in outcome. A small change in initial conditions can have a massive effect on the outcome. Nonlinear systems are a superset of chaotic systems. In Chapter 7, you’ll see how even in a system of many 0s and 1s, if you change just one bit, the result will be completely different. +
  • Competition and cooperation: One ingredient that often makes a complex system tick is the presence of both competition and cooperation among the elements. The upcoming flocking system will have three rules: alignment, cohesion, and separation. Alignment and cohesion will ask the elements to “cooperate” by trying to stay together and move together. Separation, however, will ask the elements to “compete” for space. When the time comes, try taking out just the cooperation or just the competition, and you’ll see how the system loses its complexity. Competition and cooperation are found together in living complex systems, but not in nonliving complex systems like the weather.
  • Feedback: Complex systems often include a loop that feeds the output of the system back into the system to influence its behavior in a positive or negative direction. Let’s say you decide to take public transportation to work each day because it’s the most reliable and cost-effective solution, and you’re put off by the traffic congestion and environmental impact of driving. You aren’t alone; others turn to public transportation too. The system grows more efficient and attractive, serving more people with the same resources, and meanwhile, vehicle traffic is reduced. Over time, however, the system may struggle to accommodate the rising demand, leading to overcrowding, delays, and increased fares to fund infrastructure improvements. As a result, you and others start to switch back to driving, thereby increasing traffic congestion once again and reducing public transport’s efficiency. As traffic worsens, the funds from increased fares are (hopefully) used to improve public transport infrastructure, making it more appealing once again. In this way, the cost and efficiency of public transportation are both the input of the system (determining whether you choose to use it or not) and the output (the degree of traffic congestion and subsequent cost and efficiency). Economic models are just one example of a human complex system. Others include fads and trends, elections, crowds, and traffic flow.
@@ -1471,7 +1483,7 @@

Example 5.13: Quadtree

-

The quadtree data structure is key to the Barnes-Hut algorithm, which I referenced briefly when building an n-body simulation in Chapter 2. This method uses a quadtree to approximate groups of bodies into a single one when calculating gravitational forces. This drastically reduces the number of calculations needed, allowing simulations with large numbers of bodies to run more efficiently. You can learn more about building a quadtree and applying it to a flocking system as part of Coding Challenge #98 on the Coding Train website (https://thecodingtrain.com/quadtree).

+

The quadtree data structure is key to the Barnes-Hut algorithm, which I referenced briefly when building an n-body simulation in Chapter 2. This method uses a quadtree to approximate groups of bodies into a single one when calculating gravitational forces. This drastically reduces the number of calculations needed, allowing simulations with large numbers of bodies to run more efficiently. You can learn more about building a quadtree and applying it to a flocking system as part of Coding Challenge #98 on the Coding Train website.

Exercise 5.20

Expand the bin-lattice spatial subdivision flocking sketch from Example 5.12 to use a quadtree.

diff --git a/content/06_libraries.html b/content/06_libraries.html index 8e4bc1be..294a4c55 100644 --- a/content/06_libraries.html +++ b/content/06_libraries.html @@ -51,10 +51,10 @@

Why Use a Physics Library?

Other Physics Libraries

A multitude of other physics libraries are worth exploring alongside this chapter’s two case studies, each with unique strengths that may offer advantages in certain kinds of projects. In fact, when I first began writing this book, Matter.js didn’t exist, so the physics engine I initially used to demonstrate the examples was Box2D. It was (and likely still is) the most well-known physics engine of them all.

-

Box2D (https://box2d.org) began as a set of physics tutorials written in C++ by Erin Catto for the Game Developers Conference in 2006. Since then, Box2D has evolved into a rich and elaborate open source physics engine. It’s been used for countless projects, most notably highly successful games such as the award-winning Crayon Physics and the runaway hit Angry Birds.

+

Box2D began as a set of physics tutorials written in C++ by Erin Catto for the Game Developers Conference in 2006. Since then, Box2D has evolved into a rich and elaborate open source physics engine. It’s been used for countless projects, most notably highly successful games such as the award-winning Crayon Physics and the runaway hit Angry Birds.

One important feature of Box2D is that it’s a true physics engine: it knows nothing about computer graphics and the world of pixels, and instead does all its measurements and calculations in real-world units like meters, kilograms, and seconds. It’s just that its “world” (a key term in Box2D) is a 2D plane with top, bottom, left, and right edges. You tell it things like “The gravity of the world is 9.81 newtons per kilogram, and a circle with a radius of 4 meters and a mass of 50 kilograms is located 10 meters above the world’s bottom.” Box2D will then tell you things like “One second later, the rectangle is at 5 meters from the bottom; two seconds later, it’s 10 meters below,” and so on.

While this provides for an amazingly accurate and robust physics engine (one that’s highly optimized and fast for C++ projects), it also necessitates lots of complicated code to translate back and forth between Box2D’s physics world and the world you want to draw —the pixel world of the graphics canvas. This creates a tremendous burden for the coder. I will, as best I can, continue to maintain a set of Box2D-compatible examples for this book (there are several JavaScript ports), but I believe the relative simplicity of working with a library like Matter.js that’s native to JavaScript and uses pixels as the unit of measurement will make for a more intuitive and friendly bridge from my p5.js examples.

-

Another notable library is p5play (https://p5play.org), a project initiated by Paolo Pedercini and currently led by Quinton Ashley that was specifically designed for game development. It simplifies the creation of visual objects—known as sprites—and manages their interactions (namely, collisions and overlaps). As you may have guessed from the name, p5play is tailored to work seamlessly with p5.js. It uses Box2D under the hood for physics simulation.

+

Another notable library is p5play, a project initiated by Paolo Pedercini and currently led by Quinton Ashley that was specifically designed for game development. It simplifies the creation of visual objects—known as sprites—and manages their interactions (namely, collisions and overlaps). As you may have guessed from the name, p5play is tailored to work seamlessly with p5.js. It uses Box2D under the hood for physics simulation.

Importing the Matter.js Library

In a moment, I’ll turn to working with Matter.js, created by Liam Brummitt in 2014. But before you can use an external JavaScript library in a p5.js project, you need to import it into your sketch. As you’re already quite aware, I’m using the official p5.js web editor for developing and sharing this book’s code examples. The easiest way to add a library is to edit the index.html file that’s part of every new p5.js sketch created in the editor.

@@ -216,7 +216,7 @@

Matter.js Overview

As you can see, the concepts are the same, but the specifics of the code are different. First, every method name is now preceded by Matter.Vector, which defines the namespace of the source code. This is common for JavaScript libraries; p5.js is unusual for not consistently using namespaces. For example, to draw a circle in p5.js, you call circle() rather than p5.circle(). The circle() function lives in the global namespace. This, in my view, is one of the features that makes p5.js special in terms of ease of use and beginner friendliness. However, it also means that for any code you write with p5, you can’t use circle as a variable name. Namespacing a library protects against these kinds of errors and naming conflicts, and it’s why you’ll see everything in Matter.js called with the Matter prefix.

In addition, unlike p5’s static and nonstatic versions of vector methods like add() and mult(), all vector methods in Matter.js are static. If you want to change a Matter.Vector while operating on it, you can add it as an optional argument: Matter.Vector.add(a, b, a): adds a and b and places the result in a (the third argument). You can also set an existing variable to the newly created vector object resulting from a calculation, as in v = Matter.Vector.mult(v, 2). However, this version still creates a new vector in memory rather than updating the old one.

-

I’ll cover more of the basics for working with Matter.Vector in this chapter, but for details, you can find the full documentation on the Matter.js website (https://brm.io/matter-js/).

+

I’ll cover more of the basics for working with Matter.Vector in this chapter, but for details, you can find the full documentation on the Matter.js website.

Engine

Many physics libraries include a world object to manage everything. The world is typically in charge of the coordinate space, keeping a list of all the bodies in the simulation, controlling time, and more. In Matter.js, the world is created inside an Engine object, the main controller of your physics world and simulation:

// An alias for the Matter.js Engine class
@@ -1084,7 +1084,7 @@ 

Verlet Physics with Toxiclibs.js

Toxiclibs is an independent, open source library collection for computational design tasks with Java and Processing developed by Karsten “toxi” Schmidt. The classes are purposefully kept fairly generic in order to maximize reuse in different contexts ranging from generative design, animation, interaction/interface design, data visualization to architecture and digital fabrication, use as teaching tool and more.

-

Schmidt continues to contribute to the creative coding field through his recent project, thi.ng/umbrella (https://thi.ng/umbrella). This work can be considered an indirect successor to Toxiclibs, but with a much greater scope and detail. If you like this book, you might especially enjoy exploring thi.ng/vectors (https://thi.ng/vectors), which provides more than 800 vector algebra functions using plain vanilla JavaScript arrays.

+

Schmidt continues to contribute to the creative coding field through his recent project, thi.ng umbrella. This work can be considered an indirect successor to Toxiclibs, but with a much greater scope and detail. If you like this book, you might especially enjoy exploring thi.ng vectors, which provides more than 800 vector algebra functions using plain vanilla JavaScript arrays.

While thi.ng/umbrella may be a more modern and sophisticated approach, Toxiclibs remains a versatile tool, and I continue to use a version compatible with the latest version of Processing (4.1 as of the time of this writing). For this book, we should thank our lucky stars for Toxiclibs.js, a JavaScript adaptation of the library, created by Kyle Phillips (hapticdata). I’m going to cover only a few examples related to Verlet physics, but Toxiclibs.js includes a suite of other packages with functionality related to color, geometry, math, and more.

The examples I’m about to demonstrate could also be created using Matter.js, but I’ve decided to move to Toxiclibs.js for several reasons. The library holds a special place in my heart as a personal favorite, and it’s historically significant. I also believe that showing more than one physics library is important for providing a broader understanding of the tools and approaches available.

This switch from Matter.js to Toxiclibs.js raises an important question, though: how should you decide which library to use for a project? Matter.js, or Toxiclibs.js, or something else? If you fall into one of the following two categories, your decision is a bit easier:

@@ -1129,7 +1129,7 @@

Verlet Physics with Toxiclibs.js

-

All the documentation and downloads for the library files can be found at the Toxiclibs.js website, http://haptic-data.com/toxiclibsjs. For the examples in this book, I’ll be working with a hosted CDN version of the library referenced in index.html, just as I demonstrated earlier for Matter.js. Here’s the <script> element to add:

+

All the documentation and downloads for the library files can be found at the Toxiclibs.js website. For the examples in this book, I’ll be working with a hosted CDN version of the library referenced in index.html, just as I demonstrated earlier for Matter.js. Here’s the <script> element to add:

<script src="https://cdn.jsdelivr.net/gh/hapticdata/toxiclibsjs@0.3.2/build/toxiclibs.js"></script>

My overview of Matter.js focused on a few key features of that library: world, vector, body, constraint. This has given you a head start on understanding Toxiclibs.js as well, since it follows a similar structure. The following table shows the corresponding Toxiclibs.js features:

diff --git a/content/07_ca.html b/content/07_ca.html index 9735d47d..9c3b4d6d 100644 --- a/content/07_ca.html +++ b/content/07_ca.html @@ -35,7 +35,7 @@

What Is a Cellular Automaton?

The development of CA systems is typically attributed to Stanisław Ulam and John von Neumann, who were both researchers at the Los Alamos National Laboratory in New Mexico in the 1940s. Ulam was studying the growth of crystals, and von Neumann was imagining a world of self-replicating robots. You read that right: robots that can build copies of themselves.

Von Neumann’s original cells had 29 possible states, so perhaps the idea of self-replicating robots is a bit too complex of a starting point. Instead, imagine a row of dominoes; each domino can be in one of two states: standing upright (1) or knocked down (0). Just as dominoes react to their neighboring dominoes, the behavior of each cell in a CA is influenced by the states of its neighboring cells.

This chapter explores how even the most basic rules of something like dominoes can lead to a wide array of intricate patterns and behaviors, similar to natural processes like biological reproduction and evolution. Von Neumann’s work in self-replication and CA is conceptually similar to what’s probably the most famous CA, the Game of Life, which I’ll discuss in detail later in the chapter.

-

Perhaps the most significant (and lengthy) scientific work studying CA arrived in 2002: Stephen Wolfram’s 1,280-page A New Kind of Science. Available in its entirety for free online, Wolfram’s book discusses how CA aren’t simply neat tricks but are relevant to the study of biology, chemistry, physics, and all branches of science. In a moment, I’ll turn to building a simulation of Wolfram’s work, although I’ll barely scratch the surface of the theories he outlines—my focus will be on the code implementation, not the philosophical implications. If the examples spark your curiosity, you’ll find plenty more to read about in Wolfram’s book, as well as in his ongoing research at the Wolfram Physics Project (https://www.wolframphysics.org).

+

Perhaps the most significant (and lengthy) scientific work studying CA arrived in 2002: Stephen Wolfram’s 1,280-page A New Kind of Science. Available in its entirety for free online, Wolfram’s book discusses how CA aren’t simply neat tricks but are relevant to the study of biology, chemistry, physics, and all branches of science. In a moment, I’ll turn to building a simulation of Wolfram’s work, although I’ll barely scratch the surface of the theories he outlines—my focus will be on the code implementation, not the philosophical implications. If the examples spark your curiosity, you’ll find plenty more to read about in Wolfram’s book, as well as in his ongoing research at the Wolfram Physics Project.

Elementary Cellular Automata

What’s the simplest CA you can imagine? For Wolfram, an elementary CA has three key elements:

    @@ -497,8 +497,8 @@

    The Rules of the Game

    If you’re interested in these patterns, several good out-of-the-box Game of Life online demonstrations allow you to configure the CA’s initial state and watch it run at varying speeds. Here are two examples:

    For the example I’ll build in the next section, I’ll focus on randomly initializing the states for each cell.

    The Implementation

    diff --git a/content/08_fractals.html b/content/08_fractals.html index 41af768f..585a090d 100644 --- a/content/08_fractals.html +++ b/content/08_fractals.html @@ -464,7 +464,7 @@

    The Deterministic Version

    Figure 8.17: Each generation of a fractal tree, following the given production rules. The final tree is several generations later.

    Once again, I have a nice fractal with a recursive definition: a branch is a line with two branches connected to it. What makes this fractal a bit more difficult than the previous ones is the use of the word rotate in the fractal’s rules. Each new branch must rotate relative to the previous branch, which is rotated relative to all its previous branches. Luckily, p5.js has a mechanism to keep track of rotations: transformations.

    -

    I touched on transformations in Chapter 3. They’re a set of functions, such as translate(), rotate(), scale(), push(), and pop(), that allow you to change the position, orientation, and scale of shapes in your sketch. The translate() function moves the coordinate system, rotate() rotates it, and push() and pop() help save and restore the current transformation state. If you aren’t familiar with these functions, I have a set of videos on transformations in p5.js available at the Coding Train (https://thecodingtrain.com/transformations).

    +

    I touched on transformations in Chapter 3. They’re a set of functions, such as translate(), rotate(), scale(), push(), and pop(), that allow you to change the position, orientation, and scale of shapes in your sketch. The translate() function moves the coordinate system, rotate() rotates it, and push() and pop() help save and restore the current transformation state. If you aren’t familiar with these functions, I have a set of videos on transformations in p5.js available at the Coding Train.

    I’ll begin by drawing a single branch, the trunk of the tree. Since I’m going to be using the rotate() function, I need to make sure I’m continuously translating along the branches while drawing. Remember, when you rotate in p5.js, you’re always rotating around the origin, or point (0, 0), so here the origin must always be translated to the start of the next branch being drawn (equivalent to the end of the previous branch). Since the trunk starts at the bottom of the window, I first have to translate to that spot:

    translate(width / 2, height);

    Then I can draw the trunk as a line upward:

    diff --git a/content/09_ga.html b/content/09_ga.html index 86ed12e7..e6daef35 100644 --- a/content/09_ga.html +++ b/content/09_ga.html @@ -1474,7 +1474,7 @@

    Exercise 9.14

    -

    Can you design the DNA for a flower, plant, or creature as a network of parts? One idea is to use interactive selection to evolve the design. Alternatively, you could incorporate spring forces, perhaps with Toxiclibs.js or Matter.js, to create a simplified 2D version of Sims’s creatures. What if they were to evolve according to a fitness function associated with a specific goal? For more about Sims’s techniques, you can read his 1994 paper (https://www.karlsims.com/papers/siggraph94.pdf) and watch the “Evolved Virtual Creatures” video on YouTube (https://www.youtube.com/watch?v=RZtZia4ZkX8).

    +

    Can you design the DNA for a flower, plant, or creature as a network of parts? One idea is to use interactive selection to evolve the design. Alternatively, you could incorporate spring forces, perhaps with Toxiclibs.js or Matter.js, to create a simplified 2D version of Sims’s creatures. What if they were to evolve according to a fitness function associated with a specific goal? For more about Sims’s techniques, you can read his 1994 paper and watch the “Evolved Virtual Creatures” video on YouTube.

    Ecosystem Simulation

    You may have noticed something a bit odd about the evolutionary systems I’ve built so far in this chapter. In the real world, a population of babies isn’t born all at the same time. Those babies don’t then grow up and all reproduce at exactly the same time, then instantly die, leaving the population size perfectly stable. That would be ridiculous. Not to mention that certainly no one is running around the forest with a calculator crunching numbers and assigning fitness values to all the creatures.

    diff --git a/content/10_nn.html b/content/10_nn.html index b7d99b53..1fed8daa 100644 --- a/content/10_nn.html +++ b/content/10_nn.html @@ -543,7 +543,7 @@

    Putting the “Network” in Neur

    Up until now, I’ve been visualizing a singular perceptron with one circle representing a neuron processing its input signals. Now, as I move on to larger networks, it’s more typical to represent all the elements (inputs, neurons, outputs) as circles, with arrows that indicate the flow of data. In Figure 10.13, you can see the inputs and bias flowing into the hidden layer, which then flows to the output.

    Training a simple perceptron is pretty straightforward: you feed the data through and evaluate how to change the input weights according to the error. With a multilayered perceptron, however, the training process becomes more complex. The overall output of the network is still generated in essentially the same manner as before: the inputs multiplied by the weights are summed and fed forward through the various layers of the network. And you still use the network’s guess to calculate the error (desired result – guess). But now so many connections exist between layers of the network, each with its own weight. How do you know how much each neuron or connection contributed to the overall error of the network, and how it should be adjusted?

    -

    The solution to optimizing the weights of a multilayered network is backpropagation. This process takes the error and feeds it backward through the network so it can adjust the weights of all the connections in proportion to how much they’ve contributed to the total error. The details of backpropagation are beyond the scope of this book. The algorithm uses a variety of activation functions (one classic example is the sigmoid function) as well as some calculus. If you’re interested in continuing down this road and learning more about how backpropagation works, you can find my “Toy Neural Network” project at at the Coding Train website (https://thecodingtrain.com/toy-neural-network) with accompanying video tutorials. They go through all the steps of solving XOR using a multilayered feed-forward network with backpropagation. For this chapter, however, I’d instead like to get some help and phone a friend.

    +

    The solution to optimizing the weights of a multilayered network is backpropagation. This process takes the error and feeds it backward through the network so it can adjust the weights of all the connections in proportion to how much they’ve contributed to the total error. The details of backpropagation are beyond the scope of this book. The algorithm uses a variety of activation functions (one classic example is the sigmoid function) as well as some calculus. If you’re interested in continuing down this road and learning more about how backpropagation works, you can find my “Toy Neural Network” project at at the Coding Train website with accompanying video tutorials. They go through all the steps of solving XOR using a multilayered feed-forward network with backpropagation. For this chapter, however, I’d instead like to get some help and phone a friend.

    Machine Learning with ml5.js

    That friend is ml5.js. This machine learning library can manage the details of complex processes like backpropagation so you and I don’t have to worry about them. As I mentioned earlier in the chapter, ml5.js aims to provide a friendly entry point for those who are new to machine learning and neural networks, while still harnessing the power of Google’s TensorFlow.js behind the scenes.

    To use ml5.js in a sketch, you must import it via a <script> element in your index.html file, much as you did with Matter.js and Toxiclibs.js in Chapter 6:

    @@ -836,7 +836,7 @@

    Evaluating the Model

You may have noticed that I never did this. For simplicity, I’ve instead used the entire dataset for training. After all, my dataset has only eight records; it’s much too small to divide three sets! With a large dataset, this three-way split would be more appropriate.

Using such a small dataset risks the model overfitting the data, however: the model becomes so tuned to the specific peculiarities of the training data that it’s much less effective when working with new, unseen data. The main reason to use a validation set is to monitor the model during the training process. As training progresses, if the model’s accuracy improves on the training data but deteriorates on the validation data, it’s a strong indicator that overfitting might be occurring. (The testing set is reserved strictly for the final evaluation, one more chance after training is complete to gauge the model’s performance.)

-

For more realistic scenarios, ml5.js provides a way to split up the data, as well as automatic features for employing validation data. If you’re inclined to go further, you can explore the full set of neural network examples at https://ml5js.org.

+

For more realistic scenarios, ml5.js provides a way to split up the data, as well as automatic features for employing validation data. If you’re inclined to go further, you can explore the full set of neural network examples on the ml5.js website.

Tuning the Parameters

After the evaluation step, there’s typically an iterative process of adjusting hyperparameters and going through training again to achieve the best performance from the model. While ml5.js offers capabilities for parameter tuning (which you can learn about in the library’s reference), it isn’t really geared toward making low-level, fine-grained adjustments to a model. Using TensorFlow.js directly might be your best bet if you want to explore this step in more detail, since it offers a broader suite of tools and allows for lower-level control over the training process.

In this case, tuning the parameters isn’t strictly necessary. The graph in the Visor shows a loss all the way down at 0.1, which is plenty accurate for my purposes. I’m happy to move on.

@@ -936,7 +936,7 @@

Exercise 10.7

-

Can you use the outputs of the ml5.handpose() model as the inputs to an ml5.neuralNetwork() and classify various hand gestures (like a thumbs-up or thumbs-down)? For hints, you can watch my video tutorial that walks you through this process for body poses in the machine learning track on the Coding Train at https://thecodingtrain.com/pose-classifier.

+

Can you use the outputs of the ml5.handpose() model as the inputs to an ml5.neuralNetwork() and classify various hand gestures (like a thumbs-up or thumbs-down)? For hints, you can watch my video tutorial that walks you through this process for body poses in the machine learning track on the Coding Train.

The Ecosystem Project

diff --git a/content/11_nn_ga.html b/content/11_nn_ga.html index db6d4cec..aaee3ba9 100644 --- a/content/11_nn_ga.html +++ b/content/11_nn_ga.html @@ -714,7 +714,7 @@

Sensing the Environment

} }

How can I determine if a creature’s sensor is touching the food? One approach could be to use raycasting. This technique is commonly employed in computer graphics to project straight lines (often representing beams of light) from an origin point in a scene to determine which objects they intersect with. Raycasting is useful for visibility and collision checks, exactly what I’m doing here!

-

While raycasting would provide a robust solution, it requires more mathematics than I’d like to delve into here. For those interested, an explanation and implementation are available in Coding Challenge #145 on the Coding Train (https://thecodingtrain.com/raycasting). For this example, I’ll opt for a more straightforward approach and check whether the endpoint of a sensor lies inside the food circle (see Figure 11.6).

+

While raycasting would provide a robust solution, it requires more mathematics than I’d like to delve into here. For those interested, an explanation and implementation are available in Coding Challenge #145 on the Coding Train. For this example, I’ll opt for a more straightforward approach and check whether the endpoint of a sensor lies inside the food circle (see Figure 11.6).

Figure 11.6: The endpoint of a sensor is inside or outside the food, based on its distance to the center of the food.
Figure 11.6: The endpoint of a sensor is inside or outside the food, based on its distance to the center of the food.
@@ -942,10 +942,9 @@

The Ecosystem Project

The End

If you’re still reading, thank you! You’ve reached the end of the book. But for as much material as this book contains, I’ve barely scratched the surface of the physical world we inhabit and of techniques for simulating it. I intend for this book to live as an ongoing project, and I hope to continue adding new tutorials and examples to the book’s website, as well as expand and update the accompanying video tutorials at the Coding Train website.

-

Your feedback is truly appreciated, so please get in touch via email at daniel@shiffman.net or by contributing to the GitHub repository at https://github.com/nature-of-code, in keeping with the open source spirit of the project. Share your work. Stay in touch. Let’s be two with nature.

+

Your feedback is truly appreciated, so please get in touch via email at daniel@shiffman.net or by contributing to the GitHub repository, in keeping with the open source spirit of the project. Share your work. Stay in touch. Let’s be two with nature.

-

\ No newline at end of file diff --git a/content/xx_2_image_credits.html b/content/xx_2_image_credits.html index 8d3b401e..2b943594 100644 --- a/content/xx_2_image_credits.html +++ b/content/xx_2_image_credits.html @@ -2,20 +2,20 @@

Image Credits

All emojis in the book were designed by OpenMoji, the open source emoji and icon project, licensed under CC BY-SA 4.0.

The following credits are for the photos in each chapter.

-

0. Photo from A Million Random Digits with 100,000 Normal Deviates (RAND Corporation, 2001). https://www.rand.org/pubs/monograph_reports/MR1418.html.

-

1. Marshall Islands Stick Chart by Jim Heaphy, on display at the Berkeley Art Museum and Pacific Film Archive. Licensed under CC BY-SA 3.0. https://commons.wikimedia.org/wiki/File:Micronesian_navigational_chart.jpg.

-

2. Calder, New Gallery, Charles Hayden Memorial Library, Massachusetts Institute of Technology, Cambridge, 1950, by Ezra Stoller; © Esto. https://calder.org/historical-photos/calder-at-mit-1950/.

-

3. Gala by Bridget Riley, 1974; acrylic on canvas, 159.7 by 159.7 cm; © Bridget Riley 2023, all rights reserved. https://artvee.com/dl/gala/.

-

4. Cloud chamber photograph of a positron passing through a lead plate by Carl D. Anderson, 1932. https://commons.wikimedia.org/wiki/File:PositronDiscovery.png.

-

5. Sixfinger threadfin school circling in a feeding pattern inside a cage off Hawaii from the U.S. National Oceanic and Atmospheric Administration (NOAA) photo library, Fisheries Collection, 2000. https://en.m.wikipedia.org/wiki/File:Sixfinger_threadfin_school.jpg.

-

6. Double living root bridge in East Khasi by Arshiya Urveeja Bose, 2011. Licensed under CC BY-SA 4.0. https://commons.wikimedia.org/wiki/File:Living_root_bridges,_Nongriat_village,_Meghalaya2.jpg.

-

7. Ewe Kente Stripes, Ghana by ZSM, 2008. Licensed under CC BY-SA 3.0. https://commons.wikimedia.org/wiki/File:Ewe_kente_stripes,_Ghana.jpg#filelinks.

-

7. Textile Cone by Richard Ling, 2005. A Textile cone snail (Conus textile) at Cod Hole, Great Barrier Reef, Australia. Licensed under CC BY-SA 3.0. https://commons.wikimedia.org/wiki/File:Textile_cone.JPG.

-

8. Pediment of throne hall Phra Thinang Chakri Maha Prasat with emblem of Chakri dynasty, Grand Palace of Bangkok, Thailand, by Saad Akhtar. Licensed under CC BY-SA 3.0. https://commons.wikimedia.org/wiki/File:Bangkok-SA5.jpg.

-

9. Chaco Ancestral Pueblo bowl, found at Pueblo Alto, Chaco Canyon, New Mexico, from the 11th–13th centuries, image from the National Park Service. https://commons.wikimedia.org/wiki/File:Bowl_Chaco_Culture_NM_USA.jpg.

-

10. Quipu in the Museo Machu Picchu, Casa Concha, Cusco, by Pi3.124. Licensed under CC BY-SA 4.0. https://commons.wikimedia.org/wiki/File:Quipo_in_the_Museo_Machu_Picchu,_Casa_Concha,_Cusco.jpg.

-

10. Example of MNIST dataset numbers by Suvanjanprasai, 2023. Licensed under CC BY-SA 4.0. https://commons.wikimedia.org/wiki/File:MnistExamplesModified.png.

-

11. The Star-Nose Mole, c. 1826–1828, photo from New York Public Library. https://nypl.getarchive.net/media/the-star-nose-mole-end-of-the-nose-magnified-05cbe6.

+

0. Photo from A Million Random Digits with 100,000 Normal Deviates (RAND Corporation, 2001).

+

1. Marshall Islands Stick Chart by Jim Heaphy, on display at the Berkeley Art Museum and Pacific Film Archive. Licensed under CC BY-SA 3.0.

+

2. Calder, New Gallery, Charles Hayden Memorial Library, Massachusetts Institute of Technology, Cambridge, 1950, by Ezra Stoller; © Esto.

+

3. Gala by Bridget Riley, 1974; acrylic on canvas, 159.7 by 159.7 cm; © Bridget Riley 2023, all rights reserved.

+

4. Cloud chamber photograph of a positron passing through a lead plate by Carl D. Anderson, 1932.

+

5. Sixfinger threadfin school circling in a feeding pattern inside a cage off Hawaii from the U.S. National Oceanic and Atmospheric Administration (NOAA) photo library, Fisheries Collection, 2000.

+

6. Double living root bridge in East Khasi by Arshiya Urveeja Bose, 2011. Licensed under CC BY 2.0 DEED.

+

7. Ewe Kente Stripes, Ghana by ZSM, 2008. Licensed under CC BY-SA 3.0.

+

7. Textile Cone by Richard Ling, 2005. A Textile cone snail (Conus textile) at Cod Hole, Great Barrier Reef, Australia. Licensed under CC BY-SA 3.0.

+

8. Pediment of throne hall Phra Thinang Chakri Maha Prasat with emblem of Chakri dynasty, Grand Palace of Bangkok, Thailand, by Saad Akhtar. Licensed under CC BY-SA 3.0.

+

9. Chaco Ancestral Pueblo bowl, found at Pueblo Alto, Chaco Canyon, New Mexico, from the 11th–13th centuries, image from the National Park Service.

+

10. Quipu in the Museo Machu Picchu, Casa Concha, Cusco, by Pi3.124. Licensed under CC BY-SA 4.0.

+

10. Example of MNIST dataset numbers by Suvanjanprasai, 2023. Licensed under CC BY-SA 4.0.

+

11. The Star-Nose Mole, c. 1826–1828, photo from New York Public Library.