1 
2 // written in the D programming language
3 
4 module samples.PyramidStack;
5 
6 import dchip.all;
7 
8 import samples.ChipmunkDemo;
9 
10 static cpSpace *space;
11 
12 static void
13 update(int ticks)
14 {
15     int steps = 3;
16     cpFloat dt = 1.0f/60.0f/cast(cpFloat)steps;
17 
18     for(int i=0; i<steps; i++){
19         cpSpaceStep(space, dt);
20     }
21 }
22 
23 static cpSpace *
24 init()
25 {
26     cpResetShapeIdCounter();
27 
28     space = cpSpaceNew();
29     space.iterations = 30;
30     space.gravity = cpv(0, -100);
31     space.sleepTimeThreshold = 0.5f;
32     space.collisionSlop = 0.5f;
33 
34     cpBody *_body;
35     cpBody *staticBody = space.staticBody;
36     cpShape *shape;
37 
38     // Create segments around the edge of the screen.
39     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
40     shape.e = 1.0f; shape.u = 1.0f;
41     shape.layers = NOT_GRABABLE_MASK;
42 
43     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
44     shape.e = 1.0f; shape.u = 1.0f;
45     shape.layers = NOT_GRABABLE_MASK;
46 
47     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
48     shape.e = 1.0f; shape.u = 1.0f;
49     shape.layers = NOT_GRABABLE_MASK;
50 
51     // Add lots of boxes.
52     for(int i=0; i<14; i++){
53         for(int j=0; j<=i; j++){
54             _body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForBox(1.0f, 30.0f, 30.0f)));
55             _body.p = cpv(j*32 - i*16, 300 - i*32);
56 
57             shape = cpSpaceAddShape(space, cpBoxShapeNew(_body, 30.0f, 30.0f));
58             shape.e = 0.0f; shape.u = 0.8f;
59         }
60     }
61 
62     // Add a ball to make things more interesting
63     cpFloat radius = 15.0f;
64     _body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero)));
65     _body.p = cpv(0, -240 + radius+5);
66 
67     shape = cpSpaceAddShape(space, cpCircleShapeNew(_body, radius, cpvzero));
68     shape.e = 0.0f; shape.u = 0.9f;
69 
70     return space;
71 }
72 
73 static void
74 destroy()
75 {
76     ChipmunkDemoFreeSpaceChildren(space);
77     cpSpaceFree(space);
78 }
79 
80 chipmunkDemo PyramidStack = {
81     "Pyramid Stack",
82     null,
83     &init,
84     &update,
85     &destroy,
86 };