logo资料库

The-Nature-of-Code.pdf

第1页 / 共519页
第2页 / 共519页
第3页 / 共519页
第4页 / 共519页
第5页 / 共519页
第6页 / 共519页
第7页 / 共519页
第8页 / 共519页
资料共519页,剩余部分请下载后查看
The Nature of Code
Dedication
Acknowledgments
A.1 A little bit of history
A.2 Kickstarter
Preface
P.1 What is this book?
P.2 A word about Processing
P.3 What do you need to know?
P.4 What are you using to read this book?
P.5 The “story” of this book
Part I: Inanimate objects
Part II: It’s alive!
Part III: Intelligence
P.6 This book as a syllabus
P.7 The Ecosystem Project
P.8 Where do I find the code online and submit feedback?
Table of Contents
Introduction
I.1 Random Walks
I.2 The Random Walker Class
Pseudo-Random Numbers
Exercise I.1
I.3 Probability and Non-Uniform Distributions
Exercise I.2
Exercise I.3
I.4 A Normal Distribution of Random Numbers
Calculating Mean and Standard Deviation
Exercise I.4
Exercise I.5
I.5 A Custom Distribution of Random Numbers
Exercise I.6
I.6 Perlin Noise (A Smoother Approach)
Noise Detail
Mapping Noise
Exercise I.7
Two-Dimensional Noise
Exercise I.8
Exercise I.9
Exercise I.10
I.7 Onward
Chapter 1. Vectors
1.1 Vectors, You Complete Me
1.2 Vectors for Processing Programmers
1.3 Vector Addition
Exercise 1.1
Exercise 1.2
Exercise 1.3
1.4 More Vector Math
Vector subtraction
Basic Number Properties with Vectors
Vector multiplication
More Number Properties with Vectors
1.5 Vector Magnitude
1.6 Normalizing Vectors
1.7 Vector Motion: Velocity
1.8 Vector Motion: Acceleration
Acceleration Algorithms!
Exercise 1.4
Exercise 1.5
Exercise 1.6
1.9 Static vs. Non-Static Functions
Exercise 1.7
1.10 Interactivity with Acceleration
Exercise 1.8
The Ecosystem Project
Chapter 2. Forces
2.1 Forces and Newton’s Laws of Motion
Newton’s First Law
Newton’s Third Law
Newton’s Third Law (as seen through the eyes of Processing)
2.2 Forces and Processing—Newton’s Second Law as a Function
Newton’s Second Law
Weight vs. Mass
2.3 Force Accumulation
Exercise 2.1
2.4 Dealing with Mass
Units of Measurement
Exercise 2.2
2.5 Creating Forces
Exercise 2.3
2.6 Gravity on Earth and Modeling a Force
Dealing with formulae
2.7 Friction
Exercise 2.4
2.8 Air and Fluid Resistance
Exercise 2.5
Exercise 2.6
Exercise 2.7
2.9 Gravitational Attraction
Exercise 2.8
Exercise 2.9
2.10 Everything Attracts (or Repels) Everything
Exercise 2.10
The Ecosystem Project
Chapter 3. Oscillation
3.1 Angles
What is PI?
Exercise 3.1
3.2 Angular Motion
Exercise 3.2
3.3 Trigonometry
3.4 Pointing in the Direction of Movement
Exercise 3.3
3.5 Polar vs. Cartesian Coordinates
Exercise 3.4
Exercise 3.5
3.6 Oscillation Amplitude and Period
Exercise 3.6
3.7 Oscillation with Angular Velocity
Exercise 3.7
Exercise 3.8
3.8 Waves
Exercise 3.9
Exercise 3.10
Exercise 3.11
3.9 Trigonometry and Forces: The Pendulum
Exercise 3.12
Exercise 3.13
Exercise 3.14
3.10 Spring Forces
Exercise 3.15
Exercise 3.16
The Ecosystem Project
Chapter 4. Particle Systems
4.1 Why We Need Particle Systems
4.2 A Single Particle
Exercise 4.1
Exercise 4.2
4.3 The ArrayList
4.4 The Particle System Class
Exercise 4.3
Exercise 4.4
4.5 A System of Systems
Exercise 4.5
Exercise 4.6
4.6 Inheritance and Polymorphism: An Introduction
4.7 Inheritance Basics
4.8 Particles with Inheritance
Exercise 4.7
4.9 Polymorphism Basics
4.10 Particle Systems with Polymorphism
Exercise 4.8
4.11 Particle Systems with Forces
4.12 Particle Systems with Repellers
Exercise 4.9
Exercise 4.10
4.13 Image Textures and Additive Blending
Exercise 4.11
Exercise 4.12
Exercise 4.13
Exercise 4.14
The Ecosystem Project
Chapter 5. Physics Libraries
5.1 What Is Box2D and When Is It Useful?
5.2 Getting Box2D in Processing
5.3 Box2D Basics
SETUP
DRAW
Core elements of a Box2D world:
5.4 Living in a Box2D World
5.5 Building a Box2D Body
Step 1: Define a body.
Step 2: Configure the body definition.
Step 3: Create the body.
Step 4: Set any other conditions for the body’s starting state.
5.6 Three’s Company: Bodies and Shapes and Fixtures
Step 1: Define a shape.
Step 2: Create a fixture.
Step 3: Attach the shape to the body with the fixture.
Exercise 5.1
5.7 Box2D and Processing: Reunited and It Feels So Good
Step 1: Add Box2D to our main program (i.e. setup() and draw()).
Step 2: Link every Processing Box object with a Box2D Body object.
Exercise 5.2
5.8 Fixed Box2D Objects
5.9 A Curvy Boundary
Step 1: Define a body.
Step 2: Define the Shape.
Step 3: Configure the Shape.
Step 4: Attach the Shape to the body with a Fixture.
Exercise 5.3
5.10 Complex Forms
Exercise 5.4
Exercise 5.5
5.11 Feeling Attached—Box2D Joints
Exercise 5.6
Step 1: Make sure you have two bodies ready to go.
Step 2: Define the joint.
Step 3: Configure the joint’s properties.
Step 4: Create the joint.
Exercise 5.7
Exercise 5.8
Exercise 5.9
5.12 Bringing It All Back Home to Forces
Exercise 5.10
5.13 Collision Events
Step 1: Contact, could you tell me what two things collided?
Step 2: Fixtures, could you tell me which body you are attached to?
Step 3: Bodies, could you tell me which Particles you are associated with?
Exercise 5.11
Exercise 5.12
5.14 A Brief Interlude—Integration Methods
5.15 Verlet Physics with toxiclibs
Getting toxiclibs
Core Elements of VerletPhysics
Vectors with toxiclibs
Building the toxiclibs physics world
5.16 Particles and Springs in toxiclibs
5.17 Putting It All Together: A Simple Interactive Spring
5.18 Connected Systems, Part I: String
Exercise 5.13
5.19 Connected Systems, Part II: Force-Directed Graph
Exercise 5.14
Exercise 5.15
5.20 Attraction and Repulsion Behaviors
Exercise 5.16
Exercise 5.17
The Ecosystem Project
Chapter 6. Autonomous Agents
6.1 Forces from Within
6.2 Vehicles and Steering
Why Vehicle?
6.3 The Steering Force
Exercise 6.1
Exercise 6.2
Exercise 6.3
6.4 Arriving Behavior
6.5 Your Own Desires: Desired Velocity
Exercise 6.4
Exercise 6.5
6.6 Flow Fields
Exercise 6.6
Exercise 6.7
Exercise 6.8
6.7 The Dot Product
Exercise 6.9
6.8 Path Following
6.9 Path Following with Multiple Segments
Exercise 6.10
Exercise 6.11
6.10 Complex Systems
6.11 Group Behaviors (or: Let’s not run into each other)
Exercise 6.12
Exercise 6.13
6.12 Combinations
Exercise 6.14
6.13 Flocking
Exercise 6.15
Exercise 6.16
Exercise 6.17
Exercise 6.18
Exercise 6.19
6.14 Algorithmic Efficiency (or: Why does my $@(*%! run so slowly?)
6.15 A Few Last Notes: Optimization Tricks
1) Magnitude squared (or sometimes distance squared)
2) Sine and cosine lookup tables
3) Making gajillions of unnecessary PVector objects
Exercise 6.20
Exercise 6.21
The Ecosystem Project
Chapter 7. Cellular Automata
7.1 What Is a Cellular Automaton?
7.2 Elementary Cellular Automata
7.3 How to Program an Elementary CA
7.4 Drawing an Elementary CA
Exercise 7.1
Exercise 7.2
Exercise 7.3
Exercise 7.4
7.5 Wolfram Classification
Exercise 7.5
7.6 The Game of Life
7.7 Programming the Game of Life
Exercise 7.6
Exercise 7.7
Exercise 7.8
7.8 Object-Oriented Cells
7.9 Variations of Traditional CA
Exercise 7.9
Exercise 7.10
Exercise 7.11
Exercise 7.12
Exercise 7.13
Exercise 7.14
Exercise 7.15
The Ecosystem Project
Chapter 8. Fractals
8.1 What Is a Fractal?
8.2 Recursion
8.3 The Cantor Set with a Recursive Function
Exercise 8.1
8.4 The Koch Curve and the ArrayList Technique
The “Monster” Curve
Exercise 8.2
Exercise 8.3
Exercise 8.4
Exercise 8.5
8.5 Trees
Exercise 8.6
Exercise 8.7
Exercise 8.8
Exercise 8.9
Exercise 8.10
Exercise 8.11
8.6 L-systems
Exercise 8.12
Exercise 8.13
Exercise 8.14
The Ecosystem Project
Chapter 9. The Evolution of Code
9.1 Genetic Algorithms: Inspired by Actual Events
9.2 Why Use Genetic Algorithms?
Exercise 9.1
9.3 Darwinian Natural Selection
9.4 The Genetic Algorithm, Part I: Creating a Population
9.5 The Genetic Algorithm, Part II: Selection
9.6 The Genetic Algorithm, Part III: Reproduction
9.7 Code for Creating the Population
Step 1: Initialize Population
Step 2: Selection
Exercise 9.2
Exercise 9.3
Step 3: Reproduction
Exercise 9.4
Exercise 9.5
9.8 Genetic Algorithms: Putting It All Together
Exercise 9.6
9.9 Genetic Algorithms: Make Them Your Own
Key #1: Varying the variables
Key #2: The fitness function
Exercise 9.7
Key #3: Genotype and Phenotype
9.10 Evolving Forces: Smart Rockets
9.11 Smart Rockets: Putting It All Together
Exercise 9.8
Exercise 9.9
Exercise 9.10
Exercise 9.11
Exercise 9.12
9.12 Interactive Selection
Exercise 9.14
9.13 Ecosystem Simulation
Genotype and Phenotype
Selection and Reproduction
The Ecosystem Project
Chapter 10. Neural Networks
10.1 Artificial Neural Networks: Introduction and Application
10.2 The Perceptron
10.3 Simple Pattern Recognition Using a Perceptron
10.4 Coding the Perceptron
Exercise 10.1
Exercise 10.2
10.5 A Steering Perceptron
Exercise 10.3
Exercise 10.4
10.6 It’s a “Network,” Remember?
10.7 Neural Network Diagrams
10.8 Animating Feed Forward
Exercise 10.5
Exercise 10.6
Exercise 10.7
The Ecosystem Project
The end
Further Reading
Books
Papers and Articles
Index
The Nature of Code The Nature of Code by Daniel Shiffman The publisher would go here, but there isn’t one; it’s only me. version 1.0, generated December 6, 2012 i
The Nature of Code (v1.0) Dedication Dedication For my grandmother, Bella Manel Greenfield (October 13, 1915 - April 3, 2010) Bella Manel was born in New York City. A pioneering woman in mathematics, she earned her PhD in 1939 from New York University under the supervision of Richard Courant. She worked for Ramo-Wooldridge (now TRW) and at the Rand Corporation with Richard Bellman. Later, she taught mathematics at the College of Notre Dame (now Notre Dame de Namur University) in Belmont, California, and at UCLA. The Bella Manel Prize for outstanding graduate work by a woman or minority was established at NYU’s Courant Institute in 1995. ii
Dedication Copyright © 2012 by Daniel Shiffman ISBN-13: 978-0985930806 ISBN-10: 0985930802 This work is licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License. To view a copy of this license, visit creativecommons.org (http://creativecommons.org/licenses/by-nc/3.0/) or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California 94041, USA. All of the book’s source code is licensed under the GNU Lesser General Public License (http://creativecommons.org/licenses/LGPL/2.1/) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This book was generated by the Magic Book Project (http://magicbookproject.com). Editor Editor Illustrations Illustrations Cover Design Cover Design Interior Design Interior Design Web Site Design Web Site Design Editorial and Design Assistant Editorial and Design Assistant Magic Book Lead Developers Magic Book Lead Developers Magic Book Researchers Magic Book Researchers Index Index Shannon Fry Zannah Marsh David Wilson David Wilson Steve Klise Evan Emolo Rune Madsen, Steve Klise Evan Emolo, Miguel Bermudez, Luisa Peirera Hors WordCo Indexing Services iii
The Nature of Code (v1.0) Acknowledgments Acknowledgments "The world around us moves in complicated and wonderful ways. We spend the earlier parts of our lives learning about our environment through perception and interaction. We expect the physical world around us to behave consistently with our perceptual memory, e.g. if we drop a rock it will fall due to gravity, if a gust of wind blows, lighter objects will be tossed by the wind further. This class focuses on understanding, simulating, and incorporating motion-based elements of our physical world into the digital worlds that we create. Our hope is to create intuitive, rich, and more satisfying experiences by drawing from the perceptual memories of our users." — James Tu, Dynamic Bodies course description, Spring 2003, ITP iv
Acknowledgments A.1 A little bit of history A.1 A little bit of history In 2003, as a graduate student at the Interactive Telecommunications Program (ITP) in the Tisch School of the Arts at New York University, I enrolled in a course called Dynamic Bodies. The course was taught by interaction designer and ITP adjunct professor James Tu. At the time, my work was focused on a series of software experiments that generated real- time “non-photorealistic” imagery. The applications involved capturing images from a live source and “painting” the colors with elements that moved about the screen according to various rules. The Dynamic Bodies course—which covered vectors, forces, oscillations, particle systems, recursion, steering, and springs—aligned perfectly with my work. I had been using these concepts informally in my own projects, but had never taken the time to closely examine the science behind the algorithms or learn object-oriented techniques to formalize their implementation. That very semester, I also enrolled in Foundations of Generative Art Systems, a course taught by Philip Galanter, that focused on the theory and practice of generative art, covering topics such as chaos, cellular automata, genetic algorithms, neural networks, and fractals. Both Tu’s course and Galanter’s course opened my eyes to a world of simulation algorithms and techniques that carried me through the next several years of work and teaching, and served as the foundation and inspiration for this book. But there’s another piece of the puzzle missing from this story. Galanter’s course was mostly theory-based, while Tu’s was taught using Macromedia Director and the Lingo programming language. That semester, I learned many of the algorithms by translating them into C++ (the language I was using quite awkwardly at the time, well before C++ creative coding environments like openFrameworks and Cinder had arrived). Towards the end of the semester, I discovered something called Processing (http://www.processing.org). Processing was in alpha then (version 0055) and, having had some experience with Java, it intrigued me enough to ask the question: Could this open- source, artist-friendly programming language and environment be the right place to develop a suite of tutorials and examples about programming and simulation? With the support of the ITP and Processing communities, I embarked on what has now been an almost eight- year journey of teaching a variety of programming concepts and their applications using Processing. I’d like to first thank Red Burns, ITP’s founder, who has supported and encouraged me in my work for over ten years. Dan O’Sullivan, the chair of ITP, has been my teaching mentor and was the first to suggest that I try teaching a course on Processing, giving me a reason to start assembling programming tutorials in the first place. Shawn Van Every, developer extraordinaire and author of Pro Android Media, has also been a rich source of help and inspiration at ITP over the years. ITP faculty members Clay Shirky, Danny Rozin, Katherine Dillon, Marianne Petit, Marina Zurkow, and Tom Igoe have provided a great deal of support and feedback throughout the writing of this book. The rest of the faculty and staff at ITP have also made this possible: Brian Kim, Edward Gordon, George Agudow, John Duane, Marlon Evans, Matt Berger, Megan Demarest, Midori Yasuda, and Rob Ryan. v
The Nature of Code (v1.0) The students of ITP, 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 for five years. I have stacks of draft printouts of the book with notes scrawled along the margins as well as a vast archive of student emails with corrections, comments, and generous words of encouragement. I am also indebted to the energetic and supportive community of Processing programmers and artists. I wouldn’t be writing this book if it weren’t for Casey Reas and Ben Fry, who created Processing. I’ve learned half of what I know simply from reading through the Processing source code; the elegant simplicity of the Processing language, website, and IDE has made programming accessible and fun for all of my students. I’ve received advice and inspiration from many Processing programmers including Andrés Colubri, Jer Thorp, Marius Watz, Karsten Schmidt, Robert Hodgin, Seb-Lee Delisle, and Ira Greenberg. Heather Dewey- Hagborg provided a great deal of excellent feedback on Chapter 10 (Neural Networks) and Philip Galanter helped to clarify the definitions of complexity and complex systems. Scott Murray provided some really helpful advice about inline SVGs over e-mail. Many of the titles in the Further Reading section were suggested by Golan Levin. I am indebted to Shannon Fry, who edited this book every step of the way. The knowledge that I would always have her careful and thoughtful feedback on my writing allowed me to plow ahead, aware that everything would come out sounding better after she got her hands on my chapters. A special mention goes to Zannah Marsh who worked tirelessly to create over a hundred illustrations for this book, developing a friendly and informal look. I especially want to thank her for her patience and willingness to go with the flow as we changed the illustration requirements several times. I also want to thank David Wilson, who came to my rescue at the last minute and designed the interior layout and cover for the book. I am particularly grateful to Steve Klise, who designed and built the book’s website, helping me to develop a "pay what you want" model for the digital PDF. As I’ll explain a bit more in the preface, this book was generated with a new open-source system for publishing called “The Magic Book.” A crack team of ITP programmers, designers, and artists worked over the course of more than a year to develop this system, which generates a book in a variety of formats (PDF, HTML, and more) from one single ASCIIDOC file, all designed with CSS layout. Rune Madsen began the project and developed the original Ruby / Sinatra framework. I am pretty sure I’d still be struggling with putting the book together well into 2013 if it weren’t for Rune’s dedication to seeing the project through to the end. Steve Klise contributed countless bug fixes and engineered the system that allows us to restyle code comments to the side of the code blocks themselves. Miguel Bermudez, Evan Emolo, and Luisa Pereira Hors contributed in many ways, learning the ins and outs of ASCIIDOC as well as CSS Paged Media. ITP researcher Greg Borenstein provided a tremendous amount of advice and support along the way regarding the areas of publishing for the Web and print. Prince (http://princexml.com) is the engine the Magic Book uses to generate a PDF from an HTML document, and I’d like to thank Michael Day, CEO of PrinceXML, who answered many of our questions (at lightning speed) along the way. vi
Acknowledgments Finally I’d like to thank my family: my wife, Aliki Caloyeras, who supported this project throughout while having her own giant tome to write, and my children, Elias and Olympia, motivation for finishing this up so that I could spend more time hanging out with them. I’d also like to thank my father, Bernard Shiffman, who generously lent his mathematical expertise and provided feedback along the way, as well as my mother, Doris Yaffe Shiffman, and brother, Jonathan Shiffman, who were always tremendously supportive in asking the question: “How is the book coming along?” A.2 Kickstarter A.2 Kickstarter There is another organization and community that has made this book possible: Kickstarter. In 2008, I completed work on my first book, Learning Processing, published by Morgan Kaufmann/Elsevier. Learning Processing took almost three years to finish. I didn’t take a lot of care in choosing a publisher or thinking about the terms. I just thought — “Really? You want to publish a book by me? OK, I’ll do it.” Unfortunately, my experience was not entirely positive. I had five different editors assigned to me throughout the process, and I received little to no feedback on the content itself. The publisher outsourced the typesetting, which resulted in a great deal of mistakes and inconsistencies in production. In addition, I found the pricing of the book to be off the mark. My goal was to write a friendly, inexpensive (black and white), paperback introduction to programming in Processing, and the book ended up retailing for a "textbook" price of $50. Now, I want to emphasize that my publisher had good intentions. They honestly wanted to produce the best book possible, one that I would be happy with, that they would be happy with, and that readers would enjoy. And they worked hard to make this happen. Unfortunately, they had to work within a very tight budget, and as a result were stretched extremely thin. In addition, I don’t think they were terribly familiar with the world of open- source “creative” coding environments like Processing; their world is computer science textbooks. As a result, for this Nature of Code book, I felt it was important to try self-publishing. Since I didn’t get editing support from the publisher, why not hire an editor? I wasn’t happy with the pricing, so why not set the price myself (or, in the case of the PDF, let the buyer set the price)? Then there’s the question of marketing — does a publisher add value and help you reach an audience? In some cases, the answer is yes. The O’Reilly “Make” series, for example, does a wonderful job of creating a community around their books and products. Still, in the case of learning to program in Processing, reaching the audience is as simple as one URL — processing.org. Unfortunately, I quickly discovered that there is one thing a publisher offers that I was not getting from my self-publishing path. One very important, highly crucial detail — a deadline. On my own, I floundered for two years, saying I was going to write the Nature of Code book but only drafting a little bit here and there. On my list of things I needed to do, it was always at the bottom. Then along came Kickstarter, and with an audience sitting and waiting (and vii
The Nature of Code (v1.0) having spent cash money), I lived in fear of not meeting my deadline. And the fact that you are reading this now is an indication that it worked. Most importantly, self-publishing the book has allowed me a great deal of flexibility in how I price and distribute the content. On Elsevier’s website, you can purchase Learning Processing as an e-book for $53.95. That’s right, fifty-three dollars and ninety-five cents. Incidentally, for each e-book sold I get a royalty of 5%, which is $2.70. That’s right, two dollars and seventy cents. If I self-publish, I can make the book massively cheaper. Selling a digital copy for $10, I’m reducing the cost to the reader by over eighty percent and tripling the money paid to me. I’m taking this even further with the PDF and allowing buyers to set the price themselves. In addition, by owning all the content, I am able to release the entire book online for free as well as experiment with new digital formats. The raw text of the book, as well as all the code and illustrations, is licensed under a Creative Commons Attribution-NonCommercial license and is available on GitHub, where readers can submit issues (not to mention pull requests!) with corrections and comments. Finally, by using more flexible print-on-demand services, I can more easily make changes and keep the book current, releasing new editions as often as I like. (A one-time purchase of a digital copy of the book includes lifetime upgrades for free.) So thank you to Kickstarter, both the company (especially Fred Benenson, who convinced me to take the plunge in the first place and advised me on how to license the book) as well as all the backers who took a chance on this book. Some of these backers, through generosity beyond the call of duty, earned an extra thank-you as part of their reward: • Alexandre B. • Robert Hodgin • JooYoun Paek • Angela McNamee (Boyhan) • Bob Ippolito All of the backers directly contributed to the finishing of this book. Just the sheer act of signing up to contribute money for draft and final versions lit a fire in me to finish, not to mention provided me with the resources to pay for design and editing work (and some babysitting during Saturday morning writing sessions). In addition to contributing funds, Kickstarter backers read pre-release versions of the chapters and provided tons of feedback, catching many errors and pointing out confusing sections of the book. Two such readers that I’d like to thank are Frederik Vanhoutte and Hans de Wolf, whose expert knowledge of Newtonian physics was enormously helpful in the revising of Chapters 2 and 3. viii
分享到:
收藏