OXT Community Stacks

The scripts of Box3D Playground

Version 1.0. These are the scripts exactly as they are in the stack that plays here. Each line has its number, and a link to a line keeps it.

the stack script

Box3D Playground.oxtstack, stack "Box3D Playground", 818 lines

-- Box3D Playground
--
-- A tour of box3dxt, the xTalk Suite's 3D physics library (Box3D), which
-- comes with OXT-Beyond as org.openxtalk.library.boxthreed. Four scenes
-- show what it does: every kind of shape, the joints, sensors and contact
-- events, and a terrain. The library also draws the world: each frame
-- b3RenderWorld makes a picture and this stack sets it as the imageData of
-- one image. Click a thing in the picture to kick it (a ray from the
-- camera through the pixel finds it); drag the picture to look around.
--
-- Everything is in this one script. The controls are made by pgBuildUI the
-- first time the stack opens. Licence: GPL-3.0-only.

constant kW = 640
constant kH = 400
constant kLeft = 20
constant kTop = 56

local sWorld, sScene, sMode, sPaused, sLoop, sLast
local sYaw, sPitch, sDist, sTx, sTy, sTz, sSpin
local sDownAt, sDownYaw, sDownPitch, sDragged
local sFrames, sFpsAt, sFps, sDrawMs
local sLoose, sSensor, sInside, sPassed, sHits, sTouches, sSpawnIn
local sRotor, sPiston, sCart, sNote, sOldCompression
local sSteps, sFlash, sGreen, sHover, sPicked

-- ---------------------------------------------------------------- opening

on openStack
   -- openStack goes to the card that opens, so the stack it belongs to is
   -- the card's owner: a substack's opening is passed on, ours is not
   if the short name of the owner of the target is not the short name of me then pass openStack
   pgBuildUI
   put the paintCompression into sOldCompression
   -- "rle" makes setting an image's imageData several times quicker
   set the paintCompression to "rle"
   pgScene "shapes"
end openStack

on closeStack
   pgStop
   if sOldCompression is not empty then set the paintCompression to sOldCompression
   pass closeStack
end closeStack

on pgStop
   if sLoop is not empty then cancel sLoop
   put empty into sLoop
   if sWorld is not empty then
      try
         b3WorldDestroy sWorld
      end try
   end if
   put empty into sWorld
end pgStop

function pgHasLibrary
   -- the pictures came with the library's second ABI: an older one that is
   -- still installed answers here and has no b3RenderWorld
   local tABI
   try
      put b3ABIVersion() into tABI
   catch tError
      return false
   end try
   return tABI is an integer and tABI >= 2
end pgHasLibrary

-- ------------------------------------------------------------ the window

on pgBuildUI
   local tX, tName
   if there is an image "view" of card 1 of me then exit pgBuildUI
   lock screen
   set the defaultStack to the short name of me
   set the width of me to kW + 2 * kLeft
   set the height of me to 618
   set the title of me to "Box3D Playground"
   set the backgroundColor of me to "24,27,32"
   set the resizable of me to false
   pgField "title", kLeft, 12, kW, 34, "Box3D Playground", 20, "240,240,240"
   set the textStyle of field "title" of card 1 of me to "bold"
   -- a thin frame under the picture's edge, and the picture on top of it
   create graphic "frame"
   set the style of graphic "frame" of card 1 of me to "rectangle"
   set the opaque of graphic "frame" of card 1 of me to false
   set the lineSize of graphic "frame" of card 1 of me to 1
   set the foregroundColor of graphic "frame" of card 1 of me to "70,78,92"
   set the rect of graphic "frame" of card 1 of me to kLeft - 1, kTop - 1, kLeft + kW + 1, kTop + kH + 1
   create image "view"
   set the rect of image "view" of card 1 of me to kLeft, kTop, kLeft + kW, kTop + kH
   put kLeft into tX
   repeat for each item tName in "Shapes,Joints,Sensors,Terrain"
      pgButton tName, tX, kTop + kH + 10, 92
      add 98 to tX
   end repeat
   add 14 to tX
   repeat for each item tName in "Solid,Wire,Outline"
      pgButton tName, tX, kTop + kH + 10, 72
      add 76 to tX
   end repeat
   put kLeft into tX
   repeat for each item tName in "Drop,Boom,Pause,Spin,Reset"
      pgButton tName, tX, kTop + kH + 44, 92
      add 98 to tX
   end repeat
   -- two lines each, wrapped: neither is cut off at the window's edge
   pgField "status", kLeft, kTop + kH + 78, kW, 34, empty, 11, "150,220,160"
   pgField "help", kLeft, kTop + kH + 114, kW, 34, empty, 11, "190,196,206"
   set the dontWrap of field "status" of card 1 of me to false
   set the dontWrap of field "help" of card 1 of me to false
   -- frames a second, in the picture's corner
   pgField "fps", kLeft + kW - 70, kTop + 8, 62, 20, empty, 11, "150,220,160"
   set the opaque of field "fps" of card 1 of me to true
   set the backgroundColor of field "fps" of card 1 of me to "16,18,22"
   set the textAlign of field "fps" of card 1 of me to "center"
   set the blendLevel of field "fps" of card 1 of me to 15
   set the visible of field "fps" of card 1 of me to false
   unlock screen
end pgBuildUI

on pgField pName, pX, pY, pWidth, pHeight, pText, pSize, pColor
   create field pName
   set the rect of field pName of card 1 of me to pX, pY, pX + pWidth, pY + pHeight
   set the opaque of field pName of card 1 of me to false
   set the showBorder of field pName of card 1 of me to false
   set the lockText of field pName of card 1 of me to true
   set the traversalOn of field pName of card 1 of me to false
   set the dontWrap of field pName of card 1 of me to true
   set the textSize of field pName of card 1 of me to pSize
   set the foregroundColor of field pName of card 1 of me to pColor
   put pText into field pName of card 1 of me
end pgField

-- The buttons are drawn by the stack, not by the system, so they look the
-- same under every theme and in the browser: pgPaint gives each its colours
on pgButton pName, pX, pY, pWidth
   create button pName
   set the rect of button pName of card 1 of me to pX, pY, pX + pWidth, pY + 28
   set the style of button pName of card 1 of me to "rectangle"
   set the opaque of button pName of card 1 of me to true
   set the threeD of button pName of card 1 of me to false
   set the showBorder of button pName of card 1 of me to true
   set the borderWidth of button pName of card 1 of me to 1
   set the autoHilite of button pName of card 1 of me to false
   set the showFocusBorder of button pName of card 1 of me to false
   set the textSize of button pName of card 1 of me to 12
   set the traversalOn of button pName of card 1 of me to false
   pgPaint pName, false
end pgButton

-- One button's colours: filled with the accent when what it names is on,
-- lighter under the mouse
on pgPaint pName, pOn
   local tBack, tText, tEdge
   if pOn is true then
      put "58,124,224" into tBack
      if pName is sHover then put "82,146,242" into tBack
      put "255,255,255" into tText
      put "120,176,255" into tEdge
   else
      put "44,49,58" into tBack
      if pName is sHover then put "66,74,90" into tBack
      put "226,230,238" into tText
      put "74,82,98" into tEdge
   end if
   set the backgroundColor of button pName of card 1 of me to tBack
   set the foregroundColor of button pName of card 1 of me to tText
   set the borderColor of button pName of card 1 of me to tEdge
end pgPaint

on mouseEnter
   if word 1 of the name of the target is not "button" then pass mouseEnter
   put the short name of the target into sHover
   pgMarks
end mouseEnter

on mouseLeave
   if word 1 of the name of the target is not "button" then pass mouseLeave
   put empty into sHover
   pgMarks
end mouseLeave

-- The buttons say what is on: the scene, the look, a pause and the turning
-- camera are filled with the accent colour
on pgMarks
   local tName
   if there is not a button "Pause" of card 1 of me then exit pgMarks
   lock screen
   repeat for each item tName in "Shapes,Joints,Sensors,Terrain"
      pgPaint tName, toLower(tName) is sScene
   end repeat
   repeat for each item tName in "Solid,Wire,Outline"
      pgPaint tName, itemOffset(tName, "Solid,Wire,Outline") - 1 is sMode
   end repeat
   pgPaint "Pause", sPaused is true
   pgPaint "Spin", sSpin is true
   pgPaint "Drop", false
   pgPaint "Boom", false
   pgPaint "Reset", false
   if sPaused is true then
      set the label of button "Pause" of card 1 of me to "Resume"
   else
      set the label of button "Pause" of card 1 of me to "Pause"
   end if
   unlock screen
end pgMarks

on pgSay pText
   if there is a field "status" of card 1 of me then put pText into field "status" of card 1 of me
end pgSay

on pgHelp pText
   put pText into sNote
   if there is a field "help" of card 1 of me then put pText into field "help" of card 1 of me
end pgHelp

-- ------------------------------------------------------------ the scenes

on pgScene pName
   pgStop
   if not pgHasLibrary() then
      pgSay "This stack needs the box3dxt extension (org.openxtalk.library.boxthreed)."
      pgHelp "It comes with OXT-Beyond 0.2.8-dp.3 and later, and with the web Stack Player made from it."
      exit pgScene
   end if
   -- each scene opens in the look that suits it, the hills solid and the
   -- rest outlined, until a button has chosen one
   if sPicked is not true and (sMode is empty or pName is not sScene) then
      if pName is "terrain" then
         put 0 into sMode
      else
         put 2 into sMode
      end if
   end if
   put pName into sScene
   -- a slowly turning camera, until a button says otherwise
   if sSpin is empty then put true into sSpin
   put empty into sLoose
   put empty into sInside
   put 0 into sSensor
   put 0 into sPassed
   put 0 into sHits
   put 0 into sTouches
   put 0 into sRotor
   put 0 into sPiston
   put empty into sCart
   put 0 into sSpawnIn
   put 0 into sSteps
   put empty into sFlash
   put empty into sGreen
   put false into sPaused
   put 0.6 into sYaw
   put 0.42 into sPitch
   put 16 into sDist
   put 0 into sTx
   put 0.8 into sTy
   put 0 into sTz
   b3ShapeOptionsReset
   put b3WorldCreate(0, -10, 0, 1) into sWorld
   -- a sky that is not the window's colour, so the picture has an edge:
   -- dark above and lighter at the horizon where the library can paint
   -- two colours (its ABI 3), and one colour where it cannot
   try
      b3RenderSetSky 22, 30, 52, 86, 108, 142
   catch tError
      b3RenderSetBackground 40, 54, 80
   end try
   b3RenderSetLight -0.4, -1, -0.5
   switch pName
      case "shapes"
         pgSceneShapes
         break
      case "joints"
         pgSceneJoints
         break
      case "sensors"
         pgSceneSensors
         break
      case "terrain"
         pgSceneTerrain
         break
   end switch
   put the milliseconds into sLast
   put the milliseconds into sFpsAt
   put 0 into sFrames
   put empty into sFps
   put 0 into sDrawMs
   pgBadge
   pgMarks
   -- the counts of this scene at once, not the last scene's for a second
   pgStatus
   pgTick
end pgScene

function pgFloor pHalf
   local tBody, tShape
   put b3BodyCreate(sWorld, 0, 0, -0.5, 0) into tBody
   put b3ShapeAddBox(tBody, pHalf, 0.5, pHalf, 0, 0.7, 0.1) into tShape
   b3ShapeSetColor tShape, 96, 104, 116
   return tBody
end pgFloor

-- One loose thing of the kind asked for, at a place. Each kind of shape
-- Box3D has for a moving body: sphere, capsule, box, cylinder, cone, hull.
function pgDropKind pKind, pX, pY, pZ
   local tBody, tShape, tQ
   put b3QuatFromEuler(random(600) / 100, random(600) / 100, random(600) / 100) into tQ
   put b3BodyCreateRotated(sWorld, 2, pX, pY, pZ, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tBody
   -- a little rolling resistance, so that round things come to rest on the
   -- floor instead of rolling off its edge
   b3ShapeOptionsSetRollingResistance 0.08
   switch pKind
      case "sphere"
         put b3ShapeAddSphere(tBody, 0, 0, 0, 0.45, 1, 0.5, 0.35) into tShape
         b3ShapeSetColor tShape, 235, 96, 80
         break
      case "capsule"
         put b3ShapeAddCapsule(tBody, -0.45, 0, 0, 0.45, 0, 0, 0.3, 1, 0.5, 0.2) into tShape
         b3ShapeSetColor tShape, 250, 176, 70
         break
      case "box"
         put b3ShapeAddBox(tBody, 0.45, 0.35, 0.4, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 96, 170, 240
         break
      case "cylinder"
         put b3ShapeAddCylinder(tBody, 0.8, 0.4, 16, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 120, 210, 150
         break
      case "cone"
         put b3ShapeAddCone(tBody, 0.9, 0.5, 0.12, 16, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 190, 130, 240
         break
      case "hull"
         -- an eight-faced gem: the convex hull of six points
         get b3GeometryBegin()
         get b3GeometryAddPoint(0.55, 0, 0)
         get b3GeometryAddPoint(-0.55, 0, 0)
         get b3GeometryAddPoint(0, 0.7, 0)
         get b3GeometryAddPoint(0, -0.7, 0)
         get b3GeometryAddPoint(0, 0, 0.55)
         get b3GeometryAddPoint(0, 0, -0.55)
         put b3ShapeAddHull(tBody, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 240, 230, 110
         break
   end switch
   b3ShapeOptionsReset
   if tShape is 0 then
      b3BodyDestroy tBody
      return 0
   end if
   put tBody & comma after sLoose
   return tBody
end pgDropKind

function pgAnyKind
   return item random(6) of "sphere,capsule,box,cylinder,cone,hull"
end pgAnyKind

on pgSceneShapes
   local tRamp, tShape, tKind, tX
   get pgFloor(9)
   -- a triangle mesh: a ramp of two triangles, named counter-clockwise as
   -- seen from above, the side things land on
   put b3BodyCreate(sWorld, 0, -5, 0, 0) into tRamp
   get b3GeometryBegin()
   get b3GeometryAddPoint(-3, 3, -2.5)
   get b3GeometryAddPoint(3, 0, -2.5)
   get b3GeometryAddPoint(3, 0, 2.5)
   get b3GeometryAddPoint(-3, 3, 2.5)
   get b3GeometryAddTriangle(1, 4, 3)
   get b3GeometryAddTriangle(1, 3, 2)
   put b3ShapeAddMesh(tRamp, 0.4, 0.1) into tShape
   b3ShapeSetColor tShape, 150, 140, 128
   put -6 into tX
   repeat for each item tKind in "sphere,capsule,box,cylinder,cone,hull"
      get pgDropKind(tKind, tX, 5 + random(3), -1 + random(20) / 10)
      add 1.6 to tX
   end repeat
   repeat 6 times
      get pgDropKind(pgAnyKind(), 1 + random(40) / 10, 6 + random(5), -2 + random(40) / 10)
   end repeat
   pgHelp "Every kind of shape, and a mesh ramp. Click a thing to kick it. Drag to look around. Drop adds more; Boom pushes them away."
end pgSceneShapes

on pgSceneJoints
   local tAnchor, tPrev, tLink, tShape, tX, tJoint, tPost, tBase, tA, tB, tWheel, i, tZ
   get pgFloor(9)
   -- 1. a rope of ball-and-socket (spherical) joints with a heavy ball
   put b3BodyCreate(sWorld, 0, -7, 7, 0) into tAnchor
   put b3ShapeAddBox(tAnchor, 0.2, 0.2, 0.2, 0, 0.6, 0) into tShape
   put tAnchor into tPrev
   put -7 into tX
   repeat with i = 1 to 6
      put b3BodyCreate(sWorld, 2, tX + 0.5, 7, 0) into tLink
      if i < 6 then
         put b3ShapeAddCapsule(tLink, -0.38, 0, 0, 0.38, 0, 0, 0.1, 2, 0.5, 0.1) into tShape
         b3ShapeSetColor tShape, 250, 176, 70
      else
         put b3ShapeAddSphere(tLink, 0, 0, 0, 0.6, 3, 0.5, 0.2) into tShape
         b3ShapeSetColor tShape, 235, 96, 80
      end if
      put b3JointSpherical(sWorld, tPrev, tLink, tX, 7, 0, 1, 0, 0, false) into tJoint
      put tLink into tPrev
      put tLink & comma after sLoose
      add 1 to tX
   end repeat
   -- 2. a windmill on a hinge (revolute) joint, turned by its motor
   put b3BodyCreate(sWorld, 0, 0, 1.5, -1) into tPost
   put b3ShapeAddBox(tPost, 0.2, 1.5, 0.2, 0, 0.6, 0) into tShape
   put b3BodyCreate(sWorld, 2, 0, 3.2, -0.6) into tA
   put b3ShapeAddBox(tA, 2.2, 0.18, 0.1, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 96, 170, 240
   put b3ShapeAddBox(tA, 0.18, 2.2, 0.1, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 96, 170, 240
   put b3JointRevolute(sWorld, tPost, tA, 0, 3.2, -0.6, 0, 0, 1, false) into sRotor
   b3RevoluteSetMaxMotorTorque sRotor, 400
   b3RevoluteSetMotorSpeed sRotor, 1.5
   b3RevoluteEnableMotor sRotor, true
   -- 3. a platform on a slider (prismatic) joint with a spring
   put b3BodyCreate(sWorld, 0, 5, 0.1, 3) into tBase
   put b3ShapeAddBox(tBase, 0.3, 0.1, 0.3, 0, 0.6, 0) into tShape
   put b3BodyCreate(sWorld, 2, 5, 1.6, 3) into tA
   put b3ShapeAddBox(tA, 1.4, 0.15, 1.4, 1, 0.7, 0) into tShape
   b3ShapeSetColor tShape, 120, 210, 150
   put b3JointPrismatic(sWorld, tBase, tA, 5, 1.6, 3, 0, 1, 0, false) into sPiston
   b3PrismaticSetSpringHertz sPiston, 1.5
   b3PrismaticSetSpringDampingRatio sPiston, 0.15
   b3PrismaticEnableSpring sPiston, true
   b3PrismaticSetLimits sPiston, -1.2, 1.5
   b3PrismaticEnableLimit sPiston, true
   get pgDropKind("box", 5, 5, 3)
   -- 4. two balls a fixed distance apart (distance joint)
   put b3BodyCreate(sWorld, 2, -4, 5, 4) into tA
   put b3ShapeAddSphere(tA, 0, 0, 0, 0.4, 1, 0.5, 0.4) into tShape
   b3ShapeSetColor tShape, 190, 130, 240
   put b3BodyCreate(sWorld, 2, -2.4, 5.6, 4) into tB
   put b3ShapeAddSphere(tB, 0, 0, 0, 0.4, 1, 0.5, 0.4) into tShape
   b3ShapeSetColor tShape, 190, 130, 240
   put b3JointDistance(sWorld, tA, tB, -4, 5, 4, -2.4, 5.6, 4, true) into tJoint
   put tA & comma & tB & comma after sLoose
   -- 5. two boxes glued into an L (weld joint)
   put b3BodyCreate(sWorld, 2, -5, 3, -4) into tA
   put b3ShapeAddBox(tA, 0.9, 0.2, 0.3, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 240, 230, 110
   put b3BodyCreate(sWorld, 2, -4.3, 3.8, -4) into tB
   put b3ShapeAddBox(tB, 0.2, 0.6, 0.3, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 240, 230, 110
   put b3JointWeld(sWorld, tA, tB, -4.3, 3.2, -4, false) into tJoint
   put tA & comma & tB & comma after sLoose
   -- 6. a cart on four wheel joints: suspension, and motors that drive it
   put b3BodyCreate(sWorld, 2, -3, 0.9, 6.4) into tA
   put b3ShapeAddBox(tA, 1.1, 0.2, 0.6, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 235, 96, 80
   put tA & comma after sLoose
   repeat for each item tX in "-3.8,-2.2"
      repeat for each item tZ in "5.6,7.2"
         put b3BodyCreate(sWorld, 2, tX, 0.5, tZ) into tWheel
         put b3ShapeAddSphere(tWheel, 0, 0, 0, 0.4, 1, 1.2, 0) into tShape
         b3ShapeSetColor tShape, 60, 60, 66
         put b3JointWheel(sWorld, tA, tWheel, tX, 0.5, tZ, 0, 1, 0, 0, 0, 1, false) into tJoint
         b3WheelSetSuspensionHertz tJoint, 4
         b3WheelSetSuspensionDampingRatio tJoint, 0.7
         b3WheelEnableSuspension tJoint, true
         b3WheelSetMaxSpinTorque tJoint, 12
         b3WheelSetSpinMotorSpeed tJoint, -5
         b3WheelEnableSpinMotor tJoint, true
         put tJoint & comma after sCart
      end repeat
   end repeat
   put 17 into sDist
   put 1.6 into sTy
   put -0.5 into sTx
   pgHelp "Joints: a rope of ball-and-sockets, a motor on a hinge, a sprung slider, a rod, a weld and a cart on wheel joints. Click to kick."
end pgSceneJoints

on pgSceneSensors
   local tBody, tShape, tQ, tGate
   get pgFloor(9)
   -- a chute: a tilted slab with two walls
   put b3QuatFromAxisAngle(0, 0, 1, -0.32) into tQ
   put b3BodyCreateRotated(sWorld, 0, -3, 3, 0, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tBody
   put b3ShapeAddBox(tBody, 5, 0.15, 1.6, 0, 0.2, 0.1) into tShape
   b3ShapeSetColor tShape, 150, 140, 128
   put b3ShapeAddBoxAt(tBody, 5, 0.5, 0.1, 0, 0.5, 1.6, 0, 0, 0, 1, 0, 0.2, 0.1) into tShape
   b3ShapeSetColor tShape, 120, 112, 104
   put b3ShapeAddBoxAt(tBody, 5, 0.5, 0.1, 0, 0.5, -1.6, 0, 0, 0, 1, 0, 0.2, 0.1) into tShape
   b3ShapeSetColor tShape, 120, 112, 104
   -- the sensor: a thin gate across the chute. It collides with nothing
   -- and reports what passes through it.
   put b3BodyCreateRotated(sWorld, 0, -2.4, 3.6, 0, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tGate
   b3ShapeOptionsSetSensor true
   b3ShapeOptionsSetEvents false, false, true
   put b3ShapeAddBox(tGate, 0.04, 0.75, 1.5, 0, 0, 0) into sSensor
   b3ShapeSetColor sSensor, 90, 235, 255
   b3ShapeOptionsReset
   -- a bin at the bottom
   put b3BodyCreate(sWorld, 0, 6, 0, 0) into tBody
   put b3ShapeAddBoxAt(tBody, 0.1, 0.8, 2.2, 2.2, 0.8, 0, 0, 0, 0, 1, 0, 0.5, 0.1) into tShape
   put b3ShapeAddBoxAt(tBody, 2.2, 0.8, 0.1, 0, 0.8, 2.2, 0, 0, 0, 1, 0, 0.5, 0.1) into tShape
   put b3ShapeAddBoxAt(tBody, 2.2, 0.8, 0.1, 0, 0.8, -2.2, 0, 0, 0, 1, 0, 0.5, 0.1) into tShape
   put 0 into sTx
   put 1 into sTy
   put 17 into sDist
   pgHelp "Balls turn green as they pass the bright gate (a sensor) and flash white on a hard hit (a hit event). Click one to kick it."
end pgSceneSensors

-- A ball for the sensor scene: it is noticed by sensors and reports its
-- touches and hard hits
on pgSpawnBall
   local tBody, tShape
   put b3BodyCreate(sWorld, 2, -7.2 + random(10) / 20, 6.6, -0.9 + random(18) / 10) into tBody
   b3ShapeOptionsSetEvents true, true, true
   put b3ShapeAddSphere(tBody, 0, 0, 0, 0.32, 1, 0.3, 0.45) into tShape
   b3ShapeOptionsReset
   b3ShapeSetColor tShape, 250, 176, 70
   put tBody & comma after sLoose
   -- keep the scene small: the oldest ball goes when there are too many
   if the number of items in sLoose > 36 then
      b3BodyDestroy item 1 of sLoose
      delete item 1 of sLoose
   end if
end pgSpawnBall

on pgSceneTerrain
   local tBody, tShape, tI, tJ, tN, tKind
   -- a height field: rows of heights, here rolling hills with a rim
   put 25 into tN
   -- the field starts at its body and runs along +x and +z, so the body
   -- goes at one corner to put the middle of the hills at the origin
   put b3BodyCreate(sWorld, 0, -9.6, 0, -9.6) into tBody
   get b3GeometryBegin()
   repeat with tJ = 0 to tN - 1
      repeat with tI = 0 to tN - 1
         get b3GeometryAddHeight(pgHill(tI, tJ, tN))
      end repeat
   end repeat
   put b3ShapeAddHeightField(tBody, tN, tN, 0.8, 1, 0.8, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 110, 150, 96
   repeat 14 times
      put item random(3) of "sphere,sphere,box" into tKind
      get pgDropKind(tKind, -6 + random(120) / 10, 4 + random(4), -6 + random(120) / 10)
   end repeat
   -- a low light from the side, so the slopes show
   b3RenderSetLight -0.8, -0.55, -0.3
   put 19 into sDist
   put 0.62 into sPitch
   put 1.2 into sTy
   pgHelp "A height field: 625 heights make the hills. Balls and boxes roll into the valleys and fall asleep (dimmer). Drop adds more."
end pgSceneTerrain

function pgHill pCol, pRow, pCount
   local tEdge
   put min(pCol, pRow, pCount - 1 - pCol, pCount - 1 - pRow) into tEdge
   if tEdge < 2 then return 2.6 - tEdge
   return 1.1 + 0.9 * sin(pCol * 0.55) * cos(pRow * 0.5) + 0.4 * sin((pCol + pRow) * 0.3)
end pgHill

-- -------------------------------------------------------------- the loop

on pgTick
   local tNow, tSteps, tStart
   put empty into sLoop
   if sWorld is empty then exit pgTick
   put the milliseconds into tNow
   -- as many sixtieths of a second as have passed, at most three
   put max(1, min(3, round((tNow - sLast) / 16.667))) into tSteps
   put tNow into sLast
   if not sPaused then
      repeat tSteps times
         pgStep
      end repeat
   end if
   if sSpin and sDownAt is empty then add 0.0035 * tSteps to sYaw
   put the milliseconds into tStart
   pgDraw
   put the milliseconds - tStart into sDrawMs
   add 1 to sFrames
   if tNow - sFpsAt >= 1000 then
      put round(sFrames * 1000 / (tNow - sFpsAt)) into sFps
      pgBadge
      put 0 into sFrames
      put tNow into sFpsAt
      pgStatus
   end if
   send "pgTick" to me in 10 milliseconds
   put the result into sLoop
end pgTick

on pgStep
   local i, tBody
   if sScene is "sensors" then
      subtract 1 from sSpawnIn
      if sSpawnIn <= 0 then
         pgSpawnBall
         put 22 into sSpawnIn
      end if
   end if
   b3WorldStep sWorld, 1 / 60, 4
   add 1 to sSteps
   if sScene is "sensors" then pgEvents
   -- the cart turns back before it reaches the floor's edge: a short first
   -- leg, then to and fro about where it began
   if sCart is not empty and (sSteps + 70) mod 140 is 0 then
      repeat for each item tBody in sCart
         b3WheelSetSpinMotorSpeed tBody, - b3WheelSpinMotorSpeed(tBody)
      end repeat
   end if
   -- what falls off the edge is taken out of the world
   if sLoose is not empty and sSteps mod 30 is 0 then
      repeat with i = the number of items in sLoose down to 1
         put item i of sLoose into tBody
         if b3BodyY(tBody) < -20 then
            b3BodyDestroy tBody
            delete item i of sLoose
         end if
      end repeat
   end if
end pgStep

-- Events are read by asking after each step: nothing calls the script
on pgEvents
   local i, tShape
   b3WorldUpdateSensorEvents sWorld
   repeat with i = 1 to b3SensorBeginCount()
      put b3SensorBeginVisitor(i) into tShape
      b3ShapeSetColor tShape, 110, 230, 120
      put true into sGreen[tShape]
      add 1 to sPassed
   end repeat
   b3WorldUpdateContactEvents sWorld
   add b3ContactBeginCount() to sTouches
   repeat with i = 1 to b3ContactHitCount()
      add 1 to sHits
      if b3ContactHitSpeed(i) > 6 then
         pgFlash b3ContactHitShapeA(i)
         pgFlash b3ContactHitShapeB(i)
      end if
   end repeat
   -- a flash lasts a tenth of a second, then the ball has its colour back
   repeat for each key tShape in sFlash
      subtract 1 from sFlash[tShape]
      if sFlash[tShape] <= 0 then
         delete variable sFlash[tShape]
         if b3ShapeBody(tShape) is 0 then
            delete variable sGreen[tShape]
         else if sGreen[tShape] then
            b3ShapeSetColor tShape, 110, 230, 120
         else
            b3ShapeSetColor tShape, 250, 176, 70
         end if
      end if
   end repeat
end pgEvents

on pgFlash pShape
   if pShape is 0 or pShape is sSensor then exit pgFlash
   if b3BodyType(b3ShapeBody(pShape)) is not 2 then exit pgFlash
   b3ShapeSetColor pShape, 255, 255, 255
   put 6 into sFlash[pShape]
end pgFlash

on pgCamera
   local tEx, tEy, tEz
   put sTx + sDist * cos(sPitch) * sin(sYaw) into tEx
   put sTy + sDist * sin(sPitch) into tEy
   put sTz + sDist * cos(sPitch) * cos(sYaw) into tEz
   b3RenderSetCamera tEx, tEy, tEz, sTx, sTy, sTz, 50
end pgCamera

on pgDraw
   pgCamera
   if b3RenderWorld(sWorld, kW, kH, sMode) then
      if there is an image "view" of card 1 of me then
         set the imageData of image "view" of card 1 of me to b3RenderPixels()
      end if
   end if
end pgDraw

on pgStatus
   local tText
   if sWorld is empty then exit pgStatus
   put b3WorldBodyCount(sWorld) && "bodies," && b3WorldAwakeBodyCount(sWorld) && "awake," && b3WorldJointCount(sWorld) && "joints," \
         && b3WorldContactCount(sWorld) && "contacts. A step of physics takes" && format("%.2f", b3WorldStepMs(sWorld)) && "ms, a picture" \
         && sDrawMs && "ms." into tText
   if sScene is "sensors" then
      put return & "Through the gate:" && sPassed & ", touches:" && sTouches & ", hard hits:" && sHits after tText
   end if
   if sScene is "joints" and sRotor is not 0 then
      put return & "Windmill angle" && format("%.1f", b3RevoluteAngle(sRotor)) & ", slider at" && format("%.2f", b3PrismaticTranslation(sPiston)) after tText
   end if
   pgSay tText
end pgStatus

on pgBadge
   if there is not a field "fps" of card 1 of me then exit pgBadge
   put sFps && "fps" into field "fps" of card 1 of me
   set the visible of field "fps" of card 1 of me to sFps is not empty
end pgBadge

-- ------------------------------------------------------------- the mouse

on mouseUp
   local tName
   put the short name of the target into tName
   if (word 1 of the name of the target is "image" and tName is "view") or tName is "fps" then
      if not sDragged then pgKick the mouseH - kLeft, the mouseV - kTop
      put empty into sDownAt
      exit mouseUp
   end if
   if word 1 of the name of the target is not "button" then pass mouseUp
   switch tName
      case "Shapes"
      case "Joints"
      case "Sensors"
      case "Terrain"
         pgScene toLower(tName)
         break
      case "Solid"
         put 0 into sMode
         put true into sPicked
         break
      case "Wire"
         put 1 into sMode
         put true into sPicked
         break
      case "Outline"
         put 2 into sMode
         put true into sPicked
         break
      case "Pause"
         put not sPaused into sPaused
         break
      case "Spin"
         put not sSpin into sSpin
         break
      case "Reset"
         if sScene is not empty then pgScene sScene
         break
      case "Drop"
         pgDropMore
         break
      case "Boom"
         if sWorld is not empty then b3WorldExplode sWorld, sTx, 0.3, sTz, 4, 4, 6
         break
      default
         pass mouseUp
   end switch
   pgMarks
end mouseUp

on mouseRelease
   put empty into sDownAt
   pass mouseRelease
end mouseRelease

on mouseDown
   if word 1 of the name of the target is "image" and the short name of the target is "view" then
      put the mouseH & comma & the mouseV into sDownAt
      put sYaw into sDownYaw
      put sPitch into sDownPitch
      put false into sDragged
   else
      pass mouseDown
   end if
end mouseDown

on mouseMove pX, pY
   if sDownAt is empty then pass mouseMove
   if abs(pX - item 1 of sDownAt) + abs(pY - item 2 of sDownAt) > 5 then put true into sDragged
   if sDragged then
      put sDownYaw - (pX - item 1 of sDownAt) * 0.008 into sYaw
      put max(0.08, min(1.45, sDownPitch + (pY - item 2 of sDownAt) * 0.006)) into sPitch
   end if
end mouseMove

-- A click: the ray from the camera through the picture point, cast into
-- the world; what it meets first is pushed along the ray
on pgKick pX, pY
   local tRay, tBody, tPush, tPoint
   if sWorld is empty then exit pgKick
   put b3RenderRay(pX + 0.5, pY + 0.5) into tRay
   if tRay is empty then exit pgKick
   if b3CastRayClosest(sWorld, item 1 of tRay, item 2 of tRay, item 3 of tRay, \
         100 * item 4 of tRay, 100 * item 5 of tRay, 100 * item 6 of tRay) is 0 then exit pgKick
   put b3HitBody(1) into tBody
   if b3BodyType(tBody) is not 2 then exit pgKick
   put 7 * b3BodyMass(tBody) into tPush
   put b3HitPoint(1) into tPoint
   b3BodyApplyImpulse tBody, tPush * item 4 of tRay, tPush * item 5 of tRay + 0.4 * tPush, tPush * item 6 of tRay, \
         item 1 of tPoint, item 2 of tPoint, item 3 of tPoint, true
end pgKick

on pgDropMore
   local tBody
   if sWorld is empty then exit pgDropMore
   switch sScene
      case "sensors"
         repeat 4 times
            pgSpawnBall
         end repeat
         break
      case "joints"
         get pgDropKind(pgAnyKind(), 5 + random(10) / 10 - 0.5, 7, 3)
         get pgDropKind(pgAnyKind(), -1 + random(20) / 10, 8, -0.6)
         break
      case "terrain"
         repeat 5 times
            get pgDropKind(pgAnyKind(), -5 + random(100) / 10, 5 + random(4), -5 + random(100) / 10)
         end repeat
         break
      default
         repeat 4 times
            get pgDropKind(pgAnyKind(), -5 + random(100) / 10, 7 + random(4), -3 + random(60) / 10)
         end repeat
   end switch
end pgDropMore