├── .gitignore ├── publish.sh ├── images ├── forkme.png └── sprites │ ├── ant_up.png │ ├── grass1.png │ ├── grass2.png │ ├── rock.png │ ├── water.png │ ├── water2.png │ ├── ant_down.png │ ├── ant_left.png │ ├── landmine.png │ ├── ant_right.png │ ├── moss_dark.png │ └── moss_green.png ├── README.md ├── ideas.txt ├── vector.js ├── TODO.txt ├── stylesheet.css ├── index.html ├── genalg.js ├── utils-html.js ├── faq.html ├── utils-misc.js ├── gradient.js ├── agents.js ├── world.js └── COPYING.txt /.gitignore: -------------------------------------------------------------------------------- 1 | resources 2 | -------------------------------------------------------------------------------- /publish.sh: -------------------------------------------------------------------------------- 1 | git push -f origin master:gh-pages 2 | -------------------------------------------------------------------------------- /images/forkme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/forkme.png -------------------------------------------------------------------------------- /images/sprites/ant_up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/ant_up.png -------------------------------------------------------------------------------- /images/sprites/grass1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/grass1.png -------------------------------------------------------------------------------- /images/sprites/grass2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/grass2.png -------------------------------------------------------------------------------- /images/sprites/rock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/rock.png -------------------------------------------------------------------------------- /images/sprites/water.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/water.png -------------------------------------------------------------------------------- /images/sprites/water2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/water2.png -------------------------------------------------------------------------------- /images/sprites/ant_down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/ant_down.png -------------------------------------------------------------------------------- /images/sprites/ant_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/ant_left.png -------------------------------------------------------------------------------- /images/sprites/landmine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/landmine.png -------------------------------------------------------------------------------- /images/sprites/ant_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/ant_right.png -------------------------------------------------------------------------------- /images/sprites/moss_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/moss_dark.png -------------------------------------------------------------------------------- /images/sprites/moss_green.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximecb/Gradient/HEAD/images/sprites/moss_green.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | You can try Gradient online at the following URL: 2 | [http://maximecb.github.io/Gradient](http://maximecb.github.io/Gradient) 3 | 4 | For more information, see the [FAQ page](http://maximecb.github.io/Gradient/faq.html) 5 | -------------------------------------------------------------------------------- /ideas.txt: -------------------------------------------------------------------------------- 1 | - Prey with simple AI 2 | - Movable wall blocks and movable plants 3 | - Landmines 4 | - Sexual reproduction 5 | - Sliders/checkboxes/radio button options to control the world 6 | - Separate popup window, or all at bottom? 7 | - Complicated to do in popup 8 | -------------------------------------------------------------------------------- /vector.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * Gradient: an Artificial Life Experiment 4 | * Copyright (C) 2011 Maxime Chevalier-Boisvert 5 | * 6 | * This file is part of Gradient. 7 | * 8 | * Gradient is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * Gradient is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with Gradient. If not, see . 20 | * 21 | * For more information about this program, please e-mail the 22 | * author, Maxime Chevalier-Boisvert at: 23 | * maximechevalierb /at/ gmail /dot/ com 24 | * 25 | *****************************************************************************/ 26 | 27 | //============================================================================ 28 | // 2D Vectors 29 | //============================================================================ 30 | 31 | /** 32 | @class 2D vector 33 | */ 34 | function Vector2(x, y) 35 | { 36 | this.x = x; 37 | this.y = y; 38 | } 39 | 40 | /** 41 | Add two vectors 42 | */ 43 | Vector2.add = function (v1, v2) 44 | { 45 | return new Vector2(v1.x + v2.x, v1.y + v2.y); 46 | } 47 | 48 | /** 49 | Multiply a vector by a scalar 50 | */ 51 | Vector2.scalarMul = function (v, s) 52 | { 53 | return new Vector2(v.x * s, v.y * s); 54 | } 55 | 56 | -------------------------------------------------------------------------------- /TODO.txt: -------------------------------------------------------------------------------- 1 | - [DONE] Page title 2 | - [DONE] Increase def zoom lvl 3 | - [DONE] Zoom level indication 4 | - [DONE] Animate the water (simple) 5 | - [DONE] Fix keyboard keys moving on page 6 | - [DONE] Optimize rendering using sprite caching. 7 | - [DONE] Grey out or highlight real-time/fast mode/zoom buttons? 8 | - [DONE] Plants available, only show percent, not number 9 | - [DONE] Compute world itrs/sec computation speed 10 | - [DONE] Verify that agents can see properly 11 | - [DONE] Optimize plant/block respawn mechamism 12 | - [ ] Slow down redraw rate in fast mode 13 | - [ ] Allow genes to control mutation rate 14 | - [ ] Add slightly less food 15 | - [ ] Make the walls create closed compartments 16 | - Use path finding to make sure all other cells are reachable? 17 | - Can't add new wall/water cell if this would make a clear cell unreachable 18 | - [ ] Add water, plants after walls 19 | - [ ] Add legend to FAQ page, use tile images 20 | 21 | - [DONE] Bool net inputs for surrounding cells, food/water/energy 22 | - [DONE] Bool net with atoms, AND (v1, !v2, v3, ...) 23 | - [DONE] Implement simplest genalg to start testing 24 | - [DONE] Implement mutation scheme. Mutate last 20 individuals out of 100. 25 | - [DONE] Improved integer ANN brains? 26 | - [DONE] Self-reproduction with custom action? Takes energy. 27 | 28 | - [DONE] GPL license the files 29 | - [DONE] Copyright (C) 2011 - Maxime Chevalier-Boisvert at bottom 30 | - [DONE] CSS style sheet, shared with FAQ page 31 | - [DONE] FAQ page, link under title "FAQ Page - What is this? How does it Work?" 32 | - [DONE] Deployment/upload script, use scp? 33 | - [DONE] Discrete adsense ads 34 | - [DONE] Meta keywords 35 | - [DONE] Meta description 36 | - [DONE] Fade the gradient icon on the projects page 37 | 38 | -------------------------------------------------------------------------------- /stylesheet.css: -------------------------------------------------------------------------------- 1 | body 2 | { 3 | background: #000000; 4 | 5 | color: white; 6 | font-family: "Arial", sans-serif; 7 | font-weight: normal; 8 | } 9 | 10 | div.title 11 | { 12 | margin-top: 12px; 13 | margin-bottom: 12px; 14 | 15 | text-align:center; 16 | color: white; 17 | font-family: "Arial", sans-serif; 18 | font-weight: bold; 19 | font-size: 30px; 20 | } 21 | 22 | a 23 | { 24 | color: rgb(160,160,160); 25 | font-family: "Arial", sans-serif; 26 | } 27 | a:link {text-decoration: none; } 28 | a:visited {text-decoration: none; } 29 | a:active {text-decoration: none; } 30 | a:hover {text-decoration: underline; } 31 | 32 | div.faq_link 33 | { 34 | margin-top: -5px; 35 | margin-bottom: 12px; 36 | 37 | text-align: center; 38 | font-weight: bold; 39 | font-size: 15px; 40 | } 41 | 42 | div.canvas_frame 43 | { 44 | border: 2px solid rgb(255,255,255); 45 | 46 | text-align: center; 47 | vertical-align: middle; 48 | } 49 | 50 | div.text_frame 51 | { 52 | border: 2px solid rgb(255,255,255); 53 | padding-top: 3px; 54 | padding-bottom: 3px; 55 | padding-left: 5px; 56 | padding-right: 5px; 57 | 58 | vertical-align: text-top; 59 | text-align: left; 60 | color: white; 61 | font-family: "Courier", sans-serif; 62 | font-weight: normal; 63 | font-size: 15px; 64 | } 65 | 66 | div.faq_q 67 | { 68 | margin-top: 12px; 69 | margin-bottom: 10px; 70 | 71 | text-align:left; 72 | color: red; 73 | font-family: "Arial", sans-serif; 74 | font-weight: bold; 75 | font-size: 20px; 76 | } 77 | 78 | div.ad 79 | { 80 | width:100%; 81 | margin-top: 12px; 82 | margin-bottom: 12px; 83 | 84 | text-align:center; 85 | } 86 | 87 | div.copyright 88 | { 89 | margin-top: 8px; 90 | margin-bottom: 8px; 91 | 92 | text-align:center; 93 | color: white; 94 | font-family: "Arial", sans-serif; 95 | font-weight: normal; 96 | font-size: 15px; 97 | } 98 | 99 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Gradient: an Artificial Life Experiment 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | Fork me on GitHub 22 | 23 | 24 |
25 | Gradient: an Artificial Life Experiment 26 |
27 | 28 | 31 | 32 |
33 | 34 | 35 | 36 | 43 | 44 | 45 | 47 | 48 | 49 | 82 | 83 |
37 |
38 | 39 | Your browser does not support the canvas element. 40 | 41 |
42 |
46 | 50 | 51 |
52 |
53 | 54 | 55 |
56 |
57 |
58 | 59 |      60 | 61 |
62 | 63 |
64 |
65 | 66 |      67 | 68 |
69 | 70 |
71 |
72 | 73 |    74 | 75 |    76 | 77 |    78 | 79 |
80 |
81 |
84 |
85 | 86 | 87 |
88 |
89 | 90 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /genalg.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * Gradient: an Artificial Life Experiment 4 | * Copyright (C) 2011 Maxime Chevalier-Boisvert 5 | * 6 | * This file is part of Gradient. 7 | * 8 | * Gradient is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * Gradient is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with Gradient. If not, see . 20 | * 21 | * For more information about this program, please e-mail the 22 | * author, Maxime Chevalier-Boisvert at: 23 | * maximechevalierb /at/ gmail /dot/ com 24 | * 25 | *****************************************************************************/ 26 | 27 | //============================================================================ 28 | // Genetic Algorithm Implementation 29 | //============================================================================ 30 | 31 | /** 32 | Constructor for agent evolution GA 33 | */ 34 | function GenAlg(agentClass) 35 | { 36 | /** 37 | Agent class function 38 | */ 39 | this.agentClass = agentClass; 40 | 41 | /** 42 | Population vector 43 | */ 44 | this.population = []; 45 | 46 | /** 47 | Minimum population size 48 | */ 49 | this.minPopSize = 25; 50 | 51 | /** 52 | Mutation probability, for asexual reproduction. 53 | */ 54 | this.mutProb = 0.02; 55 | 56 | /** 57 | Produced individual count 58 | */ 59 | this.indCount = 0; 60 | 61 | /** 62 | Seed individual count 63 | */ 64 | this.seedCount = 0; 65 | } 66 | 67 | /** 68 | Update the state of the GA 69 | */ 70 | GenAlg.prototype.update = function () 71 | { 72 | // Count of live agents 73 | var liveCount = 0; 74 | 75 | // For each individual in the population 76 | for (var i = 0; i < this.population.length; ++i) 77 | { 78 | var agent = this.population[i]; 79 | 80 | // If the agent is alive 81 | if (agent.isAlive()) 82 | { 83 | // Increment the live agent count 84 | liveCount++; 85 | } 86 | else 87 | { 88 | // Remove the agent from the population 89 | this.population.splice(i, 1); 90 | --i; 91 | } 92 | } 93 | 94 | // While the population size is below the minimum 95 | while (liveCount < this.minPopSize) 96 | { 97 | // Create a new agent 98 | var agent = this.newIndividual(); 99 | 100 | // Add the agent to the population 101 | this.population.push(agent); 102 | 103 | // Place the agent at random coordinates 104 | world.placeAgentRnd(agent); 105 | 106 | // Increment the live count 107 | liveCount++; 108 | 109 | // Increment the seed individuals count 110 | this.seedCount++; 111 | } 112 | } 113 | 114 | /** 115 | Create a new individual 116 | */ 117 | GenAlg.prototype.newIndividual = function () 118 | { 119 | // Create a new agent 120 | var newAgent = this.agentClass.newAgent(); 121 | 122 | // Increment the count of individuals created 123 | ++this.indCount; 124 | 125 | // Return the new agent 126 | return newAgent; 127 | } 128 | 129 | /** 130 | Mutate an individual 131 | */ 132 | GenAlg.prototype.mutate = function (agent) 133 | { 134 | // Mutate the agent 135 | var newAgent = this.agentClass.mutate(agent, this.mutProb); 136 | 137 | // Increment the count of individuals created 138 | ++this.indCount; 139 | 140 | // Return a pointer to the new agent 141 | return newAgent; 142 | } 143 | 144 | /** 145 | Create offspring for an agent 146 | */ 147 | GenAlg.prototype.makeOffspring = function (agent) 148 | { 149 | // Create a new agent through mutation 150 | var newAgent = this.mutate(agent); 151 | 152 | // Add the new agent to the population 153 | this.population.push(newAgent); 154 | 155 | // Place the new agent in the world near the parent 156 | world.placeAgentNear(newAgent, agent.position.x, agent.position.y); 157 | } 158 | 159 | -------------------------------------------------------------------------------- /utils-html.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * This file is part of the Turing-Tunes project. The project is 4 | * distributed at: 5 | * https://github.com/maximecb/Turing-Tunes 6 | * 7 | * Copyright (c) 2013, Maxime Chevalier-Boisvert. All rights reserved. 8 | * 9 | * This software is licensed under the following license (Modified BSD 10 | * License): 11 | * 12 | * Redistribution and use in source and binary forms, with or without 13 | * modification, are permitted provided that the following conditions are 14 | * met: 15 | * 1. Redistributions of source code must retain the above copyright 16 | * notice, this list of conditions and the following disclaimer. 17 | * 2. Redistributions in binary form must reproduce the above copyright 18 | * notice, this list of conditions and the following disclaimer in the 19 | * documentation and/or other materials provided with the distribution. 20 | * 3. The name of the author may not be used to endorse or promote 21 | * products derived from this software without specific prior written 22 | * permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED 25 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 26 | * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN 27 | * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 29 | * NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | * 35 | *****************************************************************************/ 36 | 37 | // Default console logging function implementation 38 | if (!window.console) console = {}; 39 | console.log = console.log || function() {}; 40 | console.warn = console.warn || function() {}; 41 | console.error = console.error || function() {}; 42 | console.info = console.info || function() {}; 43 | print = function (v) { console.log(String(v)); } 44 | 45 | // Check for typed array support 46 | if (!this.Int8Array) 47 | { 48 | console.log('No Int8Array support'); 49 | Int8Array = Array; 50 | } 51 | if (!this.Uint16Array) 52 | { 53 | console.log('No Uint16Array support'); 54 | Uint16Array = Array; 55 | } 56 | if (!this.Int32Array) 57 | { 58 | console.log('No Int32Array support'); 59 | Int32Array = Array; 60 | } 61 | if (!this.Float64Array) 62 | { 63 | console.log('No Float64Array support'); 64 | Float64Array = Array; 65 | } 66 | 67 | /** 68 | Escape a string for valid HTML formatting 69 | */ 70 | function escapeHTML(str) 71 | { 72 | str = str.replace(/\n/g, '
'); 73 | str = str.replace(/ /g, ' '); 74 | str = str.replace(/\t/g, '    '); 75 | 76 | return str; 77 | } 78 | 79 | /** 80 | Encode an array of bytes into base64 string format 81 | */ 82 | function encodeBase64(data) 83 | { 84 | assert ( 85 | data instanceof Array, 86 | 'invalid data array' 87 | ); 88 | 89 | var str = ''; 90 | 91 | function encodeChar(bits) 92 | { 93 | //console.log(bits); 94 | 95 | var ch; 96 | 97 | if (bits < 26) 98 | ch = String.fromCharCode(65 + bits); 99 | else if (bits < 52) 100 | ch = String.fromCharCode(97 + (bits - 26)); 101 | else if (bits < 62) 102 | ch = String.fromCharCode(48 + (bits - 52)); 103 | else if (bits === 62) 104 | ch = '+'; 105 | else 106 | ch = '/'; 107 | 108 | str += ch; 109 | } 110 | 111 | for (var i = 0; i < data.length; i += 3) 112 | { 113 | var numRem = data.length - i; 114 | 115 | // 3 bytes -> 4 base64 chars 116 | var b0 = data[i]; 117 | var b1 = (numRem >= 2)? data[i+1]:0 118 | var b2 = (numRem >= 3)? data[i+2]:0 119 | 120 | var bits = (b0 << 16) + (b1 << 8) + b2; 121 | 122 | encodeChar((bits >> 18) & 0x3F); 123 | encodeChar((bits >> 12) & 0x3F); 124 | 125 | if (numRem >= 2) 126 | { 127 | encodeChar((bits >> 6) & 0x3F); 128 | 129 | if (numRem >= 3) 130 | encodeChar((bits >> 0) & 0x3F); 131 | else 132 | str += '='; 133 | } 134 | else 135 | { 136 | str += '=='; 137 | } 138 | } 139 | 140 | return str; 141 | } 142 | 143 | // TODO 144 | // TODO: decodeBase64(str) 145 | // TODO 146 | 147 | -------------------------------------------------------------------------------- /faq.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Gradient FAQ Page 4 | 5 | 6 | 7 | 8 |
9 | Gradient FAQ Page 10 |
11 | 12 |
What is Gradient?
13 |

14 | Gradient is a 2D grid world in which artificial "lifeforms" live. These 15 | are simulated agents (virtual robots) which can perceive their 16 | surroundings, perform computations using their simulated neural network 17 | "brains", and act on these. The agents require energy to live and so 18 | they need to eat virtual plants and drink virtual water every so often 19 | in order to survive. They can also reproduce. This is what makes them a 20 | form of 21 | artificial life. 22 |

23 | 24 |
How does Gradient work?
25 |

26 | The agents in the gradient world initially start with randomly connected 27 | brains. These are recurrent 28 | neural networks 29 | The agents perceive the world as a series of boolean values indicating the contents 30 | of the grid cells around them. The grid world is updated iteratively. At each 31 | iteration, the agents perceive their environment, perform computations, and get 32 | to pick an action to perform (e.g.: turn left, turn right, move forward, consume 33 | food or water, produce offspring). 34 |

35 |

36 | Gradient implements a kind of 37 | genetic algorithm. 38 | The world is initially seeded with randomly created agents. If the agents 39 | do not eat food and drink water, they run out of energy and die. Inevitably, 40 | some of the agents will die of starvation. If some agents manage to eat some 41 | food and drink water, they gain energy, which allows them to survive longer. 42 | If the number of agents in the world dips below a minimum number, more 43 | random (seed) agents will be created to maintain a minimum population size. 44 |

45 |

46 | If an agent accumulates enough energy, it will be allowed to choose to 47 | voluntarily reproduce. This has an associated energy cost, and produced a 48 | new agent based on a mutated version of it's parent's neural network. 49 | Because of 50 | natural selection, 51 | the agents eventually develop enough "intelligence" to survive. That is, 52 | the agents with brains that allow them to survive more effectively 53 | become the most prevalent. 54 |

55 |

56 | The hope is that eventually, agents that are capable of seeking food 57 | and surviving long enough to reproduce will prevail, and the population 58 | will maintain itself on its own. The world then no longer needs to be 59 | seeded with random agents. Note that there is no upper limit on the 60 | population size, it is purely limited by the availability of food in 61 | the world. 62 |

63 | 64 |
How long does it take the agents to become intelligent?
65 |

66 | If you let the simulation run in "fast mode", it will run as fast 67 | as your computer will allow. The amount of time required for the agents to 68 | exhibit some degree of "intelligent" behavior (e.g.: looking for 69 | food and water) can vary. In some instances, the simulation does not seem to 70 | converge at all, and may be restarted by refreshing the webpage. I recommend 71 | you let it run for over 10 minutes in fast mode and see what happens. 72 |

73 | 74 |
Who programmed Gradient? How did it originate?
75 |

76 | I, Maxime Chevalier-Boisvert, programmed Gradient in my spare time a few 77 | years ago. It was originally written in C++ and only ran on Linux under 78 | GTK. I extended Gradient in 2009 to test some ideas for a neuroscience 79 | class project. In May 2011, I decided to port this program to JavaScript 80 | so that more people can see it and experiment with it. I believe it's 81 | also a potentially interesting and demanding JavaScript benchmark. 82 |

83 | 84 |
Is Gradient open source?
85 |

86 | Yes, all the JavaScript code for Gradient is licensed under the GPLv3. You 87 | are free to download the code, modify it and experiment with it, so long as 88 | you respect the terms of the GPL license. 89 |

90 | 91 |
What browsers does Gradient support?
92 |

93 | Gradient has been tested on the latest Google Chrome and Firefox. It requires 94 | support for the HTML5 canvas element to run, and is rather demanding in terms 95 | of JavaScript performance. At the time of this writing, the latest Internet 96 | Explorer does not support the canvas element and so will not be able to run 97 | Gradient. We recommend Google Chrome for best performance. 98 |

99 | 100 |
Are there other artificial life programs out there?
101 |

102 | Most definitely. I recommend doing a Google search for artificial life. One 103 | of the most interesting examples I have found is 104 | Polyworld, which is 105 | actually quite similar to Gradient. 106 |

107 | 108 |
109 | 117 | 120 |
121 | 122 | 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /utils-misc.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * This file is part of the Turing-Tunes project. The project is 4 | * distributed at: 5 | * https://github.com/maximecb/Turing-Tunes 6 | * 7 | * Copyright (c) 2013, Maxime Chevalier-Boisvert. All rights reserved. 8 | * 9 | * This software is licensed under the following license (Modified BSD 10 | * License): 11 | * 12 | * Redistribution and use in source and binary forms, with or without 13 | * modification, are permitted provided that the following conditions are 14 | * met: 15 | * 1. Redistributions of source code must retain the above copyright 16 | * notice, this list of conditions and the following disclaimer. 17 | * 2. Redistributions in binary form must reproduce the above copyright 18 | * notice, this list of conditions and the following disclaimer in the 19 | * documentation and/or other materials provided with the distribution. 20 | * 3. The name of the author may not be used to endorse or promote 21 | * products derived from this software without specific prior written 22 | * permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED 25 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 26 | * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN 27 | * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 29 | * NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | * 35 | *****************************************************************************/ 36 | 37 | /** 38 | Assert that a condition holds true 39 | */ 40 | function assert(condition, errorText) 41 | { 42 | if (!condition) 43 | { 44 | error(errorText); 45 | } 46 | } 47 | 48 | /** 49 | Abort execution because a critical error occurred 50 | */ 51 | function error(errorText) 52 | { 53 | alert('ERROR: ' + errorText); 54 | 55 | throw errorText; 56 | } 57 | 58 | /** 59 | Test that a value is integer 60 | */ 61 | function isInt(val) 62 | { 63 | return ( 64 | Math.floor(val) === val 65 | ); 66 | } 67 | 68 | /** 69 | Test that a value is a nonnegative integer 70 | */ 71 | function isNonNegInt(val) 72 | { 73 | return ( 74 | isInt(val) && 75 | val >= 0 76 | ); 77 | } 78 | 79 | /** 80 | Test that a value is a strictly positive (nonzero) integer 81 | */ 82 | function isPosInt(val) 83 | { 84 | return ( 85 | isInt(val) && 86 | val > 0 87 | ); 88 | } 89 | 90 | /** 91 | Get the current time in millisseconds 92 | */ 93 | function getTimeMillis() 94 | { 95 | return (new Date()).getTime(); 96 | } 97 | 98 | /** 99 | Get the current time in seconds 100 | */ 101 | function getTimeSecs() 102 | { 103 | return (new Date()).getTime() / 1000; 104 | } 105 | 106 | /** 107 | Generate a random integer within [a, b] 108 | */ 109 | function randomInt(a, b) 110 | { 111 | assert ( 112 | isInt(a) && isInt(b) && a <= b, 113 | 'invalid params to randomInt' 114 | ); 115 | 116 | var range = b - a; 117 | 118 | var rnd = a + Math.floor(Math.random() * (range + 1)); 119 | 120 | return rnd; 121 | } 122 | 123 | /** 124 | Generate a random boolean 125 | */ 126 | function randomBool() 127 | { 128 | return (randomInt(0, 1) === 1); 129 | } 130 | 131 | /** 132 | Generate a random floating-point number within [a, b] 133 | */ 134 | function randomFloat(a, b) 135 | { 136 | if (a === undefined) 137 | a = 0; 138 | if (b === undefined) 139 | b = 1; 140 | 141 | assert ( 142 | a <= b, 143 | 'invalid params to randomFloat' 144 | ); 145 | 146 | var range = b - a; 147 | 148 | var rnd = a + Math.random() * range; 149 | 150 | return rnd; 151 | } 152 | 153 | /** 154 | Generate a random value from a normal distribution 155 | */ 156 | function randomNorm(mean, variance) 157 | { 158 | // Declare variables for the points and radius 159 | var x1, x2, w; 160 | 161 | // Repeat until suitable points are found 162 | do 163 | { 164 | x1 = 2.0 * randomFloat() - 1.0; 165 | x2 = 2.0 * randomFloat() - 1.0; 166 | w = x1 * x1 + x2 * x2; 167 | } while (w >= 1.0 || w == 0); 168 | 169 | // compute the multiplier 170 | w = Math.sqrt((-2.0 * Math.log(w)) / w); 171 | 172 | // compute the gaussian-distributed value 173 | var gaussian = x1 * w; 174 | 175 | // Shift the gaussian value according to the mean and variance 176 | return (gaussian * variance) + mean; 177 | } 178 | 179 | /** 180 | Choose a random argument value uniformly randomly 181 | */ 182 | function randomChoice() 183 | { 184 | assert ( 185 | arguments.length > 0, 186 | 'must supply at least one possible choice' 187 | ); 188 | 189 | var idx = randomInt(0, arguments.length - 1); 190 | 191 | return arguments[idx]; 192 | } 193 | 194 | /** 195 | Generate a weighed random choice function 196 | */ 197 | function genChoiceFn() 198 | { 199 | assert ( 200 | arguments.length > 0 && arguments.length % 2 === 0, 201 | 'invalid argument count: ' + arguments.length 202 | ); 203 | 204 | var numChoices = arguments.length / 2; 205 | 206 | var choices = []; 207 | var weights = []; 208 | var weightSum = 0; 209 | 210 | for (var i = 0; i < numChoices; ++i) 211 | { 212 | var choice = arguments[2*i]; 213 | var weight = arguments[2*i + 1]; 214 | 215 | choices.push(choice); 216 | weights.push(weight); 217 | 218 | weightSum += weight; 219 | } 220 | 221 | assert ( 222 | weightSum > 0, 223 | 'weight sum must be positive' 224 | ); 225 | 226 | var limits = []; 227 | var limitSum = 0; 228 | 229 | for (var i = 0; i < weights.length; ++i) 230 | { 231 | var normWeight = weights[i] / weightSum; 232 | 233 | limitSum += normWeight; 234 | 235 | limits[i] = limitSum; 236 | } 237 | 238 | function choiceFn() 239 | { 240 | var r = Math.random(); 241 | 242 | for (var i = 0; i < numChoices; ++i) 243 | { 244 | if (r < limits[i]) 245 | return choices[i]; 246 | } 247 | 248 | return choices[numChoices-1]; 249 | } 250 | 251 | return choiceFn; 252 | } 253 | 254 | /** 255 | Left-pad a string to a minimum length 256 | */ 257 | function leftPadStr(str, minLen, padStr) 258 | { 259 | if (padStr === undefined) 260 | padStr = ' '; 261 | 262 | var str = String(str); 263 | 264 | while (str.length < minLen) 265 | str = padStr + str; 266 | 267 | return str; 268 | } 269 | 270 | /** 271 | Capitalize a string 272 | */ 273 | function capitalize(str) 274 | { 275 | if (str.length === 0) 276 | return str; 277 | 278 | return str[0].toUpperCase() + str.substr(1); 279 | } 280 | 281 | /** 282 | Resample and normalize an array of data points 283 | */ 284 | function resample(data, numSamples, outLow, outHigh, inLow, inHigh) 285 | { 286 | // Compute the number of data points per samples 287 | var ptsPerSample = data.length / numSamples; 288 | 289 | // Compute the number of samples 290 | var numSamples = Math.floor(data.length / ptsPerSample); 291 | 292 | // Allocate an array for the output samples 293 | var samples = new Array(numSamples); 294 | 295 | // Extract the samples 296 | for (var i = 0; i < numSamples; ++i) 297 | { 298 | samples[i] = 0; 299 | 300 | var startI = Math.floor(i * ptsPerSample); 301 | var endI = Math.min(Math.ceil((i+1) * ptsPerSample), data.length); 302 | var numPts = endI - startI; 303 | 304 | for (var j = startI; j < endI; ++j) 305 | samples[i] += data[j]; 306 | 307 | samples[i] /= numPts; 308 | } 309 | 310 | // If the input range is not specified 311 | if (inLow === undefined && inHigh === undefined) 312 | { 313 | // Min and max sample values 314 | var inLow = Infinity; 315 | var inHigh = -Infinity; 316 | 317 | // Compute the min and max sample values 318 | for (var i = 0; i < numSamples; ++i) 319 | { 320 | inLow = Math.min(inLow, samples[i]); 321 | inHigh = Math.max(inHigh, samples[i]); 322 | } 323 | } 324 | 325 | // Compute the input range 326 | var iRange = (inHigh > inLow)? (inHigh - inLow):1; 327 | 328 | // Compute the output range 329 | var oRange = outHigh - outLow; 330 | 331 | // Normalize the samples 332 | samples.forEach( 333 | function (v, i) 334 | { 335 | var normVal = (v - inLow) / iRange; 336 | samples[i] = outLow + (normVal * oRange); 337 | } 338 | ); 339 | 340 | // Return the normalized samples 341 | return samples; 342 | } 343 | 344 | -------------------------------------------------------------------------------- /gradient.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * Gradient: an Artificial Life Experiment 4 | * Copyright (C) 2011 Maxime Chevalier-Boisvert 5 | * 6 | * This file is part of Gradient. 7 | * 8 | * Gradient is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * Gradient is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with Gradient. If not, see . 20 | * 21 | * For more information about this program, please e-mail the 22 | * author, Maxime Chevalier-Boisvert at: 23 | * maximechevalierb /at/ gmail /dot/ com 24 | * 25 | *****************************************************************************/ 26 | 27 | //============================================================================ 28 | // Page interface code 29 | //============================================================================ 30 | 31 | // GUI redrawing delay 32 | const GUI_REDRAW_DELAY = 0.2; 33 | 34 | // Speed count interval 35 | const SPEED_COUNT_INTERV = 3; 36 | 37 | // Movement controls 38 | const CTRL_UP = 0; 39 | const CTRL_DOWN = 1; 40 | const CTRL_LEFT = 2; 41 | const CTRL_RIGHT = 3; 42 | 43 | /** 44 | Called after page load to initialize needed resources 45 | */ 46 | function init() 47 | { 48 | // Find the debug and stats text elements 49 | debugTextElem = findElementById("debug_text"); 50 | statsTextElem = findElementById("stats_text"); 51 | 52 | // Find the control button elements 53 | zoomInButton = findElementById("zoom_in_button"); 54 | zoomOutButton = findElementById("zoom_out_button"); 55 | realTimeButton = findElementById("real_time_button"); 56 | fastModeButton = findElementById("fast_mode_button"); 57 | 58 | // Get a reference to the canvas 59 | canvas = document.getElementById("canvas"); 60 | 61 | // Set the canvas size 62 | canvas.width = 512; 63 | canvas.height = 512; 64 | 65 | // Get a 2D context for the drawing canvas 66 | canvasCtx = canvas.getContext("2d"); 67 | 68 | // Clear the canvas 69 | clearCanvas(canvas, canvasCtx); 70 | 71 | // Create the genetic algorithm instance 72 | genAlg = new GenAlg(AntAgent); 73 | 74 | // Create the world instance 75 | world = new World(); 76 | 77 | // Generate the world map 78 | world.generate( 79 | 128, // Width 80 | 128, // Height 81 | true, // Plants respawn flag 82 | undefined, 83 | undefined, 84 | undefined, 85 | 10, // Row walls mean 86 | 1, // Row walls var 87 | 10, // Col walls mean 88 | 1 // Col walls var 89 | ); 90 | 91 | // Initialize the camera coordinates 92 | xCoord = 0; 93 | yCoord = 0; 94 | 95 | // Initialize the zoom level 96 | zoomLevel = WORLD_ZOOM_MAX - 4; 97 | 98 | // Movement control states 99 | controls = []; 100 | 101 | // Last redrawing time 102 | lastRedraw = 0; 103 | 104 | // Set the update function to be called regularly 105 | this.updateInterv = setInterval( 106 | update, 107 | WORLD_UPDATE_TIME_SLICE * 1000 108 | ); 109 | 110 | // Initialize the button states 111 | zoomInButton.disabled = (zoomLevel >= WORLD_ZOOM_MAX); 112 | zoomOutButton.disabled = (zoomLevel <= WORLD_ZOOM_MIN); 113 | realTimeButton.disabled = (world.fastMode === false); 114 | fastModeButton.disabled = (world.fastMode === true); 115 | 116 | // Store the starting time in seconds 117 | startTimeSecs = getTimeSecs(); 118 | 119 | // Initialize the speed count parameters 120 | speedCountStartTime = getTimeSecs(); 121 | speedCountStartItrs = 0; 122 | itrsPerSec = 0; 123 | 124 | } 125 | window.addEventListener("load", init, false); 126 | 127 | /** 128 | Key press handler 129 | */ 130 | function keyDown(event) 131 | { 132 | switch (event.keyCode) 133 | { 134 | case 37: controls[CTRL_LEFT] = true; break; 135 | case 38: controls[CTRL_UP] = true; break; 136 | case 39: controls[CTRL_RIGHT] = true; break; 137 | case 40: controls[CTRL_DOWN] = true; break; 138 | } 139 | 140 | // Prevent the default key behavior (window movement) 141 | event.preventDefault(); 142 | } 143 | window.addEventListener("keydown", keyDown, false); 144 | 145 | /** 146 | Key release handler 147 | */ 148 | function keyUp(event) 149 | { 150 | switch (event.keyCode) 151 | { 152 | case 37: controls[CTRL_LEFT] = false; break; 153 | case 38: controls[CTRL_UP] = false; break; 154 | case 39: controls[CTRL_RIGHT] = false; break; 155 | case 40: controls[CTRL_DOWN] = false; break; 156 | } 157 | 158 | // Prevent the default key behavior (window movement) 159 | event.preventDefault(); 160 | } 161 | window.addEventListener("keyup", keyUp, false); 162 | 163 | /** 164 | Find an element in the HTML document by its id 165 | */ 166 | function findElementById(id, elem) 167 | { 168 | if (elem === undefined) 169 | elem = document 170 | 171 | for (k in elem.childNodes) 172 | { 173 | var child = elem.childNodes[k]; 174 | 175 | if (child.attributes) 176 | { 177 | var childId = child.getAttribute('id'); 178 | 179 | if (childId == id) 180 | return child; 181 | } 182 | 183 | var nestedElem = findElementById(id, child); 184 | 185 | if (nestedElem) 186 | return nestedElem; 187 | } 188 | 189 | return null; 190 | } 191 | 192 | /** 193 | Print text to the page, for debugging purposes 194 | */ 195 | function dprintln(text) 196 | { 197 | debugTextElem.innerHTML += escapeHTML(text + '\n'); 198 | } 199 | 200 | /** 201 | Set the text in the stats box 202 | */ 203 | function printStats(text) 204 | { 205 | statsTextElem.innerHTML = escapeHTML(text); 206 | } 207 | 208 | /** 209 | Clear a canvas 210 | */ 211 | function clearCanvas(canvas, canvasCtx) 212 | { 213 | canvasCtx.fillStyle = "#111111"; 214 | canvasCtx.fillRect(0, 0, canvas.width, canvas.height); 215 | } 216 | 217 | /** 218 | Update the state of the system 219 | */ 220 | function update() 221 | { 222 | // Update the camera movement 223 | if (controls[CTRL_LEFT]) 224 | moveLeft(); 225 | if (controls[CTRL_RIGHT]) 226 | moveRight(); 227 | if (controls[CTRL_UP]) 228 | moveUp(); 229 | if (controls[CTRL_DOWN]) 230 | moveDown(); 231 | 232 | // If running in fast mode, update the world at every update 233 | if (world.fastMode === true) 234 | { 235 | genAlg.update(); 236 | world.update(); 237 | } 238 | 239 | // If the GUI needs to be redrawn 240 | if (getTimeSecs() > lastRedraw + GUI_REDRAW_DELAY) 241 | { 242 | // If running in real-time, update only before rendering 243 | if (world.fastMode === false) 244 | { 245 | genAlg.update(); 246 | world.update(); 247 | } 248 | 249 | // Render the world 250 | world.render(canvas, canvasCtx, xCoord, yCoord, zoomLevel); 251 | 252 | // Compute the time spent running 253 | var timeRunningSecs = Math.round(getTimeSecs() - startTimeSecs); 254 | 255 | // Compute the percentage of plants still available 256 | var plantPercent = (100 * world.availPlants / world.numPlants).toFixed(1); 257 | 258 | // Print some statistics 259 | printStats( 260 | 'time running: ' + timeRunningSecs + 's\n' + 261 | 'iterations/s: ' + itrsPerSec + '\n' + 262 | '\n' + 263 | 'ind. count : ' + genAlg.indCount + '\n' + 264 | 'seed inds. : ' + genAlg.seedCount + '\n' + 265 | 'itr. count : ' + world.itrCount + '\n' + 266 | 'eaten plants: ' + world.eatenPlantCount + '\n' + 267 | '\n' + 268 | 'live agents : ' + world.population.length + '\n' + 269 | 'avail. plants: ' + plantPercent + '%\n' + 270 | //'built blocks : ' + world.builtBlocks.length + '\n' + 271 | '\n' + 272 | 'zoom level: ' + zoomLevel + '\n' + 273 | 'camera x : ' + xCoord + '\n' + 274 | 'camera y : ' + yCoord 275 | ); 276 | 277 | // Update the last redraw time 278 | lastRedraw = getTimeSecs(); 279 | } 280 | 281 | // If the speed count is to be update 282 | if (getTimeSecs() > speedCountStartTime + SPEED_COUNT_INTERV) 283 | { 284 | // Recompute the update rate 285 | var itrCount = world.itrCount - speedCountStartItrs; 286 | itrsPerSec = Math.round(itrCount / SPEED_COUNT_INTERV); 287 | speedCountStartItrs = world.itrCount; 288 | speedCountStartTime = getTimeSecs(); 289 | } 290 | } 291 | 292 | /** 293 | Augment the zoom level 294 | */ 295 | function zoomIn() 296 | { 297 | // Increment the zoom level if possible 298 | if (zoomLevel < WORLD_ZOOM_MAX) 299 | ++zoomLevel; 300 | 301 | // Enable the zoom out button 302 | zoomOutButton.disabled = false; 303 | 304 | // If zooming in is no longer possible, disable the button 305 | if (zoomLevel >= WORLD_ZOOM_MAX) 306 | zoomInButton.disabled = true; 307 | } 308 | 309 | /** 310 | Reduce the zoom level 311 | */ 312 | function zoomOut() 313 | { 314 | // If we are at the minimum zoom level, stop 315 | if (zoomLevel === WORLD_ZOOM_MIN) 316 | return; 317 | 318 | // Decrement the zoom level 319 | --zoomLevel; 320 | 321 | // Enable the zoom in button 322 | zoomInButton.disabled = false; 323 | 324 | // If zooming out is no longer possible, disable the button 325 | if (zoomLevel === WORLD_ZOOM_MIN) 326 | zoomOutButton.disabled = true; 327 | 328 | // Obtain the sprite size for this zoom level 329 | var spriteSize = WORLD_SPRITE_SIZES[zoomLevel]; 330 | 331 | // Compute the coordinates at the corner of the map 332 | var cornerX = world.gridWidth - canvas.width / spriteSize; 333 | var cornerY = world.gridHeight - canvas.height / spriteSize; 334 | 335 | // Update the camera coordinates 336 | xCoord = Math.max(0, Math.min(xCoord, cornerX)); 337 | yCoord = Math.max(0, Math.min(yCoord, cornerY)); 338 | } 339 | 340 | /** 341 | Augment the world update rate 342 | */ 343 | function goFaster() 344 | { 345 | world.fastMode = true; 346 | 347 | realTimeButton.disabled = false; 348 | fastModeButton.disabled = true; 349 | } 350 | 351 | /** 352 | Reduce the world update rate 353 | */ 354 | function goSlower() 355 | { 356 | world.fastMode = false; 357 | 358 | realTimeButton.disabled = true; 359 | fastModeButton.disabled = false; 360 | } 361 | 362 | /** 363 | Move the camera left 364 | */ 365 | function moveLeft() 366 | { 367 | // compute the movement delta 368 | var delta = WORLD_ZOOM_MAX - (zoomLevel - WORLD_ZOOM_MIN) + 1; 369 | 370 | // compute the updated coordinates 371 | var newXCoord = xCoord - delta; 372 | 373 | // Update the coordinates 374 | xCoord = Math.max(0, newXCoord); 375 | } 376 | 377 | /** 378 | Move the camera right 379 | */ 380 | function moveRight() 381 | { 382 | // compute the movement delta 383 | var delta = WORLD_ZOOM_MAX - (zoomLevel - WORLD_ZOOM_MIN) + 1; 384 | 385 | // compute the updated coordinates 386 | var newXCoord = xCoord + delta; 387 | 388 | // Obtain the sprite size for this zoom level 389 | var spriteSize = WORLD_SPRITE_SIZES[zoomLevel]; 390 | 391 | // Compute the coordinates at the corner of the map 392 | var cornerX = Math.max(world.gridWidth - canvas.width / spriteSize, 0); 393 | 394 | // Update the coordinates 395 | xCoord = Math.min(newXCoord, cornerX); 396 | } 397 | 398 | /** 399 | Move the camera up 400 | */ 401 | function moveUp() 402 | { 403 | // compute the movement delta 404 | var delta = WORLD_ZOOM_MAX - (zoomLevel - WORLD_ZOOM_MIN) + 1; 405 | 406 | // compute the updated coordinates 407 | var newYCoord = yCoord - delta; 408 | 409 | // Update the coordinates 410 | yCoord = Math.max(0, newYCoord); 411 | } 412 | 413 | /** 414 | Move the camera down 415 | */ 416 | function moveDown() 417 | { 418 | // compute the movement delta 419 | var delta = WORLD_ZOOM_MAX - (zoomLevel - WORLD_ZOOM_MIN) + 1; 420 | 421 | // compute the updated coordinates 422 | var newYCoord = yCoord + delta; 423 | 424 | // Obtain the sprite size for this zoom level 425 | var spriteSize = WORLD_SPRITE_SIZES[zoomLevel]; 426 | 427 | // Compute the coordinates at the corner of the map 428 | var cornerY = Math.max(world.gridHeight - canvas.height / spriteSize, 0); 429 | 430 | // Update the coordinates 431 | yCoord = Math.min(newYCoord, cornerY); 432 | } 433 | 434 | -------------------------------------------------------------------------------- /agents.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * Gradient: an Artificial Life Experiment 4 | * Copyright (C) 2011 Maxime Chevalier-Boisvert 5 | * 6 | * This file is part of Gradient. 7 | * 8 | * Gradient is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * Gradient is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with Gradient. If not, see . 20 | * 21 | * For more information about this program, please e-mail the 22 | * author, Maxime Chevalier-Boisvert at: 23 | * maximechevalierb /at/ gmail /dot/ com 24 | * 25 | *****************************************************************************/ 26 | 27 | //============================================================================ 28 | // Virtual Agents 29 | //============================================================================ 30 | 31 | // Front direction vectors associated with ant directions 32 | const FRONT_VECTORS = 33 | [ 34 | new Vector2( 0,-1), 35 | new Vector2( 1, 0), 36 | new Vector2( 0, 1), 37 | new Vector2(-1, 0) 38 | ]; 39 | 40 | // Side direction vectors associated with ant directions 41 | const SIDE_VECTORS = 42 | [ 43 | new Vector2( 1, 0), 44 | new Vector2( 0, 1), 45 | new Vector2(-1, 0), 46 | new Vector2( 0,-1) 47 | ]; 48 | 49 | // Possible directions 50 | const AGENT_DIR_UP = 0; 51 | const AGENT_DIR_RIGHT = 1; 52 | const AGENT_DIR_DOWN = 2; 53 | const AGENT_DIR_LEFT = 3; 54 | 55 | // Possible actions 56 | const ACTION_DO_NOTHING = 0; 57 | const ACTION_MOVE_FORWARD = 1; 58 | const ACTION_ROTATE_LEFT = 2; 59 | const ACTION_ROTATE_RIGHT = 3; 60 | const ACTION_CONSUME = 4; 61 | const ACTION_REPRODUCE = 5; 62 | const ACTION_BUILD = 6; 63 | 64 | // Total number of possible actions 65 | const NUM_ACTIONS = ACTION_REPRODUCE + 1; 66 | 67 | // Starting food, water and energy quantities 68 | const START_FOOD = 250; 69 | const START_WATER = 500; 70 | const START_ENERGY = 250; 71 | 72 | // Maximum food and water and energy quantities 73 | const MAX_FOOD = 5000; 74 | const MAX_WATER = 5000; 75 | const MAX_ENERGY = 5000; 76 | 77 | // Quantities of food and water extracted by consumption 78 | const FOOD_CONS_QTY = 250; 79 | const WATER_CONS_QTY = 500; 80 | 81 | // Energy cost to produce offspring 82 | const OFFSPRING_COST = START_ENERGY + START_FOOD + 100; 83 | 84 | // Energy cost to build a wall block 85 | const BUILD_COST = 50; 86 | 87 | /** 88 | Base agent class 89 | */ 90 | function Agent() 91 | { 92 | // Reset all agent parameters 93 | this.reset(); 94 | } 95 | 96 | /** 97 | Reset the agent's parameters to their initial values 98 | */ 99 | Agent.prototype.reset = function () 100 | { 101 | // Reset the position 102 | this.position = new Vector2(0, 0); 103 | 104 | // Select a random direction for the ant 105 | this.direction = randomInt(AGENT_DIR_UP, AGENT_DIR_LEFT); 106 | 107 | // Reset the sleeping state 108 | this.sleeping = false; 109 | 110 | // Reset the agent's age 111 | this.age = 0; 112 | 113 | // Reset the food amount 114 | this.food = START_FOOD; 115 | 116 | // Reset the water amount 117 | this.water = START_WATER; 118 | 119 | // Reset the energy level 120 | this.energy = START_ENERGY; 121 | } 122 | 123 | /** 124 | Update the state of the agent 125 | */ 126 | Agent.prototype.update = function () 127 | { 128 | // Increment the agent's age 129 | this.age += 1; 130 | 131 | // If we have food and water 132 | if (this.food > 0 && this.water > 0) 133 | { 134 | // If water is the limiting element 135 | if (this.food >= this.water) 136 | { 137 | assert ( 138 | this.food > 0, 139 | 'no food available' 140 | ); 141 | 142 | // Food + water => energy 143 | this.energy += this.water; 144 | this.food -= this.water; 145 | this.water = 0; 146 | } 147 | else 148 | { 149 | assert ( 150 | this.water > 0, 151 | 'no water available' 152 | ); 153 | 154 | // Food + water => energy 155 | this.energy += this.food; 156 | this.water -= this.food; 157 | this.food = 0; 158 | } 159 | } 160 | 161 | // Decrement the energy level, living cost energy 162 | this.energy -= 1; 163 | 164 | // Think and choose an action to perform 165 | var action = this.think(); 166 | 167 | // Switch on the action 168 | switch (action) 169 | { 170 | // To do nothing 171 | case ACTION_DO_NOTHING: 172 | { 173 | } 174 | break; 175 | 176 | // To move forward 177 | case ACTION_MOVE_FORWARD: 178 | { 179 | // Attempt to move to the cell just ahead 180 | var pos = this.frontCellPos(0, 1); 181 | world.moveAgent(this, pos.x, pos.y); 182 | } 183 | break; 184 | 185 | // To rotate left 186 | case ACTION_ROTATE_LEFT: 187 | { 188 | // Shift our direction to the left 189 | this.direction = Math.abs((this.direction - 1) % 4); 190 | } 191 | break; 192 | 193 | // To rotate right 194 | case ACTION_ROTATE_RIGHT: 195 | { 196 | // Shift our direction to the right 197 | this.direction = Math.abs((this.direction + 1) % 4); 198 | } 199 | break; 200 | 201 | // To consume resources 202 | case ACTION_CONSUME: 203 | { 204 | // Attempt to consume what is in front of us 205 | this.consume(); 206 | } 207 | break; 208 | 209 | // To make offspring 210 | case ACTION_REPRODUCE: 211 | { 212 | // Attempt to reproduce 213 | this.reproduce(); 214 | } 215 | break; 216 | 217 | // To build a wall block 218 | case ACTION_BUILD: 219 | { 220 | // Attempt to build 221 | this.build(); 222 | } 223 | break; 224 | 225 | default: 226 | error('invalid agent action'); 227 | } 228 | 229 | assert( 230 | this.direction >= AGENT_DIR_UP && 231 | this.direction <= AGENT_DIR_LEFT, 232 | 'invalid agent direction after update' 233 | ); 234 | } 235 | 236 | /** 237 | Process environmental inputs and choose an action. 238 | To be set on each agent 239 | */ 240 | Agent.prototype.think = function () 241 | { 242 | error('think function not set'); 243 | } 244 | 245 | /** 246 | Test if this agent is still alive 247 | */ 248 | Agent.prototype.isAlive = function () 249 | { 250 | // The ant is alive if it still has energy 251 | return (this.energy > 0); 252 | } 253 | 254 | /** 255 | Perform the consumption action 256 | */ 257 | Agent.prototype.consume = function () 258 | { 259 | // compute the position of the cell just ahead 260 | var pos = this.frontCellPos(0, 1); 261 | 262 | // If this is a plant we can eat 263 | if ( 264 | this.food + FOOD_CONS_QTY <= MAX_FOOD && 265 | world.eatPlant(pos.x, pos.y) === true) 266 | { 267 | // Gain food 268 | this.food += FOOD_CONS_QTY; 269 | 270 | // Eating successful 271 | return true; 272 | } 273 | 274 | // Otherwise, if this cell is water 275 | else if ( 276 | this.water + WATER_CONS_QTY <= MAX_WATER && 277 | world.cellIsType(pos.x, pos.y, CELL_WATER) === true) 278 | { 279 | // Gain water 280 | this.water += WATER_CONS_QTY; 281 | 282 | // Consumption successful 283 | return true; 284 | } 285 | 286 | // Consumption failed 287 | return false; 288 | } 289 | 290 | /** 291 | Attempt to produce offspring 292 | */ 293 | Agent.prototype.reproduce = function () 294 | { 295 | // If we do not have enough energy to produce offspring, do nothing 296 | if (this.energy < OFFSPRING_COST) 297 | return; 298 | 299 | // Subtract the energy required to produce offspring 300 | this.energy -= OFFSPRING_COST; 301 | 302 | // Produce offspring from this agent 303 | genAlg.makeOffspring(this); 304 | } 305 | 306 | /** 307 | To build a wall block 308 | */ 309 | Agent.prototype.build = function () 310 | { 311 | // If we do not have enough energy to build a block, do nothing 312 | if (this.energy < BUILD_COST) 313 | return; 314 | 315 | // Subtract the energy require to build 316 | this.energy -= BUILD_COST; 317 | 318 | // Get the position of the cell ahead of us 319 | pos = this.frontCellPos(0, 1); 320 | 321 | // Try to build a block at the cell in front of us 322 | world.buildBlock(pos.x, pos.y); 323 | } 324 | 325 | /** 326 | Compute a cell position relative to our direction 327 | */ 328 | Agent.prototype.frontCellPos = function (x, y) 329 | { 330 | // compute the absolute cell position 331 | var frontVec = Vector2.scalarMul(FRONT_VECTORS[this.direction], y); 332 | var sideVec = Vector2.scalarMul(SIDE_VECTORS[this.direction], x); 333 | var cellPos = Vector2.add(this.position, Vector2.add(frontVec, sideVec)); 334 | 335 | // Return the computed cell position 336 | return cellPos; 337 | } 338 | 339 | /** 340 | @class Ant agent constructor 341 | @extends Agent 342 | */ 343 | function AntAgent(connVecs) 344 | { 345 | assert ( 346 | connVecs instanceof Array, 347 | 'expected connection vectors' 348 | ); 349 | 350 | assert ( 351 | connVecs.length === AntAgent.numStateVars, 352 | 'need connection vectors for each state var' 353 | ); 354 | 355 | // Store the connection vectors 356 | this.connVecs = connVecs; 357 | 358 | // Compile the think function 359 | this.think = this.compile(); 360 | 361 | // Initialize the state variables 362 | for (var i = 0; i < AntAgent.numStateVars; ++i) 363 | this['s' + i] = 0; 364 | } 365 | AntAgent.prototype = new Agent(); 366 | 367 | /** 368 | Number of visible cell inputs. 369 | 370 | Agent's view: 371 | F 372 | | 373 | X X X 374 | L- X X X - R 375 | X A x 376 | 377 | 8 visible cells x 5 attributes per cell = 40 boolean inputs 378 | */ 379 | AntAgent.numCellInputs = 40; 380 | 381 | /** 382 | Number of random inputs 383 | */ 384 | AntAgent.numRndInputs = 4; 385 | 386 | /* 387 | Number of field inputs. 388 | 3 local properties (food, water, energy). 389 | */ 390 | AntAgent.numFieldInputs = 3; 391 | 392 | /* 393 | Total number of agent inputs 394 | */ 395 | AntAgent.numInputs = 396 | AntAgent.numCellInputs + 397 | AntAgent.numRndInputs + 398 | AntAgent.numFieldInputs; 399 | 400 | /** 401 | Number of agent state variables 402 | */ 403 | AntAgent.numStateVars = 16 + NUM_ACTIONS; 404 | 405 | /** 406 | Maximum number of inputs per connection vector 407 | */ 408 | AntAgent.maxStateInputs = 8; 409 | 410 | /** 411 | Maximum neural connection weight 412 | */ 413 | AntAgent.maxWeight = 10.0; 414 | 415 | /** 416 | Minimum neural connection weight 417 | */ 418 | AntAgent.minWeight = -10; 419 | 420 | /** 421 | Add an input to a state connection vector 422 | */ 423 | AntAgent.addStateInput = function (connVec) 424 | { 425 | assert ( 426 | connVec.inputs.length < AntAgent.maxStateInputs, 427 | 'too many inputs' 428 | ); 429 | 430 | // Until a new input is added 431 | while (true) 432 | { 433 | // Choose a random input 434 | if (randomInt(0, 1) === 0) 435 | var varName = 'i' + randomInt(0, AntAgent.numInputs - 1); 436 | else 437 | var varName = 'this.s' + randomInt(0, AntAgent.numStateVars - 1); 438 | 439 | // If the variable is already in the list, skip it 440 | if (connVec.inputs.indexOf(varName) !== -1) 441 | continue; 442 | 443 | // Add the variable to the inputs 444 | connVec.inputs.push(varName); 445 | 446 | // Choose a random weight for the connection 447 | connVec.weights.push( 448 | randomFloat(AntAgent.minWeight, AntAgent.maxWeight) 449 | ); 450 | 451 | // Break out of the loop 452 | break; 453 | } 454 | } 455 | 456 | /** 457 | Factory function to create a new ant agent 458 | */ 459 | AntAgent.newAgent = function () 460 | { 461 | /** 462 | Generate a connection vector for a state variable 463 | */ 464 | function genConnVector() 465 | { 466 | // Choose the number of connections for this 467 | var numInputs = randomInt(1, AntAgent.maxStateInputs); 468 | 469 | var connVec = { 470 | inputs: [], 471 | weights: [] 472 | }; 473 | 474 | // Until all inputs are added 475 | for (var numAdded = 0; numAdded < numInputs;) 476 | { 477 | // Add an input connection 478 | AntAgent.addStateInput(connVec); 479 | 480 | // Increment the number of inputs added 481 | ++numAdded; 482 | } 483 | 484 | // Return the connection vector 485 | return connVec; 486 | } 487 | 488 | assert ( 489 | AntAgent.numStateVars >= NUM_ACTIONS, 490 | 'insufficient number of state variables' 491 | ); 492 | 493 | // Array for the state variable connection vectors 494 | var connVecs = new Array(AntAgent.numStateVars); 495 | 496 | // Generate connections for each state variable 497 | for (var i = 0; i < AntAgent.numStateVars; ++i) 498 | connVecs[i] = genConnVector(); 499 | 500 | // Create the new agent 501 | return new AntAgent(connVecs); 502 | } 503 | 504 | /** 505 | Return a mutated version of an agent 506 | */ 507 | AntAgent.mutate = function (agent, mutProb) 508 | { 509 | assert ( 510 | agent instanceof AntAgent, 511 | 'expected ant agent' 512 | ); 513 | 514 | assert ( 515 | mutProb >= 0 && mutProb <= 1, 516 | 'invalid mutation probability' 517 | ); 518 | 519 | // Array of connection vectors 520 | var connVecs = []; 521 | 522 | // For each connection vector 523 | for (var i = 0; i < agent.connVecs.length; ++i) 524 | { 525 | var oldVec = agent.connVecs[i]; 526 | 527 | // Copy the inputs and weights 528 | var newVec = { 529 | inputs : oldVec.inputs.slice(0), 530 | weights: oldVec.weights.slice(0) 531 | }; 532 | 533 | // For each mutation attempt 534 | for (var j = 0; j < AntAgent.maxStateInputs; ++j) 535 | { 536 | // If the mutation probability is not met, try again 537 | if (randomFloat(0, 1) >= mutProb) 538 | continue; 539 | 540 | // Get the current number of inputs 541 | var numInputs = newVec.inputs.length; 542 | 543 | // If we should remove an input 544 | if (randomBool() === true) 545 | { 546 | // If there are too few inputs, try again 547 | if (numInputs <= 1) 548 | continue; 549 | 550 | // Choose a random input and remove it 551 | var idx = randomInt(0, numInputs - 1); 552 | newVec.inputs.splice(idx, 1); 553 | newVec.weights.splice(idx, 1); 554 | } 555 | 556 | // If we should add an input 557 | else 558 | { 559 | // If there are too many inputs, try again 560 | if (numInputs >= AntAgent.maxStateInputs) 561 | continue; 562 | 563 | // Add an input to the rule 564 | AntAgent.addStateInput(newVec); 565 | } 566 | } 567 | 568 | // Add the mutated connection vector 569 | connVecs.push(newVec); 570 | } 571 | 572 | // Create the new agent 573 | return new AntAgent(connVecs); 574 | } 575 | 576 | /** 577 | Neural network activation function. 578 | Fast approximation to tanh(x/2) 579 | */ 580 | AntAgent.actFunc = function (x) 581 | { 582 | if (x < 0) 583 | { 584 | x = -x; 585 | x = x * (6 + x * (3 + x)); 586 | return -x / (x + 12); 587 | } 588 | else 589 | { 590 | x = x * (6 + x * (3 + x)); 591 | return x / (x + 12); 592 | } 593 | } 594 | 595 | /** 596 | Compile a think function for the ant agent 597 | */ 598 | AntAgent.prototype.compile = function () 599 | { 600 | // Generated source string 601 | var src = ''; 602 | 603 | /** 604 | Add a line of source input 605 | */ 606 | function addLine(str) 607 | { 608 | if (str === undefined) 609 | str = ''; 610 | 611 | src += str + '\n'; 612 | 613 | //dprintln(str); 614 | } 615 | 616 | addLine('\tassert (this instanceof AntAgent)'); 617 | addLine(); 618 | 619 | // Next cell input index 620 | var cellInIdx = 0; 621 | 622 | // For each horizontal cell position 623 | for (var x = -1; x <= 1; ++x) 624 | { 625 | // For each vertical cell position 626 | for (var y = 0; y <= 2; ++y) 627 | { 628 | // If this is the agent's position, skip it 629 | if (x === 0 && y === 0) 630 | continue; 631 | 632 | // Compute the absolute cell position 633 | addLine('\tvar pos = this.frontCellPos(' + x + ', ' + y + ');'); 634 | 635 | addLine('\tif ('); 636 | addLine('\t\tpos.x >= 0 && pos.y >= 0 &&'); 637 | addLine('\t\tpos.x < world.gridWidth && pos.y < world.gridHeight)'); 638 | addLine('\t{'); 639 | addLine('\t\tvar cell = world.getCell(pos.x, pos.y);'); 640 | addLine('\t\tvar i' + (cellInIdx + 0) + ' = (cell.agent !== null)? 1:0;'); 641 | addLine('\t\tvar i' + (cellInIdx + 1) + ' = (cell.type === CELL_WALL)? 1:0;'); 642 | addLine('\t\tvar i' + (cellInIdx + 2) + ' = (cell.type === CELL_WATER)? 1:0;'); 643 | addLine('\t\tvar i' + (cellInIdx + 3) + ' = (cell.type === CELL_PLANT)? 1:0;'); 644 | addLine('\t\tvar i' + (cellInIdx + 4) + ' = (cell.type === CELL_EATEN)? 1:0;'); 645 | addLine('\t}'); 646 | addLine('\telse'); 647 | addLine('\t{'); 648 | addLine('\t\tvar i' + (cellInIdx + 0) + ' = 0;'); 649 | addLine('\t\tvar i' + (cellInIdx + 1) + ' = 1;'); 650 | addLine('\t\tvar i' + (cellInIdx + 2) + ' = 0;'); 651 | addLine('\t\tvar i' + (cellInIdx + 3) + ' = 0;'); 652 | addLine('\t\tvar i' + (cellInIdx + 4) + ' = 0;'); 653 | addLine('\t}'); 654 | 655 | // Increment the cell input index 656 | cellInIdx += 5; 657 | } 658 | } 659 | addLine(); 660 | 661 | // For each random input 662 | for (var i = 0; i < AntAgent.numRndInputs; ++i) 663 | { 664 | var inIdx = AntAgent.numCellInputs + i; 665 | 666 | addLine('\tvar i' + inIdx + ' = randomFloat(-1, 1);'); 667 | } 668 | 669 | /** 670 | Generate a field input 671 | */ 672 | function genFieldInput(idx, field) 673 | { 674 | var inIdx = AntAgent.numCellInputs + AntAgent.numRndInputs + idx; 675 | 676 | addLine('\tvar i' + inIdx + ' = ' + field + ';'); 677 | } 678 | 679 | /** 680 | Generate a state variable update computation 681 | */ 682 | function genUpdate(connVec) 683 | { 684 | var src = ''; 685 | 686 | src += 'AntAgent.actFunc('; 687 | 688 | for (var i = 0; i < connVec.inputs.length; ++i) 689 | { 690 | var input = connVec.inputs[i]; 691 | var weight = connVec.weights[i]; 692 | 693 | if (i !== 0) 694 | src += ' + '; 695 | 696 | src += input + '*' + weight; 697 | } 698 | 699 | src += ')'; 700 | 701 | return src; 702 | } 703 | 704 | // Compile the input computations 705 | genFieldInput(0, 'this.food'); 706 | genFieldInput(1, 'this.water'); 707 | genFieldInput(2, 'this.energy'); 708 | addLine(); 709 | 710 | // Compile the state updates 711 | for (var i = 0; i < this.connVecs.length; ++i) 712 | addLine('\tthis.s' + i + ' = ' + genUpdate(this.connVecs[i]) + ';'); 713 | addLine(); 714 | 715 | // Choose the action to perform 716 | addLine('\tvar maxVal = -Infinity;'); 717 | addLine('\tvar action = 0;\n'); 718 | for (var i = 0; i < NUM_ACTIONS; ++i) 719 | { 720 | var stateIdx = AntAgent.numStateVars - NUM_ACTIONS + i; 721 | 722 | var varName = 'this.s' + stateIdx; 723 | 724 | addLine('\tif (' + varName + ' > maxVal)'); 725 | addLine('\t{'); 726 | addLine('\t\tmaxVal = ' + varName + ';'); 727 | addLine('\t\taction = ' + i + ';'); 728 | addLine('\t}'); 729 | } 730 | addLine(); 731 | 732 | // Return the chosen action 733 | addLine('\treturn action;'); 734 | 735 | // Compile the think function from its source 736 | var thinkFunc = new Function(src); 737 | 738 | // Return the thinking function 739 | return thinkFunc; 740 | } 741 | 742 | -------------------------------------------------------------------------------- /world.js: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * Gradient: an Artificial Life Experiment 4 | * Copyright (C) 2011 Maxime Chevalier-Boisvert 5 | * 6 | * This file is part of Gradient. 7 | * 8 | * Gradient is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * Gradient is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with Gradient. If not, see . 20 | * 21 | * For more information about this program, please e-mail the 22 | * author, Maxime Chevalier-Boisvert at: 23 | * maximechevalierb /at/ gmail /dot/ com 24 | * 25 | *****************************************************************************/ 26 | 27 | //============================================================================ 28 | // Virtual World 29 | //============================================================================ 30 | 31 | // World update duration 32 | const WORLD_UPDATE_TIME_SLICE = 0.1; 33 | 34 | // Number of updates to perform between checks in fast mode 35 | const WORLD_UPDATE_ITR_COUNT = 8; 36 | 37 | // Zoom level constants 38 | const WORLD_ZOOM_MIN = 0; 39 | const WORLD_ZOOM_MAX = 5; 40 | 41 | // Sprite size constants 42 | const WORLD_SPRITE_SIZES = [2, 4, 8, 16, 32, 64]; 43 | 44 | // Plant respawning delay 45 | const PLANT_RESPAWN_DELAY = 3100; 46 | 47 | // Built block decay delay 48 | const BLOCK_DECAY_DELAY = 15000; 49 | 50 | // World cell kinds 51 | const CELL_EMPTY = 0; 52 | const CELL_PLANT = 1; 53 | const CELL_EATEN = 2; 54 | const CELL_WATER = 3; 55 | const CELL_MINE = 4; 56 | const CELL_WALL = 5; 57 | 58 | /** 59 | @class World cell class 60 | */ 61 | function Cell(cellType, agent) 62 | { 63 | // If the cell type is unspecified, make it empty 64 | if (cellType === undefined) 65 | cellType = CELL_EMPTY; 66 | 67 | // If the agent is undefined, make it null 68 | if (agent === undefined) 69 | agent = null; 70 | 71 | /** 72 | Cell type 73 | */ 74 | this.type = cellType; 75 | 76 | /** 77 | Agent at this cell 78 | */ 79 | this.agent = agent; 80 | } 81 | 82 | /** 83 | @class Eaten plant class 84 | */ 85 | function EatenPlant(x, y, time) 86 | { 87 | /** 88 | Plant position 89 | */ 90 | this.x = x; 91 | this.y = y; 92 | 93 | /** 94 | Time at which to respawn 95 | */ 96 | this.respawnTime = time; 97 | 98 | assert ( 99 | isNonNegInt(this.x) && isNonNegInt(this.y), 100 | 'invalid plant coordinates' 101 | ); 102 | 103 | assert ( 104 | isNonNegInt(this.respawnTime), 105 | 'invalid plant respawn time' 106 | ); 107 | } 108 | 109 | /** 110 | @class Built block class 111 | */ 112 | function BuiltBlock(x, y, time) 113 | { 114 | /** 115 | Plant position 116 | */ 117 | this.x = x; 118 | this.y = y; 119 | 120 | /** 121 | Time at which to disappear 122 | */ 123 | this.decayTime = time; 124 | 125 | assert ( 126 | isNonNegInt(this.x) && isNonNegInt(this.y), 127 | 'invalid plant coordinates' 128 | ); 129 | 130 | assert ( 131 | isNonNegInt(this.decayTime), 132 | 'invalid block decay time' 133 | ); 134 | } 135 | 136 | /** 137 | @class Represent a simulated world and its contents 138 | */ 139 | function World() 140 | { 141 | /** 142 | World grid width 143 | */ 144 | this.gridWidth = 0; 145 | 146 | /** 147 | World grid height 148 | */ 149 | this.gridHeight = 0; 150 | 151 | /** 152 | Plants respawning flag 153 | */ 154 | this.plantsRespawn = true; 155 | 156 | /** 157 | Fast update mode flag 158 | */ 159 | this.fastMode = false; 160 | 161 | /** 162 | Total iteration count 163 | */ 164 | this.itrCount = 0; 165 | 166 | /** 167 | Last reset iteration 168 | */ 169 | this.lastResetIt = 0; 170 | 171 | /** 172 | World grid 173 | */ 174 | this.grid = []; 175 | 176 | /** 177 | Population 178 | */ 179 | this.population = []; 180 | 181 | /** 182 | Total number of plant cells 183 | */ 184 | this.numPlants = 0; 185 | 186 | /** 187 | Plants currently available to eat 188 | */ 189 | this.availPlants = 0; 190 | 191 | /** 192 | List of eaten plants 193 | */ 194 | this.eatenPlants = []; 195 | 196 | /** 197 | Total plants eaten count 198 | */ 199 | this.eatenPlantCount = 0; 200 | 201 | /** 202 | List of built blocks 203 | */ 204 | this.builtBlocks = []; 205 | 206 | /** 207 | Cache of sprites last used during rendering 208 | */ 209 | this.spriteCache = []; 210 | 211 | /** 212 | Number of images left to be loaded 213 | */ 214 | this.imgsToLoad = 0; 215 | 216 | var that = this; 217 | function loadImage(fileName) 218 | { 219 | that.imgsToLoad++; 220 | 221 | var img = new Image(); 222 | img.src = fileName; 223 | 224 | img.onload = function () { that.imgsToLoad--; } 225 | 226 | return img; 227 | } 228 | 229 | // Load the sprite images 230 | this.emptySprite = loadImage("images/sprites/grass2.png"); 231 | this.waterSprite = loadImage("images/sprites/water.png"); 232 | this.water2Sprite = loadImage("images/sprites/water2.png"); 233 | this.wallSprite = loadImage("images/sprites/rock.png"); 234 | this.plantSprite = loadImage("images/sprites/moss_green.png"); 235 | this.eatenSprite = loadImage("images/sprites/moss_dark.png"); 236 | this.mineSprite = loadImage("images/sprites/landmine.png"); 237 | this.antUSprite = loadImage("images/sprites/ant_up.png"); 238 | this.antDSprite = loadImage("images/sprites/ant_down.png"); 239 | this.antLSprite = loadImage("images/sprites/ant_left.png"); 240 | this.antRSprite = loadImage("images/sprites/ant_right.png"); 241 | } 242 | 243 | /** 244 | Generate a random world 245 | */ 246 | World.prototype.generate = function ( 247 | width, 248 | height, 249 | plantsRespawn, 250 | waterSeedProb, 251 | plantSeedProb, 252 | mineProb, 253 | rowWallsMean, 254 | rowWallsVar, 255 | colWallsMean, 256 | colWallsVar 257 | ) 258 | { 259 | // Set the default generation parameters 260 | if (plantsRespawn === undefined) 261 | plantsRespawn = false; 262 | if (waterSeedProb === undefined) 263 | waterSeedProb = 0.0012; 264 | if (plantSeedProb === undefined) 265 | plantSeedProb = 0.004; 266 | if (mineProb === undefined) 267 | mineProb = 0; 268 | if (rowWallsMean === undefined) 269 | rowWallsMean = 0; 270 | if (rowWallsVar === undefined) 271 | rowWallsVar = 0; 272 | if (colWallsMean === undefined) 273 | colWallsMean = 0; 274 | if (colWallsVar === undefined) 275 | colWallsVar = 0; 276 | 277 | // Ensure that the parameters are valid 278 | assert (width > 0 && height > 0); 279 | 280 | // Store the grid width and height 281 | this.gridWidth = width; 282 | this.gridHeight = height; 283 | 284 | // Create a new world grid and fill it with empty cells 285 | this.grid = new Array(width * height); 286 | for (var i = 0; i < this.grid.length; ++i) 287 | this.grid[i] = new Cell(); 288 | 289 | // Store the plant respawning flag 290 | this.plantsRespawn = plantsRespawn; 291 | 292 | // Clear the list of eaten plants 293 | this.eatenPlants = []; 294 | 295 | // Reset all counters 296 | this.reset(); 297 | 298 | //******************************* 299 | // Water generation 300 | //******************************* 301 | 302 | // For each row of cells 303 | for (var y = 0; y < height; ++y) 304 | { 305 | // For each column 306 | for (var x = 0; x < width; ++x) 307 | { 308 | // With a given probability 309 | if (randomFloat(0, 1) < waterSeedProb) 310 | { 311 | // Make this a water cell 312 | this.setCell(x, y, new Cell(CELL_WATER)); 313 | } 314 | } 315 | } 316 | 317 | // For each pond generation pass 318 | for (var i = 0; i < 23; ++i) 319 | { 320 | // For each row of cells 321 | for (var y = 1; y < this.gridHeight - 1; ++y) 322 | { 323 | // For each column 324 | for (var x = 1; x < this.gridWidth - 1; ++x) 325 | { 326 | // Count the number of water neighbors 327 | var numWater = this.countNeighbors(x, y, CELL_WATER); 328 | 329 | // With a certain probability 330 | if (randomFloat(0, 1) < 0.02 * numWater + (numWater? 1:0) * 0.004 * Math.exp(numWater)) 331 | { 332 | // Make this a water cell 333 | this.setCell(x, y, new Cell(CELL_WATER)); 334 | } 335 | } 336 | } 337 | } 338 | 339 | //******************************* 340 | // Wall generation 341 | //******************************* 342 | 343 | // Choose a random number of row walls 344 | var numRowWalls = Math.round(randomNorm(rowWallsMean, rowWallsVar)); 345 | 346 | // Create a map for the row walls 347 | var rowWallMap = new Array(this.gridHeight); 348 | 349 | // For each row wall to generate 350 | for (var wallCount = 0; wallCount < numRowWalls;) 351 | { 352 | // Choose a random row 353 | var y = randomInt(2, this.gridHeight - 3); 354 | 355 | // If another wall would be immediately adjacent, skip it 356 | if (rowWallMap[y - 1] === true || rowWallMap[y + 1] === true) 357 | continue; 358 | 359 | // compute the two endpoints 360 | var x1 = randomInt(1, this.gridWidth - 2); 361 | var x2 = randomInt(1, this.gridWidth - 2); 362 | 363 | // compute the length 364 | var len = Math.abs(x1 - x2); 365 | 366 | // If the wall is too short or too long, skip it 367 | if (len < 5 || len > this.gridWidth / 4) 368 | continue; 369 | 370 | // For each column 371 | for (var x = x1; x != x2 && x > 0 && x < this.gridWidth - 1; x += ((x2 - x1) > 0? 1:-1)) 372 | { 373 | // If this cell is water, skip it 374 | if (this.cellIsType(x, y, CELL_WATER) === true) 375 | break; 376 | 377 | // Make this cell a wall 378 | this.setCell(x, y, new Cell(CELL_WALL)); 379 | } 380 | 381 | // Increment the wall count 382 | ++wallCount; 383 | 384 | // update the row wall map 385 | rowWallMap[y] = true; 386 | } 387 | 388 | // Choose a random number of column walls 389 | var numColWalls = Math.round(randomNorm(colWallsMean, colWallsVar)); 390 | 391 | // Create a map for the column walls 392 | var colWallMap = new Array(this.gridWidth); 393 | 394 | // For each row wall to generate 395 | for (var wallCount = 0; wallCount < numColWalls;) 396 | { 397 | // Choose a random column 398 | var x = randomInt(2, this.gridWidth - 3); 399 | 400 | // If another wall would be immediately adjacent, skip it 401 | if (colWallMap[x - 1] === true || colWallMap[x + 1] === true) 402 | continue; 403 | 404 | // compute the two endpoints 405 | var y1 = randomInt(1, this.gridHeight - 2); 406 | var y2 = randomInt(1, this.gridHeight - 2); 407 | 408 | // compute the length 409 | var len = Math.abs(y1 - y2); 410 | 411 | // If the wall is too short or too long, skip it 412 | if (len < 5 || len > this.gridHeight / 4) 413 | continue; 414 | 415 | // For each row 416 | for (var y = y1; y != y2 && y > 0 && y < this.gridHeight; y += ((y2 - y1) > 0? 1:-1)) 417 | { 418 | // If this cell is water or any neighbor is a wall cell, skip it 419 | if (this.cellIsType(x, y, CELL_WATER) === true|| 420 | this.countNeighbors(x, y, CELL_WALL) > 1) 421 | break; 422 | 423 | // Make this cell a wall 424 | this.setCell(x, y, new Cell(CELL_WALL)); 425 | } 426 | 427 | // Increment the wall count 428 | ++wallCount; 429 | 430 | // update the column wall map 431 | colWallMap[x] = true; 432 | } 433 | 434 | //******************************* 435 | // Food generation 436 | //******************************* 437 | 438 | // For each plant generation pass 439 | for (var i = 0; i < 11; ++i) 440 | { 441 | // For each row of cells 442 | for (var y = 1; y < this.gridHeight - 1; ++y) 443 | { 444 | // For each column 445 | for (var x = 1; x < this.gridWidth - 1; ++x) 446 | { 447 | // If this cell is not empty, skip it 448 | if (this.cellIsType(x, y, CELL_EMPTY) === false) 449 | continue; 450 | 451 | // Count the number of water neighbors 452 | var numWater = this.countNeighbors(x, y, CELL_WATER); 453 | 454 | // If there are any water neighbors, continue 455 | if (numWater > 0) 456 | continue; 457 | 458 | // Count the number of plant neighbors 459 | var numPlant = this.countNeighbors(x, y, CELL_PLANT); 460 | 461 | // With a certain probability, if there are no plant neighbors 462 | if (randomFloat(0, 1) < plantSeedProb && numPlant === 0) 463 | { 464 | // Make this a plant cell 465 | this.setCell(x, y, new Cell(CELL_PLANT)); 466 | } 467 | 468 | // Otherwise, if there are plant neighbors 469 | else if (randomFloat(0, 1) < 0.04 * numPlant) 470 | { 471 | // Make this a plant cell with the same color as the neighbors 472 | this.setCell(x, y, new Cell(CELL_PLANT)); 473 | } 474 | } 475 | } 476 | } 477 | 478 | // Count the number of plants in the world 479 | this.numPlants = 0; 480 | for (var i = 0; i < this.grid.length; ++i) 481 | { 482 | if (this.grid[i].type === CELL_PLANT) 483 | this.numPlants++; 484 | } 485 | 486 | // Initialize the number of available plants 487 | this.availPlants = this.numPlants; 488 | 489 | //******************************* 490 | // Border wall generation 491 | //******************************* 492 | 493 | // For each column 494 | for (var x = 0; x < this.gridWidth; ++x) 495 | { 496 | // Make the top border a wall 497 | this.setCell(x, 0, new Cell(CELL_WALL)); 498 | 499 | // Make the bottom border a wall 500 | this.setCell(x, this.gridHeight - 1, new Cell(CELL_WALL)); 501 | } 502 | 503 | // For each row 504 | for (var y = 0; y < this.gridHeight; ++y) 505 | { 506 | // Make the left border a wall 507 | this.setCell(0, y, new Cell(CELL_WALL)); 508 | 509 | // Make the right border a wall 510 | this.setCell(this.gridWidth - 1, y, new Cell(CELL_WALL)); 511 | } 512 | } 513 | 514 | /** 515 | Reset the world to its post-creation state 516 | */ 517 | World.prototype.reset = function () 518 | { 519 | // Store the iteration count 520 | this.lastResetIt = this.itrCount; 521 | 522 | // Respawn all plants 523 | this.respawnPlants(true); 524 | 525 | // Remove all built blocks 526 | this.decayBlocks(true); 527 | 528 | // Clear the current population 529 | this.population = []; 530 | 531 | // Remove any ants from the world grid 532 | for (var i = 0; i < this.grid.length; ++i) 533 | this.grid[i].agent = null; 534 | 535 | for (var i = 0; i < this.grid.length; ++i) 536 | { 537 | assert ( 538 | this.grid[i].agent === null, 539 | 'non-null agent pointer after world reset' 540 | ); 541 | } 542 | } 543 | 544 | /** 545 | Respawn eaten plants 546 | */ 547 | World.prototype.respawnPlants = function (respawnAll) 548 | { 549 | // By default, do not respawn all plants 550 | if (respawnAll === undefined) 551 | respawnAll = false; 552 | 553 | // Remaining eaten plants array 554 | var eatenPlants = []; 555 | 556 | // For each eaten plant 557 | for (var i = 0; i < this.eatenPlants.length; ++i) 558 | { 559 | var plant = this.eatenPlants[i]; 560 | 561 | // If it is not time for this plant to be respawned, skip it 562 | if (plant.respawnTime > this.itrCount && !(respawnAll === true)) 563 | { 564 | eatenPlants.push(plant); 565 | continue; 566 | } 567 | 568 | // Make the corresponding cell a new plant 569 | this.getCell(plant.x, plant.y).type = CELL_PLANT; 570 | 571 | // Increment the available plant count 572 | this.availPlants++; 573 | 574 | assert ( 575 | this.availPlants <= this.numPlants, 576 | 'invalid available plant count' 577 | ); 578 | } 579 | 580 | // Update the eaten plants array 581 | this.eatenPlants = eatenPlants; 582 | } 583 | 584 | /** 585 | Decay built blocks 586 | */ 587 | World.prototype.decayBlocks = function (decayAll) 588 | { 589 | // By default, do not decay all blocks 590 | if (decayAll === undefined) 591 | decayAll = false; 592 | 593 | // Remaining built blocks array 594 | var builtBlocks = []; 595 | 596 | // For each eaten plant 597 | for (var i = 0; i < this.builtBlocks.length; ++i) 598 | { 599 | var block = this.builtBlocks[i]; 600 | 601 | // If it is not time for this block to be removed, skip it 602 | if (block.decayTime > this.itrCount && !(decayAll === true)) 603 | { 604 | builtBlocks.push(block); 605 | continue; 606 | } 607 | 608 | // Make the corresponding cell empty 609 | this.getCell(block.x, block.y).type = CELL_EMPTY; 610 | } 611 | 612 | // Update the built blocks array 613 | this.builtBlocks = builtBlocks; 614 | } 615 | 616 | /** 617 | Update the world state 618 | */ 619 | World.prototype.update = function () 620 | { 621 | // If fast updating mode is enabled 622 | if (this.fastMode === true) 623 | { 624 | // Get the time at which we start this update 625 | var startTime = getTimeSecs(); 626 | 627 | // Until the update time slice is elapsed 628 | while (getTimeSecs() < startTime + WORLD_UPDATE_TIME_SLICE) 629 | { 630 | // If all agents are dead, yield early 631 | if (this.population.length === 0) 632 | return; 633 | 634 | // Perform a small number of update iterations 635 | for (var i = 0; i < WORLD_UPDATE_ITR_COUNT; ++i) 636 | this.iterate(); 637 | } 638 | } 639 | else 640 | { 641 | // Iterate only once 642 | this.iterate(); 643 | } 644 | } 645 | 646 | /** 647 | Perform one world iteration 648 | */ 649 | World.prototype.iterate = function () 650 | { 651 | // For all agents in the population 652 | for (var i = 0; i < this.population.length; ++i) 653 | { 654 | var agent = this.population[i]; 655 | 656 | // Update the agent state 657 | agent.update(); 658 | 659 | // If the agent is no longer alive 660 | if (agent.isAlive() === false) 661 | { 662 | // Get the agent's position 663 | var pos = agent.position; 664 | 665 | // Nullify the agent pointer of its cell 666 | this.getCell(pos.x, pos.y).agent = null; 667 | 668 | // Remove the agent from the population 669 | this.population.splice(i, 1); 670 | 671 | // Move to the next agent in the population 672 | --i; 673 | } 674 | } 675 | 676 | // If eaten plants are to be respawned, place them back in the world 677 | if (this.plantsRespawn === true) 678 | this.respawnPlants(false); 679 | 680 | // Decay the built blocks 681 | this.decayBlocks(false); 682 | 683 | // Increment the iteration count 684 | this.itrCount++; 685 | } 686 | 687 | /** 688 | Render the world 689 | */ 690 | World.prototype.render = function (canvas, canvasCtx, xPos, yPos, zoomLevel) 691 | { 692 | assert ( 693 | isNonNegInt(zoomLevel), 694 | 'invalid zoom level' 695 | ); 696 | 697 | // If there are images left to load 698 | if (this.imgsToLoad > 0) 699 | { 700 | clearCanvas(canvas, canvasCtx); 701 | canvasCtx.fillStyle = "White"; 702 | canvasCtx.fillText("Loading sprites...", 10, 10); 703 | return; 704 | } 705 | 706 | // Ensure that the arguments are valids 707 | assert ( 708 | xPos < this.gridWidth && 709 | yPos < this.gridHeight && 710 | zoomLevel >= WORLD_ZOOM_MIN && 711 | zoomLevel <= WORLD_ZOOM_MAX 712 | ); 713 | 714 | // Get the sprite size for this zoom level 715 | var spriteSize = WORLD_SPRITE_SIZES[zoomLevel - WORLD_ZOOM_MIN]; 716 | 717 | // Compute the number of rows and columns of sprites to render 718 | var numRows = Math.ceil(canvas.height / spriteSize); 719 | var numCols = Math.ceil(canvas.width / spriteSize); 720 | 721 | // Compute the number of sprites to render 722 | var numSprites = numRows * numCols; 723 | 724 | // If the sprite cache size does not match, reset it 725 | if (this.spriteCache.length !== numSprites) 726 | { 727 | clearCanvas(canvas, canvasCtx); 728 | this.spriteCache = new Array(numSprites); 729 | } 730 | 731 | // Choose the animated water sprite 732 | var waterAnim = (this.itrCount % 4 <= 1); 733 | var waterSprite = waterAnim? this.waterSprite:this.water2Sprite; 734 | 735 | // Initialize the grid and frame y positions 736 | var gridY = yPos; 737 | var frameY = 0; 738 | 739 | // For each row 740 | for (var rowIdx = 0; rowIdx < numRows && gridY < this.gridHeight; ++rowIdx) 741 | { 742 | // Reset the grid and framey position 743 | var gridX = xPos; 744 | var frameX = 0; 745 | 746 | // For each column 747 | for (var colIdx = 0; colIdx < numCols && gridX < this.gridWidth; ++colIdx) 748 | { 749 | // Get a reference to this cell 750 | var cell = this.getCell(gridX, gridY); 751 | 752 | // Declare a reference to the sprite to draw 753 | var sprite; 754 | 755 | // If this cell contains an ant 756 | if (cell.agent !== null) 757 | { 758 | // Switch on the ant direction 759 | switch (cell.agent.direction) 760 | { 761 | // Set the sprite according to the direction 762 | case AGENT_DIR_UP : sprite = this.antUSprite; break; 763 | case AGENT_DIR_DOWN : sprite = this.antDSprite; break; 764 | case AGENT_DIR_LEFT : sprite = this.antLSprite; break; 765 | case AGENT_DIR_RIGHT: sprite = this.antRSprite; break; 766 | 767 | // Invalid agent direction 768 | default: 769 | error('invalid agent direction (' + cell.agent.direction + ')'); 770 | } 771 | } 772 | else 773 | { 774 | // Switch on the cell types 775 | switch (cell.type) 776 | { 777 | // Empty cells 778 | case CELL_EMPTY: sprite = this.emptySprite; break; 779 | 780 | // Water cells 781 | case CELL_WATER: sprite = waterSprite; break; 782 | 783 | // Wall cells 784 | case CELL_WALL: sprite = this.wallSprite; break; 785 | 786 | // Alive and eaten plants 787 | case CELL_PLANT: sprite = this.plantSprite; break; 788 | case CELL_EATEN: sprite = this.eatenSprite; break; 789 | 790 | // Mine cell 791 | case CELL_MINE: sprite = this.mineSprite; break; 792 | 793 | // Invalid cell type 794 | default: 795 | error('invalid cell type'); 796 | } 797 | } 798 | 799 | /* 800 | assert ( 801 | sprite instanceof Image, 802 | 'invalid sprite' 803 | ); 804 | 805 | assert ( 806 | isNonNegInt(frameX) && isNonNegInt(frameY), 807 | 'invalid frame coordinates' 808 | ); 809 | 810 | assert ( 811 | isPosInt(spriteSize), 812 | 'invalid sprite size' 813 | ); 814 | */ 815 | 816 | // Get the cached sprite for this frame position 817 | var cachedSprite = this.spriteCache[numCols * rowIdx + colIdx]; 818 | 819 | // If the sprite does not match the cached entry 820 | if (sprite !== cachedSprite) 821 | { 822 | // Draw the scaled sprite at the current frame position 823 | canvasCtx.drawImage(sprite, frameX, frameY, spriteSize, spriteSize); 824 | 825 | // Update the cached sprite 826 | this.spriteCache[numCols * rowIdx + colIdx] = sprite; 827 | } 828 | 829 | // Update the grid and frame position 830 | gridX += 1; 831 | frameX += spriteSize; 832 | } 833 | 834 | // Update the grid and frame position 835 | gridY += 1; 836 | frameY += spriteSize; 837 | } 838 | } 839 | 840 | /** 841 | Place an agent at a specific location on the map 842 | */ 843 | World.prototype.placeAgent = function (agent, x, y) 844 | { 845 | // Ensure that the arguments are valid 846 | assert ( 847 | x < this.gridWidth && 848 | y < this.gridHeight && 849 | agent !== null, 850 | 'invalid arguments to placeAgent' 851 | ); 852 | 853 | // If this cell is not empty, placement failed 854 | if (this.cellIsType(x, y, CELL_EMPTY) === false || 855 | this.getCell(x, y).agent !== null) 856 | return false; 857 | 858 | // Set the ant position 859 | agent.position = new Vector2(x, y); 860 | 861 | // Set the agent pointer for this cell 862 | this.getCell(x, y).agent = agent; 863 | 864 | // Add the ant to the population 865 | this.population.push(agent); 866 | 867 | // Placement successful 868 | return true; 869 | } 870 | 871 | /** 872 | Place an agent on the map at random coordinates 873 | */ 874 | World.prototype.placeAgentRnd = function (agent) 875 | { 876 | assert ( 877 | agent !== null, 878 | 'invalid parameters to placeAgentRnd' 879 | ); 880 | 881 | // Get the initial population size 882 | var initPopSize = this.population.length; 883 | 884 | // Try to place the ant up to 512 times 885 | for (var i = 0; i < 512; ++i) 886 | { 887 | // Choose random coordinates in the world 888 | var x = randomInt(0, this.gridWidth - 1); 889 | var y = randomInt(0, this.gridHeight - 1); 890 | 891 | // If the agent can be placed at these coordinates 892 | if (this.placeAgent(agent, x, y) === true) 893 | { 894 | assert ( 895 | this.population.length === initPopSize + 1, 896 | 'agent not added to population' 897 | ); 898 | 899 | assert ( 900 | world.getCell(agent.position.x, agent.position.y).agent === agent, 901 | 'agent pointer not valid after adding agent' 902 | ); 903 | 904 | // Placement successful 905 | return true; 906 | } 907 | } 908 | 909 | assert ( 910 | this.population.length === initPopSize, 911 | 'agent not added but population size changed' 912 | ); 913 | 914 | // Placement failed 915 | return false; 916 | } 917 | 918 | /** 919 | Place an agent on the map near some coordinates 920 | */ 921 | World.prototype.placeAgentNear = function (agent, x, y) 922 | { 923 | assert ( 924 | agent !== null, 925 | 'invalid parameters to placeAgentNear' 926 | ); 927 | 928 | // Get the initial population size 929 | var initPopSize = this.population.length; 930 | 931 | // Try to place the ant up to 512 times 932 | for (var i = 0; i < 512; ++i) 933 | { 934 | // Choose random coordinates in the world 935 | var nearX = x + randomInt(-12, 12); 936 | var nearY = y + randomInt(-12, 12); 937 | 938 | // If the coordinates are outside of the map, try again 939 | if (nearX < 0 || 940 | nearY < 0 || 941 | nearX >= this.gridWidth || 942 | nearY >= this.gridHeight) 943 | continue; 944 | 945 | // If the agent can be placed at these coordinates 946 | if (this.placeAgent(agent, nearX, nearY) === true) 947 | { 948 | assert ( 949 | this.population.length === initPopSize + 1, 950 | 'agent not added to population' 951 | ); 952 | 953 | assert ( 954 | world.getCell(agent.position.x, agent.position.y).agent === agent, 955 | 'agent pointer not valid after adding agent' 956 | ); 957 | 958 | // Placement successful 959 | return true; 960 | } 961 | } 962 | 963 | assert ( 964 | this.population.length === initPopSize, 965 | 'agent not added but population size changed' 966 | ); 967 | 968 | // Placement failed 969 | return false; 970 | } 971 | 972 | /** 973 | Move an ant to new coordinates 974 | */ 975 | World.prototype.moveAgent = function (agent, x, y) 976 | { 977 | // Ensure that the parameters are valid 978 | assert (agent != null); 979 | 980 | // If this moves out of the map, deny the movement 981 | if (x > this.gridWidth || y > this.gridHeight) 982 | return false; 983 | 984 | // Get the ant position 985 | const pos = agent.position; 986 | 987 | // Ensure that the agent position is valid 988 | assert ( 989 | pos.x >= 0 && pos.y >= 0 && 990 | pos.x < this.gridWidth && pos.y < this.gridHeight, 991 | 'invalid agent position' 992 | ); 993 | 994 | // Obtain references to the concerned cells 995 | orig = this.getCell(pos.x, pos.y); 996 | dest = this.getCell(x, y); 997 | 998 | // Ensure that the ant pointer is valid 999 | assert ( 1000 | orig.agent === agent, 1001 | 'invalid agent pointer' 1002 | ); 1003 | 1004 | // If the destination cell is a wall or water, deny the movement 1005 | if (dest.type === CELL_WALL || dest.type === CELL_WATER) 1006 | return false; 1007 | 1008 | // If there is already an ant at the destination, deny the movement 1009 | if (dest.agent !== null) 1010 | return false; 1011 | 1012 | // Update the pointers to perform the movement 1013 | orig.agent = null; 1014 | dest.agent = agent; 1015 | 1016 | // Update the agent position 1017 | agent.position = new Vector2(x, y); 1018 | 1019 | // Move successful 1020 | return true; 1021 | } 1022 | 1023 | /** 1024 | Eat a plant at the given coordinates 1025 | */ 1026 | World.prototype.eatPlant = function (x, y) 1027 | { 1028 | // Ensure that the parameters are valid 1029 | assert (x < this.gridWidth && y < this.gridHeight); 1030 | 1031 | // If this cell is not an available plant, stop 1032 | if (this.cellIsType(x, y, CELL_PLANT) === false) 1033 | return false; 1034 | 1035 | // Make this cell an eaten plant 1036 | this.getCell(x, y).type = CELL_EATEN; 1037 | 1038 | // Add the plant to the list of eaten plants 1039 | this.eatenPlants.push(new EatenPlant(x, y, this.itrCount + PLANT_RESPAWN_DELAY)); 1040 | 1041 | // Decrement the available plant count 1042 | this.availPlants--; 1043 | 1044 | // Increment the eaten plant count 1045 | this.eatenPlantCount++; 1046 | 1047 | // Plant successfully eaten 1048 | return true; 1049 | } 1050 | 1051 | /** 1052 | Build a block at the given coordinates 1053 | */ 1054 | World.prototype.buildBlock = function (x, y) 1055 | { 1056 | // Ensure that the parameters are valid 1057 | assert (x < this.gridWidth && y < this.gridHeight); 1058 | 1059 | // If this cell is not empty, stop 1060 | if (this.cellIsType(x, y, CELL_EMPTY) === false || 1061 | this.getCell(x,y).agent !== null) 1062 | return false; 1063 | 1064 | // Make this cell a wall block 1065 | this.getCell(x, y).type = CELL_WALL; 1066 | 1067 | // Add the block to the list of built blocks 1068 | this.builtBlocks.push(new BuiltBlock(x, y, this.itrCount + BLOCK_DECAY_DELAY)); 1069 | 1070 | // Plant successfully eaten 1071 | return true; 1072 | } 1073 | 1074 | /** 1075 | Test if a world cell is empty 1076 | */ 1077 | World.prototype.cellIsEmpty = function (x, y) 1078 | { 1079 | // Perform the test 1080 | return (this.getCell(x, y).type === CELL_EMPTY); 1081 | } 1082 | 1083 | /** 1084 | Test the type of a cell 1085 | */ 1086 | World.prototype.cellIsType = function (x, y, type) 1087 | { 1088 | // Perform the test 1089 | return (this.getCell(x, y).type === type); 1090 | } 1091 | 1092 | /** 1093 | Count cell neighbors of a given type 1094 | */ 1095 | World.prototype.countNeighbors = function (x, y, type) 1096 | { 1097 | // Count the neighbor cells of the given type 1098 | var count = 1099 | (this.cellIsType(x - 1, y - 1, type)? 1:0) + 1100 | (this.cellIsType(x , y - 1, type)? 1:0) + 1101 | (this.cellIsType(x + 1, y - 1, type)? 1:0) + 1102 | (this.cellIsType(x - 1, y , type)? 1:0) + 1103 | (this.cellIsType(x + 1, y , type)? 1:0) + 1104 | (this.cellIsType(x - 1, y + 1, type)? 1:0) + 1105 | (this.cellIsType(x , y + 1, type)? 1:0) + 1106 | (this.cellIsType(x + 1, y + 1, type)? 1:0); 1107 | 1108 | // Return the count 1109 | return count; 1110 | } 1111 | 1112 | /** 1113 | Set a given grid cell 1114 | */ 1115 | World.prototype.setCell = function (x, y, cell) 1116 | { 1117 | // Ensure that the coordinates are valid 1118 | assert ( 1119 | x >= 0 && y >= 0 && 1120 | x < this.gridWidth && y < this.gridHeight, 1121 | 'invalid coordinates in setCell' 1122 | ); 1123 | 1124 | // Ensure that the cell is valid 1125 | assert (cell instanceof Cell); 1126 | 1127 | // Set the cell reference 1128 | this.grid[y * this.gridWidth + x] = cell; 1129 | } 1130 | 1131 | /** 1132 | Get a given grid cell 1133 | */ 1134 | World.prototype.getCell = function (x, y) 1135 | { 1136 | // Ensure that the coordinates are valid 1137 | assert ( 1138 | x >= 0 && y >= 0 && 1139 | x < this.gridWidth && y < this.gridHeight, 1140 | 'invalid coordinates in getCell' 1141 | ); 1142 | 1143 | // Return a reference to the cell 1144 | return this.grid[y * this.gridWidth + x]; 1145 | } 1146 | 1147 | -------------------------------------------------------------------------------- /COPYING.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------