summaryrefslogtreecommitdiff
path: root/src/turtle-system.lisp
blob: 807986b38b7c661f229fe40357042427c5933342 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
;;;; turtle-system.lisp

(in-package #:l-system)

;;;(matrix* translate rotate scale)

(export 'f)
(export	'[)
(export	'])

(defun turtle-system (fn list radians)
  (iter (with pos = (sb-cga:vec 0.0 0.0 0.0))
	(with vec-x = (sb-cga:vec 1.0 0.0 0.0))
	(with vec-y = (sb-cga:vec 0.0 1.0 0.0))
	(with vec-z = (sb-cga:vec 0.0 0.0 1.0))
	(with pile = '())
	(with angle = radians)
	(for item in list)
	(case item
	  ;;Move forward one unit,adding data to mesh.
	  ((f)
	   (let ((new-pos
		  (vec+ pos vec-y)))
	     (appending (funcall fn pos new-pos vec-x vec-y vec-z))
	     (setf pos new-pos)))
	  ;;Move forward one unit,without adding data to mesh.
	  ((j)
	   (setf pos
		 (vec+ pos
		       vec-y)))
	  ;;Rotate left on axis z
	  ((+)
	   (setf vec-x
		 (vec-rotate-around vec-x vec-z angle))
	   (setf vec-y
		 (vec-rotate-around vec-y vec-z angle)))
	  ;;Rotate right on axis z
	  ((-)
	   (setf vec-x
		 (vec-rotate-around vec-x vec-z (- angle)))
	   (setf vec-y
		 (vec-rotate-around vec-y vec-z (- angle))))
	  ;;Rotate left on axis y
	  ((&)
	   (setf vec-x
		 (vec-rotate-around vec-x vec-y angle))
	   (setf vec-z
		 (vec-rotate-around vec-z vec-y angle)))
	  ;;Rotate right on axis y
	  ((^)
	   (setf vec-x
		 (vec-rotate-around vec-x vec-y (- angle)))
	   (setf vec-z
		 (vec-rotate-around vec-z vec-y (- angle))))
	  ;;Rotate left on axis x
	  ((\ )
	   (setf vec-z
		 (vec-rotate-around vec-z vec-x angle))
	   (setf vec-y
		 (vec-rotate-around vec-y vec-x angle)))
	  ;;Rotate right on axis x
	  ((/)
	   (setf vec-z
		 (vec-rotate-around vec-z vec-x (- angle)))
	   (setf vec-y
		 (vec-rotate-around vec-y vec-x (- angle))))
	  ;;Push the current turtle state onto a stack
	  (([)
	   (push (list pos vec-x vec-y vec-z)
		 pile))
	  ;;Pop the turtle stack, restoring an earlier state
	  ((])
	   (let* ((asd (pop pile))
		  (pos0 (pop asd))
		  (vec-x0 (pop asd))
		  (vec-y0 (pop asd))
		  (vec-z0 (pop asd)))
	     (setf pos pos0
		   vec-x vec-x0
		   vec-y vec-y0
		   vec-z vec-z0))))))

;;; Turgle utils

(defun list-of-vectors->list (list-of-vectors)
  (iterconcat #'(lambda (vec)
		  (concatenate 'list
			       vec))
	      list-of-vectors))

(defun vec-rotate-around (vec vec-rotation angle)
  "Rotate vec around vec-rotation axis by angle"
  (transform-point (vec 0.0 0.0 0.0)
		   (matrix*
		    (rotate-around vec-rotation angle)
		    (translate vec))))