1 
2 // written in the D programming language
3 
4 module samples.Bounce;
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     enum int steps = 3;
16     enum 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 void
24 add_box()
25 {
26     enum cpFloat size = 10.0f;
27     enum cpFloat mass = 1.0f;
28 
29     cpVect verts[] = [
30         cpv(-size,-size),
31         cpv(-size, size),
32         cpv( size, size),
33         cpv( size,-size),
34     ];
35 
36     cpFloat radius = cpvlength(cpv(size, size));
37 
38     cpBody *_body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts.ptr, cpvzero)));
39     _body.p = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius));
40     _body.v = cpvmult(cpv(2*frand() - 1, 2*frand() - 1), 200);
41 
42     cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(_body, 4, verts.ptr, cpvzero));
43     shape.e = 1.0f; shape.u = 0.0f;
44 }
45 
46 static cpSpace *
47 init()
48 {
49     cpResetShapeIdCounter();
50 
51     space = cpSpaceNew();
52     space.iterations = 10;
53 
54     cpBody *_body;
55     cpBody *staticBody = space.staticBody;
56     cpShape *shape;
57 
58     // Create segments around the edge of the screen.
59     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
60     shape.e = 1.0f; shape.u = 1.0f;
61     shape.layers = NOT_GRABABLE_MASK;
62 
63     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
64     shape.e = 1.0f; shape.u = 1.0f;
65     shape.layers = NOT_GRABABLE_MASK;
66 
67     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
68     shape.e = 1.0f; shape.u = 1.0f;
69     shape.layers = NOT_GRABABLE_MASK;
70 
71     shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f));
72     shape.e = 1.0f; shape.u = 1.0f;
73     shape.layers = NOT_GRABABLE_MASK;
74 
75     for(int i=0; i<10; i++)
76         add_box();
77 
78     _body = cpSpaceAddBody(space, cpBodyNew(100.0f, 10000.0f));
79 
80     shape = cpSpaceAddShape(space, cpSegmentShapeNew(_body, cpv(-75,0), cpv(75,0), 5.0f));
81     shape.e = 1.0f; shape.u = 1.0f;
82 
83     cpSpaceAddConstraint(space, cpPivotJointNew2(_body, staticBody, cpvzero, cpvzero));
84 
85     return space;
86 }
87 
88 static void
89 destroy()
90 {
91     ChipmunkDemoFreeSpaceChildren(space);
92     cpSpaceFree(space);
93 }
94 
95 chipmunkDemo Bounce = {
96     "Bounce",
97     null,
98     &init,
99     &update,
100     &destroy,
101 };