diff --git a/README.md b/README.md index 5ca56be..73be4a1 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,24 @@ -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) +Here is the HW submission: [HERE](https://mccannd.github.io/Project3-LSystems/) -# L-System Parser +Additions to the assignment: +- Ramp shader ground plane +- Tree sways / bends on the GPU. Geometry normals also account for this bend. +- Tree mesh has noise displacement on the GPU, based on precomputed noise texture. The texture is read through a bounding box that is saved in the shader. +- Angle changes to the Turtle / stack work in local axes instead of global axes -lsystem.js contains classes for L-system, Rule, and LinkedList. Here’s our suggested structure: +Submitted system: a christmas tree -**The Symbol Nodes/Linked List:** +Axiom : MB -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: +Rules: +X --> +10% : \[lFFX\]\[rFFX\]>FFX +10% : \[lFFX\]\[rFFX\]-FFX +10% : X +70% : \[lFFX\]\[rFFX\]FFX -- The next node in the linked list -- The previous node in the linked list -- The grammar symbol at theis point in the overal string +B --> \[++++X\]<<<\[++++X\]<<<\[++++X\]<<<\[++++X\] MF -- 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 diff --git a/groundRamp.png b/groundRamp.png new file mode 100644 index 0000000..483b983 Binary files /dev/null and b/groundRamp.png differ diff --git a/multicolorfractal.png b/multicolorfractal.png new file mode 100644 index 0000000..e9a8660 Binary files /dev/null and b/multicolorfractal.png differ diff --git a/multicolorperlin.png b/multicolorperlin.png new file mode 100644 index 0000000..17cdf31 Binary files /dev/null and b/multicolorperlin.png differ diff --git a/multicolorperlin2.png b/multicolorperlin2.png new file mode 100644 index 0000000..df00cd8 Binary files /dev/null and b/multicolorperlin2.png differ diff --git a/src/lsystem.js b/src/lsystem.js index e643b6d..58d0ccf 100644 --- a/src/lsystem.js +++ b/src/lsystem.js @@ -5,15 +5,76 @@ function Rule(prob, str) { this.successorString = str; // The string that will replace the char that maps to this Rule } + + // TODO: Implement a linked list class and its requisite functions // as described in the homework writeup +export class LinkedList { + constructor() { + this.head = null; + this.tail = null; + this.count = 0; + } + + pushFront(symbol) { + var node = { + symbol : symbol, + next : this.head, + prev : null + } + + if (this.count == 0) { + this.head = node; + this.tail = node; + } else { + this.head.prev = node; + this.head = node; + } + + this.count++; + } + + pushBack(symbol) { + var node = { + symbol : symbol, + prev : this.tail, + next : null + } + + if (this.count == 0) { + this.head = node; + this.tail = node; + } else { + this.tail.next = node; + this.tail = node; + } + this.count++; + } + + insertBetween(symbol, prev, next) { + var node = { + symbol : symbol, + prev : prev, + next : next + } + prev.next = node; + next.prev = node; + this.count++; + } + +} -// TODO: Turn the string into linked list +// Turn the string into linked list export function stringToLinkedList(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') var ll = new LinkedList(); + //console.log(input_string); + for (var i = 0; i < input_string.length; i++) { + ll.pushBack(input_string.charAt(i)); + } + return ll; } @@ -21,20 +82,58 @@ export function stringToLinkedList(input_string) { export function linkedListToString(linkedList) { // ex. Node1("F")->Node2("X") should be "FX" var result = ""; + for (var current = linkedList.head; current != null; current = current.next) { + result += current.symbol; + } + return result; } // TODO: Given the node to be replaced, // insert a sub-linked-list that represents replacementString function replaceNode(linkedList, node, replacementString) { + var beforeNode = node.prev; + var afterNode = node.next; + //console.log(replacementString); + var replacement = stringToLinkedList(replacementString); + + replacement.head.prev = beforeNode; + replacement.tail.next = afterNode; + + if (node == linkedList.head) { + linkedList.head = replacement.head; + } else { + beforeNode.next = replacement.head; + } + + if (node == linkedList.tail) { + linkedList.tail = replacement.tail; + } else { + afterNode.prev = replacement.tail; + } + + } export default function Lsystem(axiom, grammar, iterations) { // default LSystem - this.axiom = "FX"; + this.axiom = "MB"; this.grammar = {}; + /*this.grammar['X'] = [ + new Rule(1.0, '[-FFX'), + new Rule(0.1, '[lFFX][rFFX]-FFX'), + new Rule(0.1, 'X'), + new Rule(0.7, '[lFFX][rFFX]FFX') + ]; + + this.grammar['B'] = [ + new Rule(1.0, '[++++X]<<<[++++X]<<<[++++X]<<<[++++X] 3; i--) { + for( var i = turtle.scene.children.length - 1; i > 4; i--) { obj = turtle.scene.children[i]; turtle.scene.remove(obj); } } 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); @@ -62,6 +79,7 @@ function doLsystem(lsystem, iterations, turtle) { // called on frame updates function onUpdate(framework) { + if (turtle !== undefined) turtle.updateTime(); } // when the scene is done initializing, it will call onLoad, then on frame updates, call onUpdate diff --git a/src/shaders/floor_frag.glsl b/src/shaders/floor_frag.glsl new file mode 100644 index 0000000..68dc829 --- /dev/null +++ b/src/shaders/floor_frag.glsl @@ -0,0 +1,11 @@ +varying vec2 vUv; +uniform sampler2D ramp; +void main() { + float xd = vUv.x - 0.5; + float yd = vUv.y - 0.5; + + float dist = sqrt(xd * xd + yd * yd); + float u = min(dist * 2.0, 1.0); + vec4 col = texture2D(ramp, vec2(0.5, u)); + gl_FragColor = col; +} \ No newline at end of file diff --git a/src/shaders/floor_vert.glsl b/src/shaders/floor_vert.glsl new file mode 100644 index 0000000..a518513 --- /dev/null +++ b/src/shaders/floor_vert.glsl @@ -0,0 +1,6 @@ +varying vec2 vUv; + +void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 ); +} \ No newline at end of file diff --git a/src/shaders/lsystem_frag.glsl b/src/shaders/lsystem_frag.glsl new file mode 100644 index 0000000..9e3d060 --- /dev/null +++ b/src/shaders/lsystem_frag.glsl @@ -0,0 +1,23 @@ +varying float h; +varying vec3 n; +varying float u; +varying float l; + +vec3 lerpvec(in vec3 a, in vec3 b, in float t) +{ + float tx = t * b[0] + (1.0 - t) * a[0]; + float ty = t * b[1] + (1.0 - t) * a[1]; + float tz = t * b[2] + (1.0 - t) * a[2]; + return vec3(tx, ty, tz); +} + + +void main() { + vec3 base = vec3(0.1, 0.5, 0.16); + vec3 trunk = vec3(0.2, 0.11, 0.02); + vec3 c1 = lerpvec(trunk, base, pow(u, 0.7)); + vec3 col = lerpvec(c1, vec3(1.0, 1.0, 0.5) * n, 0.15); + col = lerpvec(vec3(0.15, 0.03, 0.15), col, l); + //gl_FragColor = vec4( h, h, h, 1.0 ); + gl_FragColor = vec4(col, 1.0 ); +} \ No newline at end of file diff --git a/src/shaders/lsystem_vert.glsl b/src/shaders/lsystem_vert.glsl new file mode 100644 index 0000000..49ac49e --- /dev/null +++ b/src/shaders/lsystem_vert.glsl @@ -0,0 +1,75 @@ +uniform sampler2D image; +uniform float xMin; +uniform float xMax; +uniform float yMin; +uniform float yMax; +uniform float zMin; +uniform float zMax; + +uniform int time; + +varying float h; +varying vec3 n; +varying float u; +varying float l; + +mat3 transpose(in mat3 m) { + mat3 n = mat3(vec3(m[0][0], m[1][0], m[2][0]), + vec3(m[0][1], m[1][1], m[2][1]), + vec3(m[0][2], m[1][2], m[2][2])); + return m; +} + + +void main() { + float yr = yMax - yMin; + + + vec3 p = (modelMatrix * vec4(position, 1.0)).xyz; + float h = pow((yMax - position.y) / (yr), 1.3); + float radial = 1.3 * (sqrt(p.x * p.x + p.z * p.z)) / (h *(xMax - xMin)); + + u = max(min(radial, 1.0), 0.0); + // bend deformation preparation + float tCoeff = 0.5 * sin(float(time) / 1000.0) + 0.55; + + + float y0 = yMax * 0.5 - yMin; // bend center + float curvature = tCoeff * 3.14 / 4.0 / yr; + float theta = curvature * (p.y - yMin); + float ct = cos(theta); + float st = sin(theta); + + + // sample texture from bounding box + float v = (p.y - yMin) / (yMax - yMin); + float ux = (p.x - xMin) / (xMax - xMin); + float uz = (p.z - zMin) / (zMax - zMin); + + mat3 jacobian = mat3(vec3(1.0, 0.0, 0.0), + vec3(0.0, ct, st), + vec3(0, -1.0 * st * (1.0 - curvature * p.z), ct * (1.0 - curvature * p.z))); + + + vec3 nor = jacobian * transpose(mat3(modelMatrix)) * normal; + l = dot(normalize(nor), vec3(0.0, 1.0, 0.0)); + l = pow(max(0.2, l), 0.4545); + + // apply deformation + p.y = 0.5 * (p.y - st * (p.z - 1.0 / curvature)); + p.z = (1.0 / curvature + ct * (p.z - 1.0 / curvature)); + + vec4 xDisp = texture2D(image, vec2(ux, v)); + vec4 zDisp = texture2D(image, vec2(uz, v)); + vec4 yDisp = texture2D(image, vec2(ux, uz)); + vec3 d = 0.5 * vec3(xDisp.x - 0.5, yDisp.y - 0.5, zDisp.z - 0.5); + + // coloration based on noise + n = vec3(xDisp.x, yDisp.y, zDisp.z); + h = v; + + vec4 intermedPos = projectionMatrix * viewMatrix * vec4(p, 1.0 ); + intermedPos = intermedPos + projectionMatrix * vec4(d, 1.0); + + gl_Position = intermedPos; +} \ No newline at end of file diff --git a/src/turtle.js b/src/turtle.js index 1db2723..953fd5d 100644 --- a/src/turtle.js +++ b/src/turtle.js @@ -1,21 +1,83 @@ const THREE = require('three') + +//var material = new THREE.MeshBasicMaterial( {color: 0x00cccc} ); +var baseTime = Date.now(); + +// bounding box +var bounds = { + xMin : -0.5, + xMax : 0.5, + yMin : 0.0, + yMax : 1.0, + zMin : -0.5, + zMax : 0.5 +}; + +var sUniforms = { + image: { + type: "t", + value: THREE.ImageUtils.loadTexture('./multicolorfractal.png') + }, + xMin : { type : "f", value : bounds.xMin}, + yMin : { type : "f", value : bounds.yMin}, + zMin : { type : "f", value : bounds.zMin}, + xMax : { type : "f", value : bounds.xMax}, + yMax : { type : "f", value : bounds.yMax}, + zMax : { type : "f", value : bounds.zMax}, + time : { type : "i", value : 0} +}; + +var material = new THREE.ShaderMaterial({ + uniforms : sUniforms, + vertexShader: require('./shaders/lsystem_vert.glsl'), + fragmentShader: require('./shaders/lsystem_frag.glsl') +}); +var geometry = new THREE.CylinderGeometry(0.1, 0.1, 2, 8, 2); +var hgeometry = new THREE.CylinderGeometry(0.1, 0.1, 1, 8, 3); + +function updateBounds() { + sUniforms.xMin.value = bounds.xMin; + sUniforms.yMin.value = bounds.yMin; + sUniforms.zMin.value = bounds.zMin; + sUniforms.xMax.value = bounds.xMax; + sUniforms.yMax.value = bounds.yMax; + sUniforms.zMax.value = bounds.zMax; +} + +function resetBounds() { + bounds.xMin = -0.5; + bounds.xMax = 0.5; + bounds.yMin = 0.0; + bounds.yMax = 1.0; + bounds.zMin = -0.5; + bounds.zMax = 0.5; + updateBounds(); +} + // A class used to encapsulate the state of a turtle at a given moment. // The Turtle class contains one TurtleState member variable. -// You are free to add features to this state class, -// such as color or whimiscality -var TurtleState = function(pos, dir) { +// pos: position in world space +// dir: local y axis +// lx: local x axis +// lz: local z axis +var TurtleState = function(pos, dir, lx, lz) { return { pos: new THREE.Vector3(pos.x, pos.y, pos.z), - dir: new THREE.Vector3(dir.x, dir.y, dir.z) + dir: new THREE.Vector3(dir.x, dir.y, dir.z), + lx: new THREE.Vector3(lx.x, lx.y, lx.z), + lz: new THREE.Vector3(lz.x, lz.y, lz.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.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0), + new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,1)); this.scene = scene; + // an array of Turtlestates saved in a stack + this.stateStack = []; // TODO: Start by adding rules for '[' and ']' then more! // Make sure to implement the functions for the new rules inside Turtle @@ -23,7 +85,15 @@ export default class Turtle { this.renderGrammar = { '+' : this.rotateTurtle.bind(this, 30, 0, 0), '-' : this.rotateTurtle.bind(this, -30, 0, 0), - 'F' : this.makeCylinder.bind(this, 2, 0.1) + '<' : this.rotateTurtle.bind(this, 0, 30, 0), + '>' : this.rotateTurtle.bind(this, 0, -30, 0), + 'l' : this.rotateTurtle.bind(this, 0, 0, 30), + 'r' : this.rotateTurtle.bind(this, 0, 0, -30), + 'F' : this.makeCylinder.bind(this, 2.0, 1.0), + 'G' : this.makeCylinder.bind(this, 1.0, 0.5), + 'H' : this.makeCylinder.bind(this, 1.0, 0.5), + '[' : this.saveTurtle.bind(this), + ']' : this.loadTurtle.bind(this) }; } else { this.renderGrammar = grammar; @@ -33,7 +103,10 @@ export default class Turtle { // Resets the turtle's position to the origin // and its orientation to the Y axis clear() { - this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); + this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0), + new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,1)); + this.stateStack = []; + resetBounds(); } // A function to help you debug your turtle functions @@ -46,11 +119,26 @@ export default class Turtle { // Rotate the turtle's _dir_ vector by each of the // Euler angles indicated by the input. rotateTurtle(x, y, z) { + + // rotate using global euler functions var e = new THREE.Euler( x * 3.14/180, y * 3.14/180, z * 3.14/180); - this.state.dir.applyEuler(e); + //this.state.dir.applyEuler(e); + + + // rotate about local axis + // local yaw + this.state.lx.applyAxisAngle(this.state.dir, y * 3.14159 / 180); + this.state.lz.applyAxisAngle(this.state.dir, y * 3.14159 / 180); + // local pitch + this.state.dir.applyAxisAngle(this.state.lx, x * 3.14159 / 180); + this.state.lz.applyAxisAngle(this.state.lx, x * 3.14159 / 180); + //local roll + this.state.dir.applyAxisAngle(this.state.lz, z * 3.14159 / 180); + this.state.lx.applyAxisAngle(this.state.lz, z * 3.14159 / 180); + } // Translate the turtle along the input vector. @@ -58,20 +146,91 @@ export default class Turtle { moveTurtle(x, y, z) { var new_vec = THREE.Vector3(x, y, z); this.state.pos.add(new_vec); + var p = this.state.pos; + // make tight bounds + if (p.x < bounds.xMin) bounds.xMin = p.x; + else if (p.x > bounds.xMax) bounds.xMax = p.x; + if (p.y < bounds.yMin) bounds.yMin = p.y; + else if (p.y > bounds.yMax) bounds.yMax = p.y; + + if (p.z < bounds.zMin) bounds.zMin = p.z; + else if (p.z > bounds.zMax) bounds.zMax = p.z; + + updateBounds(); + }; + + // saves the state of the turtle on the stack + saveTurtle() { + + var aState = new TurtleState(this.state.pos, this.state.dir, + this.state.lx, this.state.lz); + this.stateStack.push(aState); + }; + + // pops the state of the turtle off of the stack, if able + loadTurtle() { + + if (this.stateStack.length > 0) { + var aState = this.stateStack.pop(); + this.state.pos = aState.pos; + this.state.dir = aState.dir; + this.state.lx = aState.lx; + this.state.lz = aState.lz; + } }; // Translate the turtle along its _dir_ vector by the distance indicated moveForward(dist) { - var newVec = this.state.dir.multiplyScalar(dist); + var newVec = this.state.dir.multiplyScalar(1.0); + newVec = newVec.multiplyScalar(dist); this.state.pos.add(newVec); + var p = this.state.pos; + if (p.x < bounds.xMin) bounds.xMin = p.x; + else if (p.x > bounds.xMax) bounds.xMax = p.x; + if (p.y < bounds.yMin) bounds.yMin = p.y; + else if (p.y > bounds.yMax) bounds.yMax = p.y; + if (p.z < bounds.zMin) bounds.zMin = p.z; + else if (p.z > bounds.zMax) bounds.zMax = p.z; + + updateBounds(); }; // Make a cylinder of given length and width starting at turtle pos // 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} ); + makeCylinder(scaleRad, scaleLen) { + + var cylinder = new THREE.Mesh( geometry, material ); + cylinder.scale.set(scaleRad, scaleLen, scaleRad); + 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 t = this.state.dir; + var p = this.state.pos; + //var trans = p.add(t.multiplyScalar(0.5 * 2.0 * scaleLen)); + var trans = p.add(t); + mat5.makeTranslation(trans.x, trans.y, trans.z); + cylinder.applyMatrix(mat5); + + //Scoot the turtle forward by len units + this.moveForward(scaleLen); + }; + + + makeSmallCylinder(scaleRad, scaleLen) { + + + var cylinder = new THREE.Mesh( hgeometry, material ); + cylinder.scale.set(scaleRad, scaleLen, scaleRad); this.scene.add( cylinder ); //Orient the cylinder to the turtle's current direction @@ -84,19 +243,22 @@ export default class Turtle { //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)); + var t = this.state.dir; + var p = this.state.pos; + var trans = p.add(t.multiplyScalar(0.5 * 1.0 * scaleLen)); mat5.makeTranslation(trans.x, trans.y, trans.z); cylinder.applyMatrix(mat5); //Scoot the turtle forward by len units - this.moveForward(len/2); + this.moveForward(1.0 * scaleLen/2.0); }; // 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]; + //console.log(symbolNode); + var func = this.renderGrammar[symbolNode.symbol]; if (func) { func(); } @@ -109,4 +271,9 @@ export default class Turtle { this.renderSymbol(currentNode); } } + + + updateTime() { + sUniforms.time.value = (Date.now() - baseTime); + } } \ No newline at end of file