75488ffirs.indd 2 3/20/09 1:37:36 pmmedia.espora.org/.../algorithms_for_visual_design.pdfbook...

385

Upload: others

Post on 05-Jul-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

  • 75488ffirs.indd 2 3/20/09 1:37:36 PM

  • Algorithms for Visual Design Using the Processing Language

    75488ffirs.indd 1 3/20/09 1:37:36 PM

  • 75488ffirs.indd 2 3/20/09 1:37:36 PM

  • Algorithms for Visual Design Using the

    Processing Language

    Kostas Terzidis

    75488ffirs.indd 3 3/20/09 1:37:37 PM

  • Algorithms for Visual Design Using the Processing Language

    Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com

    Copyright © 2009 by Kostas Terzidis

    Published by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN: 978-0-470-37548-8

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    Library of Congress Cataloging-in-Publication Data is available from the publisher.

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appro-priate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

    Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representa-tions or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a par-ticular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disap-peared between when this work was written and when it is read.

    For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

    Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used with-out written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

    75488ffirs.indd 4 3/20/09 1:37:37 PM

    http://www.wiley.com

  • To my father, George

    75488ffirs.indd 5 3/20/09 1:37:37 PM

  • 75488ffirs.indd 6 3/20/09 1:37:37 PM

  • vii

    Kostas Terzidis is an associate professor at the Harvard Graduate School of Design. His current GSD courses are Kinetic Architecture, Algorithmic Architecture, Digital Media I & II, Cinematic Architecture, and Design Research Methods. He holds a PhD in Architecture from the University of Michigan (1994), a Masters of Architecture from Ohio State University (1989) and a Diploma of Engineering from the Aristotle University in Greece (1986). He is a registered architect in Europe where he has designed and built several commercial and residential buildings.

    His research work focuses on creative experimentation within the threshold between arts, architecture, and computer science. As a professional computer programmer, he is the author of many computer applications on form making, morphing, virtual reality, and self-organization. His most recent work is in the development of theories and techniques for algorithmic architecture. His book Expressive Form: A Conceptual Approach to Computational Design, published by London-based Spon Press (2003), offers a unique perspective on the use of computation as it relates to aesthetics, specifically in architecture and design. His latest book, Algorithmic Architecture, (Architectural Press/Elsevier, 2006), provides an ontological investigation into the terms, concepts, and processes of algorithmic architecture and provides a theoretical framework for design implementations.

    About the Author

    75488ffirs.indd 7 3/20/09 1:37:37 PM

  • 75488ffirs.indd 8 3/20/09 1:37:37 PM

  • ix

    Executive EditorCarol Long

    Senior Development EditorTom Dinse

    Production EditorAngela Smith

    Copy EditorFoxxe Editorial Services

    Editorial ManagerMary Beth Wakefield

    Production ManagerTim Tate

    Vice President and Executive Group PublisherRichard Swadley

    Vice President and Executive PublisherBarry Pruett

    Associate PublisherJim Minatel

    Project Coordinator, CoverLynsey Stanford

    CompositorCraig Johnson, Happenstance Type-O-Rama

    ProofreaderPublication Services, Inc.

    IndexerRobert Swanson

    Cover DesignerMichael Trent

    Cover Image© Kostas Terzidis

    Credits

    75488ffirs.indd 9 3/20/09 1:37:37 PM

  • 75488ffirs.indd 10 3/20/09 1:37:37 PM

  • xi

    This book was conceived as a first step towards open source development. I would like to thank the person who introduced me to the world of computer graphics back in 1986 at Ohio State University, Professor Chris Yessios. He gave me the knowledge and taught me the means of making my own tools to design and showed me how to share it with my colleagues.

    Also, I would like to thank my doctoral student at Harvard University Taro Narahara for his help in formatting the text and images of this book. Tom Dinse, Angela Smith, and Carol Long also deserve thanks for their patience and helpfulness during the preparation of this book.

    Acknowledgments

    75488ffirs.indd 11 3/20/09 1:37:37 PM

  • 75488ffirs.indd 12 3/20/09 1:37:38 PM

  • xiii

    Introduction xix

    Chapter 1 Elements of the Language 11.1 Operands and Operations 2

    1.1.1 Variable Types 21.1.2 Name Conventions 41.1.3 Arithmetic Operations 51.1.4 Logical and Relational Operations/Statements 71.1.5 Loops 81.1.6 Patterns of Numbers 10

    1.2 Graphics Elements 121.2.1 Code Structure 121.2.2 Draw Commands 131.2.3 Geometrical Objects 131.2.4 Attributes 171.2.5 Fonts and Images 201.2.6 Examples 21

    1.3 Interactivity 241.3.1 Drawing on the Screen 241.3.2 Mouse and Keyboard Events 26

    1.4 Grouping of Code 281.4.1 Arrays 281.4.2 Procedures and Functions 301.4.4 Recursion 331.4.5 Importing Processing Classes 34

    Summary 35Exercises 35

    Contents

    75488ftoc.indd 13 3/20/09 1:37:32 PM

  • xiv Contents

    Chapter 2 Points, Lines, and Shapes 412.1 Sine and Cosine Curves 422.2 Bezier Curve 472.3 Pointillist Images 482.4 Polygons 512.5 Equilateral Polygons 532.6 Responsive Polygons 542.7 Responsive Curve 56Summary 57Exercises 57

    Chapter 3 The Structure of Shapes 633.1 Introduction to Class Structures 63

    3.1.1 Defining a Class Called MyPoint 643.1.2 Adding Methods to a Class 66

    3.2 Organization of Classes 683.2.1 Class MyPoint 703.2.2 Class MySegment 703.2.3 Class MyShape 71

    3.3 Standard Transformations (move, rotate, scale) 743.4 Implementing Transformations 763.5 Creating Grids of Shapes 803.6 Class MyGroup 833.7 Selecting Objects 85Summary 90Exercises 91

    Chapter 4 Basics of Graphical User Interfaces 934.1 Basic GUI (Buttons) 944.2 Choice, Label, and TextField 984.3 Arranging GUI Objects on the Screen 994.4 Selecting Points, Segments, Shapes, or Groups 1024.5 Color Setup 1044.6 Putting the GUI Elements in Their Own Window 1064.7 Mouse Wheel Control 107Summary 107Exercises 108

    Chapter 5 Image Processing 1095.1 Displaying Images 1105.2 Preset Image Filters 1115.3 Bit Manipulation on Pixels 1155.4 A Paint Brush Tool 1185.5 Edge Detection 121Summary 123Exercises 123

    75488ftoc.indd 14 3/20/09 1:37:32 PM

  • Contents xv

    Chapter 6 Motion 1276.1 Animation Basics 1276.2 Erratic Motion 1316.3 Line Traces 1336.4 Interactive Transformations 1356.5 Double Buffering 1386.6 Motion and Friction 1406.7 Collision 1436.8 Elastic Motion 145Summary 149Exercises 149Notes 152

    Chapter 7 Advanced Graphics Algorithms 1537.1 Voronoi Tessellation 1547.2 Stochastic Search 1587.3 Fractals 1627.4 Interpolation/Extrapolation 1657.5 Cellular Automata 1687.6 Evolutionary Algorithm 172Summary 177Exercises 178Notes 180

    Chapter 8 3-D Space 1818.1 The Third Dimension 1828.2 Defining 3D Objects 1838.3 Projecting on the Screen 1878.4 Perspective Projection 1908.5 Three-Dimensional Graphics in Processing 1928.6 3D Point Formations 199

    8.6.1 Cubical Formations 1998.6.2 Spherical Formations 2018.6.3 Superquadrics 203

    Summary 205Exercises 206

    Chapter 9 Solid Geometry 2099.1 Class MyPoint 209

    9.1.1 Class MyFace 2119.1.2 Sets of Faces 2149.1.3 Class MySolid 2159.1.4 Face Visibility 220

    9.2 Shading 2239.2.1 Vectors 2259.2.2 Normalization 2269.2.3 Cross Product 227

    75488ftoc.indd 15 3/20/09 1:37:32 PM

  • xvi Contents

    9.2.4 Dot Product 2289.2.5 MyVector Class 2289.2.6 Color Tables 2299.2.7 Array of Shades 2309.2.8 Shade Calculation 2319.2.9 Class MyGroup 2349.2.10 Sorting Solids (Painter’s Algorithm) 238

    9.3 3D User Interaction 2409.3.1 Picking Objects in the Scene 2419.3.2 Simulating Menu Bars 244

    Summary 246Exercises 246Notes 247

    Chapter 10 File Read/Write 24910.1 File Formats 25010.2 Basic Write/Read in Processing 250

    10.2.1 Exporting PDF and DXF File Formats Using Processing Libraries 253

    10.2.2 Native File Write 25510.2.3 Native File Read 25610.2.4 The DXF File Format 25810.2.5 Writing DXF Files 25910.2.6 Reading DXF Files 26110.2.7 The VRML File Format 26310.2.8 Writing VRML Files 26510.2.9 Reading VRML Files 266

    10.3 Client/Server Data Transfer 268Summary 272Exercises 272

    Chapter 11 Physical Computing 27511.1 Basics of Electrical Circuits 27611.2 Arduino Microcontroller Board 27811.3 Arduino Language 27911.4 LED 28211.5 Photocell 28411.6 Pushbutton 28711.7 Servo Motor 28811.8 Sound 29011.9 Differential Values 29211.10 Responsive System: Photo-Sound 29211.11 A Feedback System: Photo-Motor 294Summary 296Exercises 296

    75488ftoc.indd 16 3/20/09 1:37:32 PM

  • Contents xvii

    Appendix A Equations of Lines and Planes 301

    Appendix B Answers to Exercises 307

    Appendix C Further Readings 335

    Index 339

    75488ftoc.indd 17 3/20/09 1:37:32 PM

  • 75488ftoc.indd 18 3/20/09 1:37:32 PM

  • xix

    How has design changed through the use of computers? Is it still valid to assume that a designer is in control of a design concept? What if there is a lack of pre-dictability over what was intended by the designer and what came out on the computer’s screen? Is computer programming necessary in design today?

    This book is about computer programming. Programming is a way of con-ceiving and embracing the unknown. At its best, programming goes beyond developing commercial applications. It becomes a way of exploring and map-ping other ways of thinking. It is the means by which one can simulate, extend, and experiment with principles, rules, and methods of traditionally human-defined theories. In developing computer programs, the programmer has to question how people think and how mental processes develop and to map them into different dimensions through the aid of computers. Computers should be acknowledged not only as machines for imitating and appropriating what is understood but also as vehicles for exploring and visualizing what is not (yet) understood. The entire sequence of specifying computer operations is similar (albeit not equal) to that of human thinking. When designing software, one is actually codifying processes of human thinking to a machine. The computer becomes a mirror of the human mind, and as such, reflects to a certain level our own way of thinking.

    However, there is an unraveling relationship between the needs of a designer and the ability of a specific computer application to address these needs. Designers rarely know what the computer is capable of providing them intel-lectually and often designers overestimate the computer’s capabilities. This can be attributed to at least two factors. First, designers are never really taught how to program (one should to look no further than the classic question/answer “What does computer programming have to do with design?”). In fact, in design

    Introduction

    75488flast.indd 19 3/20/09 1:49:26 PM

  • xx Introduction

    schools today students are taught how to use CAD tools and how to experiment within the limits of the applications, but they are never taught how to channel their creativity through the language, structure, and philosophy of program-ming. Second, CAD developers rarely release source code. They may ask the users what they want, they may offer interfaces for customization, but they will never give access to their source code. For good reasons, code is proprietary information, and information is power. So, if a designer wants to experiment with the computational design, then he or she will need to write his or her own application, including the modeling, interface, display, optimization, and debugging modules, all on their own. How many people either have the time or the know-how to do this out there? When are we going to see a Linux-like CAD system? When are we going to see a community of designers-architects-programmers sharing common source code, for their own advancement?

    It is possible to claim that a designer’s creativity is limited by the very pro-grams that are supposed to free their imagination. The motto “form follows software” is indeed a contemporary Whorfian hypothesis that still applies not only to language as a tool but also to computer tools. The reason for that is that there is a finite amount of ideas that a brain can imagine or produce by using a CAD application. If designers don’t find the tool/icon that they want, then they are simply stuck. And, conversely, whenever they use a new tool provided for them by programmers, they think that they are now able to do something new and “cool.” But are they really doing anything new? Or are they simply replicating a process already conceived by the programmer who provided the tool? Of course, if designers knew the processes, principles, and methods of the program behind the tool, then they would be empowered to always keep expanding their knowledge and scholarship by always devising solutions not tackled by anybody else. By using a conventional program, and always relying on its design possibilities, the designer/architect’s work is sooner or later at risk of being imitated, controlled, or manipulated by CAD solutions. By clut-tering the field with imitations of a type of particular software, one runs the risk of being associated not with cutting-edge research but with a mannerism of style.

    In this context, there are many designers claiming to use the computer to design. But are they really creating a new design? Or are they just rearrang-ing existing information within a domain set by the programmers? If it is the programmer who is considering all possible solutions to a design environ-ment beforehand, who is really setting the parameters and the outcome of a design solution? We saw already the I-Generation (Internet-Generation) risen out of the information age. When are we going to see the C-Generation (Code-Generation) — the generation of truly creative designers who can take their fate into their own hands?

    75488flast.indd 20 3/20/09 1:49:26 PM

  • Introduction xxi

    In the world of design today, computer programs have taken over many tra-ditionally human intellectual tasks, leaving less and less tasks for traditional designers to do. From Photoshop filters to modeling applications, and from simulation programs to virtual reality animation, and even more mundane tasks that used to need a certain talent to take on, such as rendering, paper cut-ting, or sculpting, the list of tasks diminishes day by day only to be replaced by their computational counterparts. What used to be a basis to judge somebody as a talent or a genius is no longer applicable. Dexterity, adeptness, memoriza-tion, fast calculation, and aptitude are no longer skills to seek for, nor are they reasons to admire a designer as a “genius.” The focus has shifted far away from what it used to be toward new territories. Computational tools allow not only manual, tedious, and repetitive tasks to be done quicker, cheaper, and more efficiently but also intellectual tasks that require intelligence, thought, and deci-sion making. In the process, many take advantage of the ephemeral awe that the new computational tools bring to design, either manual or intellectual, by using them as means to establish a new concept, style, or form — only to have it revealed later that their power was based on the tool they used and not on their own intellectual ability. Of course, the tool that was used was indeed developed by somebody else, that is, a programmer, who discovered the tool’s concept, mechanism, and implementation, and should, perhaps, be considered instead as the true innovator.

    As a result of the use, misuse, and, often, abuse of computational design tools, many have started to worry about the direction that design may take in the next few years. As, one by one, all design tasks are becoming computational, some regard this as a danger, misfortune, or misappropriation of what design should be and yet, others regard it as a liberation, freedom, and power towards what design should be: conceptualization. According to the latter, the designer does not need to worry anymore about the mundane, tedious, or redundant tasks in the design process, such as construction documents, schedules, databases, modeling, rendering, animation, and so forth and can now concentrate on what is most important: the concept. But what if that is also replaced? What if one day a new piece of software appears that allows one to input the building pro-gram and then produces valid designs, that is, a plan, elevation, and sections that work? And, worse, what if they are better than the designer would have ever done by himself or herself? (Even though most designers would never admit publicly that something is better than what they would have designed, yet what if deep inside they would admit it?) What then? Are we still going to continue demonizing the computer and seeking to promote geniuses when they probably don’t exist?

    If that ever happens, then obviously the focus of design will not be in the process itself, since that can be replaced, but rather in the replacement operation

    75488flast.indd 21 3/20/09 1:49:26 PM

  • xxii Introduction

    itself. The new designer will construct the tool that will enable one to design in an indirect meta-design way. As the current condition indicates, the original design is laid out in the computer program that addresses the issues, not in the mind of the user. If the tool maker and the tool user is the same person, then intention and randomness can coexist within the same system and the gap can be bridged. Maybe, then, the solution to this paradox may not be found inside or outside the designer’s mind but perhaps in the link that connects the two.

    Overview of the Book and Technology

    This book offers students, programmers, and researchers the technical, theo-retical, and design means to develop computer code that will allow them to experiment with design problems for which a solution is possible or for those for which it is not. The first type of problem is straightforward, where the methodology is to create an algorithm that will solve the problem in a series of steps. It is about the codification of ideas that are preconceived in the mind of the designer and await a way to manifest them in a physical form. Sample cases are given that address various problems such as geometrical, topological, represen-tational, numerical, and so forth. In contrast, there is another set of problems, in which a solution is not preconceived, or even known. This book offers a series of procedures that can function as building blocks for designers to experi-ment, explore, or channel their thoughts, ideas, and principles into potential solutions. The computer language used in this book is a new, fascinating, and easy-to-use language called Processing, and it has been used quite extensively in the visual arts over the last few years. Although this book offers a quick and concise introduction to the language itself, the core of the book focuses on the development of algorithms that can enhance the structure and strategy of the design process. These algorithms and techniques are quite advanced and not only offer the means to construct new design tools but also function as a way of understanding the complexity involved in today’s design problems. Such algorithms include Voronoi tessellation, stochastic search, morphing, cellular automata, and evolutionary algorithms.

    How This Book Is Organized

    This book is divided into 11 chapters. It is assumed that the reader of the book has no previous knowledge of programming. Nevertheless, the topics of each chapter are organized so that successive chapters contain progressively more complex topics that are based on the previous chapters. Each chapter covers a

    75488flast.indd 22 3/20/09 1:49:26 PM

  • Introduction xxiii

    discrete topic that allows you to build your knowledge not only by reading the chapters but also by applying the knowledge through relevant exercises.

    This book introduces basic structures and processes of programming in Processing in order to clarify and illustrate some of the mechanisms, relation-ships, and connections behind the forms generated. This is not intended to be an exhaustive introduction to programming but rather an indication of the potential and a point of reference for assessing the value of algorithms.

    Chapter 1■■ is a general introduction to the elements, operands, and opera-tions of the Processing language. It covers basic concepts such as vari-ables, arithmetic and logical operations, loops, arrays, and procedures. It also shows how to create basic geometry, how to affect their attributes, and how to interact with them. A series of exercises allows the reader to explore and test more possibilities.

    Chapter 2■■ shows how to use points in order to construct curves or images, and how to use lines to construct shapes. It uses trigonometric functions as well as polynomials to determine the positions of points along a curve. Shapes are constructed by using trigonometric functions to place points along a circumference establishing equilateral polygons.

    Chapter 3■■ introduces the concept of class and how classes can be used to organize code in hierarchical entities. This chapter introduces the classes of a point, a segment, a shape, and then a group. Each class contains methods that allow it to interact with other classes in a complementary, hierarchical, and object-oriented way. The advantage of this methodology is speed, organization, and interaction that allows objects or their subparts to be selected, modified, or deleted.

    Chapter 4■■ introduces basic elements of a graphic user interface (GUI) such as buttons, choice menus, labels, and text fields. The objective is first to arrange them in the screen to provide an interactive environment, but more importantly to connect them with the classes introduced in Chapter 3. In such a way, the graphical user interface elements can determine the position, orientation, and size of geometrical entities such as vertices, edges, faces, or groups as well as their color.

    Chapter 5■■ shows you how to process images. An image is a collection of colored pixels and can be changed by the application of certain func-tions that affect the color of specific pixels or their neighboring pixels. Grayscale, threshold, inversion, blur, or poster are some of the many image processing filters. However, you will look further into the structure of a pixel and see how it is represented in the computer’s memory and then use this information to speed up the process so as to produce any possible filter. You will also look into interactive paint brushes and edge detection.

    75488flast.indd 23 3/20/09 1:49:26 PM

  • xxiv Introduction

    Chapter 6■■ is about motion. Motion is simply a visual phenomenon based on the speedy redraw of the screen. You will see how to produce motion using images or geometrical objects, how to constrain the motion within boundaries, and how to affect the direction or position of motion. You are introduced to the use of transformation operations and how they can be used to produce repetitive, recursive, or random patterns. Finally, you look into physics-based motion showing how to use friction, collision, and elasticity.

    Chapter 7■■ is a collection of advanced graphics algorithms that can be used as techniques for design projects. These algorithms include Voronoi tessellation, stochastic search, fractals, hybridization, cellular automata, and evolutionary algorithms. Voronoi tessellation is shown as a method of subdividing the screen into multiple areas using pixels as finite ele-ments. Stochastic search is a method of random search in space until a given or an optimum condition is met. Fractals are recursive patterns that subdivide an initial base shape into subelements and then repeat the process infinitely. Hybridization is a procedure in which an object changes its shape in order to obtain another form. Cellular automata are discrete elements that are affected by their neighboring elements’ changes. Finally, evolutionary algorithms use biological Darwinian selection to optimize or solve a problem. Even though they are abstract, these algorithms have been used quite extensively to address or solve design problems and can function as metaphors or inspiration for similar design projects.

    Chapter 8■■ introduces you to the concept of 3D space in the context of geometry. This is done through projections and transformation of three-dimensional points into two-dimensional viewing screens. Single or multiple objects can be viewed either statically or dynamically by rotat-ing the scene. Formations of multiple objects are being studied as grids in space, spheres, or superquadrics.

    Chapter 9■■ introduces basic concepts of solid geometry using the class structures introduced earlier in Chapter 3. Here you are introduced to classes for a point, a face, a solid, and a group. Each class contains the appropriate methods that allow it to interact with the other classes. Specifically, faces are arranged to form extruded polygons and then checked for visibility. Shading of faces is also introduced using vector geometry. Finally, objects or subelements can be selected and transformed in a user interactive environment.

    Chapter 10■■ shows you the structure of files and how they can be used to save information or to input new information to a design project. You will cover basic file read and write operations and then look into the structure of universal file formats such as PDF, MOV, DXF, and VRML.

    75488flast.indd 24 3/20/09 1:49:26 PM

  • Introduction xxv

    These will be used to interchange information between Processing and other applications, such as Acrobat, AutoCAD, Rhino, QuickTime, and so forth. The purpose is to take advantage of each application’s tools and use them to enhance the initial processing form, or conversely, to input an application’s file into Processing for further enhancements. You will also be introduced to client-server data transfer as a means of connecting to remote servers.

    Chapter 11■■ shows you how to use Processing to produce physical motion in the environment. This will be done through electrical circuits and devices, such as photocells, motors, buttons, speakers, LEDs, and the like. You see how to process information coming in the computer and how to output information to the external physical world. You will be using a microcontroller called Arduino, which uses a computer language based on Processing. You will also see how input and output information can be connected in responsive and feedback systems and how this can be useful in a design or installation context.

    Each chapter, apart from its theoretical and technical dimension, also contains a series of exercises that are meant to help the reader understand and explore possibilities beyond the chapter’s content. For each exercise a solution is given in Appendix B so that the reader can try and then compare solutions.

    Who Should Read This Book

    This book is aimed mainly at students (design, art, computation, architecture, etc.) and professionals (web developers, software developers, designers, archi-tects, computer scientists). Since it addresses both a computer language and advanced algorithms, it can be seen as a textbook or a manual as well as a reference book.

    From my experience as a professor and a software developer, there are many students, instructors, developers, and regular folks that cannot find a book that will teach them graphics software development in a simple, no-prerequisite, hands-on manner. Most of these people are ready to start writing software, and they are waiting for the chance. This book does it in a great and efficient way taking you much further than any other book.

    Tools You Will Need

    The language used in the book is Processing, an open source, free-of-charge, powerful, and yet simple computer language that can be downloaded from the Internet. The version of Processing used in this book is the latest at this time,

    75488flast.indd 25 3/20/09 1:49:26 PM

  • xxvi Introduction

    that is, version 1. You should also know that Processing is based on another language called Java, which is also available free of charge from the Internet. In the last chapter of this book, a physical device is introduced called Arduino that also uses a version of the Processing language called, appropriately enough, Arduino. The version used in this book is Arduino 0012.

    What’s on the Web Site

    All code shown in this book together with the exercises can be found at the book’s web site at www.wiley.com.

    From Here

    One of the main objectives of this book, compared to other computer graphics books, is to take away the fear of complexity or the assumption of prerequisites that most books have. There is a large audience of computer graphics–thirsty readers that simply cannot understand existing books because either they are full of mathematical formulas or assume that the reader already knows the basics. As a computer scientist and designer-architect, I have developed this book with this in mind. In addition, my experience with teaching computer graphics programming to design-oriented students with no programming expe-rience guided me as well. The book is a bridge between the creative designer and the computer savvy.

    75488flast.indd 26 3/20/09 1:49:26 PM

  • Algorithms for Visual Design Using the Processing Language

    75488flast.indd 27 3/20/09 1:49:26 PM

  • 75488flast.indd 28 3/20/09 1:49:27 PM

  • 1

    Processing is a computer language originally conceived by Ben Fry and Casey Reas, students at the time (2001) at MIT. Their objective was to develop a simple language for use by designers and artists so that they could experiment without needing an extensive knowledge of computer programming. They began with Java, a popular computer language at that time, yet quite complicated for non-computer-science programmers, and developed a set of simpler commands and scripts. They also developed an editor so that typing, compiling, and execut-ing code could be integrated. Specifically, the compiler used (called jikes) is for the Java language, so any statement in Java can also be included within the Processing language and will be consequently compiled.

    Some of the characteristics of Processing (and Java) language are:

    Multi-platform:■■ Any program runs on Windows, Mac OS, or Linux.

    Secure:■■ Allows high-level cryptography for the exchange of important private information.

    Network-centric:■■ Applications can be built around the internet protocols.

    Dynamic:■■ Allows dynamic memory allocation and memory garbage collection.

    International:■■ Supports international characters.

    C h a p t e r

    1

    Elements of the Language

    75488c01.indd 1 3/22/09 5:42:19 PM

  • 2 Chapter 1 ■ Elements of the Language

    Performance:■■ Provides high performance with just-in-time compiles and optimizers.

    Simplicity:■■ Processing is easier to learn than other languages such as a C, C++, or even Java.

    The basic linguistic elements used in Processing are constants, variables, procedures, classes, and libraries, and the basic operations are arithmetical, logi-cal, combinatorial, relational, and classificatory arranged under specific gram-matical and syntactical rules. These elements and operations are designed to address the numerical nature of computers, while at the same time providing the means to compose logical patterns. Thus, it can be claimed that the Processing language assumes that a design can be generated through the manipulation of arithmetic and logical patterns and yet may have meaning attributed to it as a result of these manipulations.

    The following sections examine basic structures and processes in Processing as they relate to graphics in two dimensions (2D) and three dimensions (3D). This is not intended to be an exhaustive introduction to Processing but rather an introduction to the elements and processes used in the context of 2D and 3D graphics. We will start with basic elements and processes, give examples, and then move into more complex topics.

    1.1 Operands and Operations

    The basic structure of a computer language involves operations performed with elements called operands. The operands are basic elements of the language, such as variables, names, or numbers and the operations involve basic arithmetic and logical ones such as addition, multiplication, equality, or inequality. The next section introduces the basic operands and operations used in Processing and their corresponding syntax.

    1.1.1 Variable TypesVariables are used to hold data values. Variables can be of different types: if they hold whole numbers, they are called integer variables; if they hold true/false data, they are called booleans; if they hold fractional numbers they are called float, etc. In Processing, as well as in most computer languages, the syntax for declaring a variable is:

    type name

    For instance:

    int myAge = 35

    75488c01.indd 2 3/22/09 5:42:19 PM

  • Chapter 1 ■ Elements of the Language 3

    declares an integer variable called myAge. Depending on the type of data you want to store, you might use different variable types:

    boolean■■ , which is 1-bit long and can take values of either true or false:

    boolean isInside = false;

    char■■ , which is 16-bit long and therefore can store 216 (= 65,536) different characters (assuming that each character corresponds to one number, which is its ASCII code):

    char firstLetter = ‘A’;

    byte■■ , which is an 8-bit element and therefore can store 28 (= 256) different binary patterns:

    byte b = 20;

    int■■ , which is 32 bits long, can define integer (whole) numbers:

    int number_of_squares = 25;

    float■■ , which is 32 bits long, can define real numbers:

    double pi = 3.14159;

    color■■ , which is a group of three numbers that defines a color using red, green, and blue. Each number is between 0 and 255:

    color c = color(255, 0, 0);

    String■■ , which is a collection of characters used for words and phrases:

    String myName = “Tony”;

    Be aware that a string is defined as characters within double quotation marks. It is different from char where we use single quotation marks.

    Table 1-1 lists the variable types and their characteristics.

    Table 1-1: Variable Types

    TypE SizE DESCripTion

    boolean 1 bit True or false

    char 16-bits Keyboard characters

    byte 8 bits or 1 byte 0–255 numbers

    int 32 bits Integer numbers

    float 32 bits Real fractional numbers

    color 4 bytes or 32 bytes Red, Green, Blue, and Transparency

    String 64 bits Set of characters that form words

    75488c01.indd 3 3/22/09 5:42:19 PM

  • 4 Chapter 1 ■ Elements of the Language

    1.1.1.1 Cast

    A variable of one type can be cast (i.e., converted) to another type. For example:

    float dist = 3.5;

    int x = int(dist);

    Here the value of the float variable dist can be cast to an integer x. After the casting, x will be 3 (i.e., the fractional or decimal part is omitted). The following command allows casting between different types:

    boolean(), int(), float(), str(), byte().

    For example:

    float dist = 3.5;

    String s = str(dist);

    will create the string value “3.5” (not the float number 3.5).

    1.1.2 Name ConventionsWhen you declare a variable (which is a made up name) you also need to tell what type it is and (if necessary) to give it an initial value. You use the following format:

    type name = value;

    For example:

    int myAge = 35;

    declares an integer variable called myAge and assigns to it the data value 35, which is a whole number. All data types, if no initial value is given, default to 0. Booleans default to false and strings to “” (empty).

    You choose a variable’s name and, for the sake of readable code, it should make sense in the context of a problem. If you declare a variable that holds names, you should call it names or newNames, or something that makes sense given the context. Variables usually start with lower case, and when you want to composite more than one word, you use upper case for the next word. This is also referred to as intercapping. For example:

    names or newNames or newPeopleNames

    warning A name cannot start with a number, contain an empty space or contain any special characters except the underscore. For example, 1thing, x-y, and the plan are invalid names, but thing1, x_y, and the_plan are valid names.

    75488c01.indd 4 3/22/09 5:42:20 PM

  • Chapter 1 ■ Elements of the Language 5

    Booleans usually start with the prefix “is” For example:

    isLightOn or isItRaining

    As an example of initializing variables and data, let’s define information about a circle. The following types, variables, and initializations can be used:

    String name = “MyCircle”;

    int location_x = 22;

    int location_y = 56;

    float radius = 4.5;

    boolean isNurbs = false;

    In this case, we define information about a circle, that is, its name, its x and y pixel location on the screen (integer numbers), its radius, and an indication of its method of construction.

    1.1.3 Arithmetic OperationsAll the basic arithmetic operations, such as addition, subtraction, multipli-cation, and division are available in Processing using the symbols shown in Table 1-2.

    Table 1-2: Arithmetic Operations

    opEraTor USE DESCripTion

    + op1 + op2 Adds op1 and op2

    - op1 - op2 Subtracts op2 from op1

    * op1 * op2 Multiplies op1 by op2

    / op1 / op2 Divides op1 by op2

    % op1 % op2 Computes the remainder of dividing op1 by op2

    For example, to get the sum of two numbers, you can write:

    int sum; // not initialized because we do not know how much

    sum = 5 + 6; // now sum is 11

    Note that the addition operation occurs on the right side of the equal sign, and the result is assigned to the variable on the left side of the equal sign. This is always the case for operations, and it may seem odd, as it uses the opposite syntax to the statement 1 + 1 = 2. Note also the two slashes. They represent comments. Anything after // is ignored by Processing until the end of the line.

    75488c01.indd 5 3/22/09 5:42:20 PM

  • 6 Chapter 1 ■ Elements of the Language

    Therefore, // is for one-line comments. If you want to write multiline comments, use /* to start and */ to end. For example:

    /* this statement is ignored

    by processing even though I change

    lines

    */

    // this is ignored until the end of the line

    The multiplication symbol is *, and the division is /. For example:

    float result;

    result = 0.5 + 35.2 / 29.1; //this may be ambiguous

    Since the result of this operation may seem ambiguous, you can use paren-theses to define the parts of the formula to be executed first:

    result = (0.5 + 35.2) / 29.1;

    This is obviously different from:

    result = 0.5 + (35.2 / 29.1);

    However, there is a priority to the various symbols — if you can remember it, then you do not need to use parentheses. The sequence in which the opera-tions will be executed follows this order: (,),*, /, %, +, -, as shown in Table 1-3.

    Table 1-3: Precedence Operations Execution

    TypE SymboL

    postfix operators ( )

    multiplicative * / %

    additive + -

    Finally, one useful operation is the remainder (%) operation. It is the remain-der of the division of two numbers. Note that a remainder is always less than the divisor:

    int moduloResult;

    moduloResult = 10 % 2; //the result is 0

    moduloResult = 9 % 2; //the result is 1

    Processing provides convenient shortcuts for all of the arithmetic operations. For instance, x+=1 is equivalent to x = x + 1 or y/=z is equivalent to y = y / z. These shortcuts are summarized in Table 1-4.

    75488c01.indd 6 3/22/09 5:42:20 PM

  • Chapter 1 ■ Elements of the Language 7

    Table 1-4: Equivalent Operations

    opEraTor USE EqUivaLEnT To

    += op1 += op2 op1 = op1 + op2

    -= op1 -= op2 op1 = op1 - op2

    *= op1 *= op2 op1 = op1 * op2

    /= op1 /= op2 op1 = op1 / op2

    %= op1 %= op2 op1 = op1 % op2

    1.1.4 Logical and Relational Operations/StatementsLogical operations define the truthfulness of a conditional statement. Logical operations are tested with the word if, which represents a guess needed to be tested. In Processing, if statements have the following format:

    if( condition )

    …;

    else

    …;

    The conditions can be one of the following: equal, not equal, greater, or smaller. These conditions are represented by the following symbols:

    if(a==b) // if a is equal to b

    if(a!=b) // if a is not equal to b

    if(a>b) // if a is greater than to b

    if(a>=b) // if a is greater than or equal to b

    if(ac) //if a is greater than b and a is greater than c

    if(a>b || a >c) //if a is greater than b or a is greater than c

    Here is an example of a conditional statement:

    String userName = “Kostas”;

    boolean itsMe;

    if( username == “Kostas”) {

    itsMe = true;

    }

    75488c01.indd 7 3/22/09 5:42:20 PM

  • 8 Chapter 1 ■ Elements of the Language

    else {

    itsMe = false;

    }

    Note that the left and right curly brackets ({) and (}) are used to group sets of statements. If there is only one statement, we can omit the curly brackets, as in:

    if( username == “Kostas”)

    itsMe = true;

    else

    itsMe = false;

    Also, note that the semicolon (;) at the end of each statement indicates the end of the statement. Table 1-5 lists and describes the basic logical and relational operations.

    Table 1-5: Logical Operators

    opEraTor USE rETUrnS TrUE if

    > op1 > op2 op1 is greater than op2

    >= op1 >= op2 op1 is greater than or equal to op2

    < op1 < op2 op1 is less than op2

  • Chapter 1 ■ Elements of the Language 9

    The start condition is the initial number to start counting. The end condition is the number to end the counting. The modification step is the pace of repetition. For example, a loop from 0 to 9 is:

    for(int i=0; i

  • 10 Chapter 1 ■ Elements of the Language

    expression and executing its block until the expression returns false. For exam-ple, in the loop:

    int i=0;

    while(i

  • Chapter 1 ■ Elements of the Language 11

    Table 1-7: Repetition Patterns

    formULa rESULT

    x = i/3; 00011122233344455566

    x = i/4; 00001111222233334444

    x = ($i+1)/2; 011223344556677889910

    x = ($i+2)/2; 1122334455667788991010

    x = i%2; 01010101010101010101

    x = i%3; 01201201201201201201

    x = i%4; 01230123012301230123

    x = (i+1)%4; 12301230123012301230

    x = (i+2)%4; 23012301230123012301

    x = (i/2)%2; 00110011001100110011

    x = (i/3)%2; 00011100011100011100

    x = (i/4)%2; 00112233001122330011

    These patterns can be classified into three categories. Consider the three columns in Table 1-8: In the left column are division operations, in the right column are modulo operations. The middle column includes the combination of division and modulo operators. Note that divisions result in double, triple, quadruple, etc. repetitions of the counter i. In contrast, modulo operations result in repetition of the counter i as long as it is less than the divisor. Also, notice that the addition (or subtraction) of units to the variable i results in a shift left (or right) of the resulting sequences (column 1 and 2, row 4 and 5).

    Table 1-8: Pattern Classification

    DiviSion opEraTionS CombinaTion moDULo opEraTionS

    for(int i=0; i

  • 12 Chapter 1 ■ Elements of the Language

    DiviSion opEraTionS CombinaTion moDULo opEraTionS

    for(int i=0; i

  • Chapter 1 ■ Elements of the Language 13

    The word void means that the procedure does not return any value back, that is, it returns void. The word setup() is the name of the default “setup” section, and the parentheses are there in case you need to insert parameters for processing; here they are empty, that is, (). The curly brackets { and } denote the beginning and end of the process and normally should include the com-mands to be executed.

    1.2.2 Draw CommandsThe draw() command contains almost all geometrical, type, and image com-mands with their corresponding attributes. The coordinate system of the screen (shown in Figure 1-1) is anchored on the upper-left corner with the x-axis extend-ing horizontally from left to right, the y-axis extending vertically from top to bottom, and the z-axis (for 3D purposes) extending perpendicular to the screen towards the user.

    (0,0) +x

    +y+y

    (0,0,0)

    +x+z

    figure 1-1: A two- and three-dimensional coordinate system used by Processing

    1.2.3 Geometrical ObjectsThe main geometrical objects are:

    point() ■■ makes a point (i.e., a dot). It takes two integer numbers to spec-ify the location’s coordinates, starting from the upper-left corner. For example:

    point(20,30);

    75488c01.indd 13 3/22/09 5:42:21 PM

  • 14 Chapter 1 ■ Elements of the Language

    will draw a point at the following location: 20 pixels right and 30 pixels below the upper left corner of the window, as shown in Figure 1-2.

    figure 1-2: A point

    line() ■■ draws a line segment between two points. It takes four inte-ger numbers to specify the beginning and end point coordinates. For example,

    line(20,30,50,60);

    will draw a line segment from point 20,30 to point 50,60 (shown in Figure 1-3).

    figure 1-3: A line

    And

    line(20,30,20,50);

    line(10,40,30,40);

    will draw a cross at location 20,40 (see Figure 1-4).

    figure 1-4: Two lines in the form of a cross

    rect() ■■ draws a rectangle. It takes as parameters four integers to specify the x and y coordinates of the starting point and the width and height of the rectangle. For example:

    rect(30,30,50,20);

    75488c01.indd 14 3/22/09 5:42:21 PM

  • Chapter 1 ■ Elements of the Language 15

    will draw a rectangle at location 30,30 (i.e., the coordinates of the rectangle’s upper-left corner), as shown in Figure 1-5, with a width of 50 pixels and height of 20 pixels. If the command rectMode(CENTER) precedes the rect() command, then the first two coordinates (i.e., 30 and 30) refer to the center of the rectangle, not its upper-left corner.

    figure 1-5: A rectangle

    ellipse()■■ draws an ellipse. It takes four integers to specify the center point and the width and height. For example:

    ellipse(30,30,50,20);

    will draw an ellipse (shown in Figure 1-6) at location 30,30 (center point) with a width of 50 pixels and height of 20 pixels (also the dimensions of a bounding box to the ellipse).

    figure 1-6: An ellipse

    arc()■■ draws an arc. It takes four integers to specify the center point and the width and height of the bounding box and two float numbers to indi-cate the beginning and end angle in radians. For example,

    arc(50,50,70,70,0,PI/2);

    will draw an arc at location 50,50 (center point) with a width of 70 pixels and height of 70 pixels (bounding box) with an angle from 0 to p/2 degrees, as shown in Figure 1-7. Notice that angle is drawn in a clockwise direction.

    figure 1-7: An arc

    75488c01.indd 15 3/22/09 5:42:21 PM

  • 16 Chapter 1 ■ Elements of the Language

    The syntax of the parameters is arc(x,y,width,height,start,end).

    curve()■■ draws a curve between two points. It takes as parameters the coordinates of the two points and their anchors. For example:

    noFill();

    curve(20,80,20,20,80,20,80,80);

    curve(20,20,80,20,80,80,20,80);

    curve(80,20,80,80,20,80,20,20);

    will produce Figure 1-8.

    figure 1-8: A curve

    The syntax of the parameters is:

    curve(first anchor x, first anchor y, first point x, first point y,

    second point x, second point y, second anchor x, second anchor y)

    bezier()■■ draws a Bezier curve between two points, as shown in Figure 1-9. It takes as parameters the coordinates of the two points and their anchors. For example:

    noFill();

    bezier(20,80,20,20,80,20,80,80);

    figure 1-9: A Bezier curve

    The syntax of the parameters is:

    bezier(first anchor x,first anchor y,first point x,first point y,

    second point x,second point y,second anchor x,second anchor y)

    vertex()■■ produces a series of vertices connected through lines. It requires a beginShape() and an endShape() command to indicate the beginning and end of the vertices. For example, the number patterns shown earlier in this chapter can be visualized through simple algorithms. In that sense, the following code will produce a pattern of points shown in Figure 1-10.

    75488c01.indd 16 3/22/09 5:42:21 PM

  • Chapter 1 ■ Elements of the Language 17

    for(int i=0; i

  • 18 Chapter 1 ■ Elements of the Language

    figure 1-12: Two rectangles filled with gray

    and

    fill(0,200,0);

    rect(30,30,50,20);

    rect(40,40,20,30);

    will draw two nearly green rectangles as shown in Figure 1-13. (Note that although you can’t see the color in this book, the code does indeed produce green filled rectangles.) If the second parameter that corresponds to the green value was the maximum number 255, then the rectangles would really be filled with true green.

    figure 1-13: Two rectangles filled with the color green

    noFill() ■■ will not paint the inside of a shape. For example:

    noFill();

    rect(30,30,50,20);

    rect(40,40,20,30);

    will draw only the bounding line but will not paint the interior surface, as shown in Figure 1-14.

    figure 1-14: Two rectangles with no color

    stroke()■■ will paint the bounding line of a shape to a specified gray or color. It takes either one integer number between 0 and 255 to specify a

    75488c01.indd 18 3/22/09 5:42:21 PM

  • Chapter 1 ■ Elements of the Language 19

    level of gray (0 being black and 255 being white) or three integer numbers between 0 and 255 to specify an RGB color. For example:

    stroke(100);

    rect(30,30,50,20);

    rect(40,40,20,30);

    will paint the boundary lines with a gray value, as shown in Figure 1-15.

    figure 1-15: Two rectangles with gray strokes

    ■■ noStroke() will draw no boundary to the shape. For example:

    noStroke();

    rect(30,30,50,20);

    rect(40,40,20,30);

    will draw the shape in Figure 1-16.

    figure 1-16: Two rectangles with no strokes

    s■■ trokeWeight() will increase the width of the stroke. It takes an integer num-ber that specifies the number of pixels of the stroke’s width. For example,

    strokeWeight(4);

    rect(30,30,50,20);

    rect(40,40,20,30);

    will draw the shape in Figure 1-17.

    figure 1-17: Two rectangles with thick strokes

    75488c01.indd 19 3/22/09 5:42:21 PM

  • 20 Chapter 1 ■ Elements of the Language

    background()■■ specifies the gray value or color of the display background. It takes either one integer number between 0–255 to specify a level of gray (0 being black and 255 being white) or three integer numbers between 0–255 to specify an RGB color. For example,

    background(200);

    will paint the background dark grey, as shown in Figure 1-18.

    figure 1-18: A grey background

    1.2.5 Fonts and ImagesApart from simple geometrical objects and their attributes, the Processing language supports text and images. Those are invoked using more complex commands. These commands can either create new text and images or import existing fonts and image files. The following section shows briefly these com-mands, although images will be further elaborated in Chapter 5 of this book.

    createFont()■■ creates a Processing-compatible font out of existing fonts in your computer. It takes the name of a font and the size. It returns the newly created font which needs to be loaded (textFont) and then dis-played (text) at a specified location. For example,

    PFont myFont = createFont(“Times”, 32);

    textFont(myFont);

    text(“P”,50,50);

    displays Figure 1-19.

    figure 1-19: A text placed at the center of the window

    The first line creates a font out of the existing Times font at a size of 32. The command will return back the new font which is called here myFont. This

    75488c01.indd 20 3/22/09 5:42:21 PM

  • Chapter 1 ■ Elements of the Language 21

    font is then loaded using the textFont command, which can be displayed at any location in the screen using the text command.

    loadImage()■■ will load and display an existing image. It takes the location of the image and returns a PImage object that can be displayed using the image command. For example,

    PImage myImage = loadImage(“c:/data/image.jpg”);

    image(myImage, 0, 0);

    will display an image at location 0,0 (i.e. the origin). Figure 1-20 shows an example.

    figure 1-20: An image placed at the upper left corner of the window

    If a directory is not mentioned, then Processing will look for the image within the same directory that the code is (or inside the sub-directory “data”). The image will be drawn on the default 100 × 100 screen. If it is larger it will be cropped and if smaller it will be left with an empty margin (as in Figure 1-20).

    1.2.6 ExamplesThis section introduced the basic graphics commands for geometrical objects, text, and images. These graphical objects are assumed to be static as paintings. The next section introduces motion and interactivity using the draw() command and by redrawing the screen to create an illusion of motion.

    The follow code demonstrates most of the graphics commands introduced so far. Figure 1-21 shows an example.

    size(300,200); //size of the display

    background(150); //set a dark background

    PImage myImage = loadImage(“c:/data/image.jpg”); //get an image

    image(myImage, 100, 50); //display it at the center of the screen

    noFill(); //for an empty rectangle

    strokeWeight(4); //make a think line

    rect(90,40, myImage.width+20, myImage.height+20); //make a rectangle

    frame

    75488c01.indd 21 3/22/09 5:42:21 PM

  • 22 Chapter 1 ■ Elements of the Language

    PFont myFont = createFont(“Times”, 32); //create a font

    textFont(myFont); //load the font

    fill(250); //change the color of the text to almost white

    text(“What is this?”,50,100); //display the text

    figure 1-21: A combination of images, text, and a rectangle

    The following code and figures provide examples of loops using graphics elements.

    for(int i=0; i

  • Chapter 1 ■ Elements of the Language 23

    for(int i=100; i>0; i=i-2){

    rect(0,0,i,i);

    }

    for(int i=0; i0; i=i-4){

    ellipse(i,50,i,i);

    }

    75488c01.indd 23 3/22/09 5:42:22 PM

  • 24 Chapter 1 ■ Elements of the Language

    1.3 Interactivity

    So far, we have seen graphics elements displayed on the window as static enti-ties. They appear to be stationary even though, as we will see, they are redrawn continuously on the computer screen. In this section, we will show how to take graphical elements and redraw them fast enough to produce the illusion of motion. This subject will be expanded further in Chapter 6.

    1.3.1 Drawing on the ScreenAs discussed earlier in this chapter, the structure of Processing code is divided in two main sections: the setup and draw section. The setup section is used to define initial environment properties (e.g. screen size, background color, loading images/fonts, etc.) and the draw section for executing the drawing commands (e.g. point, line, ellipse, image, etc.). The structure of the code is as follows:

    void setup(){

    }

    void draw(){

    }

    By default, in Processing the draw area is executed repeatedly in a loop. The speed of this loop can be controlled by using the frameRate command to set the number of frames per second. For example, if we want to draw a vertical line that moves horizontally (as illustrated in Figure 1-22) then the following code can be used:

    1 void setup(){

    2 size(300,100);

    3 }

    4

    5 int i=0;

    6 void draw(){

    7 line(i,0,i,100);

    8 i++;

    9 }

    figure 1-22: A moving line leaving a trace

    75488c01.indd 24 3/22/09 5:42:22 PM

  • Chapter 1 ■ Elements of the Language 25

    The first three lines are used to set the size of the display. In line 5 an integer variable i is initialized to 0. It will be used as a counter. It is defined outside of the draw area. Line 8 increases the counter by 1 every time the screen redraws itself. So, then the line is being redrawn in increments of one pixel in the hori-zontal direction. In the resulting effect, the black line leaves a trace as it is redrawn that over time creates an increasingly black area.

    The next example redraws the background every time the draw command is executed, creating an animating effect. This produces a line that seems to move from left to right one pixel at a time, illustrated in Figure 1-23.

    1 void setup(){

    2 size(300,100);

    3 }

    4

    5 int i=0;

    6 void draw(){

    7 background(200);

    8 line(i%300,0,i%300,100);

    9 i++;

    10 }

    figure 1-23: A moving line leaving no trace

    Note that in line 8 we modulate the counter i by 300 so that when it reaches 300 it sets itself back to zero. Finally, in the last example, we replace the counter i with the mouse coordinates that are defined in Processing by mouseX and mouseY. In that way, we can get an interactive effect where the line is redrawn every time the mouse is moved, as illustrated in Figure 1-24.

    1 void setup(){

    2 size(300,100);

    3 }

    4

    5 void draw(){

    6 background(200);

    7 line(mouseX,0,mouseX,100);

    8 }

    75488c01.indd 25 3/22/09 5:42:22 PM

  • 26 Chapter 1 ■ Elements of the Language

    figure 1-24: A line moved to follow the mouse’s location

    1.3.2 Mouse and Keyboard EventsA mouse’s or keyboard’s activity can be captured by using the mouseDragged, mouseMoved, mousePressed, mouseReleased, or keyPressed events. In each case, a series of commands can be activated every time the corresponding event is triggered. The structure of the code is:

    void setup(){

    }

    void draw(){

    }

    void mousePressed(){

    }

    void keyPressed(){

    }

    In specific, these events are used in the following way:

    ■■ mousePressed() is called when a mouse button is pressed. For example,

    1 void draw(){2 }34 void mousePressed(){5 rect(mouseX,mouseY, 10,10);6 }

    produces the result shown in Figure 1-25.

    figure 1-25: Randomly located rectangles by the press of the mouse button

    75488c01.indd 26 3/22/09 5:42:22 PM

  • Chapter 1 ■ Elements of the Language 27

    mouseDragged()■■ is called when a mouse is dragged. For example,

    1 void draw(){2 }34 void mouseDragged(){5 rect(mouseX,mouseY, 10,10);6 }

    will result in Figure 1-26.

    figure 1-26: Rectangles following the location of the mouse

    ■■ keyPressed() is called when a mouse is pressed. For example,

    1 void draw(){2 }34 void keyPressed(){5 int x = int(random(0,100));6 int y = int(random(0,100));7 rect(x,y, 10,10);8 }

    will result in Figure 1-27.

    figure 1-27: Randomly located rectangles by the press of any keyboard key

    The example above uses a random generator to produce x and y coordi-nates. This is done by calling the random() function; we pass two numbers that correspond to the lower and upper limit (i.e. 0,100). Then we cast the resulting random numbers to integers. This is done because the random function always returns float numbers.

    75488c01.indd 27 3/22/09 5:42:22 PM

  • 28 Chapter 1 ■ Elements of the Language

    1.4 Grouping of Code

    Computer code can be seen as language statements that convey a process to be executed by a computer. As a linguistic structure, code can be grouped into sentences, paragraphs, sections, etc. In the following sections we will examine basic structures of code that can store information (arrays), be referred to (pro-cedures) and be self-referential (recursion).

    1.4.1 ArraysAn array is an ordered set of data. It appears as a variable that can hold multiple values at the same time, but essentially it is a pointer to the memory addresses of where that data are held. We assign or extract the data values of an array by pointing at the index of the array, i.e., a number indicating the sequential order of the element of the array. For example, we may refer to the fifth or sixth ele-ment in an array. We can have arrays of any type, i.e., booleans, integers, strings, etc. We define an array by using the [] symbol. For example:

    String [] names = {“Kostas”, “Ivan”, “Jeff”, “Jie Eun”};

    float [] temperatures = {88.9, 89.1, 89.0, 93.4, 95.2, 101.2};

    int [] num_of_transactions = new int[50];

    boolean [] isOff;

    The above arrays define 4, 6, 50, or no elements, respectively, either populated or not. The word new is used to create and initialize the array (or, in technical terms, allocate memory for it). The term populate means that we are assigning specific values to the array, i.e. populating its content. In this case, we initialized the array num_of_transactions to 50 integer values. While creating an array we can fill it with data and then have access to them by pointing to an index number. For example, the following code:

    for(int i=0; i

  • Chapter 1 ■ Elements of the Language 29

    The above statement will return the second element (which should be the name Ivan). If we have a two-dimensional array we initialize it as:

    int twoDArray[][] = new int[5][100];

    It will initialize an array of 5 rows and 100 columns and we access its ele-ments in the following way:

    int someElement = twoDArray[2][18];

    The above statement will return the element at the third row and the nine-teenth column. Arrays are very useful for storing a set of data under the same name. For example, float coords[][] can hold all the values of data residing at x and y coordinates of a grid.

    While arrays may start with a specific number of positions, it is possible that they need to be expanded in order to receive new data values. Also, it is pos-sible that they need to be shortened as the data values are much less than the positions. Consider the problem of a butterfly hunter who starts the day with a set of jars. What if she finds more butterflies than the available jars? What if she finds fewer and carries around empty jars? Processing (as well as Java) has dynamic memory allocation, i.e. memory allocated whenever it is necessary. So, in the case of the butterfly hunter, there is no need to pre-estimate the number of jars. She goes out with no jars, and every time a butterfly is caught, a jar is fetched from the camp. So, for convenience, there are, at least, five important methods associated with arrays:

    array.length■■ : returns the number of elements of an array

    sort(■■ array): sorts the elements of an array in alphabetic order

    append(■■ array,data): expands an array by one element and adds data value

    subset(■■ array,offset,length): creates a subset of an array at offset for a specified length

    expand(■■ array,size): expands an array by a total size position retaining the existing data values

    The following code shows how an array can be created, populated, sorted, and then shortened and expanded:

    1 String [] s = new String[0]; //new empty array

    2 s = append(s,”Kostas”);

    3 s = append(s,”Nashid”);

    4 s = append(s,”Jie Eun”);

    5 print(s.length); //should be 3

    6 for(int i=0; i

  • 30 Chapter 1 ■ Elements of the Language

    9 s = sort(s);

    10 for(int i=0; i

  • Chapter 1 ■ Elements of the Language 31

    11 for(int i=0; i

  • 32 Chapter 1 ■ Elements of the Language

    beginning of the procedure’s name; this means that the procedure does not return anything, i.e. it returns “void.” The next paragraph covers this in more detail. Finally, we enclose the actual set of code lines that perform the procedure within curly brackets. The code itself is simply a generic version of the previous code and it uses the parameters that are passed through the procedure in line 1. Once we define a procedure, then we can call it by using the following code:

    1 void setup(){

    2 size(500,400);

    3 stairs(10,10,15);

    4 stairs(100,200,13);

    5 stairs(300,200,10 );

    6 }

    Lines 3, 4, and 5 make calls to the procedure defined earlier in lines 1 through 4. These calls are placed within the setup() section which is also a procedure and evident from the word void. In this way, the procedure stairs and the procedure setup are groups of code that reside within the same program. The result of this program is exactly the same as in Figure 1-28.

    Similarly, we can define a procedure that can perform a task and then returns a value. This type of procedure is also referred to as a function. For example, let’s say we want to create a method that can calculate the area of a rectangle given its two sides and return the result as a float. Here is how it can be done:

    float getArea(float w, float h){

    int myResult = w * h;

    return myResult;

    }

    In the above example, we have declared a method called getArea and we use two float numbers w and h as parameters for the width and height of the rectangle. Within the method we define a variable called myResult, and we assign to it the result of the multiplication of the two parameters w and h. The procedure then returns the result. To invoke the method from another part of the code we write:

    float a = getArea(3.5, 2.6);

    The method getArea() will do the calculation. This can be very useful in organizing code through statements and commands that call one another. For example, if you want the surface area of a sphere you can call:

    float sa = getSurfaceArea(float r);

    The method getSurfaceArea will do the math with or without your knowledge or supervision. Sometimes methods can be very complex such as morph(object a,object b) or very simple such as getArea(float w,float h).

    75488c01.indd 32 3/22/09 5:42:22 PM

  • Chapter 1 ■ Elements of the Language 33

    1.4.4 RecursionA recursion is a repetitive procedure in which part of the repetition involves a call to the procedure itself. In other words, the procedure is not only a group of code that serves an external-to-itself purpose, but it also involves its own existence in the grouping of the code. Let’s examine a simple case of recursion used to calculate a factorial of a number. Please recall that a factorial of a num-ber is the product of all the positive integer numbers less or equal to itself. For example, the factorial of 5 is 120 which is the product 1*2*3*4*5. In the following two columns we show two procedures that calculate the factorial of a number using iteration (left) and recursion (right).

    1 void setup(){

    2 println(factorial(5));

    3 }

    4 int factorial(int n){

    5 int fact = 1;

    6 for(int i=n; i>=1; i-- )

    7 fact *= i;

    8 return fact;

    9 }

    1 void setup(){

    2 print(factorial(5));

    3 }

    4 int factorial(int n){

    5 if(n

  • 34 Chapter 1 ■ Elements of the Language

    Recursion can be used to produce graphical objects, as in the case of a series of nested circles constructed through the code shown below:

    1 void setup(){

    2 RecCircle(80);

    3 }

    4 int RecCircle(int r){

    5 ellipse(50,50,r,r);

    6 if(r

  • Chapter 1 ■ Elements of the Language 35

    Summary

    This chapter introduced you to data types, arithmetic and logical operations, loops, arrays, methods, and classes. At this point you should know how con-stants and variables are declared, how conditional statements are made, how to loop with a counter and use it within the loop, what arrays are and how we declare, fill, and access their members, what are procedures and how they are called, and finally how recursions are formed. We also used these concepts to draw simple shapes on the screen and then explained the mechanisms of generating simple drawings in Processing.

    Exercises

    note Answers to the exercises are provided in Appendix B.

    1. Memorize the symbols/types and their meaning:

    boolean for >= %

    int (

  • 36 Chapter 1 ■ Elements of the Language

    3. How many bits does the “boolean” primitive have?

    A. 2 bits

    B. 1 bit

    C. 8 bits

    D. 32 bits

    4. What is the result of the following program?

    int a=0;

    for (int i=0; i

  • Chapter 1 ■ Elements of the Language 37

    for(int i=0; i

  • 38 Chapter 1 ■ Elements of the Language

    13. Write the code that will produce the following patterns:

    75488c01.indd 38 3/22/09 5:42:24 PM

  • Chapter 1 ■ Elements of the Language 39

    75488c01.indd 39 3/22/09 5:42:24 PM

  • 40 Chapter 1 ■ Elements of the Language

    75488c01.indd 40 3/22/09 5:42:24 PM

  • 41

    Geometry is the study of properties, measurement, and relationships of points, lines, angles, surfaces, and solids. Whereas Euclidean geometry is concerned with intuitive definitions of elements and their relationships, analytical geom-etry is concerned with the quantitative study of the relations and the properties of geometrical elements. The notion of quantity as a means of representing or displaying geometric information is key to computer graphics applications. In addition to conceiving geometrical elements as abstract entities, it is also neces-sary to represent and handle them as quantifiable information using flat screen displays populated with finite sized pixels. In that sense, abstract mathematical concepts such as infinity, eternal, or continuous can be replaced with those of finite, ephemeral, or discontinuous.

    The dominant mode for representing geometric objects in computer graphics still adheres to the hierarchical sequence of points-lines-surfaces-solids. Yet, a point is simply a pixel on the screen, a line is a sequence of pixels, and a shape is an area of pixels. In that sense, a computer graphics programmer is offered a repertoire of finite-sized light intensities bounded to a finite length screen with a finite amount of colors. Within this finite domain, the most amazing forms, scenes, or animated pictures can be produced. The purpose of this chapter is

    C h a p t e r

    2

    Points, Lines, and Shapes

    75488c02.indd 41 3/20/09 1:38:56 PM

  • 42 Chapter 2 n Points, Lines, and Shapes

    to show how it is possible to create geometric entities and how such elements can be combined into complex shapes.

    2.1 Sine and Cosine Curves

    Trigonometry is the study of the relationships among the angles and sides of a triangle. In the right triangle shown in Figure 2-1, the sine of angle a is the ratio of BC/AB, and the cosine is the ratio AC/AB (It’s a right triangle because one of the angles is 90 degrees, or a “right angle”).

    Aa

    b

    c

    C

    B

    Figure 2-1: A right triangle

    A sine or a cosine can take values between –1 and 1. The progress of sine or cosine values for a changing angle, say in the form of a counter from 0 to 360, is along the path of a curve. So, an interesting feature of sines and cosines is that, when we calculate their value for rotating angles, we get a “circular” behavior. Consider the following code:

    1 for(int i=0; i

  • Chapter 2 n Points, Lines, and Shapes 43

    get the cosine of the counter i (converted to radians), then exaggerated by 50.0. Since the result is a double, we cast it into an int to assign it to y:

    int x = i;

    int y = int(50. * sin(radians( i)) );

    Then we draw the result using the point() command. So, as x moves on a linear increment based on the looping counter i (with values 0,1,2,3,4,5, . . . ,499), y moves in the y direction, up and down. Note that we also move the whole scene 100 pixels lower in the y direction to center it on the window (see line 4). The result is shown in Figure 2-2.

    Figure 2-2: The output of a sine representation

    So, the result is a set of dots (“.”) starting at (0,100) and then as x goes from 0,1,2,3,4, . . . 500, y produces cosine values. Since we know from trigonometry that a cosine will always be between –1 and 1, we multiply by 50 to make y a value between –50 and 50. Obviously, the resulting numbers place the points along the path of a curve. These numbers are sample values that result from the x and y parameters. The more we decrease the distance between consecutive i values, the more precise the path is. If we want to shorten the curve in the x direction, then we need to do the following adjustment to the x coordinate:

    1 for(int i=0; i

  • 44 Chapter 2 n Points, Lines, and Shapes

    Figure 2-3: The output of a cosine representation

    If we reverse the values of x and y, as is done in the following code, then we can obtain a rotated curve, as shown in Figure 2-4.

    1 for(int i=0; i

  • Chapter 2 n Points, Lines, and Shapes 45

    Figure 2-5: The output of the combination of a sine and cosine representation

    A circle! We will use this technique later on to rotate objects in the screen, because basically what we are doing here is forcing x and y to move on the perimeter of a circle. Or, to be precise, we force x and y to rotate around a center 13.8 times, since the counter goes from 0 to 5,000. If the counter is going from 0 to 180, as shown here:

    1 for(int i=0; i

  • 46 Chapter 2 n Points, Lines, and Shapes

    here is i and, consequently, the resulting circle is a parametric one. However, in analytic geometry, the equation for generating a circle is different:

    x2 + y2 = r2

    Such an equation denotes that for every point on a plane, only the points that satisfy the above equation are part of a circle of radius r and center (0,0). The following code generates such a circle (shown on the left in Figure 2-7):

    1 for(int x = -50; x

  • Chapter 2 n Points, Lines, and Shapes 47

    2.2 Bezier Curve

    As we have seen, a curve can be generated by sampling points from a paramet-ric equation. In the case of the parametric equation x = sin(a), we derive points’ coordinates based on the increments of the angle a. In a similar way, we can use more complex parametric equations to derive x and y coordinates of complex curves based on a changing parameter, t. So, by using a parametric equation of the form

    p t p f ti ii

    n

    ( ) ( )==∑

    0

    where t lies between 0 and 1, we can replace the function f(t) with a Bernstein polynomial Bi,n(t) = t

    i(1 – t)n – 1. This polynomial can be constructed based on the number of points (or degrees) given. So, for 3, 4, 5, and 6 points the poly-nomial becomes:

    B3(t) = (1-t)2p0 + 2t(1-t)p

    1 + t2p

    2

    B4(t) = (1-t)3p0 + 3t(1-t)2p

    1 + 3t2(1-t)p

    2 + t3p

    3

    B5(t) = (1-t)4p0 + 4t(1-t)3p

    1 + 6u2(1-t)2p

    2 + 4t3(1-t)p

    3 + t4p

    4

    B6(t) = (1-t)5p0 + 5t(1-t)4p

    1 + 10t2(1-t)3p

    2 + 10t3(1-t)2p

    3 +

    5t4(1-t)p4 + t5p

    5

    In the mathematical notation, a cubic Bezier curve is defined through the following equation:

    B P P P P( ) ( ) ( ) ( )t t t t t t t t= − + − + − +1 3 1 3 13 02

    12

    23

    3 , ∈∈ 0 1, .

    Where P0, P1, P2, and P3 are points in three-dimensional space, and the parameter t can have values between 0 and 1. In the following code, we use the preceding equation to extract the coordinates of a Bezier curve based on four points:

    float P0x = 10., P0y = 10.;

    float P1x = 10., P1y = 40.;

    float P2x = 40., P2y = 60.;

    float P3x = 80., P3y = 20.;

    for(float t=0.; t

  • 48 Chapter 2 n Points, Lines, and Shapes

    float y = pow((1 - t),3)*P0y + 3*t*pow((1 - t),2)*P1y +

    3*pow(t,2)*(1 - t)*P2y + pow(t,3)*P3y;

    point(x,y);

    }

    We then draw the four points together with the resulting sampled points (see Figure 2-8).

    Figure 2-8: A Bezier curve based on four points

    The resulting points (left) are the same as we would have obtained by using the bezier() command provided by Processing, as shown on the right and in the following code:

    noFill();

    bezier(P0x,P0y,P1x,P1y,P2x,P2y,P3x,P3y);

    rectMode(CENTER);

    rect(P0x,P0y,5,5);

    rect(P1x,P1y,5,5);

    rect(P2x,P2y,5,5);

    rect(P3x,P3y,5,5);

    2.3 Pointillist Images

    Since we know how to create circles, or better, how to address “circular” behav-iors, we will now use that knowledge to create images using simple mathemat-ics. We will use the point() method to draw a point at a position (x, y) on the screen and then color it using the stroke() method. For example,

    point( 10, 20);

    will draw a point at location (10,20). Now, if we replace 10 with a counter vari-able i we will have:

    for(int x=0; x

  • Chapter 2 n Points, Lines, and Shapes 49

    This, as expected, will draw a red line 100 pixels long. If we loop twice in both directions, we can get a red area of 100 × 100 pixels through the following code:

    for(int x=0; x

  • 50 Chapter 2 n Points, Lines, and Shapes

    5 int red = (int)(255. * cos( PI/180. * x) );6 int green = (int)(255. * sin( PI/180. * y));7 int blue = 0;89 red = abs(red) % 255;10 green = abs(green) % 255;11 blue = abs(blue) % 255;1213 stroke(red, green, blue);14 rect(x, y,1,1);15 }16 }

    Figure 2-10: A color scheme as an output of an algorithm

    The image shows the color behavior of the combinations of sine and cosine of the x and y coordinates. Blue is absent from the image, since we always assign it 0. Now, if we involve blue in the picture by multiplying red and green, as in the following code, we get the interesting result shown in Figure 2-11.

    int red = int (255. * cos( PI/180. * x) );int green = int (255. * sin( PI/180. * y)); int blue = red * green;

    Figure 2-11: A color scheme as an output of a constraint-based algorithm

    We can “carve out” the preceding pattern, as shown in Figure 2-12, by setting conditions in the code: for instance, any value above a certain color level could be omitted (thus, setting a threshold):

    size(360,180); for(int x = 0; x

  • Chapter 2 n Points, Lines, and Shapes 51

    for(int y = 0; y

  • 52 Chapter 2 n Points, Lines, and Shapes

    Figure 2-13: A polygon in the form of a square

    Another way to create a polygon is through an array of x and y coordinates. An array is a set of memorized data values that can be accessed in an ordered way. The following code shows how to create a square using two arrays for the x and y coordinates. Instead of explicitly presetting the x and y coordinates using independent variables for each vertex point, we store them in an array that can be accessed in an ordered fashion for retrieval.

    1 int n = 4;

    2 int[] xArray = new int[n]; //allocate memory

    3 int[] yArray = new int[n];

    4 xArray[0] = 20; //first point

    5 yArray[0] = 20;

    6 xArray[1] = 20; //second point

    7 yArray[1] = 80;

    8 xArray[2] = 80; //third point

    9 yArray[2] = 80;

    10 xArray[3] = 80; //fourth point

    11 yArray[3] = 20;

    12 beginShape(POLYGON);

    13 for(int i = 0; i < n; i++)

    14 vertex(xArray[i],yArray[i]); //retrieve in an ordered fashion

    15 endShape(CLOSE);

    First, we need to create two arrays with four integers each. Then we assign values to the array positions one by one. Finally, we draw the polygon using the vertex() method. The resulting polygon (shown in Figure 2-14) will look the same as that shown in Figure 2-13 (the difference is in the way it is constructed).

    Figure 2-14: A polygon in the form of a square constructed through arrays

    75488c02.indd 52 3/20/09 1:39:00 PM

  • Chapter 2 n Points, Lines, and Shapes 53

    In this example, we used the arrays to fill in the points and then we passed them to the vertex() method. The advantage of this method is that the arrays not only store information that can be reused later but can be changed and modified through the course of the session. However, it would be perhaps bet-ter if we could create a general algorithm that would fill the arrays with the necessary coordinates instead of pre-calculating and “hard-coding” the data. This problem is addressed in the next section.

    2.5 Equilateral Polygons

    In an equilateral polygon, vertex points are distributed along a circle in equal intervals. Earlier in this chapter you learned how to create circles using para-metric equations (i.e., involving an angle and a radius). The next step is to create circular polygons, that is, polygons created through arrays that are obtained by distributing points equally on the perimeter of a circle. The following code demonstrates this method with a simple algorithm making use of our knowl-edge of the sine and cosine:

    1 int n = 5;

    2 float[] xArray = new float[n]; //allocate memory for 5 points

    3 float[] yArray = new float[n];

    4 void setup(){

    5 float angle = 2 * PI / n; //divide the circle in n sections

    6 for(int i =0; i< n; i++){ //create points along a circle

    7 xArray[i] = 50. + 30. * sin(angle*i);

    8 yArray[i] = 50. + 30. * cos(angle*i);

    9 }

    10 }

    11 void draw (){

    12 beginShape(POLYGON);

    13 for(int i = 0; i < n; i++)

    14 vertex(xArray[i],yArray[i]);

    15 endShape(CLOSE);

    16 }

    After creating the arrays of size n, you need to fill them with points. To do that, loop for n times and each time the x and y values are assigned. These values are calculated through the following algorithm:

    First, divide a full circle (2*PI) by ■n n sections, which correspond to the number of the equilateral polygon’s sides (or the size of the array), and name this ratio “angle”.

    Then, store the coordinates of each polygon’s vertex in the arrays by using ■nthe parametric equation of the circle.

    Use the stored values in the arrays to draw the polygon vertices. ■n

    75488c02.indd 53 3/20/09 1:39:00 PM

  • 54 Chapter 2 n Points, Lines, and Shapes

    The resulting shape is shown in Figure 2-15.

    Figure 2-15: A central polygon implemented for five sides

    2.6 Responsive Polygons

    So far, the polygons that we have been constructing reside on the screen at a specific location, but they are not interactive. In other words, after a point is laid down, there is no way for the system to interact with it in order to rearrange it in another pattern or make it responsive to the user’s actions. The following code develops a method of locating the coordinate positions for each point and then using that information to track and reposition them.

    1 int n = 5;

    2 float[] px = new float[n];

    3 float[] py = new float[n];

    4 void setup(){

    5 float angle = 2 * PI / n; //divide the circle in n sect

    6 for(int i =0; i< n; i++){

    7 px[i] = 50. + 30. * sin(angle*i);

    8 py[i] = 50. + 30. * cos(angle*i);

    9 }

    10 }

    11 void draw (){

    12 background(200);

    13 beginShape(POLYGON);