diff --git a/.gitignore b/.gitignore index 5171c54..2f6141d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules -npm-debug.log \ No newline at end of file +npm-debug.log +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md index 5ca56be..76ca400 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,3 @@ +# [Project 3: L-System](https://github.com/CIS700-Procedural-Graphics/Project3-LSystems) -The objective of this assignment is to create an L System parser and generate interesting looking plants. Start by forking and then cloning this repository: [https://github.com/CIS700-Procedural-Graphics/Project3-LSystems](https://github.com/CIS700-Procedural-Graphics/Project3-LSystems) - -# L-System Parser - -lsystem.js contains classes for L-system, Rule, and LinkedList. Here’s our suggested structure: - -**The Symbol Nodes/Linked List:** - -Rather than representing our symbols as a string like in many L-system implementations, we prefer to use a linked list. This allows us to store additional information about each symbol at time of parsing (e.g. what iteration was this symbol added in?) Since we’re adding and replacing symbols at each iteration, we also save on the overhead of creating and destroying strings, since linked lists of course make it easy to add and remove nodes. You should write a Linked List class with Nodes that contain at least the following information: - -- The next node in the linked list -- The previous node in the linked list -- The grammar symbol at theis point in the overal string - -We also recommend that you write the following functions to interact with your linked list: - -- A function to symmetrically link two nodes together (e.g. Node A’s next is Node B, and Node B’s prev is Node A) -- A function to expand one of the symbol nodes of the linked list by replacing it with several new nodes. This function should look at the list of rules associated with the symbol in the linked list’s grammar dictionary, then generate a uniform random number between 0 and 1 in order to determine which of the Rules should be used to expand the symbol node. You will refer to a Rule’s probability and compare it to your random number in order to determine which Rule should be chosen. - -**Rules:** - -These are containers for the preconditions, postconditions and probability of a single replacement operation. They should operate on a symbol node in your linked list. - -**L-system:** - -This is the parser, which will loop through your linked list of symbol nodes and apply rules at each iteration. - -Implement the following functions in L-System so that you can apply grammar rules to your axiom given some number of iterations. More details and implementation suggestions about functions can be found in the TODO comments - -- `stringToLinkedList(input_string)` -- `linkedListToString(linkedList)` -- `replaceNode(linkedList, node, replacementString)` -- `doIterations(num)` - -## Turtle - -`turtle.js` has a function called renderSymbol that takes in a single node of a linked list and performs an operation to change the turtle’s state based on the symbol contained in the node. Usually, the turtle’s change in state will result in some sort of rendering output, such as drawing a cylinder when the turtle moves forward. We have provided you with a few example functions to illustrate how to write your own functions to be called by renderSymbol; these functions are rotateTurtle, moveTurtle, moveForward, and makeCylinder. If you inspect the constructor of the Turtle class, you can see how to associate an operation with a grammar symbol. - -- Modify turtle.js to support operations associated with the symbols `[` and `]` - - When you parse `[` you need to store the current turtle state somewhere - - When you parse `]` you need to set your turtle’s state to the most recently stored state. Think of this a pushing and popping turtle states on and off a stack. For example, given `F[+F][-F]`, the turtle should draw a Y shape. Note that your program must be capable of storing many turtle states at once in a stack. - -- In addition to operations for `[` and `]`, you must invent operations for any three symbols of your choosing. - - -## Interactivity - -Using dat.GUI and the examples provided in the reference code, make some aspect of your demo an interactive variable. For example, you could modify: - -1. the axiom -2. Your input grammer rules and their probability -3. the angle of rotation of the turtle -4. the size or color or material of the cylinder the turtle draws, etc! - -## L-System Plants - -Design a grammar for a new procedural plant! As the preceding parts of this assignment are basic computer science tasks, this is where you should spend the bulk of your time on this assignment. Come up with new grammar rules and include screenshots of your plants in your README. For inspiration, take a look at Example 7: Fractal Plant in Wikipedia: https://en.wikipedia.org/wiki/L-system Your procedural plant must have the following features - -1. Grow in 3D. Take advantage of three.js! -2. Have flowers or leaves that are added as a part of the grammar -3. Variation. Different instances of your plant should look distinctly different! -4. A twist. Broccoli trees are cool and all, but we hope to see sometime a little more surprising in your grammars - -# Publishing Your code - -Running `npm run deploy` will automatically build your project and push it to gh-pages where it will be visible at `username.github.io/repo-name`. NOTE: You MUST commit AND push all changes to your MASTER branch before doing this or you may lose your work. The `git` command must also be available in your terminal or command prompt. If you're using Windows, it's a good idea to use Git Bash. \ No newline at end of file +Created a tree using L-systems. GUI controls included to manipulate the tree, such as changing the initial axiom string, the number of iterations and the rotation value used to rotate the branches. \ No newline at end of file diff --git a/src/lsystem.js b/src/lsystem.js index e643b6d..d45268c 100644 --- a/src/lsystem.js +++ b/src/lsystem.js @@ -7,6 +7,174 @@ function Rule(prob, str) { // TODO: Implement a linked list class and its requisite functions // as described in the homework writeup +function Node(grammarSymbol) { + this.symbol = grammarSymbol; + this.param = []; + this.cond = null; + /*this.cond = function (s , min) { + return s >= min; + };*/ + this.previous = null; + this.next = null; +} + +function LinkedList() { + this.head = null; + this.tail = null; + this.rotation = 30; +} + +LinkedList.prototype.setSym = function (nodeA, nodeB) { + if (nodeA) + nodeA.next = nodeB; + if (nodeB) + nodeB.prev = nodeA; +} + + +LinkedList.prototype.printParameter = function () { + + var temp = this.head; + var str = ""; + while (temp) { + + str += (temp.symbol); + if (temp.symbol == 'A') { + + str += "(" + temp.param[0] + "," + temp.param[1] + ")"; + } + + else if (temp.symbol != '[' && temp.symbol != ']') { + + str += "(" + temp.param[0] + ")"; + } + + + //str += ("-->"); + temp = temp.next; + } + + console.log(str); + +} + +LinkedList.prototype.print = function () { + + var temp = this.head; + var str = ""; + while (temp) { + + str += (temp.symbol); + //str += ("-->"); + temp = temp.next; + } + + console.log(str); + +} + +LinkedList.prototype.printReversed = function () { + + var temp = this.tail; + var str = ""; + while (temp) { + + str += (temp.symbol); + //sstr += ("-->"); + temp = temp.prev; + } + + console.log(str); + +} + +// replaceNode(linkedList, node, replacementString) +LinkedList.prototype.expand = function (node, grammar) { + + var rules = grammar[node.symbol]; + + if (rules) { + + var r = Math.random(); + var selectedRule = rules[0]; + + + for (var i = 0; i < rules.length; i++) { + + if (rules[i].probability >= r) { + selectedRule = rules[i]; + } + } + + + replaceNode(this, node, selectedRule.successorString); + } + +} + + +LinkedList.prototype.expandParameter = function (node) { + + + if (node.symbol != "A") + return; + + var r1 = 0.8; + var r2 = 0.8; + var alpha1 = 30.0; + var alpha2 = -30.0; + var phi1 = 137.0; + var phi2 = 137.0; + var q = 0.5; + var e = 0.5; + var min = 0.0; + var n = 10; + var s = node.param[0]; + var w = node.param[1]; + + var str = "!"; + str += "(" + w + ")"; //w + str += "F(" + s + ")"; //s + str += "[+(" + alpha1 + ")"; + str += "/(" + phi1 + ")"; + str += "A(" + s * r1 + "," + w * Math.pow(q,e) + ")]"; + + str += "[+(" + alpha2 + ")"; + str += "/(" + phi2 + ")"; + str += "A(" + s * r2 + "," + w * Math.pow(1.0-q,e) + ")]"; + //console.log(str); + + replaceNode(this, node, str); +} + +LinkedList.prototype.addNode = function(node) { + + if (this.head != null) { + this.tail.next = node; + node.prev = this.tail; + this.tail = node; + } else { + this.head = node; + this.tail = node; + } + + return node; +}; + +LinkedList.prototype.add = function(value) { + var node = new Node(value); + + if (this.head != null) { + this.tail.next = node; + node.prev = this.tail; + this.tail = node; + } else { + this.head = node; + this.tail = node; + } + + return node; +}; // TODO: Turn the string into linked list export function stringToLinkedList(input_string) { @@ -14,6 +182,66 @@ export function stringToLinkedList(input_string) { // you should return a linked list where the head is // at Node('F') and the tail is at Node('X') var ll = new LinkedList(); + + for (var i = 0, len = input_string.length; i < len; i++) { + ll.add(input_string[i]); + } + + return ll; +} + +export function stringParameterToLinkedList(input_string) { + // ex. assuming input_string = "F+X" + // you should return a linked list where the head is + // at Node('F') and the tail is at Node('X') + + //console.log(input_string); + var str = input_string.replace(/ *\([^)]*\) */g, ""); //strip out params + var params = input_string.match(/ *\([^)]*\) */g); //save params + //var str2 = "!(w)F(s)[+(30)/(137)A(12,23)][+(-30)/(137)A(22,110)]"; + //var myArray = input_string.match(/ *\([^)]*\) */g); + //console.log(myArray); + + var ll = new LinkedList(); + var offset = 0; + + for (var i = 0; i < str.length; i++) + { + var node = new Node(str[i]); + + if (str[i] == '[' || str[i] == ']') { + + offset++; + ll.addNode(node); + + } + else if (str[i] != 'A') { + + var re = /\(([+-]?\d+\.?\d*)\).*/; + var symbolParams = params[i-offset].match(re); //get params + + for (var j = 0; j < symbolParams.length-1; j++) { + node.param[j] = symbolParams[j+1] + } + + ll.addNode(node); + } + else { + + var re = /\(([+-]?\d+\.?\d*),([+-]?\d+\.?\d*)\)/; + var symbolParams = params[i-offset].match(re); //get params + + for (var j = 0; j < symbolParams.length-1; j++) { + node.param[j] = symbolParams[j+1] + } + node.cond = 's >= 0'; + + ll.addNode(node); + } + } + + //console.log(ll); + return ll; } @@ -21,21 +249,81 @@ export function stringToLinkedList(input_string) { export function linkedListToString(linkedList) { // ex. Node1("F")->Node2("X") should be "FX" var result = ""; + + var temp = linkedList.head; + + while(temp.next) { + + result+= temp.symbol; + temp = temp.next; + } + return result; } // TODO: Given the node to be replaced, // insert a sub-linked-list that represents replacementString function replaceNode(linkedList, node, replacementString) { + + if (replacementString == "") + return; + + var subLinkedList = stringToLinkedList(replacementString); + //var subLinkedList = stringParameterToLinkedList(replacementString); + + //if node is head + if (node.prev == null) { + + linkedList.setSym(subLinkedList.tail, linkedList.head.next); + linkedList.head = subLinkedList.head; + + } else if (node.next == null) { //node is tail + + linkedList.setSym(linkedList.tail.prev, subLinkedList.head); + linkedList.tail = subLinkedList.tail; + + } else { //node is in middle of list + + linkedList.setSym(node.prev, subLinkedList.head); + linkedList.setSym(subLinkedList.tail, node.next); + } + } export default function Lsystem(axiom, grammar, iterations) { // default LSystem - this.axiom = "FX"; + //this.axiom = "A(100.0,30.0)"; + this.rotation = 30.0; + this.axiom = "X"; this.grammar = {}; this.grammar['X'] = [ + new Rule(1.0, 'F[+/YS]F[-//YS]+/Y') + //new Rule(0.5, 'F[-XS]F[+&XS]+X') + ]; + this.grammar['Y'] = [ + new Rule(1.0, 'F[-&XS]F[+&&XS]+&X') + //new Rule(0.5, 'F[-XS]F[+&XS]+X') + ]; + this.grammar['F'] = [ + new Rule(1.0, 'F') + ]; + /*this.grammar['X'] = [ new Rule(1.0, '[-FX][+FX]') + ];*/ + /*this.grammar['X'] = [ + new Rule(1.0, '+v[GY]v[GY]v[GY]'), + //new Rule(1.0, '-v[+GY]v[+GY]v[+GY]') ]; + + this.grammar['Y'] = [ + new Rule(1.0, 'v[GY]v[HZ]') + ]; + + this.grammar['Z'] = [ + new Rule(1.0, '[+wJZ][+wwJZ][+wwwJZ]') + ];*/ + + this.iterations = 0; // Set up the axiom string @@ -63,14 +351,44 @@ export default function Lsystem(axiom, grammar, iterations) { this.axiom = axiom; } } - + + this.updateRotation = function(rotation) { + // Setup axiom + if (typeof rotation !== "undefined") { + this.rotation = rotation; + } + } + // TODO // This function returns a linked list that is the result // of expanding the L-system's axiom n times. // The implementation we have provided you just returns a linked // list of the axiom. this.doIterations = function(n) { - var lSystemLL = StringToLinkedList(this.axiom); + var lSystemLL = stringToLinkedList(this.axiom); + lSystemLL.rotation = this.rotation; + //var lSystemLL = stringParameterToLinkedList(this.axiom); + + var temp = n; + while (n > 0) { + + var temp = lSystemLL.head; + + while(temp) { + + var next = temp.next; + + var node = lSystemLL.expand(temp, this.grammar); + //var node = lSystemLL.expandParameter(temp, this.grammar); + + + temp = next; + } + n--; + } + //lSystemLL.printParameter(); + //lSystemLL.print(); + return lSystemLL; } } \ No newline at end of file diff --git a/src/main.js b/src/main.js index f0c6600..f58b38f 100644 --- a/src/main.js +++ b/src/main.js @@ -34,7 +34,7 @@ function onLoad(framework) { }); gui.add(lsys, 'axiom').onChange(function(newVal) { - lsys.UpdateAxiom(newVal); + lsys.updateAxiom(newVal); doLsystem(lsys, lsys.iterations, turtle); }); @@ -42,6 +42,13 @@ function onLoad(framework) { clearScene(turtle); doLsystem(lsys, newVal, turtle); }); + + gui.add(lsys, 'rotation', 0, 90).step(1).onChange(function(newVal) { + clearScene(turtle); + lsys.updateRotation(newVal); + doLsystem(lsys, lsys.iterations, turtle); + }); + } // clears the scene by removing all geometries added by turtle.js @@ -54,7 +61,7 @@ function clearScene(turtle) { } function doLsystem(lsystem, iterations, turtle) { - var result = lsystem.DoIterations(iterations); + var result = lsystem.doIterations(iterations); turtle.clear(); turtle = new Turtle(turtle.scene); turtle.renderSymbols(result); diff --git a/src/turtle.js b/src/turtle.js index 1db2723..3d24dbe 100644 --- a/src/turtle.js +++ b/src/turtle.js @@ -10,24 +10,101 @@ var TurtleState = function(pos, dir) { dir: new THREE.Vector3(dir.x, dir.y, dir.z) } } + export default class Turtle { - + constructor(scene, grammar) { this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); this.scene = scene; + this.states = []; + //this.lineWidth = 3.0; // TODO: Start by adding rules for '[' and ']' then more! // Make sure to implement the functions for the new rules inside Turtle - if (typeof grammar === "undefined") { + if (typeof grammar === "undefined") { + + this.renderGrammar = function(node) { + switch(node.symbol) { + case '!': + this.lineWidth = node.param[0]; + break; + case '+': + this.rotateTurtle(node.param[0], 0, 0); + //this.rotateTurtle(0, -node.param[0], 0); + break; + case '/': + //this.rotateTurtle(0, 0, -node.param[0]); + var a = Math.random(); + this.rotateTurtle(0, 0, node.param[0]); + break; + case '&': + var a = Math.random(); + this.rotateTurtle(0, 0, -node.param[0]); + //this.rotateTurtle(0, 0, -node.param[0]); + break; + case '-': + this.rotateTurtle(-node.param[0], 0, 0); + break; + case 'v': + this.rotateTurtle(0, 120, 0); + break; + case 'w': + this.rotateTurtle(0, 60, 0); + break; + case 'F': + //for (var i = 0; i < 10; i++) + this.makeCylinder(2, 0.1) + //this.makeCylinder(node.param[0], this.lineWidth); + break; + case 'G': + for (var i = 0; i < 8; i++) + this.makeCylinder(2, 2.0) //this.makeCylinder(node.param[0], this.lineWidth); + break; + case 'H': + for (var i = 0; i < 6; i++) + this.makeCylinder(2, 1.0) //this.makeCylinder(node.param[0], this.lineWidth); + break; + case 'J': + for (var i = 0; i < 4; i++) + this.makeCylinder(2, 0.5) //this.makeCylinder(node.param[0], this.lineWidth); + case 'S': + this.makeSphere(2, 0.3) + break; + case '[': + this.pushState(); + break; + case ']': + this.popState(); + break; + default: + break; + } + + } + + + } else { + this.renderGrammar = grammar; + } + + + + /*if (typeof grammar === "undefined") { this.renderGrammar = { '+' : this.rotateTurtle.bind(this, 30, 0, 0), '-' : this.rotateTurtle.bind(this, -30, 0, 0), - 'F' : this.makeCylinder.bind(this, 2, 0.1) + 'v' : this.rotateTurtle.bind(this, 0, 120, 0), + 'w' : this.rotateTurtle.bind(this, 0, 60, 0), + 'F' : this.makeCylinder.bind(this, 2, 0.1), + //'G' : this.makeCylinder.bind(this, 1, 0.3), + // 'H' : this.makeCylinder.bind(this, 1, 0.1), + '[' : this.pushState.bind(this), + ']' : this.popState.bind(this) }; } else { this.renderGrammar = grammar; - } + }*/ } // Resets the turtle's position to the origin @@ -42,6 +119,14 @@ export default class Turtle { console.log(this.state.pos) console.log(this.state.dir) } + + pushState() { + this.states.push(new TurtleState(this.state.pos, this.state.dir)); + } + + popState() { + this.state = this.states.pop(); + } // Rotate the turtle's _dir_ vector by each of the // Euler angles indicated by the input. @@ -70,7 +155,7 @@ export default class Turtle { // Moves turtle pos ahead to end of the new cylinder makeCylinder(len, width) { var geometry = new THREE.CylinderGeometry(width, width, len); - var material = new THREE.MeshBasicMaterial( {color: 0x00cccc} ); + var material = new THREE.MeshBasicMaterial( {color: 0xFF69B4} ); var cylinder = new THREE.Mesh( geometry, material ); this.scene.add( cylinder ); @@ -92,20 +177,48 @@ export default class Turtle { this.moveForward(len/2); }; + + makeSphere(len, width) { + var geometry = new THREE.SphereGeometry(width, width, len); + var material = new THREE.MeshBasicMaterial( {color: 0xffffff} ); + var cylinder = new THREE.Mesh( geometry, material ); + this.scene.add( cylinder ); + + //Orient the cylinder to the turtle's current direction + var quat = new THREE.Quaternion(); + quat.setFromUnitVectors(new THREE.Vector3(0,1,0), this.state.dir); + var mat4 = new THREE.Matrix4(); + mat4.makeRotationFromQuaternion(quat); + cylinder.applyMatrix(mat4); + + + //Move the cylinder so its base rests at the turtle's current position + var mat5 = new THREE.Matrix4(); + var trans = this.state.pos.add(this.state.dir.multiplyScalar(0.5 * len)); + mat5.makeTranslation(trans.x, trans.y, trans.z); + cylinder.applyMatrix(mat5); + + //Scoot the turtle forward by len units + this.moveForward(len/2); + }; + // Call the function to which the input symbol is bound. // Look in the Turtle's constructor for examples of how to bind // functions to grammar symbols. renderSymbol(symbolNode) { - var func = this.renderGrammar[symbolNode.character]; - if (func) { - func(); - } + // var func = this.renderGrammar[symbolNode.symbol]; + var func = this.renderGrammar(symbolNode); + if (func) { + func(); + } + }; // Invoke renderSymbol for every node in a linked list of grammar symbols. renderSymbols(linkedList) { var currentNode; for(currentNode = linkedList.head; currentNode != null; currentNode = currentNode.next) { + currentNode.param[0] = linkedList.rotation; this.renderSymbol(currentNode); } }