2 * This file is part of NumptyPhysics
3 * Copyright (C) 2008 Tim Edmonds
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
25 Transform::Transform( float32 scale
, float32 rotation
, const Vec2
& translation
)
27 set( scale
, rotation
, translation
);
30 void Transform::set( float32 scale
, float32 rotation
, const Vec2
& translation
)
32 if ( scale
==0.0f
&& rotation
==0.0f
&& translation
==Vec2(0,0) ) {
35 m_rot
.Set( rotation
);
37 m_rot
.col1
.x
*= scale
;
38 m_rot
.col1
.y
*= scale
;
39 m_rot
.col2
.x
*= scale
;
40 m_rot
.col2
.y
*= scale
;
41 m_invrot
= m_rot
.Invert();
46 Transform
worldToScreen( 0.5f
, M_PI
/2, Vec2(240,0) );
48 void configureScreenTransform( int w
, int h
)
52 FULLSCREEN_RECT
= Rect(0,0,w
-1,h
-1);
53 if ( w
==WORLD_WIDTH
&& h
==WORLD_HEIGHT
) { //unity
54 worldToScreen
.set( 0.0f
, 0.0f
, Vec2(0,0) );
58 if ( h
> w
) { //portrait
63 float scalew
= (float)w
/(float)WORLD_WIDTH
;
64 float scaleh
= (float)h
/(float)WORLD_HEIGHT
;
65 if ( scalew
< scaleh
) {
66 worldToScreen
.set( scalew
, rot
, tr
);
68 worldToScreen
.set( scaleh
, rot
, tr
);
79 struct JointDef
: public b2RevoluteJointDef
81 JointDef( b2Body
* b1
, b2Body
* b2
, const b2Vec2
& pt
)
83 Initialize( b1
, b2
, pt
);
84 maxMotorTorque
= 10.0f
;
90 struct BoxDef
: public b2PolygonDef
92 void init( const Vec2
& p1
, const Vec2
& p2
, int attr
)
94 b2Vec2 barOrigin
= p1
;
96 bar
*= 1.0f
/PIXELS_PER_METREf
;
97 barOrigin
*= 1.0f
/PIXELS_PER_METREf
;;
98 SetAsBox( bar
.Length()/2.0f
, 0.1f
,
99 0.5f
*bar
+ barOrigin
, vec2Angle( bar
));
100 // SetAsBox( bar.Length()/2.0f+b2_toiSlop, b2_toiSlop*2.0f,
101 // 0.5f*bar + barOrigin, vec2Angle( bar ));
103 if ( attr
& ATTRIB_GROUND
) {
105 } else if ( attr
& ATTRIB_GOAL
) {
107 } else if ( attr
& ATTRIB_TOKEN
) {
118 Stroke( const Path
& path
)
121 m_colour
= brushColours
[DEFAULT_BRUSH
];
123 m_origin
= m_rawPath
.point(0);
124 m_rawPath
.translate( -m_origin
);
129 Stroke( const std::string
& str
)
133 m_colour
= brushColours
[DEFAULT_BRUSH
];
135 m_origin
= Vec2(400,240);
137 const char *s
= str
.c_str();
138 while ( *s
&& *s
!=':' && *s
!='\n' ) {
140 case 't': setAttribute( ATTRIB_TOKEN
); setPlayer(0); break;
141 case 'T': setAttribute( ATTRIB_TOKEN
); setPlayer(1); break;
142 case 'g': setAttribute( ATTRIB_GOAL
); setPlayer(0); break;
143 case 'G': setAttribute( ATTRIB_GOAL
); setPlayer(1); break;
144 case 'f': setAttribute( ATTRIB_GROUND
); break;
145 case 's': setAttribute( ATTRIB_SLEEPING
); break;
146 case 'd': setAttribute( ATTRIB_DECOR
); break;
148 if ( *s
>= '0' && *s
<= '9' ) {
149 col
= col
*10 + *s
-'0';
155 if ( col
>= 0 && col
< NUM_BRUSHES
) {
156 m_colour
= brushColours
[col
];
161 if ( m_rawPath
.size() < 2 ) {
162 throw "invalid stroke def";
164 m_origin
= m_rawPath
.point(0);
165 m_rawPath
.translate( -m_origin
);
166 setAttribute( ATTRIB_DUMMY
);
169 void reset( b2World
* world
=NULL
)
171 if (m_body
&& world
) {
172 world
->DestroyBody( m_body
);
176 m_drawnBbox
.tl
= m_origin
;
177 m_drawnBbox
.br
= m_origin
;
178 m_jointed
[0] = m_jointed
[1] = false;
179 m_shapePath
= m_rawPath
;
184 std::string
asString()
188 if ( hasAttribute(ATTRIB_TOKEN
) ) s
<<'t';
189 if ( hasAttribute(ATTRIB_GOAL
) ) s
<<'g';
190 if ( hasAttribute(ATTRIB_GROUND
) ) s
<<'f';
191 if ( hasAttribute(ATTRIB_SLEEPING
) ) s
<<'s';
192 if ( hasAttribute(ATTRIB_DECOR
) ) s
<<'d';
193 for ( int i
=0; i
<NUM_BRUSHES
; i
++ ) {
194 if ( m_colour
==brushColours
[i
] ) s
<<i
;
198 for ( int i
=0; i
<m_xformedPath
.size(); i
++ ) {
199 const Vec2
& p
= m_xformedPath
.point(i
);
200 s
<<' '<< p
.x
<< ',' << p
.y
;
206 void setAttribute( Attribute a
)
209 if ( m_attributes
& ATTRIB_TOKEN
) m_colour
= brushColours
[RED_BRUSH
];
210 else if ( m_attributes
& ATTRIB_GOAL
) m_colour
= brushColours
[YELLOW_BRUSH
];
213 void setPlayer( int player
)
223 void clearAttribute( Attribute a
)
228 bool hasAttribute( Attribute a
)
230 return (m_attributes
&a
) != 0;
232 void setColour( int c
)
237 void createBodies( b2World
& world
)
240 if ( hasAttribute( ATTRIB_DECOR
) ){
241 return; //decorators have no physical embodiment
243 int n
= m_shapePath
.numPoints();
246 bodyDef
.position
= m_origin
;
247 bodyDef
.position
*= 1.0f
/PIXELS_PER_METREf
;
248 bodyDef
.userData
= this;
249 if ( m_attributes
& ATTRIB_SLEEPING
) {
250 bodyDef
.isSleeping
= true;
252 m_body
= world
.CreateBody( &bodyDef
);
253 for ( int i
=1; i
<n
; i
++ ) {
255 boxDef
.init( m_shapePath
.point(i
-1),
256 m_shapePath
.point(i
),
258 m_body
->CreateShape( &boxDef
);
260 m_body
->SetMassFromShapes();
266 bool maybeCreateJoint( b2World
& world
, Stroke
* other
)
268 if ( (m_attributes
&ATTRIB_CLASSBITS
)
269 != (other
->m_attributes
&ATTRIB_CLASSBITS
) ) {
270 return false; // can only joint matching classes
271 } else if ( hasAttribute(ATTRIB_GROUND
) ) {
272 return true; // no point jointing grounds
273 } else if ( m_body
&& other
->body() ) {
275 int n
= m_xformedPath
.numPoints();
276 for ( int end
=0; end
<2; end
++ ) {
277 if ( !m_jointed
[end
] ) {
278 const Vec2
& p
= m_xformedPath
.point( end
? n
-1 : 0 );
279 if ( other
->distanceTo( p
) <= JOINT_TOLERANCE
) {
280 //printf("jointed end %d d=%f\n",end,other->distanceTo( p ));
282 pw
*= 1.0f
/PIXELS_PER_METREf
;
283 JointDef
j( m_body
, other
->m_body
, pw
);
284 world
.CreateJoint( &j
);
285 m_jointed
[end
] = true;
291 return m_jointed
[0] && m_jointed
[1];
293 return true; ///nothing to do
296 void draw( Canvas
& canvas
)
298 if ( m_hide
< HIDE_STEPS
) {
299 bool thick
= (canvas
.width() > 400);
301 canvas
.drawPath( m_screenPath
, canvas
.makeColour(m_colour
), thick
);
304 m_drawnBbox
= m_screenBbox
;
307 void addPoint( const Vec2
& pp
)
309 Vec2 p
= pp
; p
-= m_origin
;
310 if ( p
== m_rawPath
.point( m_rawPath
.numPoints()-1 ) ) {
312 m_rawPath
.append( p
);
317 void origin( const Vec2
& p
)
322 pw
*= 1.0f
/PIXELS_PER_METREf
;
323 m_body
->SetXForm( pw
, m_body
->GetAngle() );
328 b2Body
* body() { return m_body
; }
330 float32
distanceTo( const Vec2
& pt
)
332 float32 best
= 100000.0;
334 for ( int i
=1; i
<m_xformedPath
.numPoints(); i
++ ) {
335 Segment
s( m_xformedPath
.point(i
-1), m_xformedPath
.point(i
) );
336 float32 d
= s
.distanceTo( pt
);
337 //printf(" d[%d]=%f %d,%d\n",i,d,m_rawPath.point(i-1).x,m_rawPath.point(i-1).y);
358 return m_xformedPath
.bbox();
363 return (!m_drawn
|| transform()) && !hasAttribute(ATTRIB_DELETED
);
372 // stash the body where no-one will find it
373 m_body
->SetXForm( b2Vec2(0.0f
,SCREEN_HEIGHT
*2.0f
), 0.0f
);
374 m_body
->SetLinearVelocity( b2Vec2(0.0f
,0.0f
) );
375 m_body
->SetAngularVelocity( 0.0f
);
382 return m_hide
>= HIDE_STEPS
;
387 return m_rawPath
.numPoints();
391 static float32
vec2Angle( b2Vec2 v
)
393 return b2Atan2(v
.y
, v
.x
);
398 float32 thresh
= SIMPLIFY_THRESHOLDf
;
399 m_rawPath
.simplify( thresh
);
400 m_shapePath
= m_rawPath
;
402 while ( m_shapePath
.numPoints() > MULTI_VERTEX_LIMIT
) {
403 thresh
+= SIMPLIFY_THRESHOLDf
;
404 m_shapePath
.simplify( thresh
);
410 // distinguish between xformed raw and shape path as needed
412 if ( m_hide
< HIDE_STEPS
) {
413 //printf("hide %d\n",m_hide);
414 Vec2 o
= m_screenBbox
.centroid();
416 m_screenPath
.scale( 0.99 );
418 m_screenBbox
= m_screenPath
.bbox();
422 } else if ( m_body
) {
423 if ( hasAttribute( ATTRIB_DECOR
) ) {
424 return false; // decor never moves
425 } else if ( hasAttribute( ATTRIB_GROUND
)
426 && m_xformAngle
== m_body
->GetAngle() ) {
427 return false; // ground strokes never move.
428 } else if ( m_xformAngle
!= m_body
->GetAngle()
429 || ! (m_xformPos
== m_body
->GetPosition()) ) {
430 //printf("transform stroke - rot or pos\n");
431 b2Mat22
rot( m_body
->GetAngle() );
432 b2Vec2 orig
= PIXELS_PER_METREf
* m_body
->GetPosition();
433 m_xformedPath
= m_rawPath
;
434 m_xformedPath
.rotate( rot
);
435 m_xformedPath
.translate( Vec2(orig
) );
436 m_xformAngle
= m_body
->GetAngle();
437 m_xformPos
= m_body
->GetPosition();
438 worldToScreen
.transform( m_xformedPath
, m_screenPath
);
439 m_screenBbox
= m_screenPath
.bbox();
441 //printf("transform none\n");
445 //printf("transform no body\n");
446 m_xformedPath
= m_rawPath
;
447 m_xformedPath
.translate( m_origin
);
448 worldToScreen
.transform( m_xformedPath
, m_screenPath
);
449 m_screenBbox
= m_screenPath
.bbox();
463 float32 m_xformAngle
;
473 Scene::Scene( bool noWorld
)
480 worldAABB
.lowerBound
.Set(-100.0f
, -100.0f
);
481 worldAABB
.upperBound
.Set(100.0f
, 100.0f
);
483 b2Vec2
gravity(0.0f
, 10.0f
*PIXELS_PER_METREf
/GRAVITY_FUDGEf
);
485 m_world
= new b2World(worldAABB
, gravity
, doSleep
);
486 m_world
->SetContactListener( this );
499 Stroke
* Scene::newStroke( const Path
& p
, int colour
, int attribs
) {
500 Stroke
*s
= new Stroke(p
);
502 case 0: s
->setAttribute( ATTRIB_TOKEN
); break;
503 case 1: s
->setAttribute( ATTRIB_GOAL
); break;
504 default: s
->setColour( brushColours
[colour
] ); break;
507 m_strokes
.append( s
);
511 bool Scene::deleteStroke( Stroke
*s
) {
513 int i
= m_strokes
.indexOf(s
);
514 if ( i
>= m_protect
) {
516 m_strokes
.erase( m_strokes
.indexOf(s
) );
524 void Scene::extendStroke( Stroke
* s
, const Vec2
& pt
)
531 void Scene::moveStroke( Stroke
* s
, const Vec2
& origin
)
534 int i
= m_strokes
.indexOf(s
);
535 if ( i
>= m_protect
) {
542 bool Scene::activate( Stroke
*s
)
544 if ( s
->numPoints() > 1 ) {
545 s
->createBodies( *m_world
);
552 void Scene::activateAll()
559 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
560 m_strokes
[i
]->createBodies( *m_world
);
561 if (m_strokes
[i
]->hasAttribute(ATTRIB_TOKEN
)) { m_num_token
++;}
562 if (m_strokes
[i
]->hasAttribute(ATTRIB_GOAL
)) { m_num_goal
++; }
563 if (m_strokes
[i
]->getPlayer() + 1 > m_num_player
) { m_num_player
= m_strokes
[i
]->getPlayer() + 1; }
565 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
566 createJoints( m_strokes
[i
] );
570 void Scene::createJoints( Stroke
*s
)
572 for ( int j
=m_strokes
.size()-1; j
>=0; j
-- ) {
573 if ( s
!= m_strokes
[j
] ) {
574 //printf("try join to %d\n",j);
575 s
->maybeCreateJoint( *m_world
, m_strokes
[j
] );
576 m_strokes
[j
]->maybeCreateJoint( *m_world
, s
);
583 m_world
->Step( ITERATION_TIMESTEPf
, SOLVER_ITERATIONS
);
584 // clean up delete strokes
585 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
586 if ( m_strokes
[i
]->hasAttribute(ATTRIB_DELETED
) ) {
587 m_strokes
[i
]->clearAttribute(ATTRIB_DELETED
);
588 m_strokes
[i
]->hide();
591 // check for token respawn
592 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
593 if ( m_strokes
[i
]->hasAttribute( ATTRIB_TOKEN
)
594 && !BOUNDS_RECT
.intersects( m_strokes
[i
]->worldBbox() ) ) {
595 reset( m_strokes
[i
] );
596 activate( m_strokes
[i
] );
601 // b2ContactListener callback when a new contact is detected
602 void Scene::Add(const b2ContactPoint
* point
)
604 // check for completion
605 //if (c->GetManifoldCount() > 0) {
606 Stroke
* s1
= (Stroke
*)point
->shape1
->GetBody()->GetUserData();
607 Stroke
* s2
= (Stroke
*)point
->shape2
->GetBody()->GetUserData();
610 if ( s2
->hasAttribute(ATTRIB_TOKEN
) ) {
613 if ( s1
->hasAttribute(ATTRIB_TOKEN
)
614 && s2
->hasAttribute(ATTRIB_GOAL
) ) {
615 s2
->setAttribute(ATTRIB_DELETED
);
616 if (m_num_goal
== 1) {
617 m_winner
= s1
->getPlayer();
623 bool Scene::isCompleted()
625 /* if we only have one goal, m_winner has already been set */
626 if ((m_num_goal
== 1) && (m_winner
!= -1)) {
630 else if (m_num_goal
> 1)
632 int left
[m_num_player
];
633 for(int n
=0; n
<m_num_player
; n
++) {
637 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
638 if ( m_strokes
[i
]->hasAttribute( ATTRIB_GOAL
)
639 && !m_strokes
[i
]->hidden() ) {
640 left
[m_strokes
[i
]->getPlayer()]++;
644 for ( int n
=0; n
<m_num_player
; n
++) {
655 int Scene::getWinner()
657 return m_num_player
== 1 ? -1 : m_winner
;
660 Rect
Scene::dirtyArea()
662 Rect
r(0,0,0,0),temp
;
664 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
665 if ( m_strokes
[i
]->isDirty() ) {
666 // acumulate new areas to draw
667 temp
= m_strokes
[i
]->screenBbox();
668 if ( !temp
.isEmpty() ) {
672 r
.expand( m_strokes
[i
]->screenBbox() );
674 // plus prev areas to erase
675 r
.expand( m_strokes
[i
]->lastDrawnBbox() );
680 if ( !r
.isEmpty() ) {
681 // expand to allow for thick lines
688 void Scene::draw( Canvas
& canvas
, const Rect
& area
)
691 canvas
.setBackground( m_bgImage
);
693 canvas
.setBackground( 0 );
695 canvas
.clear( area
);
696 Rect clipArea
= area
;
701 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
702 if ( area
.intersects( m_strokes
[i
]->screenBbox() ) ) {
703 m_strokes
[i
]->draw( canvas
);
706 //canvas.drawRect( area, 0xffff0000, false );
709 void Scene::reset( Stroke
* s
)
711 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
712 if (s
==NULL
|| s
==m_strokes
[i
]) {
713 m_strokes
[i
]->reset(m_world
);
718 Stroke
* Scene::strokeAtPoint( const Vec2 pt
, float32 max
)
721 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
722 float32 d
= m_strokes
[i
]->distanceTo( pt
);
723 //printf("stroke %d dist %f\n",i,d);
735 while ( m_strokes
.size() ) {
740 //step is required to actually destroy bodies and joints
741 m_world
->Step( ITERATION_TIMESTEPf
, SOLVER_ITERATIONS
);
745 void Scene::setGravity( const std::string
& s
)
748 if ( sscanf( s
.c_str(), "%f,%f", &x
, &y
)==2) {
751 g
*= PIXELS_PER_METREf
/GRAVITY_FUDGEf
;
752 m_world
->SetGravity( g
);
755 fprintf(stderr
,"invalid gravity vector\n");
759 bool Scene::load( unsigned char *buf
, int bufsize
)
761 std::string
s( (const char*)buf
, bufsize
);
762 std::stringstream
in( s
, std::ios::in
);
766 bool Scene::load( const std::string
& file
)
768 std::ifstream
in( file
.c_str(), std::ios::in
);
772 bool Scene::load( std::istream
& in
)
775 if ( g_bgImage
==NULL
) {
776 g_bgImage
= new Image("paper.png");
777 g_bgImage
->scale( SCREEN_WIDTH
, SCREEN_HEIGHT
);
779 m_bgImage
= g_bgImage
;
781 while ( !in
.eof() ) {
789 bool Scene::parseLine( const std::string
& line
)
793 case 'T': m_title
= line
.substr(line
.find(':')+1); return true;
794 case 'B': m_bg
= line
.substr(line
.find(':')+1); return true;
795 case 'A': m_author
= line
.substr(line
.find(':')+1); return true;
797 Stroke
*s
= new Stroke(line
);
801 case 'G': setGravity(line
.substr(line
.find(':')+1));return true;
803 } catch ( const char* e
) {
804 printf("Stroke error: %s\n",e
);
809 void Scene::protect( int n
)
811 m_protect
= (n
==-1 ? m_strokes
.size() : n
);
814 bool Scene::save( const std::string
& file
)
816 printf("saving to %s\n",file
.c_str());
817 std::ofstream
o( file
.c_str(), std::ios::out
);
819 o
<< "Title: "<<m_title
<<std::endl
;
820 o
<< "Author: "<<m_author
<<std::endl
;
821 o
<< "Background: "<<m_bg
<<std::endl
;
822 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
823 o
<< m_strokes
[i
]->asString();
833 Image
*Scene::g_bgImage
= NULL
;