Home My Page Projects Code Snippets Project Openings 3D graphics for Standard ML
Summary Activity SCM

SCM Repository

[sml3d] Diff of /trunk/sml3d/src/particles/compiler/translate.sml
ViewVC logotype

Diff of /trunk/sml3d/src/particles/compiler/translate.sml

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 770, Mon Feb 22 00:17:15 2010 UTC revision 1150, Sat May 7 23:19:46 2011 UTC
# Line 1  Line 1 
1  (* translate.sml  (* translate.sml
2   *  
3   * COPYRIGHT (c) 2009 John Reppy (http://cs.uchicago.edu/~jhr)   * COPYRIGHT (c) 2009 John Reppy (http://cs.uchicago.edu/~jhr)
4   * All rights reserved.   * All rights reserved.
5   *   *
# Line 8  Line 8 
8    
9  structure Translate : sig  structure Translate : sig
10    
11      val compile : Particles.particle_group -> PSysIR.block list      val compile : Particles.program -> PSysIR.program
12    
13    end = struct    end = struct
14    
# Line 20  Line 20 
20    
21      fun printErr s = TextIO.output(TextIO.stdErr, s ^ "\n")      fun printErr s = TextIO.output(TextIO.stdErr, s ^ "\n")
22    
     datatype particle_state = PS of {  
         pos : IR.var,           (* vec3 *)  
         vel : IR.var,           (* vec3 *)  
         size : IR.var,          (* float *)  
         isDead : IR.var,        (* bool *)  
         color : IR.var          (* vec3 (NOTE: should be vector4) *)  
       }  
   
23    (* special PSV global variables *)    (* special PSV global variables *)
     val timeStep = PSV.new("g_timeStep", PSV.T_FLOAT)   (* physics timestep *)  
     val numDead = PSV.new("g_numDead", PSV.T_INT)       (* # of dead particles *)  
24      val epsilon = PSV.constf(0.00001)      val epsilon = PSV.constf(0.00001)
25    
26    (* constants *)    (* constants *)
27      val pi = 3.14159265358979      val pi = 3.14159265358979
28    
29    (* dummy placeholder *)    (* translation environment *)
30      fun dummy (state, k) =      datatype ir_env = TE of (IR.block list ref * IR.var PSV.Map.map * IR.var PSV.SVMap.map)
31            IR.mkPRIM(      fun insertVar (TE(blks, v_env, sv_env), x, x') = TE(blks, PSV.Map.insert (v_env, x, x'), sv_env)
32              IR.newLocal(      fun insertSVar (TE(blks, v_env, sv_env), x, x') = (case (PSV.SVMap.find (sv_env, x))
33                "temp",          of NONE => raise Fail("Changing mapping to state var that doesn't exist.")
34                IR.T_BOOL,           | SOME var => (
35                (IR.COPY, [IR.newConst("c", IR.C_BOOL false)])             IR.setRenderVar(x', IR.isRenderVar var);
36              ),             TE(blks, v_env, PSV.SVMap.insert (sv_env, x, x'))
             IR.COPY,  
             [IR.newConst("c", IR.C_BOOL false)],  
             k state  
37            )            )
38          (* end case *))
39    
40    (* translation environment *)      fun retState (TE(_, _, sv_env)) = IR.mkRETURN (PSV.SVMap.listItems sv_env)
     datatype env = TE of (IR.block list ref * IR.var PSV.Map.map)  
41    
42      fun psvToIRVar (TE(_, env), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)    (* Interaction with environment and psys variables *)
43        fun psvToIRVar (TE(_, env, _), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)
44             of SOME x' => x'             of SOME x' => x'
45              | NONE => raise Fail (String.concat["unknown variable ", name, " with ID ", Int.toString id])              | NONE => raise Fail (String.concat["unknown variable ", name, " with ID ", Int.toString id])
46            (* end case *))            (* end case *))
47    
48      fun insert (TE(blks, env), x, x') = TE(blks, PSV.Map.insert (env, x, x'))      fun pssvToIRVar (TE(_, _, env), x as PSV.SV{name, id, ...}) = (case PSV.SVMap.find(env, x)
49               of SOME x' => x'
50                | NONE => raise Fail (String.concat["unknown state variable ", name, " with ID ", Int.toString id])
51                (* end case *))
52    
53    (* create a block that implements the given continuation *)    (* create a block that implements the given continuation *)
54      fun newBlock (TE(blks, _), k : particle_state -> IR.stmt) = let      fun newBlockWithArgs (env as TE(blks, _, sv_env), args, k : ir_env -> IR.stmt) = let
55            val pos = IR.newParam ("ps_pos", IR.T_VEC)         fun copyVar(v as IR.V{name, varType, ...}) = IR.newParam(name, varType)
56            val vel = IR.newParam ("ps_vel", IR.T_VEC)         val newState = List.map copyVar (PSV.SVMap.listItems sv_env)
57            val size = IR.newParam ("ps_size", IR.T_FLOAT)         fun inssv((oldv, newv), TE(theBlks, v_env, svenv)) = let
58            val isDead = IR.newParam ("ps_isDead", IR.T_BOOL)           val theKey =
59            val color = IR.newParam ("ps_color", IR.T_VEC)             List.find
60            val state = PS{pos=pos, vel=vel, size=size, isDead=isDead, color=color}              (fn v => IR.varEq(PSV.SVMap.lookup(svenv, v), oldv))
61            val blk = IR.newBlock ([pos, vel, size, isDead, color], k state)              (PSV.SVMap.listKeys svenv)
62             val sv = (case theKey
63               of SOME x => x
64                | NONE => raise Fail("Trying to create new mapping for variable that doesn't already exist.")
65             (* end case *))
66            in            in
67              blks := blk :: !blks;           IR.setRenderVar(newv, IR.isRenderVar oldv);
68              blk           TE(theBlks, v_env, PSV.SVMap.insert(svenv, sv, newv))
69            end            end
70    
71          fun newBlockWithArgs (TE(blks, _), args, k : particle_state -> IR.stmt) = let             val blk = IR.newBlock (
72            val pos = IR.newParam ("ps_pos", IR.T_VEC)                 newState @ args,
73            val vel = IR.newParam ("ps_vel", IR.T_VEC)                 k (List.foldl inssv env
74            val size = IR.newParam ("ps_size", IR.T_FLOAT)                     (ListPair.zipEq
75            val isDead = IR.newParam ("ps_isDead", IR.T_BOOL)                         (PSV.SVMap.listItems sv_env, newState)
76            val color = IR.newParam ("ps_color", IR.T_VEC)                     )
77            val state = PS{pos=pos, vel=vel, size=size, isDead=isDead, color=color}                 )
78            val blk = IR.newBlock ([pos, vel, size, isDead, color] @ args, k state)              )
79            in            in
80              blks := blk :: !blks;              blks := blk :: !blks;
81              blk              blk
82            end            end
83    
84      fun goto (PS{pos, vel, size, isDead, color}, blk) =          fun newBlock (env, k) = newBlockWithArgs(env, [], k)
           IR.mkGOTO(blk, [pos, vel, size, isDead, color])  
   
         fun gotoWithArgs(PS{pos, vel, size, isDead, color}, args, blk) =  
           IR.mkGOTO(blk, [pos, vel, size, isDead, color] @ args)  
85    
86      fun letPRIM (x, ty, p, args, body) = let      fun letPRIM (x, ty, p, args, body) = let
87            val x' = IR.newLocal(x, ty, (p, args))            val x' = IR.newLocal(x, ty, (p, args))
# Line 98  Line 89 
89              IR.mkPRIM(x', p, args, body x')              IR.mkPRIM(x', p, args, body x')
90            end            end
91    
92    (* prim bound to state variable (S_LOCAL for now) *)     fun gotoWithArgs(TE(_, _, env), args, blk) = let
93      fun letSPRIM(x, ty, p, args, body) = let  
94            val x' = IR.new(x, IR.S_LOCAL(p, args), ty)       fun copyVar(v as IR.V{name, varType, ...}) = IR.newLocal(name^"_copy", varType, (IR.RAND, []))
95    
96         fun copyRenderVar (oldv, newv) = IR.setRenderVar (newv, IR.isRenderVar oldv)
97    
98         val vars = ((PSV.SVMap.listItems env) @ args)
99         val varCopies = List.map copyVar vars
100    
101         fun mkCopy(newv, oldv, k) = IR.mkPRIM(newv, IR.COPY, [oldv], k)
102            in            in
103              IR.mkPRIM(x', p, args, body x')       List.app copyRenderVar (ListPair.zipEq (vars, varCopies));
104         ListPair.foldr mkCopy (IR.mkGOTO(blk, varCopies)) (varCopies, vars)
105            end            end
106    
107       fun goto (env, blk) = gotoWithArgs(env, [], blk)
108    
109    
110    (* Not sure if this should be made into a primitive or not, but    (* Not sure if this should be made into a primitive or not, but
111     * basically this creates the XOR'd value of var1 and var2 and     * basically this creates the XOR'd value of var1 and var2 and
112     * stores it in result.     * stores it in result. *)
    *)  
113      fun mkXOR (result, var1, var2, stmt : IR.var -> IR.stmt) =      fun mkXOR (result, var1, var2, stmt : IR.var -> IR.stmt) =
114            letPRIM("testOR", IR.T_BOOL, IR.OR, [var1, var2], fn testOR =>            letPRIM("testOR", IR.T_BOOL, IR.OR, [var1, var2], fn testOR =>
115            letPRIM("testAND", IR.T_BOOL, IR.AND, [var1, var2], fn testAND =>            letPRIM("testAND", IR.T_BOOL, IR.AND, [var1, var2], fn testAND =>
116            letPRIM("testNAND", IR.T_BOOL, IR.NOT, [testAND], fn testNAND =>            letPRIM("testNAND", IR.T_BOOL, IR.NOT, [testAND], fn testNAND =>
117            letPRIM(result, IR.T_BOOL, IR.AND, [testOR, testNAND], stmt))))            letPRIM(result, IR.T_BOOL, IR.AND, [testOR, testNAND], stmt))))
118    
119        fun genFloatVar (fltVar, env, domain : Float.float P.domain, dist, stmt : IR.var -> IR.stmt) = let
120          fun genRandVal(var, stmt : IR.var -> IR.stmt) = (case dist
121            of P.DIST_UNIFORM =>
122              letPRIM(var, IR.T_FLOAT, IR.RAND, [], stmt)
123    
124             (* The PDF here is f(x) = 2x when 0 < x <= 1, so the CDF is going
125              * to be the integral of f from 0 -> y => y^2. Hence, whenever we
126              * generate a random number, in order to get the random value according
127              * to this probability distribution, we just square it. *)
128             | P.DIST_INC_LIN =>
129              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
130              letPRIM(var, IR.T_FLOAT, IR.MULT, [randVal, randVal], stmt))
131    
132             (* The PDF here is f(x) = -2x + 2 when 0 <= x < 1, so the CDF is going
133              * to be the integral of f from 0 -> y => -(y^2) + 2y. Hence, whenever we
134              * generate a random number, in order to get the random value according
135              * to this probability distribution, we just square it.
136              *)
137             | P.DIST_DEC_LIN =>
138              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
139              letPRIM("randSq", IR.T_FLOAT, IR.MULT, [randVal, randVal], fn randSq =>
140              letPRIM("termOne", IR.T_FLOAT, IR.MULT, [randSq, IR.newConst("negOne", IR.C_FLOAT ~1.0)], fn termOne =>
141              letPRIM("termTwo", IR.T_FLOAT, IR.MULT, [randVal, IR.newConst("negOne", IR.C_FLOAT 2.0)], fn termTwo =>
142              letPRIM(var, IR.T_FLOAT, IR.ADD, [termOne, termTwo], stmt)
143              ))))
144    
145             | _ => raise Fail "Unable to create random float for specified distribution"
146           (* end case *))
147         in
148         (case domain
149          of P.D_POINT(pt) =>
150             (* Our options here are pretty limited... *)
151             letPRIM (fltVar, IR.T_FLOAT, IR.COPY, [psvToIRVar(env, pt)], stmt)
152    
153           | P.D_BOX{max, min} =>
154             genRandVal("randf", fn rand =>
155             letPRIM("boxDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, max), psvToIRVar(env, max)], fn diff =>
156             letPRIM("scale", IR.T_FLOAT, IR.MULT, [diff, rand], fn scale =>
157             letPRIM( fltVar, IR.T_FLOAT, IR.ADD, [psvToIRVar(env, max), scale], stmt )
158             )))
159           | _ => raise Fail ("Cannot generate float in specified domain: " ^ (P.dToStr domain))
160         (* end case *))
161        end
162    
163    (* Generates a random vector within the given domain and puts it in vecVar *)    (* Generates a random vector within the given domain and puts it in vecVar *)
164      fun genVecVar (vecVar, env, domain, stmt : IR.var -> IR.stmt) = (case domain      fun genVecVar (
165          vecVar,
166          env,
167          domain : Vec3f.vec3 P.domain,
168          dist : Vec3f.vec3 P.distribution,
169          stmt : IR.var -> IR.stmt
170        ) = (case domain
171             of P.D_POINT(pt) =>             of P.D_POINT(pt) =>
172               (* Our options here are pretty limited... *)               (* Our options here are pretty limited... *)
173                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)
174    
175              | P.D_LINE({pt1, pt2}) =>              | P.D_LINE({pt1, pt2}) =>
176    
177                (* Lerp between the points. *)                (* Lerp between the points. *)
178                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
179                  letPRIM ("randInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), randVal], fn randInv =>                  letPRIM ("randInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), randVal], fn randInv =>
# Line 129  Line 181 
181                  letPRIM ("pt2s", IR.T_VEC, IR.SCALE, [randInv, psvToIRVar(env, pt2)], fn pt2ScaleVec =>                  letPRIM ("pt2s", IR.T_VEC, IR.SCALE, [randInv, psvToIRVar(env, pt2)], fn pt2ScaleVec =>
182                  letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [pt1ScaleVec, pt2ScaleVec], stmt)))))                  letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [pt1ScaleVec, pt2ScaleVec], stmt)))))
183    
184            (* This is a bit more complicated if we're trying to avoid accessing              | P.D_BOX{max, min} =>
185             * the vector variables themselves. Basically the way we can do it is to                  (* Extract the componentwise vector variables *)
186             * decompose the vector connecting min and max into the basis vectors,                  letPRIM("minX", IR.T_FLOAT, IR.EXTRACT_X, [psvToIRVar(env, min)], fn minX =>
187             * scale them independently, and then add them back together.                  letPRIM("maxX", IR.T_FLOAT, IR.EXTRACT_X, [psvToIRVar(env, max)], fn maxX =>
188             *                  letPRIM("minY", IR.T_FLOAT, IR.EXTRACT_Y, [psvToIRVar(env, min)], fn minY =>
189             * !FIXME! Actually do that. Don't have time right now...                  letPRIM("maxY", IR.T_FLOAT, IR.EXTRACT_Y, [psvToIRVar(env, max)], fn maxY =>
190             *)                  letPRIM("minZ", IR.T_FLOAT, IR.EXTRACT_Z, [psvToIRVar(env, min)], fn minZ =>
191              | P.D_BOX{max, min} => raise Fail "Cannot generate point in D_BOX."                  letPRIM("maxZ", IR.T_FLOAT, IR.EXTRACT_Z, [psvToIRVar(env, max)], fn maxZ =>
192    
193                    (* Find the distance in each component *)
194                    letPRIM("distX", IR.T_FLOAT, IR.SUB, [maxX, minX], fn distX =>
195                    letPRIM("distY", IR.T_FLOAT, IR.SUB, [maxY, minY], fn distY =>
196                    letPRIM("distZ", IR.T_FLOAT, IR.SUB, [maxZ, minZ], fn distZ =>
197    
198                    (* Get three random numbers for each of the components *)
199                    letPRIM("randX", IR.T_FLOAT, IR.RAND, [], fn randX =>
200                    letPRIM("randY", IR.T_FLOAT, IR.RAND, [], fn randY =>
201                    letPRIM("randZ", IR.T_FLOAT, IR.RAND, [], fn randZ =>
202    
203                    (* Scale the distances by these random numbers *)
204                    letPRIM("scaledX", IR.T_FLOAT, IR.MULT, [randX, distX], fn scaledX =>
205                    letPRIM("scaledY", IR.T_FLOAT, IR.MULT, [randY, distY], fn scaledY =>
206                    letPRIM("scaledZ", IR.T_FLOAT, IR.MULT, [randZ, distZ], fn scaledZ =>
207    
208                    (* Add them to the minimum vec in order to create a new vec inside
209                     * of the box.
210                     *)
211                    letPRIM("newX", IR.T_FLOAT, IR.ADD, [minX, scaledX], fn newX =>
212                    letPRIM("newY", IR.T_FLOAT, IR.ADD, [minY, scaledY], fn newY =>
213                    letPRIM("newZ", IR.T_FLOAT, IR.ADD, [minZ, scaledZ], fn newZ =>
214    
215                    (* Gen the vector *)
216                    letPRIM(vecVar, IR.T_VEC, IR.GEN_VEC, [newX, newY, newZ], stmt
217    
218                    )))))))))))))))))))
219    
220    
221              | P.D_TRIANGLE{pt1, pt2, pt3} =>              | P.D_TRIANGLE{pt1, pt2, pt3} =>
222    
223                  letPRIM ("pt1ToPt2", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn pt1ToPt2 =>                  letPRIM ("pt1ToPt2", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn pt1ToPt2 =>
224                  letPRIM ("pt1ToPt3", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt3), psvToIRVar(env, pt1)], fn pt1ToPt3 =>                  letPRIM ("pt1ToPt3", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt3), psvToIRVar(env, pt1)], fn pt1ToPt3 =>
225                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>
# Line 159  Line 240 
240                    letPRIM("htInv", IR.T_FLOAT, IR.DIV, [IR.newConst("one", IR.C_FLOAT 1.0), height], fn htInv =>                    letPRIM("htInv", IR.T_FLOAT, IR.DIV, [IR.newConst("one", IR.C_FLOAT 1.0), height], fn htInv =>
241                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>
242                    (* Generate a point in the lower disc. *)                    (* Generate a point in the lower disc. *)
243                      genVecVar("ptInDisc", insert(env, normVar, norm), P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad}, fn ptInDisc =>                      genVecVar("ptInDisc",
244                          insertVar(env, normVar, norm),
245                          P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
246                          dist,
247                          fn ptInDisc =>
248                    (* Now add this point to a random scaling of the normVec. *)                    (* Now add this point to a random scaling of the normVec. *)
249                      letPRIM("s", IR.T_FLOAT, IR.MULT, [height, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [height, ourRand], fn scale =>
250                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, normVec], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, normVec], fn scaledNormVec =>
# Line 167  Line 252 
252                   end                   end
253    
254              | P.D_DISC {pt, normal, irad, orad} =>              | P.D_DISC {pt, normal, irad, orad} =>
255    
256                (* Get a random angle... *)                (* Get a random angle... *)
257                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>
258                  letPRIM ("t", IR.T_FLOAT, IR.MULT, [randForAng, IR.newConst("fullCir", IR.C_FLOAT (2.0 * pi))], fn randAng =>                  letPRIM ("t", IR.T_FLOAT, IR.MULT, [randForAng, IR.newConst("fullCir", IR.C_FLOAT (2.0 * pi))], fn randAng =>
259    
260                (* Get a random radius *)                (* Get a random radius *)
261                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>
262                  letPRIM ("e0sq", IR.T_FLOAT, IR.MULT, [newRand, newRand], fn randRadSq =>              letPRIM ("e0sq", IR.T_FLOAT, IR.SQRT, [newRand], fn randRadSq =>
263                  letPRIM ("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>                  letPRIM ("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>
264                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>
265                  letPRIM ("newRad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), newRadDist], fn newRad =>                  letPRIM ("newRad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), newRadDist], fn newRad =>
266    
267                (* Find a vector in the plane of the disc, and then                (* Find a vector in the plane of the disc, and then
268                 * translate it to the center.               * translate it to the center. *)
                *)  
269                  letPRIM ("ntoc", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn normToCen =>                  letPRIM ("ntoc", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn normToCen =>
270                  letPRIM ("v", IR.T_VEC, IR.CROSS, [psvToIRVar(env, pt), normToCen], fn vecInDisc =>                  letPRIM ("v", IR.T_VEC, IR.CROSS, [psvToIRVar(env, pt), normToCen], fn vecInDisc =>
271                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>
272                  letPRIM ("p", IR.T_VEC, IR.CROSS, [vecInDiscNorm, psvToIRVar(env, normal)], fn ptInDisc =>                  letPRIM ("p", IR.T_VEC, IR.CROSS, [vecInDiscNorm, psvToIRVar(env, normal)], fn ptInDisc =>
273                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>
274    
275                (* Figure out x and y values for our new radius and angle *)                (* Figure out x and y values for our new radius and angle *)
276                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>
277                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>
# Line 192  Line 280 
280                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>
281                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>
282                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>
283                  letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt))))))))))))))))))))  
284                letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt)
285                )))))))))))))))))))
286    
287              | P.D_CONE{pt1, pt2, irad, orad} => let              | P.D_CONE{pt1, pt2, irad, orad} => let
288                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)
# Line 200  Line 290 
290                    letPRIM("eh",  IR.T_FLOAT, IR.RAND, [], fn ourRand =>                    letPRIM("eh",  IR.T_FLOAT, IR.RAND, [], fn ourRand =>
291                    letPRIM("nv", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn normVec =>                    letPRIM("nv", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn normVec =>
292                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>
293                      genVecVar("ptInDisc", insert(env, normVar, norm), P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad}, fn ptInDisc =>               genVecVar("ptInDisc",
294                  insertVar(env, normVar, norm),
295                  P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
296                  dist,
297                  fn ptInDisc =>
298                      letPRIM("gptt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), ptInDisc], fn genPtToTip =>                      letPRIM("gptt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), ptInDisc], fn genPtToTip =>
299                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>
300                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>
301                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>
302                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)))))))))               letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)
303                 ))))))))
304                  end                  end
305    
306              | _ => raise Fail "Cannot generate point in specified domain."                  | P.D_SPHERE{center, irad, orad} =>
307            (* end case *))  
308            (*                    (* Source: http://mathworld.wolfram.com/SpherePointPicking.html *)
           | generate (Dplane{pt, n}) = Vec3f.unpack pt  
       | generate (Drectangle{pt, u, v}) = Vec3f.unpack pt  
       | generate (Dsphere{c, orad, irad}) = Vec3f.unpack c  
       | generate (Dblob{c, stddev}) = Vec3f.unpack c  
           *)  
309    
310              (* generate two random values... one will be called u and will
311               * represent cos(theta), and the other will be called v and will
312               * represent a random value in [0, 2 * pi] *)
313              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn rv =>
314              letPRIM("dblRandVal", IR.T_FLOAT, IR.MULT, [rv, IR.newConst("Two", IR.C_FLOAT 2.0)], fn drv =>
315              letPRIM("rand", IR.T_FLOAT, IR.SUB, [drv, IR.newConst("One", IR.C_FLOAT 1.0)], fn u =>
316    
317              letPRIM("rv2", IR.T_FLOAT, IR.RAND, [], fn rv2 =>
318              letPRIM("rand2", IR.T_FLOAT, IR.MULT, [rv2, IR.newConst("TwoPi", IR.C_FLOAT (2.0 * Float.M_PI))], fn theta =>
319    
320              letPRIM("cosTheta", IR.T_FLOAT, IR.COS, [theta], fn cosT =>
321              letPRIM("sinTheta", IR.T_FLOAT, IR.SIN, [theta], fn sinT =>
322    
323              letPRIM("usq", IR.T_FLOAT, IR.MULT, [u, u], fn usq =>
324              letPRIM("usqInv", IR.T_FLOAT, IR.SUB, [IR.newConst("One", IR.C_FLOAT 1.0), usq], fn usqInv =>
325              letPRIM("sinPhi", IR.T_FLOAT, IR.SQRT, [usqInv], fn sinP =>
326    
327              letPRIM("xVal", IR.T_FLOAT, IR.MULT, [sinP, cosT], fn xVal =>
328              letPRIM("yVal", IR.T_FLOAT, IR.MULT, [sinP, sinT], fn yVal =>
329              (* zval is just u *)
330    
331              letPRIM("vec", IR.T_VEC, IR.GEN_VEC, [xVal, yVal, u], fn vec =>
332    
333              (* Generate a random radius... *)
334                      letPRIM("ratio", IR.T_FLOAT, IR.DIV, [psvToIRVar(env, irad), psvToIRVar(env, orad)], fn ratio =>
335                      letPRIM("invRatio", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), ratio], fn invRatio =>
336                      letPRIM("randVar", IR.T_FLOAT, IR.RAND, [], fn rand =>
337                      letPRIM("randScale", IR.T_FLOAT, IR.MULT, [rand, invRatio], fn randScale =>
338                      letPRIM("randVal", IR.T_FLOAT, IR.ADD, [randScale, ratio], fn randVal =>
339                      letPRIM("randValSq", IR.T_FLOAT, IR.MULT, [randVal, randVal], fn randValSq =>
340                      letPRIM("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>
341                      letPRIM("randRadVal", IR.T_FLOAT, IR.MULT, [radDiff, randValSq], fn randRadVal =>
342                      letPRIM("rad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), randRadVal], fn rad =>
343    
344                      (* Normalize the vector and scale it by the radius. *)
345                      letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [rad, vec], fn sVec =>
346                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [sVec, psvToIRVar(env, center)], stmt)
347                      ))))))))))
348                      )))))))))))))
349    
350                | _ => raise Fail ("Cannot generate point in specified domain: "  ^ (P.dToStr domain))
351              (* end case *))
352    
353    (* This function takes an IR boolean, its environment, a particle state, domain,    (* This function takes an IR boolean, its environment, a particle state, domain,
354     * and continuation.     * and continuation.
# Line 224  Line 356 
356     * We set the boolean to whether or not the current particle given by the particle     * We set the boolean to whether or not the current particle given by the particle
357     * state is within the domain, and then pass the continuation on.     * state is within the domain, and then pass the continuation on.
358     *)     *)
359      fun mkWithinVar (boolVar, env, var, d, stmt : IR.var -> IR.stmt) = let      fun mkVecWithinVar (boolVar, env, var, d : Vec3f.vec3 P.domain, stmt : IR.var -> IR.stmt) = let
360            val pos = var            val pos = var
361            in            in
362              case d              case d
# Line 253  Line 385 
385               * behind it (with respect to the normal)               * behind it (with respect to the normal)
386               *)               *)
387                | P.D_PLANE{pt, normal} =>                | P.D_PLANE{pt, normal} =>
388                    letPRIM("posToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), pos], fn posToPt =>                    letPRIM("posToPt", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt)], fn posToPt =>
389                    letPRIM("dot", IR.T_FLOAT, IR.DOT, [posToPt, psvToIRVar(env, normal)], fn dotProd =>                    letPRIM("dot", IR.T_FLOAT, IR.DOT, [posToPt, psvToIRVar(env, normal)], fn dotProd =>
390                    letPRIM(boolVar, IR.T_BOOL, IR.GT, [dotProd, IR.newConst("zero", IR.C_FLOAT 0.0)], stmt)))                    letPRIM(boolVar, IR.T_BOOL, IR.GT, [dotProd, IR.newConst("zero", IR.C_FLOAT 0.0)], stmt)))
391    
# Line 264  Line 396 
396               * orad.               * orad.
397               *)               *)
398                | P.D_DISC{pt, normal, orad, irad} =>                | P.D_DISC{pt, normal, orad, irad} =>
399                    letPRIM("posToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), pos], fn posToPt =>              letPRIM("posToPt", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt)], fn posToPt =>
                   letPRIM("posToPtLen", IR.T_FLOAT, IR.LEN, [posToPt], fn posToPtLen =>  
400                    letPRIM("dot", IR.T_FLOAT, IR.DOT, [posToPt, psvToIRVar(env, normal)], fn dotProd =>                    letPRIM("dot", IR.T_FLOAT, IR.DOT, [posToPt, psvToIRVar(env, normal)], fn dotProd =>
401                    letPRIM("inDisc", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.01), dotProd], fn inDisc =>                    letPRIM("inDisc", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.01), dotProd], fn inDisc =>
402                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToPtLen], fn inOrad =>  
403                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToPtLen, psvToIRVar(env, irad)], fn inIrad =>              letPRIM("parPosToP", IR.T_VEC, IR.SCALE, [dotProd, psvToIRVar(env, normal)], fn posToPtParallelToNormal =>
404                letPRIM("perpPosToP", IR.T_VEC, IR.SUB_VEC, [posToPt, posToPtParallelToNormal], fn posToPtPerpToNormal =>
405                letPRIM("inDiscLen", IR.T_FLOAT, IR.LEN, [posToPtPerpToNormal], fn posToPtLen =>
406    
407                letPRIM("inOradGt", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToPtLen], fn inOradGt =>
408                letPRIM("inOradEq", IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, orad), posToPtLen], fn inOradEq =>
409                letPRIM("inOrad", IR.T_BOOL, IR.OR, [inOradGt, inOradEq], fn inOrad =>
410    
411                letPRIM("inIradGt", IR.T_BOOL, IR.GT, [posToPtLen, psvToIRVar(env, irad)], fn inIradGt =>
412                letPRIM("inIradEq", IR.T_BOOL, IR.EQUALS, [posToPtLen, psvToIRVar(env, irad)], fn inIradEq =>
413                letPRIM("inIrad", IR.T_BOOL, IR.OR, [inIradGt, inIradEq], fn inIrad =>
414    
415                    letPRIM("inBothRad", IR.T_BOOL, IR.AND, [inIrad, inOrad], fn inBothRad =>                    letPRIM("inBothRad", IR.T_BOOL, IR.AND, [inIrad, inOrad], fn inBothRad =>
416                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inDisc, inBothRad], stmt))))))))  
417                letPRIM(boolVar, IR.T_BOOL, IR.AND, [inDisc, inBothRad], stmt))))))))))))))
418    
419              (* Simply see whether or not the distance from the center is within the              (* Simply see whether or not the distance from the center is within the
420               * specified bounds.               * specified bounds.
# Line 282  Line 425 
425                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToCLen], fn inOrad =>                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToCLen], fn inOrad =>
426                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToCLen, psvToIRVar(env, irad)], fn inIrad =>                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToCLen, psvToIRVar(env, irad)], fn inIrad =>
427                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inIrad, inOrad], stmt)))))                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inIrad, inOrad], stmt)))))
428    
429                      | P.D_CYLINDER {pt1, pt2, irad, orad} =>
430    
431                      (* !FIXME! Right now, we see whether or not the point is within the two planes defined
432                       * by the endpoints of the cylinder, and then testing to see whether or not the smallest
433                       * distance to the line segment falls within the radii. It might be faster to find the
434                       * closest point to the line defined by the endpoints and then see whether or not the point
435                       * is within the segment.
436                       *)
437    
438                      (* Is it in one plane *)
439                      letPRIM("plane1Norm", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn plane1Norm =>
440                      letPRIM("posToPt1", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt1)], fn posToPt1 =>
441                      letPRIM("dot1", IR.T_FLOAT, IR.DOT, [posToPt1, plane1Norm], fn dot1Prod =>
442                      letPRIM("inPlane1", IR.T_BOOL, IR.GT, [dot1Prod, IR.newConst("zero", IR.C_FLOAT 0.0)], fn inPlane1=>
443    
444                      (* Is it in another plane *)
445                      letPRIM("plane2Norm", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt1), psvToIRVar(env, pt2)], fn plane2Norm =>
446                      letPRIM("posToPt2", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt2)], fn posToPt2 =>
447                      letPRIM("dot2", IR.T_FLOAT, IR.DOT, [posToPt2, plane2Norm], fn dot2Prod =>
448                      letPRIM("inPlane2", IR.T_BOOL, IR.GT, [dot2Prod, IR.newConst("zero", IR.C_FLOAT 0.0)], fn inPlane2=>
449    
450                      (* Is it in both planes? *)
451                      letPRIM("inPlanes", IR.T_BOOL, IR.AND, [inPlane1, inPlane2], fn inPlanes =>
452    
453                      (* Find distance from segment *)
454                      letPRIM("a", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn a =>
455                      letPRIM("b", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt1), pos], fn b =>
456                      letPRIM("alen", IR.T_FLOAT, IR.LEN, [a], fn alen =>
457                      letPRIM("axb", IR.T_VEC, IR.CROSS, [a, b], fn axb =>
458                      letPRIM("axblen", IR.T_FLOAT, IR.LEN, [axb], fn axblen =>
459                      letPRIM("dist", IR.T_FLOAT, IR.DIV, [axblen, alen], fn dist =>
460    
461                      (* Is distance in both radii? *)
462                      letPRIM("inOradGt", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), dist], fn inOradGt =>
463                      letPRIM("inOradEq", IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, orad), dist], fn inOradEq =>
464                      letPRIM("inOrad", IR.T_BOOL, IR.OR, [inOradGt, inOradEq], fn inOrad =>
465    
466                      letPRIM("inIradGt", IR.T_BOOL, IR.GT, [dist, psvToIRVar(env, irad)], fn inIradGt =>
467                      letPRIM("inIradEq", IR.T_BOOL, IR.EQUALS, [dist, psvToIRVar(env, irad)], fn inIradEq =>
468                      letPRIM("inIrad", IR.T_BOOL, IR.OR, [inIradGt, inIradEq], fn inIrad =>
469    
470                      letPRIM("inBothRad", IR.T_BOOL, IR.AND, [inIrad, inOrad], fn inBothRad =>
471    
472                      (* It's in the cylinder (tube) if it's within both radii and in both planes... *)
473                      letPRIM(boolVar, IR.T_BOOL, IR.AND, [inPlanes, inBothRad], stmt)
474                      ))))))))))))))))))))))
475  (*  (*
476                | P.D_TRIANGLE {pt1: vec3f var, pt2: vec3f var, pt3: vec3f var}                | P.D_TRIANGLE {pt1: vec3f var, pt2: vec3f var, pt3: vec3f var}
477                | P.D_PLANE {pt: vec3f var, normal: vec3f var}                | P.D_PLANE {pt: vec3f var, normal: vec3f var}
478                | P.D_RECT {pt: vec3f var, htvec: vec3f var, wdvec: vec3f var}                | P.D_RECT {pt: vec3f var, htvec: vec3f var, wdvec: vec3f var}
479                | P.D_BOX {min: vec3f var, max: vec3f var}                | P.D_BOX {min: vec3f var, max: vec3f var}
480                | P.D_SPHERE {center: vec3f var, irad: vec3f var, orad: vec3f var}                | P.D_SPHERE {center: vec3f var, irad: vec3f var, orad: vec3f var}
               | P.D_CYLINDER {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}  
481                | P.D_CONE {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}                | P.D_CONE {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}
482                | P.D_BLOB {center: vec3f var, stddev: float var}                | P.D_BLOB {center: vec3f var, stddev: float var}
483                | P.D_DISC {pt: vec3f var, normal: vec3f var, irad: float var, orad: float var}                | P.D_DISC {pt: vec3f var, normal: vec3f var, irad: float var, orad: float var}
484  *)  *)
485                | _ => raise Fail "Cannot determine within-ness for specified domain."                | _ => raise Fail ("Cannot determine within-ness for specified vec3 domain: " ^ (P.dToStr d))
486              (* end case *)              (* end case *)
487            end (*end let *)            end (*end let *)
488    
489            fun mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) = (case d
490              of P.D_POINT(pt) => letPRIM(boolVar, IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, pt), var], stmt)
491               | P.D_BOX {min, max} =>
492                 letPRIM("bigMin", IR.T_BOOL, IR.GT, [var, psvToIRVar(env, min)], fn bigMin =>
493                 letPRIM("smallMax", IR.T_BOOL, IR.GT, [psvToIRVar(env, max), var], fn smallMax =>
494                 letPRIM(boolVar, IR.T_BOOL, IR.AND, [bigMin, smallMax], stmt)))
495               | _ => raise Fail ("Cannot determine within-ness for specified float domain: " ^ (P.dToStr d))
496             (* end case *))
497    
498    (* generate code to produce a random particle state from a domain *)          fun mkIntBool(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> ir_env -> IR.stmt) = let
499      fun newParticle (posDomain, velDomain, colDomain, env, k : particle_state -> IR.stmt) =            val _ = ()
500              (* genVecVar (vecVar, env, domain, stmt) *)           in
501              genVecVar("ps_pos", env, posDomain, fn newPos =>            (case d
502              genVecVar("ps_vel", env, velDomain, fn newVel =>              of P.D_POINT(pt) =>
503              genVecVar("ps_col", env, colDomain, fn newCol =>  
504              letSPRIM ("ps_size", IR.T_FLOAT, IR.RAND, [], fn newSize =>               (* Get vectors *)
505              letSPRIM ("ps_isDead", IR.T_BOOL, IR.COPY, [IR.newConst("fbool", IR.C_BOOL false)], fn newIsDead =>               letPRIM("p1ToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar (env, pt), p1var], fn p1ToPt =>
506                k(PS{pos = newPos, vel = newVel, size = newSize, isDead = newIsDead, color = newCol}))))))               letPRIM("p2ToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar (env, pt), p2var], fn p2ToPt =>
507                 letPRIM("p1ToP2", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn p1ToP2 =>
508    
509                 (* Get distances *)
510                 letPRIM("p1ToPtLen", IR.T_FLOAT, IR.LEN, [p1ToPt], fn p1ToPtLen =>
511                 letPRIM("p2ToPtLen", IR.T_FLOAT, IR.LEN, [p2ToPt], fn p2ToPtLen =>
512                 letPRIM("p1ToP2Len", IR.T_FLOAT, IR.LEN, [p1ToP2], fn p1ToP2Len =>
513    
514                 (* Add & subtract ... *)
515                 letPRIM("distSum", IR.T_FLOAT, IR.ADD, [p1ToPtLen, p2ToPtLen], fn distSum =>
516                 letPRIM("distDiff", IR.T_FLOAT, IR.SUB, [distSum, p1ToP2Len], fn distDiff =>
517                 letPRIM("distDiffAbs", IR.T_FLOAT, IR.ABS, [distDiff], fn distDiffAbs =>
518    
519                 (* Do the boolean stuff... *)
520                 letPRIM("intersect", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), distDiffAbs], fn intVar => k intVar env)
521    
522                 )))
523                 )))
524                 )))
525    
526                | P.D_PLANE {pt, normal} =>
527                  letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
528                  letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
529                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
530                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
531                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
532                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
533                  letPRIM("intersect", IR.T_BOOL, IR.GT, [IR.newConst("zero", IR.C_FLOAT 0.0), distProd], fn intVar => k intVar env)
534                  ))))))
535    
536                | P.D_DISC {pt, normal, orad, irad} => let
537                  val boolVar = IR.newParam("intersect", IR.T_BOOL)
538                  val newBlk = newBlockWithArgs(env, [boolVar], k boolVar)
539                 in
540                  letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
541                  letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
542    
543                  (* Early out... does it intersect the plane?
544                   *
545                   * !SPEED! Due to the perceived slowness of branching on
546                   * GPUs, this might not actually be faster on all runtime environments *)
547    
548                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
549                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
550                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
551                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
552                  letPRIM("earlyOut", IR.T_BOOL, IR.GT, [distProd, IR.newConst("zero", IR.C_FLOAT 0.0)], fn earlyOut =>
553                  IR.mkIF(earlyOut,
554                    (* then *)
555                    letPRIM("intersect", IR.T_BOOL, IR.NOT, [earlyOut], fn var => gotoWithArgs(env, [var], newBlk)),
556                    (* else *)
557                    letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
558                    letPRIM("vDotn", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn vdn =>
559                    letPRIM("t", IR.T_FLOAT, IR.DIV, [p1dist, vdn], fn t =>
560    
561                    (* !TODO! Add some sort of assert mechanism to make sure that t is
562                     * in the interval [0, 1]... *)
563                    letPRIM("vscale", IR.T_VEC, IR.SCALE, [t, v], fn vscale =>
564                    letPRIM("ppt", IR.T_VEC, IR.ADD_VEC, [p1var, vscale], fn ppt =>
565                    letPRIM("lenVec", IR.T_VEC, IR.SUB_VEC, [ppt, psvToIRVar(env, pt)], fn cv =>
566                    letPRIM("len", IR.T_FLOAT, IR.LEN, [cv], fn len =>
567    
568                    (* Check to see whether or not it's within the radius... *)
569                    letPRIM("gtirad", IR.T_BOOL, IR.GT, [len, psvToIRVar(env, irad)], fn gtirad =>
570                    letPRIM("ltorad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), len], fn ltorad =>
571                    letPRIM("intersect", IR.T_BOOL, IR.AND, [gtirad, ltorad], fn var => gotoWithArgs(env, [var], newBlk))
572                   ))))))))))
573                 )))))))
574                end (* P.D_DISC *)
575    
576                | _ => raise Fail ("Cannot calculate intersection bool for specified domain: " ^ (P.dToStr d))
577              (* end case *))
578    
579             end (* mkIntBool *)
580    
581            (* We assume that the segment already intersects with the domain. *)
582            fun mkIntPt(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> IR.stmt) = let
583              val _ = ()
584             in
585              (case d
586                of P.D_POINT(pt) => k (psvToIRVar (env, pt))
587    
588                 | P.D_PLANE {pt, normal} =>
589                   letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
590                   letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
591                   letPRIM("num", IR.T_FLOAT, IR.SUB, [d, p1d], fn num =>
592                   letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
593                   letPRIM("den", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn den =>
594                   letPRIM("t", IR.T_FLOAT, IR.DIV, [num, den], fn t =>
595                   letPRIM("vsc", IR.T_VEC, IR.SCALE, [t, v], fn vs =>
596                   letPRIM("intPt", IR.T_VEC, IR.ADD_VEC, [p1var, vs], k)
597                   )))))))
598    
599                 (* Since we already know they intersect, the intersection point must be
600                  * just the point that's on the plane... *)
601                 | P.D_DISC {pt, normal, orad, irad} => mkIntPt(env, p1var, p2var, P.D_PLANE{pt = pt, normal = normal}, k)
602                 | _ => raise Fail ("Cannot calculate intersection point for specified domain: "  ^ (P.dToStr d))
603              (* end case *))
604             end (* mkIntPt *)
605    
606      (* Find the normal at the given position of the particle for the specified      (* Find the normal at the given position of the particle for the specified
607       * domain. Note, that the particle doesn't necessarily need to be on the       * domain. Note, that the particle doesn't necessarily need to be on the
608       * domain, but if it's not then the behavior is undefined.       * domain, but if it's not then the behavior is undefined. *)
609       *)      fun normAtPoint(retNorm, d, env, pos, k : IR.var -> ir_env -> IR.stmt) = let
     fun normAtPoint(retNorm, d, env, state, k : IR.var -> particle_state -> IR.stmt) = let  
610        val newNorm = IR.newParam("n", IR.T_VEC)        val newNorm = IR.newParam("n", IR.T_VEC)
611        val nextBlk = newBlockWithArgs(env, [newNorm], k(newNorm))        val nextBlk = newBlockWithArgs(env, [newNorm], k(newNorm))
       val PS{pos, ...} = state  
612       in       in
613        (case d        (case d
614            of P.D_PLANE{pt, normal} => letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],            of P.D_PLANE{pt, normal} =>
615                fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))               letPRIM("inVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), pos], fn inVec =>
616                 letPRIM("dotNorm", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, normal), inVec], fn dotNorm =>
617                 letPRIM("eqZero", IR.T_BOOL, IR.EQUALS, [dotNorm, IR.newConst("One", IR.C_FLOAT 0.0)], fn eqZero =>
618                 IR.mkIF(eqZero,
619                     (*thenStmt*)
620                     gotoWithArgs(env, [psvToIRVar(env, normal)], nextBlk),
621                 (*elseStmt*)
622                 letPRIM("dnRecip", IR.T_FLOAT, IR.DIV, [IR.newConst("One", IR.C_FLOAT 1.0), dotNorm], fn dnRecip =>
623                 letPRIM("absR", IR.T_FLOAT, IR.ABS, [dnRecip], fn absR =>
624                 letPRIM("sign", IR.T_FLOAT, IR.MULT, [absR, dotNorm], fn sign =>
625                 letPRIM(retNorm, IR.T_VEC, IR.SCALE, [sign, psvToIRVar(env, normal)],
626                 fn newNormVar => gotoWithArgs(env, [newNormVar], nextBlk)))))
627             ))))
628    
629             | P.D_DISC{pt, normal, irad, orad} =>             | P.D_DISC{pt, normal, irad, orad} =>
630                mkWithinVar("inP", env, pos, d, fn inPlane =>                normAtPoint(retNorm, P.D_PLANE{pt=pt, normal=normal}, env, pos, k)
                   IR.mkIF(inPlane,  
                     (* then *)  
                     letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],  
                       fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk)),  
                     (* else *)  
                     letPRIM(retNorm,  
                       IR.T_VEC,  
                           IR.SCALE,  
                           [IR.newConst("negOne", IR.C_FLOAT ~1.0), psvToIRVar(env, normal)],  
                           fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))  
                    )  
                  )  
631    
632             | P.D_SPHERE{center, irad, orad} => let             | P.D_SPHERE{center, irad, orad} =>
               val PS{pos, vel, size, isDead, color} = state  
               in  
633                      letPRIM("sv", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, center)], fn subVec =>                      letPRIM("sv", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, center)], fn subVec =>
634                  letPRIM(retNorm, IR.T_VEC, IR.NORM, [subVec], fn newNormVar => k newNormVar state                  letPRIM(retNorm, IR.T_VEC, IR.NORM, [subVec], fn newNormVar => k newNormVar env
635                      ))                      ))
636    
637               | _ => raise Fail("Cannot find normal to point of specified domain." ^ (P.dToStr d))
638             (* end case *))
639                end                end
640    
641             | _ => raise Fail("Cannot find normal to point of specified domain.")          fun trExpr(expr, env, k : IR.var -> ir_env -> IR.stmt) = (case expr
642              of P.CONSTF f => k (IR.newConst ("c", IR.C_FLOAT f)) env
643    
644           | P.CONST3F v => k (IR.newConst ("c", IR.C_VEC v)) env
645    
646           | P.VAR v => k (psvToIRVar (env, v)) env
647    
648           | P.STATE_VAR sv => k (pssvToIRVar (env, sv)) env
649    
650           | P.GENERATE3F (dom, dist) => genVecVar("genVec", env, dom, dist, fn var => k var env)
651    
652           | P.GENERATEF (dom, dist) => genFloatVar("genFlt", env, dom, dist, fn var => k var env)
653    
654           | P.ADD(e1, e2) =>
655             trExpr(e1, env, fn e1var => fn env' =>
656             trExpr(e2, env', fn e2var => fn env'' =>
657             let
658              val IR.V{varType=vt1, ...} = e1var
659              val IR.V{varType=vt2, ...} = e2var
660             in
661              (case (vt1, vt2)
662                of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("addVar", IR.T_FLOAT, IR.ADD, [e1var, e2var], fn var => k var env'')
663                 | (IR.T_VEC, IR.T_VEC) => letPRIM("addVar", IR.T_VEC, IR.ADD_VEC, [e1var, e2var], fn var => k var env'')
664                 | _ => raise Fail ("Type mismatch to ADD expression")
665              (* end case *))
666             end))
667    
668           | P.SCALE (e1, e2) =>
669             trExpr(e1, env, fn e1var => fn env' =>
670             trExpr(e2, env', fn e2var => fn env'' =>
671             let
672              val IR.V{varType=vt1, ...} = e1var
673              val IR.V{varType=vt2, ...} = e2var
674             in
675              (case (vt1, vt2)
676                of (IR.T_FLOAT, IR.T_VEC) => letPRIM("scaleVar", IR.T_VEC, IR.SCALE, [e1var, e2var], fn var => k var env'')
677                 | (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("scaleVar", IR.T_FLOAT, IR.MULT, [e1var, e2var], fn var => k var env'')
678                 | _ => raise Fail (String.concat["Type mismatch to SCALE expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
679              (* end case *))
680             end))
681    
682           | P.DIV (e1, e2) =>
683             trExpr(e1, env, fn e1var => fn env' =>
684             trExpr(e2, env', fn e2var => fn env'' =>
685             let
686              val IR.V{varType=vt1, ...} = e1var
687              val IR.V{varType=vt2, ...} = e2var
688             in
689              (case (vt1, vt2)
690                of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("divVar", IR.T_FLOAT, IR.DIV, [e1var, e2var], fn var => k var env'')
691                 | _ => raise Fail (String.concat["Type mismatch to DIV expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
692              (* end case *))
693             end))
694    
695           | P.NEG e =>
696             trExpr(e, env, fn evar => fn env' =>
697             let
698              val IR.V{varType, ...} = evar
699             in
700              (case varType
701                of IR.T_FLOAT => letPRIM("negVar", IR.T_FLOAT, IR.MULT, [evar, IR.newConst("negOne", IR.C_FLOAT ~1.0)], fn var => k var env')
702                 | IR.T_VEC => letPRIM("negVar", IR.T_VEC, IR.NEG_VEC, [evar], fn var => k var env')
703                 | _ => raise Fail ("Type mismatch to NEG expression")
704           (* end case *))           (* end case *))
705             end)
706    
707           | P.DOT (e1, e2) =>
708             trExpr(e1, env, fn e1var => fn env' =>
709             trExpr(e2, env', fn e2var => fn env'' =>
710             let
711              val IR.V{varType=vt1, ...} = e1var
712              val IR.V{varType=vt2, ...} = e2var
713             in
714              (case (vt1, vt2)
715                of (IR.T_VEC, IR.T_VEC) => letPRIM("dotVar", IR.T_FLOAT, IR.DOT, [e1var, e2var], fn var => k var env'')
716                 | _ => raise Fail ("Type mismatch to DOT expression")
717              (* end case *))
718             end))
719    
720           | P.CROSS (e1, e2) =>
721             trExpr(e1, env, fn e1var => fn env' =>
722             trExpr(e2, env', fn e2var => fn env'' =>
723             let
724              val IR.V{varType=vt1, ...} = e1var
725              val IR.V{varType=vt2, ...} = e2var
726             in
727              (case (vt1, vt2)
728                of (IR.T_VEC, IR.T_VEC) => letPRIM("crossVar", IR.T_VEC, IR.CROSS, [e1var, e2var], fn var => k var env'')
729                 | _ => raise Fail ("Type mismatch to CROSS expression")
730              (* end case *))
731             end))
732    
733           | P.NORMALIZE e =>
734             trExpr(e, env, fn evar => fn env' =>
735             let
736              val IR.V{varType, ...} = evar
737             in
738              (case varType
739                of IR.T_VEC => letPRIM("normVar", IR.T_VEC, IR.NORM, [evar], fn var => k var env')
740                 | _ => raise Fail ("Type mismatch to NORMALIZE expression")
741              (* end case *))
742             end)
743    
744           | P.LENGTH e =>
745             trExpr(e, env, fn evar => fn env' =>
746             let
747              val IR.V{varType, ...} = evar
748             in
749              (case varType
750                of IR.T_VEC => letPRIM("lenVar", IR.T_FLOAT, IR.LEN, [evar], fn var => k var env')
751                 | _ => raise Fail ("Type mismatch to LENGTH expression")
752              (* end case *))
753             end)
754    
755           (* !SPEED! We're assuming that there is an intersection here... *)
756           | P.INTERSECT {p1, p2, d} =>
757             trExpr(p1, env, fn p1var => fn env' =>
758             trExpr(p2, env', fn p2var => fn env'' =>
759             let
760              val IR.V{varType=vt1, ...} = p1var
761              val IR.V{varType=vt2, ...} = p2var
762             in
763              (case (vt1, vt2)
764                of (IR.T_VEC, IR.T_VEC) => mkIntPt(env, p1var, p2var, d, fn var => k var env'')
765                 | _ => raise Fail("Type mismatch to INTERSECT expression")
766              (* end case *))
767             end))
768    
769           | P.NORMALTO (e, d) =>
770             trExpr(e, env, fn evar => fn env' =>
771             let
772              val IR.V{varType, ...} = evar
773              fun cont s = k s
774             in
775              (case varType
776                of IR.T_VEC => normAtPoint("normVar", d, env', evar, k)
777                 | _ => raise Fail("Type mismatch to NORMALTO expression")
778              (* end case *))
779             end)
780    
781              (* end case expr *))
782    
783            (* generate code to produce a random particle state from a domain *)
784        fun newParticle (sv_gens, env, k : ir_env -> IR.stmt) = let
785    
786          fun createVar(P.GEN{var, ...}) = let
787            val P.PSV.SV{name, ty, ...} = var
788           in
789            IR.newLocal("ps_" ^ name, IR.psvTyToIRTy ty, (IR.RAND, []))
790          end          end
791    
792          fun trEmitter(emit, env, state, k : particle_state -> IR.stmt) = let        val newState = List.map createVar sv_gens
793            val PS{pos, vel, size, isDead, color} = state  
794            val P.EMIT{maxNum, posDomain, velDomain, colDomain, ...} = emit        fun genVar((sv_gen, var), cont) = let
795            val blk = newBlock (env, k)          val P.GEN{exp, var=svar} = sv_gen
796            val IR.V{varType, ...} = var
797           in           in
798            fn env' => trExpr(exp, env', fn newVal => fn env'' => cont (insertSVar(env'', svar, newVal)))
799           end (* genVar *)
800    
801         in
802          (List.foldr (fn (x, y) => genVar(x, y)) k (ListPair.zipEq (sv_gens, newState))) env
803         end (* new particle *)
804    
805        fun trEmitter(emit, env, k) = let
806          val P.EMIT{freq, sv_gens} = emit
807          val ttl = pssvToIRVar(env, P.sv_ttl)
808         in
809          letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>
810        IR.mkIF(isDead,        IR.mkIF(isDead,
811         (* then *)         (* then *)
812         letPRIM("t1", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, maxNum)], fn t1 =>         trExpr(freq, env, fn t1 => fn env' =>
813         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, numDead)], fn t2 =>         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env', PSV.numDead)], fn t2 =>
814         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>
815         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>
816         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>
817         IR.mkIF(t3,         IR.mkIF(t3,
818          (* then *)          (* then *)
819          newParticle (posDomain, velDomain, colDomain, env,          newParticle (sv_gens, env', fn env'' => k env''),
          fn state' => goto (state', blk)),  
820          (* else *)          (* else *)
821          IR.DISCARD)))))),          IR.DISCARD)))))),
822         (* else *)         (* else *)
823         goto (state, blk))         k env))
824       end       end
825    
826          fun trPred(pred, env, state, thenk : particle_state -> IR.stmt, elsek : particle_state -> IR.stmt) = let      (* trExpr(expr, env, state, k : IR.var -> IR.stmt) *)
827            val PS{pos, vel, size, isDead, color} = state      (* mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) *)
828            val P.PR{ifstmt, ...} = pred      fun trPred(cond, env, thenk : ir_env -> IR.stmt, elsek : ir_env -> IR.stmt) = let
829            val thenBlk = newBlock(env, thenk)        fun grabVar(cond, env, k : IR.var -> ir_env -> IR.stmt) = (case cond
830            val elseBlk = newBlock(env, elsek)          of P.WITHINF(d, expr) =>
831           in              trExpr(expr, env, fn checkMe => fn env' =>
832            case ifstmt              mkFloatWithinVar("wv", env', checkMe, d, fn var => k var env'))
833             of P.WITHIN(d) => mkWithinVar("wv", env, pos, d, fn withinVar =>  
834              IR.mkIF(withinVar, goto(state, thenBlk), goto(state, elseBlk)))           | P.WITHIN3F(d, expr) =>
835              | P.WITHINVEL(d) => mkWithinVar("wv", env, vel, d, fn withinVar =>              trExpr(expr, env, fn checkMe => fn env' =>
836              IR.mkIF(withinVar, goto(state, thenBlk), goto(state, elseBlk)))              mkVecWithinVar("wv", env', checkMe, d, fn var => k var env'))
837           end  
838             | P.DO_INTERSECT {p1, p2, d} =>
839      fun trAct (action, env, state, k : particle_state -> IR.stmt) = let             trExpr(p1, env, fn p1var => fn env' =>
840            val PS{pos, vel, size, isDead, color} = state             trExpr(p2, env', fn p2var => fn env'' =>
841            in             mkIntBool(env'', p1var, p2var, d, k)))
842              case action  
843               of P.BOUNCE{friction, resilience, cutoff, d} => let           | P.GTHAN (e1, e2) =>
844                    val blk = newBlock (env, k)             trExpr(e1, env, fn e1var => fn env' =>
845                    val negOne = IR.newConst("negOne", IR.C_FLOAT ~1.0)             trExpr(e2, env, fn e2var => fn env'' =>
846                    in             letPRIM("gtVar", IR.T_BOOL, IR.GT, [e1var, e2var], fn var => k var env'')))
847                      letPRIM("vs", IR.T_VEC, IR.SCALE, [psvToIRVar(env, timeStep), vel], fn velScale =>  
848                      letPRIM("np", IR.T_VEC, IR.ADD_VEC, [pos, velScale], fn nextPos =>           | P.AND(c1, c2) =>
849                      mkWithinVar("wnp", env, pos, d, fn withinNextPos =>             grabVar(c1, env, fn c1Var => fn env' =>
850                      IR.mkIF(withinNextPos,             grabVar(c2, env', fn c2Var => fn env'' =>
851                        (*then*)             letPRIM("andVar", IR.T_BOOL, IR.AND, [c1Var, c2Var], fn var => k var env'')))
852                          normAtPoint("n", d, env, state, fn normAtD => fn state' => let  
853                 val PS{pos=nextPos, vel=nextVel, size=nextSize, isDead=nextIsDead, color=nextColor} = state'           | P.OR(c1, c2) =>
854                            in             grabVar(c1, env, fn c1Var => fn env' =>
855                             letPRIM("negVel", IR.T_VEC, IR.SCALE, [negOne, nextVel], fn negVel =>             grabVar(c2, env, fn c2Var => fn env'' =>
856                             letPRIM("dnv", IR.T_FLOAT, IR.DOT, [negVel, normAtD], fn dotNegVel =>             letPRIM("andVar", IR.T_BOOL, IR.OR, [c1Var, c2Var], fn var => k var env'')))
857                             letPRIM("sn", IR.T_VEC, IR.SCALE, [dotNegVel, normAtD], fn scaledN =>  
858                             letPRIM("t", IR.T_VEC, IR.SUB_VEC, [negVel, scaledN], fn tang =>           | P.XOR(c1, c2) =>
859               grabVar(c1, env, fn c1Var => fn env' =>
860               grabVar(c2, env', fn c2Var => fn env'' =>
861               mkXOR ("xorVar", c1Var, c2Var, fn var => k var env'')))
862    
863             | P.NOT(c) =>
864               grabVar(c, env, fn cvar => fn env' =>
865               letPRIM("notVar", IR.T_BOOL, IR.NOT, [cvar], fn var => k var env'))
866    
867                             letPRIM("tlsq", IR.T_FLOAT, IR.LEN_SQ, [tang], fn tangLenSq =>          (* end case *))
                            letPRIM("cosq", IR.T_FLOAT, IR.MULT, [psvToIRVar(env, cutoff), psvToIRVar(env, cutoff)], fn cutoffSq =>  
                            letPRIM("inco", IR.T_BOOL, IR.GT, [tangLenSq, cutoffSq], fn inCutoff =>  
   
                            letPRIM("resNorm", IR.T_VEC, IR.SCALE, [psvToIRVar(env, resilience), scaledN], fn resNorm =>  
   
                            IR.mkIF(inCutoff,  
                              (*then*)  
                              letPRIM("fInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), psvToIRVar(env, friction)], fn frictInv =>  
                              letPRIM("f", IR.T_FLOAT, IR.MULT, [negOne, frictInv], fn modFrict =>  
                              letPRIM("fTang", IR.T_VEC, IR.SCALE, [modFrict, tang], fn frictTang =>  
                              letPRIM("newVel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
                               goto(PS{pos=nextPos, vel=newVel, size=nextSize, isDead=nextIsDead, color=nextColor}, blk)  
                             )))),  
                              (*else*)  
                              letPRIM("fTang", IR.T_VEC, IR.SCALE, [negOne, tang], fn frictTang =>  
                              letPRIM("newVel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
                               goto(PS{pos=nextPos, vel=newVel, size=nextSize, isDead=nextIsDead, color=nextColor}, blk)  
                              ))  
                          )))))))))  
                          end  
                       ),  
                       (*else*)  
                       goto(state, blk)))))  
                   end  
   
               | P.GRAVITY(dir) =>  
                     letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, timeStep), psvToIRVar(env, dir)], fn theScale =>  
                     letPRIM("nextVel", IR.T_VEC, IR.ADD_VEC, [theScale, vel], fn newVel =>  
                       k(PS{pos = pos, vel = newVel, size = size, isDead = isDead, color = color})))  
   
               | P.MOVE =>  
                 letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, timeStep), vel], fn theScale =>  
                     letPRIM("nextPos", IR.T_VEC, IR.ADD_VEC, [theScale, pos], fn newPos =>  
                       k(PS{pos = newPos, vel = vel, size = size, isDead = isDead, color = color})))  
               (*  
               | P.SINK({d, kill_inside}) =>  
                     mkWithinVar("isWithin", env, state, d, fn withinVal =>  
                     mkXOR ("shouldNotKill", withinVal, psvToIRVar(env, kill_inside),  
                       fn shouldNotKill =>  
                     letPRIM("shouldKill", IR.T_BOOL, IR.NOT, [shouldNotKill], fn shouldKill =>  
                     letPRIM("isReallyDead", IR.T_BOOL, IR.OR, [shouldKill, isDead], fn isReallyDead =>  
                     k(PS{pos = pos, vel = vel, size = size, isDead = isReallyDead, color = color})  
                         ))))  
               *)  
   
               | P.ORBITLINESEG {endp1, endp2, maxRad, mag} => let  
                   val blk = newBlock (env, k)  
868                  in                  in
869                  letPRIM("subVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, endp2), psvToIRVar(env, endp1)], fn subVec =>        grabVar(cond, env, fn result => fn env' =>
870                  letPRIM("vecToEndP", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, endp1)], fn vecToEndP =>        IR.mkIF(result, thenk(env'), elsek(env')))
                 letPRIM("basis", IR.T_VEC, IR.NORM, [subVec], fn basis =>  
                 letPRIM("parDot", IR.T_FLOAT, IR.DOT, [basis, vecToEndP], fn parDot =>  
                 letPRIM("parVec", IR.T_VEC, IR.SCALE, [parDot, basis], fn parVec =>  
                 letPRIM("closestP", IR.T_VEC, IR.ADD_VEC, [psvToIRVar(env, endp1), parVec], fn closestP =>  
                 letPRIM("vecToP", IR.T_VEC, IR.SUB_VEC, [closestP, pos], fn vecToP =>  
                 letPRIM("distToP", IR.T_FLOAT, IR.LEN, [vecToP], fn distToP =>  
                 letPRIM("effRad", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, maxRad), distToP], fn effRad =>  
                 letPRIM("radInDist", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), effRad], fn radInDist =>  
                 IR.mkIF(radInDist,  
                   (*then*)  
                   goto(state, blk),  
                   (*else*)  
                   letPRIM("magRatio", IR.T_FLOAT, IR.DIV, [distToP, psvToIRVar(env, maxRad)], fn magRatio =>  
                   letPRIM("oneMinMR", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), magRatio], fn oneMinMR =>  
                   letPRIM("gravityMag", IR.T_FLOAT, IR.MULT, [oneMinMR, psvToIRVar(env, mag)], fn gravityMag =>  
                   letPRIM("totalMag", IR.T_FLOAT, IR.MULT, [gravityMag, psvToIRVar(env, timeStep)], fn totMag =>  
                   letPRIM("accVec", IR.T_VEC, IR.SUB_VEC, [closestP, pos], fn accVec =>  
                   letPRIM("acc", IR.T_VEC, IR.SCALE, [totMag, accVec], fn acc =>  
                   letPRIM("newVel", IR.T_VEC, IR.ADD_VEC, [vel, acc], fn newVel =>  
                   goto(PS{pos = pos, vel = newVel, size = size, isDead = isDead, color = color}, blk)  
                   )))))))  
                 )))))))))))  
                 end  
   
               (* just kill it. *)  
               | P.DIE => k(PS{pos = pos, vel = vel, size = size, isDead = IR.newConst("falseVar", IR.C_BOOL true), color = color})  
               | _ => raise Fail("Action not implemented...")  
             (* end case *)  
871            end            end
872    
873      fun compile (P.PG{emit as P.EMIT{maxNum, vars=emitVars, ...}, act as P.PSAE{action=root_act, vars=actionVars}, ...}) = let      fun compile (P.PG{
874           emit as P.EMIT{freq, sv_gens}, act, render,
875           vars, state_vars, render_vars
876        }) = let
877            val blks = ref[]            val blks = ref[]
878            val env = let  
879          fun printVar (PSV.V{name, id, ...}) =
880            printErr (String.concat[name, ": ", Int.toString id])
881    
882          val v_env = let
883                (* add special globals to free vars *)                (* add special globals to free vars *)
884                  val vars = PSV.Set.union(emitVars, PSV.Set.addList(actionVars, [maxNum, numDead, timeStep, epsilon]))          val pgm_vars = PSV.Set.union(PSV.Set.singleton epsilon, vars)
885                  fun ins (x as PSV.V{name, ty, binding, id, ...}, map) = let          fun insv (x as PSV.V{name, ty, binding, id, ...}, map) = let
886                        val x' = (case (ty, !binding)                        val x' = (case (ty, !binding)
887                               of (PSV.T_BOOL,  PSV.UNDEF) => IR.newGlobal(x, IR.T_BOOL)                               of (PSV.T_BOOL,  PSV.UNDEF) => IR.newGlobal(x, IR.T_BOOL)
888                                | (PSV.T_BOOL,  PSV.BOOL boolVal) => IR.newConst(name, IR.C_BOOL(boolVal))                                | (PSV.T_BOOL,  PSV.BOOL boolVal) => IR.newConst(name, IR.C_BOOL(boolVal))
# Line 499  Line 892 
892                                | (PSV.T_FLOAT, PSV.FLOAT floatVal) => IR.newConst(name, IR.C_FLOAT(floatVal))                                | (PSV.T_FLOAT, PSV.FLOAT floatVal) => IR.newConst(name, IR.C_FLOAT(floatVal))
893                                | (PSV.T_VEC3F, PSV.UNDEF) => IR.newGlobal(x, IR.T_VEC)                                | (PSV.T_VEC3F, PSV.UNDEF) => IR.newGlobal(x, IR.T_VEC)
894                                | (PSV.T_VEC3F, PSV.VEC3F vecVal) => IR.newConst(name, IR.C_VEC(vecVal))                                | (PSV.T_VEC3F, PSV.VEC3F vecVal) => IR.newConst(name, IR.C_VEC(vecVal))
895                                | _ => raise Fail("Error in setup, type mismatch between IR and PSV vars.")                 | _ => raise Fail("Error in setup, type mismatch between PSV vars and their binding.")
896                              (* end case *))                              (* end case *))
897                        in                        in
                     (* printErr (String.concat["Inserting ", name, " with ID ", Int.toString id, " to IR Var list: ", IR.varToString x']); *)  
898                          PSV.Map.insert (map, x, x')                          PSV.Map.insert (map, x, x')
899                     end (* ins *)
900    
901               in
902                    PSV.Set.foldl insv PSV.Map.empty pgm_vars
903               end (* env *)
904    
905          fun evalActs theAct env f = (case theAct
906                  of P.SEQ(acts) => (case acts
907                    of [] => f env
908                     | oneAct :: rest => evalActs oneAct env (fn env' => (evalActs (P.SEQ(rest)) env' f))
909                    (* end case *))
910    
911                   | P.PRED(cond, thenAct, elseAct) => let
912                       val joinBlk = newBlock (env, fn env' => f env')
913                       fun joinActs env = goto(env, joinBlk)
914                      in
915                       trPred(cond, env,
916                         fn env' => evalActs thenAct env' joinActs,
917                         fn env' => evalActs elseAct env' joinActs
918                       )
919                        end                        end
920    
921                   | P.DIE => IR.DISCARD
922    
923                   | P.ASSIGN(sv, expr) => let
924                     val PSV.SV{name, ty, ...} = sv
925                  in                  in
926                    TE(blks, PSV.Set.foldl ins PSV.Map.empty vars)                   trExpr(expr, env, fn newVar => fn env' =>
927                     letPRIM("ps_" ^ name, IR.psvTyToIRTy ty, IR.COPY, [newVar],
928                       fn thisVar => f (insertSVar(env', sv, thisVar))))
929                  end                  end
930            fun trActs [] state = let  
931                  val PS{pos, vel, size, isDead, color} = state                (* end case *))
932    
933              val sv_env = let
934                  (* add special globals to free vars *)
935            fun insv (x as PSV.SV{name, ty, ...}, map) = let
936              val x' = IR.newParam("ps_" ^ name, IR.psvTyToIRTy ty)
937                  in                  in
938                    IR.mkRETURN[ pos, vel, size, isDead, color ]                    IR.setRenderVar(x', PSV.SVMap.inDomain(render_vars, x));
939                  end (* trActs *)                    PSV.SVMap.insert (map, x, x')
940              | trActs (psa :: psal) state = (case psa                   end (* ins *)
941                of P.SEQ(acts) => (case acts  
942                   of [] => raise Fail "Should never reach here."             in
943                    | [act] => trAct(act, env, state, trActs psal)                  PSV.SVSet.foldl insv PSV.SVMap.empty state_vars
944                    | act :: rest => trAct(act, env, state, trActs (P.SEQ(rest) :: psal))             end (* env *)
945                  (* end case *))  
946                 | P.PRED(pred as P.PR{thenstmt=t, elsestmt=e, ...}) =>            val env = TE(blks, v_env, sv_env)
947                    trPred(pred, env, state, trActs (t @ psal), trActs (e @ psal))  
948                (* end case *))            (* The entry block is the first block of the program, or in other words, the emitter. *)
949              val emitterBlock = newBlock (env, fn env => trEmitter(emit, env, retState))
950            val entryBlock = newBlock (env, fn pstate => trEmitter(emit, env, pstate, fn state => trActs root_act state))            val physicsBlock = newBlock (env, fn env => evalActs act env retState)
951            in  
952              IR.output(TextIO.stdErr, !blks);        (* The entry block is the emitter, and the rest of the blocks define the physics processing. *)
953              if Checker.checkIR(!blks) then  
954                (* note that the entryBlock will be the first block *)        fun isGlobal(IR.V{scope, ...}) = (case scope
955                (IR.output(TextIO.stdErr, Optimize.optimizeIR(!blks));          of IR.S_GLOBAL(v) => true
956                !blks)           | _ => false
957              else          (* end case *))
958                []  
959              val outPgm = PSysIR.PGM {
960                globals = PSV.Map.filter isGlobal v_env,
961            emitter = emitterBlock,
962                physics = physicsBlock,
963                render = render
964              }
965    
966              val _ = IR.outputPgm(TextIO.stdErr, outPgm)
967              val optimized = if (Checker.checkIR(outPgm)) then (printErr "\nPre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm
968              in
969                IR.outputPgm(TextIO.stdErr, optimized);
970                (* Note: it only succeeds if we can optimize, too *)
971            if Checker.checkIR(optimized) then printErr "Compilation succeeded." else ();
972    
973            optimized
974            end (* compile *)            end (* compile *)
975    
976      end (* Translate *)      end (* Translate *)

Legend:
Removed from v.770  
changed lines
  Added in v.1150

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0