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 1129, Mon Apr 25 18:55:18 2011 UTC revision 1149, Sat May 7 19:14:12 2011 UTC
# 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 *)  
       ttl : IR.var,             (* float *)  
       color : IR.var,   (* vec3 (NOTE: should be vector4) *)  
       user : IR.var list  
     }  
 *)  
     type particle_state = IR.var list  
   
23    (* special PSV global variables *)    (* special PSV global variables *)
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    
     fun retState s = IR.mkRETURN s  
   
29    (* translation environment *)    (* translation environment *)
30      datatype env = TE of (IR.block list ref * IR.var PSV.Map.map)      datatype ir_env = TE of (IR.block list ref * IR.var PSV.Map.map * IR.var PSV.SVMap.map)
31      fun insert (TE(blks, env), x, x') = TE(blks, PSV.Map.insert (env, x, x'))      fun insertVar (TE(blks, v_env, sv_env), x, x') = TE(blks, PSV.Map.insert (v_env, x, x'), sv_env)
32        fun insertSVar (TE(blks, v_env, sv_env), x, x') = TE(blks, v_env, PSV.SVMap.insert (sv_env, x, x'))
33    
34    (* Interaction with environment and state variables *)      fun retState (TE(_, _, sv_env)) = IR.mkRETURN (PSV.SVMap.listItems sv_env)
35      fun psvToIRVar (TE(_, env), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)  
36      (* Interaction with environment and psys variables *)
37        fun psvToIRVar (TE(_, env, _), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)
38             of SOME x' => x'             of SOME x' => x'
39              | 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])
40              (* end case *))              (* end case *))
41    
42          fun findIRVarByName (state, name) = let      fun pssvToIRVar (TE(_, _, env), x as PSV.SV{name, id, ...}) = (case PSV.SVMap.find(env, x)
43            fun eq (var as IR.V{name=st_name, ...}) = st_name = ("ps_" ^ name)             of SOME x' => x'
44           in              | NONE => raise Fail (String.concat["unknown state variable ", name, " with ID ", Int.toString id])
           (case (List.find eq state)  
             of SOME sv => sv  
              | NONE => raise Fail ("Could not find var mapping.")  
45            (* end case *))            (* end case *))
          end  
   
         fun getIRVarForSV (v as PSV.SV{name, ...}, state) = findIRVarByName(state, name)  
46    
47     (* create a block that implements the given continuation *)     (* create a block that implements the given continuation *)
48      fun newBlockWithArgs (TE(blks, _), state , args, k : particle_state -> IR.stmt) = let      fun newBlockWithArgs (env as TE(blks, _, sv_env), args, k : ir_env -> IR.stmt) = let
49         fun copyVar(v as IR.V{name, varType, ...}) = IR.newParam(name, varType)         fun copyVar(v as IR.V{name, varType, ...}) = IR.newParam(name, varType)
50         val newState = List.map copyVar state         val newState = List.map copyVar (PSV.SVMap.listItems sv_env)
51             val blk = IR.newBlock (newState @ args, k newState)         fun inssv((oldv, newv), TE(theBlks, v_env, svenv)) = let
52             val theKey =
53               List.find
54                (fn v => IR.varEq(PSV.SVMap.lookup(svenv, v), oldv))
55                (PSV.SVMap.listKeys svenv)
56            in
57             (case theKey
58               of SOME sv => TE(theBlks, v_env, PSV.SVMap.insert(svenv, sv, newv))
59                | NONE => raise Fail("Trying to create new mapping for variable that doesn't already exist.")
60             (* end case *))
61            end
62    
63               val blk = IR.newBlock (
64                   newState @ args,
65                   k (List.foldl inssv env
66                       (ListPair.zipEq
67                           (PSV.SVMap.listItems sv_env, newState)
68                       )
69                   )
70                )
71            in            in
72             blks := blk :: !blks;             blks := blk :: !blks;
73             blk             blk
74            end            end
75    
76          fun newBlock (env, state, k) = newBlockWithArgs(env, state, [], k)          fun newBlock (env, k) = newBlockWithArgs(env, [], k)
77    
78      fun gotoWithArgs(state, args, blk) = IR.mkGOTO(blk, state @ args)      fun gotoWithArgs(TE(_, _, env), args, blk) = IR.mkGOTO(blk, (PSV.SVMap.listItems env) @ args)
79      fun goto (state, blk) = gotoWithArgs(state, [], blk)      fun goto (env, blk) = gotoWithArgs(env, [], blk)
80    
81      fun letPRIM (x, ty, p, args, body) = let      fun letPRIM (x, ty, p, args, body) = let
82            val x' = IR.newLocal(x, ty, (p, args))            val x' = IR.newLocal(x, ty, (p, args))
# Line 84  Line 86 
86    
87    (* 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
88     * basically this creates the XOR'd value of var1 and var2 and     * basically this creates the XOR'd value of var1 and var2 and
89     * stores it in result.     * stores it in result. *)
    *)  
90      fun mkXOR (result, var1, var2, stmt : IR.var -> IR.stmt) =      fun mkXOR (result, var1, var2, stmt : IR.var -> IR.stmt) =
91            letPRIM("testOR", IR.T_BOOL, IR.OR, [var1, var2], fn testOR =>            letPRIM("testOR", IR.T_BOOL, IR.OR, [var1, var2], fn testOR =>
92            letPRIM("testAND", IR.T_BOOL, IR.AND, [var1, var2], fn testAND =>            letPRIM("testAND", IR.T_BOOL, IR.AND, [var1, var2], fn testAND =>
# Line 100  Line 101 
101           (* The PDF here is f(x) = 2x when 0 < x <= 1, so the CDF is going           (* The PDF here is f(x) = 2x when 0 < x <= 1, so the CDF is going
102            * to be the integral of f from 0 -> y => y^2. Hence, whenever we            * to be the integral of f from 0 -> y => y^2. Hence, whenever we
103            * generate a random number, in order to get the random value according            * generate a random number, in order to get the random value according
104            * to this probability distribution, we just square it.            * to this probability distribution, we just square it. *)
           *)  
105           | P.DIST_INC_LIN =>           | P.DIST_INC_LIN =>
106            letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>            letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
107            letPRIM(var, IR.T_FLOAT, IR.MULT, [randVal, randVal], stmt))            letPRIM(var, IR.T_FLOAT, IR.MULT, [randVal, randVal], stmt))
# Line 119  Line 119 
119            letPRIM(var, IR.T_FLOAT, IR.ADD, [termOne, termTwo], stmt)            letPRIM(var, IR.T_FLOAT, IR.ADD, [termOne, termTwo], stmt)
120            ))))            ))))
121    
122           | _ => raise Fail "Unable to create random float for specified distribution."           | _ => raise Fail "Unable to create random float for specified distribution"
123         (* end case *))         (* end case *))
124       in       in
125       (case domain       (case domain
# Line 133  Line 133 
133           letPRIM("scale", IR.T_FLOAT, IR.MULT, [diff, rand], fn scale =>           letPRIM("scale", IR.T_FLOAT, IR.MULT, [diff, rand], fn scale =>
134           letPRIM( fltVar, IR.T_FLOAT, IR.ADD, [psvToIRVar(env, max), scale], stmt )           letPRIM( fltVar, IR.T_FLOAT, IR.ADD, [psvToIRVar(env, max), scale], stmt )
135           )))           )))
136         | _ => raise Fail "Cannot generate float in specified domain."         | _ => raise Fail ("Cannot generate float in specified domain: " ^ (P.dToStr domain))
137       (* end case *))       (* end case *))
138      end      end
139    
# Line 150  Line 150 
150                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)
151    
152              | P.D_LINE({pt1, pt2}) =>              | P.D_LINE({pt1, pt2}) =>
153    
154                (* Lerp between the points. *)                (* Lerp between the points. *)
155                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
156                  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 195  Line 196 
196    
197    
198              | P.D_TRIANGLE{pt1, pt2, pt3} =>              | P.D_TRIANGLE{pt1, pt2, pt3} =>
199    
200                  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 =>
201                  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 =>
202                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>
# Line 216  Line 218 
218                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>
219                    (* Generate a point in the lower disc. *)                    (* Generate a point in the lower disc. *)
220                      genVecVar("ptInDisc",                      genVecVar("ptInDisc",
221                        insert(env, normVar, norm),                        insertVar(env, normVar, norm),
222                        P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},                        P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
223                        dist,                        dist,
224                        fn ptInDisc =>                        fn ptInDisc =>
# Line 227  Line 229 
229                   end                   end
230    
231              | P.D_DISC {pt, normal, irad, orad} =>              | P.D_DISC {pt, normal, irad, orad} =>
232    
233                (* Get a random angle... *)                (* Get a random angle... *)
234                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>
235                  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 =>
236    
237                (* Get a random radius *)                (* Get a random radius *)
238                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>
239                  letPRIM ("e0sq", IR.T_FLOAT, IR.MULT, [newRand, newRand], fn randRadSq =>              letPRIM ("e0sq", IR.T_FLOAT, IR.SQRT, [newRand], fn randRadSq =>
240                  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 =>
241                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>
242                  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 =>
243    
244                (* Find a vector in the plane of the disc, and then                (* Find a vector in the plane of the disc, and then
245                 * translate it to the center.               * translate it to the center. *)
                *)  
246                  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 =>
247                  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 =>
248                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>
249                  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 =>
250                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>
251    
252                (* Figure out x and y values for our new radius and angle *)                (* Figure out x and y values for our new radius and angle *)
253                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>
254                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>
# Line 252  Line 257 
257                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>
258                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>
259                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>
260                  letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt))))))))))))))))))))  
261                letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt)
262                )))))))))))))))))))
263    
264              | P.D_CONE{pt1, pt2, irad, orad} => let              | P.D_CONE{pt1, pt2, irad, orad} => let
265                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)
# Line 261  Line 268 
268                    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 =>
269                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>
270                      genVecVar("ptInDisc",                      genVecVar("ptInDisc",
271                        insert(env, normVar, norm),                insertVar(env, normVar, norm),
272                        P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},                        P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
273                        dist,                        dist,
274                        fn ptInDisc =>                        fn ptInDisc =>
# Line 269  Line 276 
276                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>
277                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>
278                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>
279                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)))))))))               letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)
280                 ))))))))
281                  end                  end
282    
283                  | P.D_SPHERE{center, irad, orad} =>                  | P.D_SPHERE{center, irad, orad} =>
284    
285            (* generate two random angles... *)                    (* Source: http://mathworld.wolfram.com/SpherePointPicking.html *)
286            letPRIM("r1", IR.T_FLOAT, IR.RAND, [], fn randForAngOne =>  
287            letPRIM("t1", IR.T_FLOAT, IR.MULT, [randForAngOne, IR.newConst("fullCit", IR.C_FLOAT (2.0 * pi))], fn randAngOne =>            (* generate two random values... one will be called u and will
288            letPRIM("r2", IR.T_FLOAT, IR.RAND, [], fn randForAngTwo =>             * represent cos(theta), and the other will be called v and will
289            letPRIM("t2", IR.T_FLOAT, IR.MULT, [randForAngTwo, IR.newConst("fullCit", IR.C_FLOAT (2.0 * pi))], fn randAngTwo =>             * represent a random value in [0, 2 * pi] *)
290              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn rv =>
291            (* Generate vector in the sphere ... *)            letPRIM("dblRandVal", IR.T_FLOAT, IR.MULT, [rv, IR.newConst("Two", IR.C_FLOAT 2.0)], fn drv =>
292            (* If my math is correct this should be            letPRIM("rand", IR.T_FLOAT, IR.SUB, [drv, IR.newConst("One", IR.C_FLOAT 1.0)], fn u =>
293             * <(cos t1)(cos t2), (sin t1)(cos t2), sin t2>  
294             * This is different from wikipedia's article on spherical coordinates            letPRIM("rv2", IR.T_FLOAT, IR.RAND, [], fn rv2 =>
295             * because of a phase shift, but for the generation of random numbers,            letPRIM("rand2", IR.T_FLOAT, IR.MULT, [rv2, IR.newConst("TwoPi", IR.C_FLOAT (2.0 * Float.M_PI))], fn theta =>
296             * it's irrelevant.  
297             *)            letPRIM("cosTheta", IR.T_FLOAT, IR.COS, [theta], fn cosT =>
298            letPRIM("cost1", IR.T_FLOAT, IR.COS, [randAngOne], fn cost1 =>            letPRIM("sinTheta", IR.T_FLOAT, IR.SIN, [theta], fn sinT =>
299            letPRIM("cost2", IR.T_FLOAT, IR.COS, [randAngTwo], fn cost2 =>  
300            letPRIM("sint1", IR.T_FLOAT, IR.SIN, [randAngOne], fn sint1 =>            letPRIM("usq", IR.T_FLOAT, IR.MULT, [u, u], fn usq =>
301            letPRIM("sint2", IR.T_FLOAT, IR.SIN, [randAngTwo], fn sint2 =>            letPRIM("usqInv", IR.T_FLOAT, IR.SUB, [IR.newConst("One", IR.C_FLOAT 1.0), usq], fn usqInv =>
302              letPRIM("sinPhi", IR.T_FLOAT, IR.SQRT, [usqInv], fn sinP =>
303            letPRIM("xVal", IR.T_FLOAT, IR.MULT, [cost1, cost2], fn xVal =>  
304            letPRIM("yVal", IR.T_FLOAT, IR.MULT, [sint1, cost2], fn yVal =>            letPRIM("xVal", IR.T_FLOAT, IR.MULT, [sinP, cosT], fn xVal =>
305            (* zval is just sint2 *)            letPRIM("yVal", IR.T_FLOAT, IR.MULT, [sinP, sinT], fn yVal =>
306              (* zval is just u *)
307            letPRIM("xVec", IR.T_VEC, IR.SCALE, [xVal, IR.newConst("xDir", IR.C_VEC {x=1.0, y=0.0, z=0.0})], fn xVec =>  
308            letPRIM("yVec", IR.T_VEC, IR.SCALE, [yVal, IR.newConst("yDir", IR.C_VEC {x=0.0, y=1.0, z=0.0})], fn yVec =>            letPRIM("vec", IR.T_VEC, IR.GEN_VEC, [xVal, yVal, u], fn vec =>
           letPRIM("zVec", IR.T_VEC, IR.SCALE, [sint2, IR.newConst("zDir", IR.C_VEC {x=0.0, y=0.0, z=1.0})], fn zVec =>  
   
           letPRIM("addedVecs", IR.T_VEC, IR.ADD_VEC, [xVec, yVec], fn addedVecs =>  
           letPRIM("notNormVec", IR.T_VEC, IR.ADD_VEC, [addedVecs, zVec], fn nnVec =>  
           letPRIM("vec", IR.T_VEC, IR.NORM, [nnVec], fn vec =>  
309    
310            (* Generate a random radius... *)            (* Generate a random radius... *)
311                    letPRIM("ratio", IR.T_FLOAT, IR.DIV, [psvToIRVar(env, irad), psvToIRVar(env, orad)], fn ratio =>                    letPRIM("ratio", IR.T_FLOAT, IR.DIV, [psvToIRVar(env, irad), psvToIRVar(env, orad)], fn ratio =>
# Line 319  Line 322 
322                    letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [rad, vec], fn sVec =>                    letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [rad, vec], fn sVec =>
323                    letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [sVec, psvToIRVar(env, center)], stmt)                    letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [sVec, psvToIRVar(env, center)], stmt)
324                    ))))))))))                    ))))))))))
325                    ))))))))))))                    )))))))))))))
                   ))))  
326    
327              | _ => raise Fail "Cannot generate point in specified domain."              | _ => raise Fail ("Cannot generate point in specified domain: "  ^ (P.dToStr domain))
328            (* end case *))            (* end case *))
           (*  
           | 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  
           *)  
329    
330    (* This function takes an IR boolean, its environment, a particle state, domain,    (* This function takes an IR boolean, its environment, a particle state, domain,
331     * and continuation.     * and continuation.
# Line 463  Line 459 
459                | P.D_BLOB {center: vec3f var, stddev: float var}                | P.D_BLOB {center: vec3f var, stddev: float var}
460                | 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}
461  *)  *)
462                | _ => raise Fail "Cannot determine within-ness for specified vec3 domain."                | _ => raise Fail ("Cannot determine within-ness for specified vec3 domain: " ^ (P.dToStr d))
463              (* end case *)              (* end case *)
464            end (*end let *)            end (*end let *)
465    
# Line 473  Line 469 
469               letPRIM("bigMin", IR.T_BOOL, IR.GT, [var, psvToIRVar(env, min)], fn bigMin =>               letPRIM("bigMin", IR.T_BOOL, IR.GT, [var, psvToIRVar(env, min)], fn bigMin =>
470               letPRIM("smallMax", IR.T_BOOL, IR.GT, [psvToIRVar(env, max), var], fn smallMax =>               letPRIM("smallMax", IR.T_BOOL, IR.GT, [psvToIRVar(env, max), var], fn smallMax =>
471               letPRIM(boolVar, IR.T_BOOL, IR.AND, [bigMin, smallMax], stmt)))               letPRIM(boolVar, IR.T_BOOL, IR.AND, [bigMin, smallMax], stmt)))
472             | _ => raise Fail "Cannot determine within-ness for specified float domain."             | _ => raise Fail ("Cannot determine within-ness for specified float domain: " ^ (P.dToStr d))
473           (* end case *))           (* end case *))
474    
475          fun mkIntBool(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> IR.stmt) = let          fun mkIntBool(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> ir_env -> IR.stmt) = let
476            val _ = ()            val _ = ()
477           in           in
478            (case d            (case d
# Line 498  Line 494 
494               letPRIM("distDiffAbs", IR.T_FLOAT, IR.ABS, [distDiff], fn distDiffAbs =>               letPRIM("distDiffAbs", IR.T_FLOAT, IR.ABS, [distDiff], fn distDiffAbs =>
495    
496               (* Do the boolean stuff... *)               (* Do the boolean stuff... *)
497               letPRIM("intersect", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), distDiffAbs], k)               letPRIM("intersect", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), distDiffAbs], fn intVar => k intVar env)
498    
499               )))               )))
500               )))               )))
501               )))               )))
502    
503              | _ => raise Fail ("Cannot calculate intersection for specified domain")              | P.D_PLANE {pt, normal} =>
504                  letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
505                  letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
506                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
507                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
508                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
509                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
510                  letPRIM("intersect", IR.T_BOOL, IR.GT, [IR.newConst("zero", IR.C_FLOAT 0.0), distProd], fn intVar => k intVar env)
511                  ))))))
512    
513                | P.D_DISC {pt, normal, orad, irad} => let
514                  val boolVar = IR.newParam("intersect", IR.T_BOOL)
515                  val newBlk = newBlockWithArgs(env, [boolVar], k boolVar)
516                 in
517                  letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
518                  letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
519    
520                  (* Early out... does it intersect the plane?
521                   *
522                   * !SPEED! Due to the perceived slowness of branching on
523                   * GPUs, this might not actually be faster on all runtime environments *)
524    
525                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
526                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
527                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
528                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
529                  letPRIM("earlyOut", IR.T_BOOL, IR.GT, [distProd, IR.newConst("zero", IR.C_FLOAT 0.0)], fn earlyOut =>
530                  IR.mkIF(earlyOut,
531                    (* then *)
532                    letPRIM("intersect", IR.T_BOOL, IR.NOT, [earlyOut], fn var => gotoWithArgs(env, [var], newBlk)),
533                    (* else *)
534                    letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
535                    letPRIM("vDotn", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn vdn =>
536                    letPRIM("t", IR.T_FLOAT, IR.DIV, [p1dist, vdn], fn t =>
537    
538                    (* !TODO! Add some sort of assert mechanism to make sure that t is
539                     * in the interval [0, 1]... *)
540                    letPRIM("vscale", IR.T_VEC, IR.SCALE, [t, v], fn vscale =>
541                    letPRIM("ppt", IR.T_VEC, IR.ADD_VEC, [p1var, vscale], fn ppt =>
542                    letPRIM("lenVec", IR.T_VEC, IR.SUB_VEC, [ppt, psvToIRVar(env, pt)], fn cv =>
543                    letPRIM("len", IR.T_FLOAT, IR.LEN, [cv], fn len =>
544    
545                    (* Check to see whether or not it's within the radius... *)
546                    letPRIM("gtirad", IR.T_BOOL, IR.GT, [len, psvToIRVar(env, irad)], fn gtirad =>
547                    letPRIM("ltorad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), len], fn ltorad =>
548                    letPRIM("intersect", IR.T_BOOL, IR.AND, [gtirad, ltorad], fn var => gotoWithArgs(env, [var], newBlk))
549                   ))))))))))
550                 )))))))
551                end (* P.D_DISC *)
552    
553                | _ => raise Fail ("Cannot calculate intersection bool for specified domain: " ^ (P.dToStr d))
554            (* end case *))            (* end case *))
555    
556           end (* mkIntBool *)           end (* mkIntBool *)
557    
558            (* We assume that the segment already intersects with the domain. *)
559          fun mkIntPt(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> IR.stmt) = let          fun mkIntPt(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> IR.stmt) = let
560            val _ = ()            val _ = ()
561           in           in
562            (case d            (case d
563              of P.D_POINT(pt) => k (psvToIRVar (env, pt))              of P.D_POINT(pt) => k (psvToIRVar (env, pt))
564               | _ => raise Fail ("Cannot calculate intersection for specified domain")  
565                 | P.D_PLANE {pt, normal} =>
566                   letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
567                   letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
568                   letPRIM("num", IR.T_FLOAT, IR.SUB, [d, p1d], fn num =>
569                   letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
570                   letPRIM("den", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn den =>
571                   letPRIM("t", IR.T_FLOAT, IR.DIV, [num, den], fn t =>
572                   letPRIM("vsc", IR.T_VEC, IR.SCALE, [t, v], fn vs =>
573                   letPRIM("intPt", IR.T_VEC, IR.ADD_VEC, [p1var, vs], k)
574                   )))))))
575    
576                 (* Since we already know they intersect, the intersection point must be
577                  * just the point that's on the plane... *)
578                 | P.D_DISC {pt, normal, orad, irad} => mkIntPt(env, p1var, p2var, P.D_PLANE{pt = pt, normal = normal}, k)
579                 | _ => raise Fail ("Cannot calculate intersection point for specified domain: "  ^ (P.dToStr d))
580            (* end case *))            (* end case *))
581           end (* mkIntPt *)           end (* mkIntPt *)
582    
583      (* 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
584       * 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
585       * domain, but if it's not then the behavior is undefined.       * domain, but if it's not then the behavior is undefined. *)
586       *)      fun normAtPoint(retNorm, d, env, pos, k : IR.var -> ir_env -> IR.stmt) = let
     fun normAtPoint(retNorm, d, env, pos, state, k : IR.var -> particle_state -> IR.stmt) = let  
587        val newNorm = IR.newParam("n", IR.T_VEC)        val newNorm = IR.newParam("n", IR.T_VEC)
588        val nextBlk = newBlockWithArgs(env, state, [newNorm], k(newNorm))        val nextBlk = newBlockWithArgs(env, [newNorm], k(newNorm))
589       in       in
590        (case d        (case d
591            of P.D_PLANE{pt, normal} => letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],            of P.D_PLANE{pt, normal} =>
592                fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))               letPRIM("inVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), pos], fn inVec =>
593                 letPRIM("dotNorm", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, normal), inVec], fn dotNorm =>
594                 letPRIM("eqZero", IR.T_BOOL, IR.EQUALS, [dotNorm, IR.newConst("One", IR.C_FLOAT 0.0)], fn eqZero =>
595                 IR.mkIF(eqZero,
596                     (*thenStmt*)
597                     gotoWithArgs(env, [psvToIRVar(env, normal)], nextBlk),
598                 (*elseStmt*)
599                 letPRIM("dnRecip", IR.T_FLOAT, IR.DIV, [IR.newConst("One", IR.C_FLOAT 1.0), dotNorm], fn dnRecip =>
600                 letPRIM("absR", IR.T_FLOAT, IR.ABS, [dnRecip], fn absR =>
601                 letPRIM("sign", IR.T_FLOAT, IR.MULT, [absR, dotNorm], fn sign =>
602                 letPRIM(retNorm, IR.T_VEC, IR.SCALE, [sign, psvToIRVar(env, normal)],
603                 fn newNormVar => gotoWithArgs(env, [newNormVar], nextBlk)))))
604             ))))
605    
606             | P.D_DISC{pt, normal, irad, orad} =>             | P.D_DISC{pt, normal, irad, orad} =>
607                mkVecWithinVar("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))  
                    )  
                  )  
608    
609             | P.D_SPHERE{center, irad, orad} =>             | P.D_SPHERE{center, irad, orad} =>
610                      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 =>
611                  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
612                    ))                    ))
613    
614             | _ => raise Fail("Cannot find normal to point of specified domain.")             | _ => raise Fail("Cannot find normal to point of specified domain." ^ (P.dToStr d))
615           (* end case *))           (* end case *))
616          end          end
617    
618          fun trExpr(expr, env, state, k : IR.var -> IR.stmt) = (case expr          fun trExpr(expr, env, k : IR.var -> ir_env -> IR.stmt) = (case expr
619            of P.CONSTF f => k (IR.newConst ("c", IR.C_FLOAT f))            of P.CONSTF f => k (IR.newConst ("c", IR.C_FLOAT f)) env
620    
621         | P.CONST3F v => k (IR.newConst ("c", IR.C_VEC v))         | P.CONST3F v => k (IR.newConst ("c", IR.C_VEC v)) env
622    
623         | P.VAR v => k (psvToIRVar (env, v))         | P.VAR v => k (psvToIRVar (env, v)) env
624    
625         | P.STATE_VAR sv => k (getIRVarForSV (sv, state))         | P.STATE_VAR sv => k (pssvToIRVar (env, sv)) env
626    
627         | P.GENERATE3F (dom, dist) => genVecVar("genVec", env, dom, dist, k)         | P.GENERATE3F (dom, dist) => genVecVar("genVec", env, dom, dist, fn var => k var env)
628    
629         | P.GENERATEF (dom, dist) => genFloatVar("genFlt", env, dom, dist, k)         | P.GENERATEF (dom, dist) => genFloatVar("genFlt", env, dom, dist, fn var => k var env)
630    
631         | P.ADD(e1, e2) =>         | P.ADD(e1, e2) =>
632           trExpr(e1, env, state, fn e1var =>           trExpr(e1, env, fn e1var => fn env' =>
633           trExpr(e2, env, state, fn e2var =>           trExpr(e2, env', fn e2var => fn env'' =>
634           let           let
635            val IR.V{varType=vt1, ...} = e1var            val IR.V{varType=vt1, ...} = e1var
636            val IR.V{varType=vt2, ...} = e2var            val IR.V{varType=vt2, ...} = e2var
637           in           in
638            (case (vt1, vt2)            (case (vt1, vt2)
639              of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("addVar", IR.T_FLOAT, IR.ADD, [e1var, e2var], k)              of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("addVar", IR.T_FLOAT, IR.ADD, [e1var, e2var], fn var => k var env'')
640               | (IR.T_VEC, IR.T_VEC) => letPRIM("addVar", IR.T_VEC, IR.ADD_VEC, [e1var, e2var], k)               | (IR.T_VEC, IR.T_VEC) => letPRIM("addVar", IR.T_VEC, IR.ADD_VEC, [e1var, e2var], fn var => k var env'')
641               | _ => raise Fail ("Type mismatch to ADD expression")               | _ => raise Fail ("Type mismatch to ADD expression")
642            (* end case *))            (* end case *))
643           end))           end))
644    
645         | P.SCALE (e1, e2) =>         | P.SCALE (e1, e2) =>
646           trExpr(e1, env, state, fn e1var =>           trExpr(e1, env, fn e1var => fn env' =>
647           trExpr(e2, env, state, fn e2var =>           trExpr(e2, env', fn e2var => fn env'' =>
648           let           let
649            val IR.V{varType=vt1, ...} = e1var            val IR.V{varType=vt1, ...} = e1var
650            val IR.V{varType=vt2, ...} = e2var            val IR.V{varType=vt2, ...} = e2var
651           in           in
652            (case (vt1, vt2)            (case (vt1, vt2)
653              of (IR.T_FLOAT, IR.T_VEC) => letPRIM("scaleVar", IR.T_VEC, IR.SCALE, [e1var, e2var], k)              of (IR.T_FLOAT, IR.T_VEC) => letPRIM("scaleVar", IR.T_VEC, IR.SCALE, [e1var, e2var], fn var => k var env'')
654               | (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("addVar", IR.T_FLOAT, IR.MULT, [e1var, e2var], k)               | (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("scaleVar", IR.T_FLOAT, IR.MULT, [e1var, e2var], fn var => k var env'')
655               | _ => raise Fail ("Type mismatch to SCALE expression")               | _ => raise Fail (String.concat["Type mismatch to SCALE expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
656            (* end case *))            (* end case *))
657           end))           end))
658    
659         | P.DIV (e1, e2) =>         | P.DIV (e1, e2) =>
660           trExpr(e1, env, state, fn e1var =>           trExpr(e1, env, fn e1var => fn env' =>
661           trExpr(e2, env, state, fn e2var =>           trExpr(e2, env', fn e2var => fn env'' =>
662           let           let
663            val IR.V{varType=vt1, ...} = e1var            val IR.V{varType=vt1, ...} = e1var
664            val IR.V{varType=vt2, ...} = e2var            val IR.V{varType=vt2, ...} = e2var
665           in           in
666            (case (vt1, vt2)            (case (vt1, vt2)
667              of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("divVar", IR.T_FLOAT, IR.DIV, [e1var, e2var], k)              of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("divVar", IR.T_FLOAT, IR.DIV, [e1var, e2var], fn var => k var env'')
668               | _ => raise Fail ("Type mismatch to DIV expression")               | _ => raise Fail (String.concat["Type mismatch to DIV expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
669            (* end case *))            (* end case *))
670           end))           end))
671    
672         | P.NEG e =>         | P.NEG e =>
673           trExpr(e, env, state, fn evar =>           trExpr(e, env, fn evar => fn env' =>
674           let           let
675            val IR.V{varType, ...} = evar            val IR.V{varType, ...} = evar
676           in           in
677            (case varType            (case varType
678              of IR.T_FLOAT => letPRIM("negVar", IR.T_FLOAT, IR.MULT, [evar, IR.newConst("negOne", IR.C_FLOAT ~1.0)], k)              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')
679               | IR.T_VEC => letPRIM("negVar", IR.T_VEC, IR.NEG_VEC, [evar], k)               | IR.T_VEC => letPRIM("negVar", IR.T_VEC, IR.NEG_VEC, [evar], fn var => k var env')
680               | _ => raise Fail ("Type mismatch to NEG expression")               | _ => raise Fail ("Type mismatch to NEG expression")
681            (* end case *))            (* end case *))
682           end)           end)
683    
684         | P.DOT (e1, e2) =>         | P.DOT (e1, e2) =>
685           trExpr(e1, env, state, fn e1var =>           trExpr(e1, env, fn e1var => fn env' =>
686           trExpr(e2, env, state, fn e2var =>           trExpr(e2, env', fn e2var => fn env'' =>
687           let           let
688            val IR.V{varType=vt1, ...} = e1var            val IR.V{varType=vt1, ...} = e1var
689            val IR.V{varType=vt2, ...} = e2var            val IR.V{varType=vt2, ...} = e2var
690           in           in
691            (case (vt1, vt2)            (case (vt1, vt2)
692              of (IR.T_VEC, IR.T_VEC) => letPRIM("dotVar", IR.T_FLOAT, IR.DOT, [e1var, e2var], k)              of (IR.T_VEC, IR.T_VEC) => letPRIM("dotVar", IR.T_FLOAT, IR.DOT, [e1var, e2var], fn var => k var env'')
693               | _ => raise Fail ("Type mismatch to DOT expression")               | _ => raise Fail ("Type mismatch to DOT expression")
694            (* end case *))            (* end case *))
695           end))           end))
696    
697         | P.CROSS (e1, e2) =>         | P.CROSS (e1, e2) =>
698           trExpr(e1, env, state, fn e1var =>           trExpr(e1, env, fn e1var => fn env' =>
699           trExpr(e2, env, state, fn e2var =>           trExpr(e2, env', fn e2var => fn env'' =>
700           let           let
701            val IR.V{varType=vt1, ...} = e1var            val IR.V{varType=vt1, ...} = e1var
702            val IR.V{varType=vt2, ...} = e2var            val IR.V{varType=vt2, ...} = e2var
703           in           in
704            (case (vt1, vt2)            (case (vt1, vt2)
705              of (IR.T_VEC, IR.T_VEC) => letPRIM("crossVar", IR.T_VEC, IR.CROSS, [e1var, e2var], k)              of (IR.T_VEC, IR.T_VEC) => letPRIM("crossVar", IR.T_VEC, IR.CROSS, [e1var, e2var], fn var => k var env'')
706               | _ => raise Fail ("Type mismatch to CROSS expression")               | _ => raise Fail ("Type mismatch to CROSS expression")
707            (* end case *))            (* end case *))
708           end))           end))
709    
710         | P.NORMALIZE e =>         | P.NORMALIZE e =>
711           trExpr(e, env, state, fn evar =>           trExpr(e, env, fn evar => fn env' =>
712           let           let
713            val IR.V{varType, ...} = evar            val IR.V{varType, ...} = evar
714           in           in
715            (case varType            (case varType
716              of IR.T_VEC => letPRIM("normVar", IR.T_VEC, IR.NORM, [evar], k)              of IR.T_VEC => letPRIM("normVar", IR.T_VEC, IR.NORM, [evar], fn var => k var env')
717               | _ => raise Fail ("Type mismatch to NORMALIZE expression")               | _ => raise Fail ("Type mismatch to NORMALIZE expression")
718            (* end case *))            (* end case *))
719           end)           end)
720    
721         | P.LENGTH e =>         | P.LENGTH e =>
722           trExpr(e, env, state, fn evar =>           trExpr(e, env, fn evar => fn env' =>
723           let           let
724            val IR.V{varType, ...} = evar            val IR.V{varType, ...} = evar
725           in           in
726            (case varType            (case varType
727              of IR.T_VEC => letPRIM("lenVar", IR.T_VEC, IR.LEN, [evar], k)              of IR.T_VEC => letPRIM("lenVar", IR.T_FLOAT, IR.LEN, [evar], fn var => k var env')
728               | _ => raise Fail ("Type mismatch to LENGTH expression")               | _ => raise Fail ("Type mismatch to LENGTH expression")
729            (* end case *))            (* end case *))
730           end)           end)
731    
732         (* !SPEED! We're assuming that there is an intersection here... *)         (* !SPEED! We're assuming that there is an intersection here... *)
733         | P.INTERSECT {p1, p2, d} =>         | P.INTERSECT {p1, p2, d} =>
734           trExpr(p1, env, state, fn p1var =>           trExpr(p1, env, fn p1var => fn env' =>
735           trExpr(p2, env, state, fn p2var =>           trExpr(p2, env', fn p2var => fn env'' =>
736           let           let
737            val IR.V{varType=vt1, ...} = p1var            val IR.V{varType=vt1, ...} = p1var
738            val IR.V{varType=vt2, ...} = p2var            val IR.V{varType=vt2, ...} = p2var
739           in           in
740            (case (vt1, vt2)            (case (vt1, vt2)
741              of (IR.T_VEC, IR.T_VEC) => mkIntPt(env, p1var, p2var, d, k)              of (IR.T_VEC, IR.T_VEC) => mkIntPt(env, p1var, p2var, d, fn var => k var env'')
742               | _ => raise Fail("Type mismatch to INTERSECT expression")               | _ => raise Fail("Type mismatch to INTERSECT expression")
743            (* end case *))            (* end case *))
744           end))           end))
745    
746         | P.NORMALTO (e, d) =>         | P.NORMALTO (e, d) =>
747           trExpr(e, env, state, fn evar =>           trExpr(e, env, fn evar => fn env' =>
748           let           let
749            val IR.V{varType, ...} = evar            val IR.V{varType, ...} = evar
750            fun cont s = k s            fun cont s = k s
751           in           in
752            (case varType            (case varType
753              of IR.T_VEC => normAtPoint("normVar", d, env, evar, state, fn var => fn state' => k var)              of IR.T_VEC => normAtPoint("normVar", d, env', evar, k)
754               | _ => raise Fail("Type mismatch to NORMALTO expression")               | _ => raise Fail("Type mismatch to NORMALTO expression")
755            (* end case *))            (* end case *))
756           end)           end)
# Line 696  Line 758 
758            (* end case expr *))            (* end case expr *))
759    
760            (* generate code to produce a random particle state from a domain *)            (* generate code to produce a random particle state from a domain *)
761      fun newParticle (sv_gens, env, state, k : particle_state -> IR.stmt) = let      fun newParticle (sv_gens, env, k : ir_env -> IR.stmt) = let
762    
763        fun createVar(P.GEN{var, ...}) = let        fun createVar(P.GEN{var, ...}) = let
764          val P.PSV.SV{name, ty, ...} = var          val P.PSV.SV{name, ty, ...} = var
# Line 707  Line 769 
769        val newState = List.map createVar sv_gens        val newState = List.map createVar sv_gens
770    
771        fun genVar((sv_gen, var), cont) = let        fun genVar((sv_gen, var), cont) = let
772          val P.GEN{exp, ...} = sv_gen          val P.GEN{exp, var=svar} = sv_gen
773          val IR.V{varType, ...} = var          val IR.V{varType, ...} = var
774         in         in
775          (* This is kind of a hack, but it'll get optimized out. *)          fn env' => trExpr(exp, env', fn newVal => fn env'' => cont (insertSVar(env'', svar, newVal)))
         trExpr(exp, env, state, fn newVal => IR.mkPRIM(var, IR.COPY, [newVal], cont))  
776         end (* genVar *)         end (* genVar *)
777    
778       in       in
779        List.foldr (fn (x, y) => genVar(x, y)) (k newState) (ListPair.zipEq (sv_gens, newState))        (List.foldr (fn (x, y) => genVar(x, y)) k (ListPair.zipEq (sv_gens, newState))) env
780       end (* new particle *)       end (* new particle *)
781    
782      fun trEmitter(emit, env, state, k : particle_state -> IR.stmt) = let      fun trEmitter(emit, env, k) = let
783        val P.EMIT{freq, sv_gens} = emit        val P.EMIT{freq, sv_gens} = emit
784        val blk = newBlock (env, state, k)        val ttl = pssvToIRVar(env, P.sv_ttl)
       val ttl = findIRVarByName(state, "ttl")  
785       in       in
786        letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>        letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>
787        IR.mkIF(isDead,        IR.mkIF(isDead,
788         (* then *)         (* then *)
789         trExpr(freq, env, state, fn t1 =>         trExpr(freq, env, fn t1 => fn env' =>
790         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, PSV.numDead)], fn t2 =>         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env', PSV.numDead)], fn t2 =>
791         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>
792         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>
793         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>
794         IR.mkIF(t3,         IR.mkIF(t3,
795          (* then *)          (* then *)
796          newParticle (sv_gens, env, state, fn state' => retState state'),          newParticle (sv_gens, env', fn env'' => k env''),
797          (* else *)          (* else *)
798          IR.DISCARD)))))),          IR.DISCARD)))))),
799         (* else *)         (* else *)
800         retState state))         k env))
801       end       end
802    
 (*  
 //  
     fun trPred(pred, env, state, thenk : particle_state -> IR.stmt, elsek : particle_state -> IR.stmt) = let  
       val P.PR{ifstmt, ...} = pred  
     in  
       case ifstmt  
        of P.WITHIN(d) => mkWithinVar("wv", env, pos, d, fn withinVar =>  
                IR.mkIF(withinVar, thenk(state), elsek(state)))  
          | P.WITHINVEL(d) => mkWithinVar("wv", env, vel, d, fn withinVar =>  
                IR.mkIF(withinVar, thenk(state), elsek(state)))  
      end  
 //  
 //    fun trAct (action, env, state, k : particle_state -> IR.stmt) = let/  
 //        val PS{pos, vel, size, ttl, color, user} = state  
 //        in  
 //          case action  
 //           of P.BOUNCE{friction, resilience, cutoff, d} => let  
 //                val blk = newBlock (env, user, k)  
 //                val negOne = IR.newConst("negOne", IR.C_FLOAT ~1.0)  
 //                in  
 //                  letPRIM("vs", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), vel], fn velScale =>  
 //                  letPRIM("np", IR.T_VEC, IR.ADD_VEC, [pos, velScale], fn nextPos =>  
 //                  mkWithinVar("wcp", env, pos, d, fn withinCurPos =>  
 //                  mkWithinVar("wnp", env, nextPos, d, fn withinNextPos =>  
 //                  letPRIM("nwcp", IR.T_BOOL, IR.NOT, [withinCurPos], fn notWithinCurPos =>  
 //                  letPRIM("sb", IR.T_BOOL, IR.AND, [notWithinCurPos, withinNextPos], fn shouldBounce =>  
 //                  IR.mkIF(shouldBounce,  
 //                    (*then*)  
 //                      normAtPoint("n", d, env, state, fn normAtD => fn state' => let  
 //               val PS{pos=nextPos, vel=nextVel, size=nextSize, ttl=nextIsDead, color=nextColor, user=nextUser} = state'  
 //                        in  
 //                         letPRIM("negVel", IR.T_VEC, IR.SCALE, [negOne, nextVel], fn negVel =>  
 //                         letPRIM("dnv", IR.T_FLOAT, IR.DOT, [negVel, normAtD], fn dotNegVel =>  
 //                         letPRIM("sn", IR.T_VEC, IR.SCALE, [dotNegVel, normAtD], fn scaledN =>  
 //                         letPRIM("t", IR.T_VEC, IR.SUB_VEC, [negVel, scaledN], fn tang =>  
 //  
 //                         letPRIM("tlsq", IR.T_FLOAT, IR.LEN_SQ, [tang], fn tangLenSq =>  
 //                         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, ttl=nextIsDead, color=nextColor, user=nextUser}, blk)  
 //                          )))),  
 //                           (*else*)  
 //                           letPRIM("fTang", IR.T_VEC, IR.SCALE, [negOne, tang], fn frictTang =>  
 //                           letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
 //                            goto(PS{pos=nextPos, vel=newVel, size=nextSize, ttl=nextIsDead, color=nextColor, user=nextUser}, blk)  
 //                           ))  
 //                       )))))))))  
 //                       end  
 //                    ),  
 //                    (*else*)  
 //                    goto(state, blk))))))))  
 //                end  
 //  
 //            | P.ACCEL dir =>  
 //                  letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), psvToIRVar(env, dir)], fn theScale =>  
 //                  letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [theScale, vel], fn newVel =>  
 //                    k(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, user = user})))  
 //  
 //            | P.MOVE =>  
 //              letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), vel], fn theScale =>  
 //                  letPRIM("ps_pos", IR.T_VEC, IR.ADD_VEC, [theScale, pos], fn newPos =>  
 //                    k(PS{pos = newPos, vel = vel, size = size, ttl = ttl, color = color, user = user})))  
 //  
 //            | P.ORBITPOINT {center, mag, maxRad} => let  
 //                val blk = newBlock (env, user, k)  
 //               in  
 //                letPRIM("toCenter", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, center), pos], fn toCenter =>  
 //                letPRIM("dist", IR.T_FLOAT, IR.LEN, [toCenter], fn dist =>  
 //                letPRIM("radInDist", IR.T_BOOL, IR.GT, [dist, psvToIRVar(env, maxRad)], fn radInDist =>  
 //                IR.mkIF(radInDist,  
 //                  (* then *)  
 //                  goto(state, blk),  
 //                  (* else *)  
 //                letPRIM("magRatio", IR.T_FLOAT, IR.DIV, [dist, 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, PSV.timeStep)], fn totMag =>  
 //                letPRIM("acc", IR.T_VEC, IR.SCALE, [totMag, toCenter], fn acc =>  
 //                letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [vel, acc], fn newVel =>  
 //                goto(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, user=user}, blk)  
 //                ))))))))))  
 //               end  
 //  
 //  
 //            | P.ORBITLINESEG {endp1, endp2, maxRad, mag} => let  
 //                val blk = newBlock (env, user, k)  
 //              in  
 //              letPRIM("subVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, endp2), psvToIRVar(env, endp1)], fn subVec =>  
 //              letPRIM("vecToEndP", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, endp1)], fn vecToEndP =>  
 //              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, PSV.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("ps_vel", IR.T_VEC, IR.ADD_VEC, [vel, acc], fn newVel =>  
 //                goto(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, user=user}, blk)  
 //                )))))))  
 //              )))))))))))  
 //              end  
 //  
 //            (* just kill it. *)  
 //            (* | P.DIE => k(PS{pos = pos, vel = vel, size = size, ttl = IR.newConst("falseVar", IR.C_BOOL true), color = color, dummy=dummy}) *)  
 //            | P.DIE => IR.DISCARD  
 //            | _ => raise Fail("Action not implemented...")  
 //          (* end case *)  
 //        end  
 *)  
   
803      (* trExpr(expr, env, state, k : IR.var -> IR.stmt) *)      (* trExpr(expr, env, state, k : IR.var -> IR.stmt) *)
804      (* mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) *)      (* mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) *)
805      fun trPred(cond, env, state, thenk : particle_state -> IR.stmt, elsek : particle_state -> IR.stmt) = let      fun trPred(cond, env, thenk : ir_env -> IR.stmt, elsek : ir_env -> IR.stmt) = let
806        fun grabVar(cond, env, state, k : IR.var -> IR.stmt) = (case cond        fun grabVar(cond, env, k : IR.var -> ir_env -> IR.stmt) = (case cond
807          of P.WITHINF(d, expr) =>          of P.WITHINF(d, expr) =>
808              trExpr(expr, env, state, fn checkMe =>              trExpr(expr, env, fn checkMe => fn env' =>
809              mkFloatWithinVar("wv", env, checkMe, d, k))              mkFloatWithinVar("wv", env', checkMe, d, fn var => k var env'))
810    
811           | P.WITHIN3F(d, expr) =>           | P.WITHIN3F(d, expr) =>
812              trExpr(expr, env, state, fn checkMe =>              trExpr(expr, env, fn checkMe => fn env' =>
813              mkVecWithinVar("wv", env, checkMe, d, k))              mkVecWithinVar("wv", env', checkMe, d, fn var => k var env'))
814    
815           | P.DO_INTERSECT {p1, p2, d} =>           | P.DO_INTERSECT {p1, p2, d} =>
816             trExpr(p1, env, state, fn p1var =>             trExpr(p1, env, fn p1var => fn env' =>
817             trExpr(p2, env, state, fn p2var =>             trExpr(p2, env', fn p2var => fn env'' =>
818             mkIntBool(env, p1var, p2var, d, k)))             mkIntBool(env'', p1var, p2var, d, k)))
819    
820           | P.GTHAN (e1, e2) =>           | P.GTHAN (e1, e2) =>
821             trExpr(e1, env, state, fn e1var =>             trExpr(e1, env, fn e1var => fn env' =>
822             trExpr(e2, env, state, fn e2var =>             trExpr(e2, env, fn e2var => fn env'' =>
823             letPRIM("gtVar", IR.T_BOOL, IR.GT, [e1var, e2var], k)))             letPRIM("gtVar", IR.T_BOOL, IR.GT, [e1var, e2var], fn var => k var env'')))
824    
825           | P.AND(c1, c2) =>           | P.AND(c1, c2) =>
826             grabVar(c1, env, state, fn c1Var =>             grabVar(c1, env, fn c1Var => fn env' =>
827             grabVar(c2, env, state, fn c2Var =>             grabVar(c2, env', fn c2Var => fn env'' =>
828             letPRIM("andVar", IR.T_BOOL, IR.AND, [c1Var, c2Var], k)))             letPRIM("andVar", IR.T_BOOL, IR.AND, [c1Var, c2Var], fn var => k var env'')))
829    
830           | P.OR(c1, c2) =>           | P.OR(c1, c2) =>
831             grabVar(c1, env, state, fn c1Var =>             grabVar(c1, env, fn c1Var => fn env' =>
832             grabVar(c2, env, state, fn c2Var =>             grabVar(c2, env, fn c2Var => fn env'' =>
833             letPRIM("andVar", IR.T_BOOL, IR.OR, [c1Var, c2Var], k)))             letPRIM("andVar", IR.T_BOOL, IR.OR, [c1Var, c2Var], fn var => k var env'')))
834    
835           | P.XOR(c1, c2) =>           | P.XOR(c1, c2) =>
836             grabVar(c1, env, state, fn c1Var =>             grabVar(c1, env, fn c1Var => fn env' =>
837             grabVar(c2, env, state, fn c2Var =>             grabVar(c2, env', fn c2Var => fn env'' =>
838             mkXOR ("xorVar", c1Var, c2Var, k)))             mkXOR ("xorVar", c1Var, c2Var, fn var => k var env'')))
839    
840           | P.NOT(c) =>           | P.NOT(c) =>
841             grabVar(c, env, state, fn cvar =>             grabVar(c, env, fn cvar => fn env' =>
842             letPRIM("notVar", IR.T_BOOL, IR.NOT, [cvar], k))             letPRIM("notVar", IR.T_BOOL, IR.NOT, [cvar], fn var => k var env'))
843    
844          (* end case *))          (* end case *))
845       in       in
846        grabVar(cond, env, state, fn result =>        grabVar(cond, env, fn result => fn env' =>
847        IR.mkIF(result, thenk(state), elsek(state)))        IR.mkIF(result, thenk(env'), elsek(env')))
848       end       end
849    
850      fun compile (P.PG{      fun compile (P.PG{
# Line 923  Line 853 
853      }) = let      }) = let
854        val blks = ref[]        val blks = ref[]
855    
856          fun printVar (PSV.V{name, id, ...}) =
857            printErr (String.concat[name, ": ", Int.toString id])
858    
859        val demand = IR.getDemand(render)        val demand = IR.getDemand(render)
860        fun getIRNameForSV (v as PSV.SV{name, ...}) =        fun getIRNameForSV (v as PSV.SV{name, ...}) =
861         (case (PSV.SVMap.find (render_vars, v))         (case (PSV.SVMap.find (render_vars, v))
# Line 939  Line 872 
872         (* end case *))         (* end case *))
873    
874        fun convertToIR (v as PSV.SV{ty, ...}) = IR.newParam(getIRNameForSV v, IR.psvTyToIRTy ty)        fun convertToIR (v as PSV.SV{ty, ...}) = IR.newParam(getIRNameForSV v, IR.psvTyToIRTy ty)
875        val env = let        val v_env = let
876                (* add special globals to free vars *)                (* add special globals to free vars *)
877          val pgm_vars = PSV.Set.union(PSV.Set.singleton epsilon, vars)          val pgm_vars = PSV.Set.union(PSV.Set.singleton epsilon, vars)
878          fun insv (x as PSV.V{name, ty, binding, id, ...}, map) = let          fun insv (x as PSV.V{name, ty, binding, id, ...}, map) = let
# Line 957  Line 890 
890                     in                     in
891                          PSV.Map.insert (map, x, x')                          PSV.Map.insert (map, x, x')
892                     end (* ins *)                     end (* ins *)
893    
894                  in                  in
895                    TE( blks, PSV.Set.foldl insv PSV.Map.empty pgm_vars )                  PSV.Set.foldl insv PSV.Map.empty pgm_vars
896                  end (* env *)                  end (* env *)
897    
898        fun evalActs theAct state f = (case theAct        fun evalActs theAct env f = (case theAct
899                of P.SEQ(acts) => (case acts                of P.SEQ(acts) => (case acts
900                  of [] => f state                  of [] => f env
901                   | oneAct :: rest => evalActs oneAct state (fn state' => (evalActs (P.SEQ(rest)) state' f))                   | oneAct :: rest => evalActs oneAct env (fn env' => (evalActs (P.SEQ(rest)) env' f))
902                  (* end case *))                  (* end case *))
903    
904                 | P.PRED(cond, thenAct, elseAct) =>                 | P.PRED(cond, thenAct, elseAct) => let
905                   trPred(cond, env, state,                     val joinBlk = newBlock (env, fn env' => f env')
906                     fn state' => evalActs thenAct state' f,                     fun joinActs env = goto(env, joinBlk)
907                     fn state' => evalActs elseAct state' f                    in
908                       trPred(cond, env,
909                         fn env' => evalActs thenAct env' joinActs,
910                         fn env' => evalActs elseAct env' joinActs
911                   )                   )
912                      end
913    
914                 | P.DIE => IR.DISCARD                 | P.DIE => IR.DISCARD
915    
916                 | P.ASSIGN(sv, expr) => let                 | P.ASSIGN(sv, expr) => let
917                   val PSV.SV{ty, ...} = sv                   val PSV.SV{ty, ...} = sv
                  fun replaceStateVar (var, []) = [var]  
                    | replaceStateVar (var, nv :: svars) = let  
                      val IR.V{name=nvname, ...} = nv  
                      val IR.V{name=varname, ...} = var  
918                      in                      in
919                       if nvname = varname then                   trExpr(expr, env, fn newVar => fn env' =>
                        var :: svars  
                      else  
                        nv :: replaceStateVar(var, svars)  
                     end  
                 in  
                  trExpr(expr, env, state, fn newVar =>  
920                   letPRIM(getIRNameForSV sv, IR.psvTyToIRTy ty, IR.COPY, [newVar],                   letPRIM(getIRNameForSV sv, IR.psvTyToIRTy ty, IR.COPY, [newVar],
921                     fn thisVar => f (replaceStateVar(thisVar, state))))                     fn thisVar => f (insertSVar(env', sv, thisVar))))
922                  end                  end
923    
924                (* end case *))                (* end case *))
925    
926              val sv_env = let
927                  (* add special globals to free vars *)
928            fun insv (x as PSV.SV{name, ty, ...}, map) = let
929              val x' = IR.newParam("ps_" ^ name, IR.psvTyToIRTy ty)
930                     in
931                      PSV.SVMap.insert (map, x, x')
932                     end (* ins *)
933    
934               in
935                    PSV.SVSet.foldl insv PSV.SVMap.empty state_vars
936               end (* env *)
937    
938              val env = TE(blks, v_env, sv_env)
939    
940            (* The entry block is the first block of the program, or in other words, the emitter. *)            (* The entry block is the first block of the program, or in other words, the emitter. *)
941            val entryBlock = newBlock (            val emitterBlock = newBlock (env, fn env => trEmitter(emit, env, retState))
942              env,            val physicsBlock = newBlock (env, fn env => evalActs act env retState)
             List.map convertToIR (PSV.SVSet.listItems state_vars),  
             fn pstate => trEmitter(  
               emit,  
               env,  
               pstate,  
               fn state => evalActs act state retState  
             )  
           )  
943    
944        (* The entry block is the emitter, and the rest of the blocks define the physics processing. *)        (* The entry block is the emitter, and the rest of the blocks define the physics processing. *)
945    
# Line 1014  Line 948 
948           | _ => false           | _ => false
949          (* end case *))          (* end case *))
950    
       fun extractVarMap(TE(blks, map)) = map  
   
       fun convertDemand (name, x) = ("ps_" ^ name, x)  
   
951            val outPgm = PSysIR.PGM {            val outPgm = PSysIR.PGM {
952              globals = PSV.Map.filter isGlobal (extractVarMap env),              globals = PSV.Map.filter isGlobal v_env,
953              persistents = List.map convertDemand demand,              persistents = demand,
954              uveOptimized = false,              uveOptimized = false,
955          emitter = entryBlock,          emitter = emitterBlock,
956              physics = List.nth(!blks, 1),              physics = physicsBlock,
957              render = render              render = render
958            }            }
959    
960            val optimized = if (Checker.checkIR(outPgm)) then (printErr "Pre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm            val _ = IR.outputPgm(TextIO.stdErr, outPgm)
961              val optimized = if (Checker.checkIR(outPgm)) then (printErr "\nPre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm
962            in            in
963              (* IR.outputPgm(TextIO.stdErr, outPgm); *)              IR.outputPgm(TextIO.stdErr, optimized);
   
964              (* Note: it only succeeds if we can optimize, too *)              (* Note: it only succeeds if we can optimize, too *)
965          if Checker.checkIR(optimized) then printErr "Compilation succeeded." else ();          if Checker.checkIR(optimized) then printErr "Compilation succeeded." else ();
966    

Legend:
Removed from v.1129  
changed lines
  Added in v.1149

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