BGE patch: Relink actuators with target within group when duplicating group; generali...
[blender.git] / source / gameengine / Ketsji / KX_GameObject.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Game object wrapper
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #if defined(_WIN64)
36 typedef unsigned __int64 uint_ptr;
37 #else
38 typedef unsigned long uint_ptr;
39 #endif
40
41 #ifdef WIN32
42 // This warning tells us about truncation of __long__ stl-generated names.
43 // It can occasionally cause DevStudio to have internal compiler warnings.
44 #pragma warning( disable : 4786 )     
45 #endif
46
47
48 #define KX_INERTIA_INFINITE 10000
49 #include "RAS_IPolygonMaterial.h"
50 #include "KX_BlenderMaterial.h"
51 #include "KX_GameObject.h"
52 #include "RAS_MeshObject.h"
53 #include "KX_MeshProxy.h"
54 #include <stdio.h> // printf
55 #include "SG_Controller.h"
56 #include "KX_IPhysicsController.h"
57 #include "SG_Node.h"
58 #include "SG_Controller.h"
59 #include "KX_ClientObjectInfo.h"
60 #include "RAS_BucketManager.h"
61 #include "KX_RayCast.h"
62 #include "KX_PythonInit.h"
63 #include "KX_PyMath.h"
64 #include "SCA_IActuator.h"
65 #include "SCA_ISensor.h"
66
67 // This file defines relationships between parents and children
68 // in the game engine.
69
70 #include "KX_SG_NodeRelationships.h"
71
72 KX_GameObject::KX_GameObject(
73         void* sgReplicationInfo,
74         SG_Callbacks callbacks,
75         PyTypeObject* T
76 ) : 
77         SCA_IObject(T),
78         m_bDyna(false),
79         m_layer(0),
80         m_bSuspendDynamics(false),
81         m_bUseObjectColor(false),
82         m_bIsNegativeScaling(false),
83         m_pBlenderObject(NULL),
84         m_bVisible(true),
85         m_pPhysicsController1(NULL),
86         m_pPhysicsEnvironment(NULL),
87         m_pHitObject(NULL),
88         m_isDeformable(false)
89 {
90         m_ignore_activity_culling = false;
91         m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
92         m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
93
94         // define the relationship between this node and it's parent.
95         
96         KX_NormalParentRelation * parent_relation = 
97                 KX_NormalParentRelation::New();
98         m_pSGNode->SetParentRelation(parent_relation);
99         
100
101 };
102
103
104
105 KX_GameObject::~KX_GameObject()
106 {
107         // is this delete somewhere ?
108         //if (m_sumoObj)
109         //      delete m_sumoObj;
110         delete m_pClient_info;
111         //if (m_pSGNode)
112         //      delete m_pSGNode;
113         if (m_pSGNode)
114         {
115                 // must go through controllers and make sure they will not use us anymore
116                 // This is important for KX_BulletPhysicsControllers that unregister themselves
117                 // from the object when they are deleted.
118                 SGControllerList::iterator contit;
119                 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
120                 for (contit = controllers.begin();contit!=controllers.end();++contit)
121                 {
122                         (*contit)->ClearObject();
123                 }
124                 m_pSGNode->SetSGClientObject(NULL);
125         }
126 }
127
128
129
130 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) 
131 {
132         return NULL;
133 }
134
135
136
137 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
138 {
139         return NULL;
140 }
141
142
143
144 const STR_String & KX_GameObject::GetText()
145 {
146         return m_text;
147 }
148
149
150
151 float KX_GameObject::GetNumber()
152 {
153         return 0;
154 }
155
156
157
158 STR_String KX_GameObject::GetName()
159 {
160         return m_name;
161 }
162
163
164
165 void KX_GameObject::SetName(STR_String name)
166 {
167         m_name = name;
168 };                                                              // Set the name of the value
169
170
171
172 void KX_GameObject::ReplicaSetName(STR_String name)
173 {
174 }
175
176
177
178
179
180
181 KX_IPhysicsController* KX_GameObject::GetPhysicsController()
182 {
183         return m_pPhysicsController1;
184 }
185
186
187
188
189
190 KX_GameObject* KX_GameObject::GetParent()
191 {
192         KX_GameObject* result = NULL;
193         SG_Node* node = m_pSGNode;
194         
195         while (node && !result)
196         {
197                 node = node->GetSGParent();
198                 if (node)
199                         result = (KX_GameObject*)node->GetSGClientObject();
200         }
201         
202         if (result)
203                 result->AddRef();
204
205         return result;
206         
207 }
208
209 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
210 {
211         if (obj && GetSGNode()->GetSGParent() != obj->GetSGNode())
212         {
213                 // Make sure the objects have some scale
214                 MT_Vector3 scale1 = NodeGetWorldScaling();
215                 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
216                 if (fabs(scale2[0]) < FLT_EPSILON || 
217                         fabs(scale2[1]) < FLT_EPSILON || 
218                         fabs(scale2[2]) < FLT_EPSILON || 
219                         fabs(scale1[0]) < FLT_EPSILON || 
220                         fabs(scale1[1]) < FLT_EPSILON || 
221                         fabs(scale1[2]) < FLT_EPSILON) { return; }
222
223                 // Remove us from our old parent and set our new parent
224                 RemoveParent(scene);
225                 obj->GetSGNode()->AddChild(GetSGNode());
226
227                 // Set us to our new scale, position, and orientation
228                 scale1[0] = scale1[0]/scale2[0];
229                 scale1[1] = scale1[1]/scale2[1];
230                 scale1[2] = scale1[2]/scale2[2];
231                 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
232                 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale1;
233
234                 NodeSetLocalScale(scale1);
235                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
236                 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
237                 NodeUpdateGS(0.f,true);
238                 // object will now be a child, it must be removed from the parent list
239                 CListValue* rootlist = scene->GetRootParentList();
240                 if (rootlist->RemoveValue(this))
241                         // the object was in parent list, decrement ref count as it's now removed
242                         Release();
243                 if (m_pPhysicsController1) 
244                 {
245                         m_pPhysicsController1->SuspendDynamics(true);
246                 }
247         }
248 }
249
250 void KX_GameObject::RemoveParent(KX_Scene *scene)
251 {
252         if (GetSGNode()->GetSGParent())
253         {
254                 // Set us to the right spot 
255                 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
256                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
257                 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
258
259                 // Remove us from our parent
260                 GetSGNode()->DisconnectFromParent();
261                 NodeUpdateGS(0.f,true);
262                 // the object is now a root object, add it to the parentlist
263                 CListValue* rootlist = scene->GetRootParentList();
264                 if (!rootlist->SearchValue(this))
265                         // object was not in root list, add it now and increment ref count
266                         rootlist->Add(AddRef());
267                 if (m_pPhysicsController1) 
268                 {
269                         m_pPhysicsController1->RestoreDynamics();
270                 }
271         }
272 }
273
274 void KX_GameObject::ProcessReplica(KX_GameObject* replica)
275 {
276         replica->m_pPhysicsController1 = NULL;
277         replica->m_pSGNode = NULL;
278         replica->m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
279         replica->m_pClient_info->m_gameobject = replica;
280 }
281
282
283
284 CValue* KX_GameObject::GetReplica()
285 {
286         KX_GameObject* replica = new KX_GameObject(*this);
287         
288         // this will copy properties and so on...
289         CValue::AddDataToReplica(replica);
290         ProcessReplica(replica);
291         
292         return replica;
293 }
294
295
296
297 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
298 {
299         if (m_pPhysicsController1)
300                 m_pPhysicsController1->ApplyForce(force,local);
301 }
302
303
304
305 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
306 {
307         if (m_pPhysicsController1)
308                 m_pPhysicsController1->ApplyTorque(torque,local);
309 }
310
311
312
313 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
314 {
315         if (m_pPhysicsController1) // (IsDynamic())
316         {
317                 m_pPhysicsController1->RelativeTranslate(dloc,local);
318         }
319         GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
320 }
321
322
323
324 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
325 {
326         MT_Matrix3x3 rotmat(drot);
327
328         GetSGNode()->RelativeRotate(rotmat,local);
329
330         if (m_pPhysicsController1) { // (IsDynamic())
331                 m_pPhysicsController1->RelativeRotate(rotmat,local); 
332         }
333 }
334
335
336
337 /**
338 GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
339 */
340 double* KX_GameObject::GetOpenGLMatrix()
341 {
342         // todo: optimize and only update if necessary
343         double* fl = m_OpenGL_4x4Matrix.getPointer();
344         MT_Transform trans;
345         
346         trans.setOrigin(GetSGNode()->GetWorldPosition());
347         trans.setBasis(GetSGNode()->GetWorldOrientation());
348         
349         MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
350         m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
351         trans.scale(scaling[0], scaling[1], scaling[2]);
352         trans.getValue(fl);
353
354         return fl;
355 }
356
357
358
359 void KX_GameObject::Bucketize()
360 {
361         double* fl = GetOpenGLMatrix();
362
363         for (size_t i=0;i<m_meshes.size();i++)
364                 m_meshes[i]->Bucketize(fl, this, m_bUseObjectColor, m_objectColor);
365 }
366
367
368
369 void KX_GameObject::RemoveMeshes()
370 {
371         double* fl = GetOpenGLMatrix();
372
373         for (size_t i=0;i<m_meshes.size();i++)
374                 m_meshes[i]->RemoveFromBuckets(fl, this);
375
376         //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
377
378         m_meshes.clear();
379 }
380
381
382
383 void KX_GameObject::UpdateNonDynas()
384 {
385         if (m_pPhysicsController1)
386         {
387                 m_pPhysicsController1->SetSumoTransform(true);
388         }
389 }
390
391
392
393 void KX_GameObject::UpdateTransform()
394 {
395         if (m_pPhysicsController1)
396                 m_pPhysicsController1->SetSumoTransform(false);
397 }
398
399 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
400 {
401         ((KX_GameObject*)gameobj)->UpdateTransform();
402 }
403
404
405 void KX_GameObject::SetDebugColor(unsigned int bgra)
406 {
407         for (size_t i=0;i<m_meshes.size();i++)
408                 m_meshes[i]->DebugColor(bgra);  
409 }
410
411
412
413 void KX_GameObject::ResetDebugColor()
414 {
415         SetDebugColor(0xff000000);
416 }
417
418 void KX_GameObject::InitIPO(bool ipo_as_force,
419                                                         bool ipo_add,
420                                                         bool ipo_local)
421 {
422         SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
423
424         while (it != GetSGNode()->GetSGControllerList().end()) {
425                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
426                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
427                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
428                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
429                 it++;
430         }
431
432
433 void KX_GameObject::UpdateIPO(float curframetime,
434                                                           bool recurse) 
435 {
436         // just the 'normal' update procedure.
437         GetSGNode()->SetSimulatedTime(curframetime,recurse);
438         GetSGNode()->UpdateWorldData(curframetime);
439         UpdateTransform();
440 }
441
442 // IPO update
443 void 
444 KX_GameObject::UpdateMaterialData(
445                 MT_Vector4 rgba,
446                 MT_Vector3 specrgb,
447                 MT_Scalar hard,
448                 MT_Scalar spec,
449                 MT_Scalar ref,
450                 MT_Scalar emit,
451                 MT_Scalar alpha
452
453         )
454 {
455         int mesh = 0;
456         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
457                 RAS_MaterialBucket::Set::iterator mit = m_meshes[mesh]->GetFirstMaterial();
458                 for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
459                 {
460                         RAS_IPolyMaterial* poly = (*mit)->GetPolyMaterial();
461                         if(poly->GetFlag() & RAS_BLENDERMAT )
462                         {
463                                 SetObjectColor(rgba);
464                                 KX_BlenderMaterial *m =  static_cast<KX_BlenderMaterial*>(poly);
465                                 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
466                         }
467                 }
468         }
469 }
470 bool
471 KX_GameObject::GetVisible(
472         void
473         )
474 {
475         return m_bVisible;
476 }
477
478 void
479 KX_GameObject::SetVisible(
480         bool v
481         )
482 {
483         m_bVisible = v;
484 }
485
486 void
487 KX_GameObject::SetLayer(
488         int l
489         )
490 {
491         m_layer = l;
492 }
493
494 int
495 KX_GameObject::GetLayer(
496         void
497         )
498 {
499         return m_layer;
500 }
501
502 // used by Python, and the actuatorshould _not_ be misused by the
503 // scene!
504 void 
505 KX_GameObject::MarkVisible(
506         bool visible
507         )
508 {
509         /* If explicit visibility settings are used, this is
510          * determined on this level. Maybe change this to mesh level
511          * later on? */
512         
513         double* fl = GetOpenGLMatrixPtr()->getPointer();
514         for (size_t i=0;i<m_meshes.size();i++)
515         {
516                 m_meshes[i]->MarkVisible(fl,this,visible,m_bUseObjectColor,m_objectColor);
517         }
518 }
519
520
521 // Always use the flag?
522 void 
523 KX_GameObject::MarkVisible(
524         void
525         )
526 {
527         double* fl = GetOpenGLMatrixPtr()->getPointer();
528         for (size_t i=0;i<m_meshes.size();i++)
529         {
530                 m_meshes[i]->MarkVisible(fl,
531                                          this,
532                                          m_bVisible,
533                                          m_bUseObjectColor,
534                                          m_objectColor
535                         );
536         }
537 }
538
539
540 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
541 {
542         if (m_pPhysicsController1)
543                 m_pPhysicsController1->SetLinearVelocity(lin_vel + m_pPhysicsController1->GetLinearVelocity(),local);
544 }
545
546
547
548 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
549 {
550         if (m_pPhysicsController1)
551                 m_pPhysicsController1->SetLinearVelocity(lin_vel,local);
552 }
553
554
555
556 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
557 {
558         if (m_pPhysicsController1)
559                 m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
560 }
561
562 void KX_GameObject::ResolveCombinedVelocities(
563         const MT_Vector3 & lin_vel,
564         const MT_Vector3 & ang_vel,
565         bool lin_vel_local,
566         bool ang_vel_local
567 ){
568         if (m_pPhysicsController1)
569         {
570
571                 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
572                 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
573                 m_pPhysicsController1->resolveCombinedVelocities(
574                         lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
575         }
576 }
577
578
579 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
580 {
581         m_bUseObjectColor = true;
582         m_objectColor = rgbavec;
583 }
584
585 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
586 {
587         MT_Matrix3x3 orimat;
588         MT_Vector3 vect,ori,z,x,y;
589         MT_Scalar len;
590
591         vect = dir;
592         len = vect.length();
593         if (MT_fuzzyZero(len))
594         {
595                 cout << "alignAxisToVect() Error: Null vector!\n";
596                 return;
597         }
598         
599         if (fac<=0.0) {
600                 return;
601         }
602         
603         // normalize
604         vect /= len;
605         orimat = GetSGNode()->GetWorldOrientation();
606         switch (axis)
607         {       
608                 case 0: //x axis
609                         ori = MT_Vector3(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
610                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector paralell to the pivot?
611                                 ori = MT_Vector3(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
612                         if (fac == 1.0) {
613                                 x = vect;
614                         } else {
615                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
616                                 len = x.length();
617                                 if (MT_fuzzyZero(len)) x = vect;
618                                 else x /= len;
619                         }
620                         y = ori.cross(x);
621                         z = x.cross(y);
622                         break;
623                 case 1: //y axis
624                         ori = MT_Vector3(orimat[0][0], orimat[1][0], orimat[2][0]);
625                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
626                                 ori = MT_Vector3(orimat[0][2], orimat[1][2], orimat[2][2]);
627                         if (fac == 1.0) {
628                                 y = vect;
629                         } else {
630                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
631                                 len = y.length();
632                                 if (MT_fuzzyZero(len)) y = vect;
633                                 else y /= len;
634                         }
635                         z = ori.cross(y);
636                         x = y.cross(z);
637                         break;
638                 case 2: //z axis
639                         ori = MT_Vector3(orimat[0][1], orimat[1][1], orimat[2][1]);
640                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
641                                 ori = MT_Vector3(orimat[0][0], orimat[1][0], orimat[2][0]);
642                         if (fac == 1.0) {
643                                 z = vect;
644                         } else {
645                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
646                                 len = z.length();
647                                 if (MT_fuzzyZero(len)) z = vect;
648                                 else z /= len;
649                         }
650                         x = ori.cross(z);
651                         y = z.cross(x);
652                         break;
653                 default: //wrong input?
654                         cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
655                         return;
656         }
657         x.normalize(); //normalize the vectors
658         y.normalize();
659         z.normalize();
660         orimat = MT_Matrix3x3(  x[0],y[0],z[0],
661                                                         x[1],y[1],z[1],
662                                                         x[2],y[2],z[2]);
663         if (GetSGNode()->GetSGParent() != NULL)
664         {
665                 // the object is a child, adapt its local orientation so that 
666                 // the global orientation is aligned as we want.
667                 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
668                 NodeSetLocalOrientation(invori*orimat);
669         }
670         else
671                 NodeSetLocalOrientation(orimat);
672 }
673
674 MT_Scalar KX_GameObject::GetMass()
675 {
676         if (m_pPhysicsController1)
677         {
678                 return m_pPhysicsController1->GetMass();
679         }
680         return 0.0;
681 }
682
683 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
684 {
685         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
686         MT_Matrix3x3 ori;
687         if (m_pPhysicsController1)
688         {
689                 velocity = m_pPhysicsController1->GetLinearVelocity();
690                 
691                 if (local)
692                 {
693                         ori = GetSGNode()->GetWorldOrientation();
694                         
695                         locvel = velocity * ori;
696                         return locvel;
697                 }
698         }
699         return velocity;        
700 }
701
702 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
703 {
704         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
705         MT_Matrix3x3 ori;
706         if (m_pPhysicsController1)
707         {
708                 velocity = m_pPhysicsController1->GetAngularVelocity();
709                 
710                 if (local)
711                 {
712                         ori = GetSGNode()->GetWorldOrientation();
713                         
714                         locvel = velocity * ori;
715                         return locvel;
716                 }
717         }
718         return velocity;        
719 }
720
721
722
723 // scenegraph node stuff
724
725 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
726 {
727         if (m_pPhysicsController1)
728         {
729                 m_pPhysicsController1->setPosition(trans);
730         }
731
732         if (GetSGNode())
733                 GetSGNode()->SetLocalPosition(trans);
734 }
735
736
737
738 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
739 {
740         if (m_pPhysicsController1)
741         {
742                 m_pPhysicsController1->setOrientation(rot.getRotation());
743         }
744         if (GetSGNode())
745                 GetSGNode()->SetLocalOrientation(rot);
746         else
747         {
748                 int i;
749                 i=0;
750         }
751 }
752
753
754
755 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
756 {
757         if (m_pPhysicsController1)
758         {
759                 m_pPhysicsController1->setScaling(scale);
760         }
761         
762         if (GetSGNode())
763                 GetSGNode()->SetLocalScale(scale);
764 }
765
766
767
768 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
769 {
770         if (GetSGNode())
771                 GetSGNode()->RelativeScale(scale);
772 }
773
774 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
775 {
776         SG_Node* parent = m_pSGNode->GetSGParent();
777         if (parent != NULL)
778         {
779                 // Make sure the objects have some scale
780                 MT_Vector3 scale = parent->GetWorldScaling();
781                 if (fabs(scale[0]) < FLT_EPSILON || 
782                         fabs(scale[1]) < FLT_EPSILON || 
783                         fabs(scale[2]) < FLT_EPSILON)
784                 { 
785                         return; 
786                 }
787                 scale[0] = 1.0/scale[0];
788                 scale[1] = 1.0/scale[1];
789                 scale[2] = 1.0/scale[2];
790                 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
791                 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
792                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
793         }
794         else 
795         {
796                 NodeSetLocalPosition(trans);
797         }
798 }
799
800
801 void KX_GameObject::NodeUpdateGS(double time,bool bInitiator)
802 {
803         if (GetSGNode())
804                 GetSGNode()->UpdateWorldData(time);
805 }
806
807
808
809 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
810 {
811         return GetSGNode()->GetWorldOrientation();
812 }
813
814
815
816 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
817 {
818         return GetSGNode()->GetWorldScaling();
819 }
820
821
822
823 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
824 {
825         return GetSGNode()->GetWorldPosition();
826 }
827
828 /* Suspend/ resume: for the dynamic behaviour, there is a simple
829  * method. For the residual motion, there is not. I wonder what the
830  * correct solution is for Sumo. Remove from the motion-update tree?
831  *
832  * So far, only switch the physics and logic.
833  * */
834
835 void KX_GameObject::Resume(void)
836 {
837         if (m_suspended) {
838                 SCA_IObject::Resume();
839                 GetPhysicsController()->RestoreDynamics();
840
841                 m_suspended = false;
842         }
843 }
844
845 void KX_GameObject::Suspend()
846 {
847         if ((!m_ignore_activity_culling) 
848                 && (!m_suspended))  {
849                 SCA_IObject::Suspend();
850                 GetPhysicsController()->SuspendDynamics();
851                 m_suspended = true;
852         }
853 }
854
855
856
857
858 /* ------- python stuff ---------------------------------------------------*/
859
860
861
862
863 PyMethodDef KX_GameObject::Methods[] = {
864         {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
865         {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
866         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
867         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
868         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
869         {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
870         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
871         {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
872         {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
873         {"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
874         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_O},
875         {"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
876         {"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
877         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
878         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
879         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
880         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
881         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
882         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
883         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
884         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
885         {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_NOARGS},
886         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_O},
887         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
888         {"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
889         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
890         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
891         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
892         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
893         KX_PYMETHODTABLE(KX_GameObject, rayCast),
894         KX_PYMETHODTABLE(KX_GameObject, getDistanceTo),
895         {NULL,NULL} //Sentinel
896 };
897
898
899
900 /*
901 bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
902                                                                                         MT_Vector3& pos,
903                                                                                         MT_Vector3& pos2)
904 {
905         PyObject* pylist;
906         PyObject* pylist2;
907         bool error = (PyArg_ParseTuple(args,"OO",&pylist,&pylist2)) != 0;
908
909         pos = ConvertPythonPylist(pylist);
910         pos2 = ConvertPythonPylist(pylist2);
911                 
912         return error;
913 }
914 */
915
916 PyObject* KX_GameObject::PyEndObject(PyObject* self)
917 {
918
919         KX_Scene *scene = PHY_GetActiveScene();
920         scene->DelayedRemoveObject(this);
921         
922         return Py_None;
923
924 }
925
926
927 PyObject* KX_GameObject::PyGetPosition(PyObject* self)
928 {
929         return PyObjectFrom(NodeGetWorldPosition());
930 }
931
932
933
934 PyTypeObject KX_GameObject::Type = {
935         PyObject_HEAD_INIT(&PyType_Type)
936                 0,
937                 "KX_GameObject",
938                 sizeof(KX_GameObject),
939                 0,
940                 PyDestructor,
941                 0,
942                 __getattr,
943                 __setattr,
944                 0, //&MyPyCompare,
945                 __repr,
946                 0, //&cvalue_as_number,
947                 0,
948                 0,
949                 0,
950                 0
951 };
952
953
954
955 PyParentObject KX_GameObject::Parents[] = {
956         &KX_GameObject::Type,
957                 &SCA_IObject::Type,
958                 &CValue::Type,
959                 NULL
960 };
961
962
963
964
965 PyObject* KX_GameObject::_getattr(const STR_String& attr)
966 {
967         if (m_pPhysicsController1)
968         {
969                 if (attr == "mass")
970                         return PyFloat_FromDouble(GetPhysicsController()->GetMass());
971         }
972
973         if (attr == "parent")
974         {       
975                 KX_GameObject* parent = GetParent();
976                 if (parent)
977                 {
978                         parent->AddRef();
979                         return parent;
980                 }
981                 Py_RETURN_NONE;
982         }
983
984         if (attr == "visible")
985                 return PyInt_FromLong(m_bVisible);
986         
987         if (attr == "position")
988                 return PyObjectFrom(NodeGetWorldPosition());
989         
990         if (attr == "orientation")
991                 return PyObjectFrom(NodeGetWorldOrientation());
992         
993         if (attr == "scaling")
994                 return PyObjectFrom(NodeGetWorldScaling());
995                 
996         if (attr == "name")
997                 return PyString_FromString(m_name.ReadPtr());
998         if (attr == "timeOffset") {
999                 if (m_pSGNode->GetSGParent()->IsSlowParent()) {
1000                         return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(m_pSGNode->GetSGParent()->GetParentRelation())->GetTimeOffset());
1001                 } else {
1002                         return PyFloat_FromDouble(0.0);
1003                 }
1004         }
1005         
1006         
1007         _getattr_up(SCA_IObject);
1008 }
1009
1010 int KX_GameObject::_setattr(const STR_String& attr, PyObject *value)    // _setattr method
1011 {
1012         if (attr == "mass")
1013                 return 1;
1014         
1015         if (attr == "parent")
1016                 return 1;
1017                 
1018         if (PyInt_Check(value))
1019         {
1020                 int val = PyInt_AsLong(value);
1021                 if (attr == "visible")
1022                 {
1023                         SetVisible(val != 0);
1024                         return 0;
1025                 }
1026         }
1027
1028         if (PyFloat_Check(value))
1029         {
1030                 MT_Scalar val = PyFloat_AsDouble(value);
1031                 if (attr == "timeOffset") {
1032                         if (m_pSGNode->GetSGParent() && m_pSGNode->GetSGParent()->IsSlowParent()) {
1033                                 static_cast<KX_SlowParentRelation *>(m_pSGNode->GetSGParent()->GetParentRelation())->SetTimeOffset(val);
1034                                 return 0;
1035                         } else {
1036                                 return 0;
1037                         }               
1038                 }
1039         }
1040         
1041         if (PySequence_Check(value))
1042         {
1043                 if (attr == "orientation")
1044                 {
1045                         MT_Matrix3x3 rot;
1046                         if (PyObject_IsMT_Matrix(value, 3))
1047                         {
1048                                 if (PyMatTo(value, rot))
1049                                 {
1050                                         NodeSetLocalOrientation(rot);
1051                                         NodeUpdateGS(0.f,true);
1052                                         return 0;
1053                                 }
1054                                 return 1;
1055                         }
1056                         
1057                         if (PySequence_Size(value) == 4)
1058                         {
1059                                 MT_Quaternion qrot;
1060                                 if (PyVecTo(value, qrot))
1061                                 {
1062                                         rot.setRotation(qrot);
1063                                         NodeSetLocalOrientation(rot);
1064                                         NodeUpdateGS(0.f,true);
1065                                         return 0;
1066                                 }
1067                                 return 1;
1068                         }
1069                         
1070                         if (PySequence_Size(value) == 3)
1071                         {
1072                                 MT_Vector3 erot;
1073                                 if (PyVecTo(value, erot))
1074                                 {
1075                                         rot.setEuler(erot);
1076                                         NodeSetLocalOrientation(rot);
1077                                         NodeUpdateGS(0.f,true);
1078                                         return 0;
1079                                 }
1080                                 return 1;
1081                         }
1082                         
1083                         return 1;
1084                 }
1085                 
1086                 if (attr == "position")
1087                 {
1088                         MT_Point3 pos;
1089                         if (PyVecTo(value, pos))
1090                         {
1091                                 NodeSetLocalPosition(pos);
1092                                 NodeUpdateGS(0.f,true);
1093                                 return 0;
1094                         }
1095                         return 1;
1096                 }
1097                 
1098                 if (attr == "scaling")
1099                 {
1100                         MT_Vector3 scale;
1101                         if (PyVecTo(value, scale))
1102                         {
1103                                 NodeSetLocalScale(scale);
1104                                 NodeUpdateGS(0.f,true);
1105                                 return 0;
1106                         }
1107                         return 1;
1108                 }
1109         }
1110         
1111         if (PyString_Check(value))
1112         {
1113                 if (attr == "name")
1114                 {
1115                         m_name = PyString_AsString(value);
1116                         return 0;
1117                 }
1118         }
1119         
1120         /* Need to have parent settable here too */
1121         
1122         return SCA_IObject::_setattr(attr, value);
1123 }
1124
1125
1126 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, 
1127                                                                                          PyObject* args, 
1128                                                                                          PyObject* kwds)
1129 {
1130         // only can get the velocity if we have a physics object connected to us...
1131         int local = 0;
1132         if (PyArg_ParseTuple(args,"|i",&local))
1133         {
1134                 return PyObjectFrom(GetLinearVelocity((local!=0)));
1135         }
1136         else
1137         {
1138                 return NULL;
1139         }
1140 }
1141
1142 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self, 
1143                                                                                          PyObject* args, 
1144                                                                                          PyObject* kwds)
1145 {
1146         int local = 0;
1147         PyObject* pyvect;
1148         
1149         if (PyArg_ParseTuple(args,"O|i",&pyvect,&local)) {
1150                 MT_Vector3 velocity;
1151                 if (PyVecTo(pyvect, velocity)) {
1152                         setLinearVelocity(velocity, (local!=0));
1153                         Py_RETURN_NONE;
1154                 }
1155         }
1156         return NULL;
1157 }
1158
1159 PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* value)
1160 {
1161         int visible = PyInt_AsLong(value);
1162         
1163         if (visible==-1 && PyErr_Occurred()) {
1164                 PyErr_SetString(PyExc_TypeError, "expected 0 or 1");
1165                 return NULL;
1166         }
1167         
1168         MarkVisible(visible!=0);
1169         m_bVisible = (visible!=0);
1170         Py_RETURN_NONE;
1171         
1172 }
1173
1174 PyObject* KX_GameObject::PyGetVisible(PyObject* self)
1175 {
1176         return PyInt_FromLong(m_bVisible);      
1177 }
1178
1179 PyObject* KX_GameObject::PyGetState(PyObject* self)
1180 {
1181         int state = 0;
1182         state |= GetState();
1183         return PyInt_FromLong(state);
1184 }
1185
1186 PyObject* KX_GameObject::PySetState(PyObject* self, PyObject* value)
1187 {
1188         int state_i = PyInt_AsLong(value);
1189         unsigned int state = 0;
1190         
1191         if (state_i == -1 && PyErr_Occurred()) {
1192                 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
1193                 return NULL;
1194         }
1195         
1196         state |= state_i;
1197         if ((state & ((1<<30)-1)) == 0) {
1198                 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1199                 return NULL;
1200         }
1201         SetState(state);
1202         
1203         Py_RETURN_NONE;
1204 }
1205
1206
1207
1208 PyObject* KX_GameObject::PyGetVelocity(PyObject* self, 
1209                                                                            PyObject* args, 
1210                                                                            PyObject* kwds)
1211 {
1212         // only can get the velocity if we have a physics object connected to us...
1213         MT_Vector3 velocity(0.0,0.0,0.0);
1214         MT_Point3 point(0.0,0.0,0.0);
1215         
1216         
1217         PyObject* pypos = NULL;
1218         if (PyArg_ParseTuple(args, "|O", &pypos))
1219         {
1220                 if (pypos)
1221                         PyVecTo(pypos, point);
1222         }
1223         else {
1224                 return NULL;
1225         }
1226         
1227         if (m_pPhysicsController1)
1228         {
1229                 velocity = m_pPhysicsController1->GetVelocity(point);
1230         }
1231         
1232         return PyObjectFrom(velocity);
1233 }
1234
1235
1236
1237 PyObject* KX_GameObject::PyGetMass(PyObject* self)
1238 {
1239         return PyFloat_FromDouble(GetPhysicsController()->GetMass());
1240 }
1241
1242
1243
1244 PyObject* KX_GameObject::PyGetReactionForce(PyObject* self)
1245 {
1246         // only can get the velocity if we have a physics object connected to us...
1247         return PyObjectFrom(GetPhysicsController()->getReactionForce());
1248 }
1249
1250
1251
1252 PyObject* KX_GameObject::PyEnableRigidBody(PyObject* self)
1253 {
1254         GetPhysicsController()->setRigidBody(true);
1255
1256         Py_RETURN_NONE;
1257 }
1258
1259
1260
1261 PyObject* KX_GameObject::PyDisableRigidBody(PyObject* self)
1262 {
1263         GetPhysicsController()->setRigidBody(false);
1264
1265         Py_RETURN_NONE;
1266 }
1267
1268
1269
1270 PyObject* KX_GameObject::PyGetParent(PyObject* self)
1271 {
1272         KX_GameObject* parent = this->GetParent();
1273         if (parent)
1274         {
1275                 parent->AddRef();
1276                 return parent;
1277         }
1278         Py_RETURN_NONE;
1279 }
1280
1281 PyObject* KX_GameObject::PySetParent(PyObject* self, PyObject* value)
1282 {
1283         if (!PyObject_TypeCheck(value, &KX_GameObject::Type)) {
1284                 PyErr_SetString(PyExc_TypeError, "expected a KX_GameObject type");
1285                 return NULL;
1286         }
1287         
1288         // The object we want to set as parent
1289         CValue *m_ob = (CValue*)value;
1290         KX_GameObject *obj = ((KX_GameObject*)m_ob);
1291         KX_Scene *scene = PHY_GetActiveScene();
1292         
1293         this->SetParent(scene, obj);
1294                 
1295         Py_RETURN_NONE;
1296 }
1297
1298 PyObject* KX_GameObject::PyRemoveParent(PyObject* self)
1299 {
1300         KX_Scene *scene = PHY_GetActiveScene();
1301         this->RemoveParent(scene);
1302         Py_RETURN_NONE;
1303 }
1304
1305 PyObject* KX_GameObject::PyGetMesh(PyObject* self, 
1306                                                                    PyObject* args, 
1307                                                                    PyObject* kwds)
1308 {
1309         int mesh = 0;
1310
1311         if (PyArg_ParseTuple(args, "|i", &mesh))
1312         {
1313                 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
1314                 {
1315                         KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
1316                         return meshproxy;
1317                 }
1318         }
1319         Py_RETURN_NONE;
1320 }
1321
1322
1323
1324
1325
1326 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self, PyObject* value)
1327 {
1328         float collisionMargin = PyFloat_AsDouble(value);
1329         
1330         if (collisionMargin==-1 && PyErr_Occurred()) {
1331                 PyErr_SetString(PyExc_TypeError, "expected a float");
1332                 return NULL;
1333         }
1334         
1335         if (m_pPhysicsController1)
1336         {
1337                 m_pPhysicsController1->setMargin(collisionMargin);
1338                 Py_RETURN_NONE;
1339         }
1340         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
1341         return NULL;
1342 }
1343
1344
1345
1346 PyObject* KX_GameObject::PyApplyImpulse(PyObject* self, 
1347                                                                                 PyObject* args, 
1348                                                                                 PyObject* kwds)
1349 {
1350         PyObject* pyattach;
1351         PyObject* pyimpulse;
1352         
1353         if (!m_pPhysicsController1)     {
1354                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
1355                 return NULL;
1356         }
1357         
1358         if (PyArg_ParseTuple(args, "OO", &pyattach, &pyimpulse))
1359         {
1360                 MT_Point3  attach;
1361                 MT_Vector3 impulse;
1362                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
1363                 {
1364                         m_pPhysicsController1->applyImpulse(attach, impulse);
1365                         Py_RETURN_NONE;
1366                 }
1367
1368         }
1369         
1370         return NULL;
1371 }
1372
1373
1374
1375 PyObject* KX_GameObject::PySuspendDynamics(PyObject* self)
1376 {
1377         SuspendDynamics();
1378         Py_RETURN_NONE;
1379 }
1380
1381
1382
1383 PyObject* KX_GameObject::PyRestoreDynamics(PyObject* self)
1384 {
1385         RestoreDynamics();
1386         Py_RETURN_NONE;
1387 }
1388
1389
1390
1391 PyObject* KX_GameObject::PyGetOrientation(PyObject* self) //keywords
1392 {
1393         return PyObjectFrom(NodeGetWorldOrientation());
1394 }
1395
1396
1397
1398 PyObject* KX_GameObject::PySetOrientation(PyObject* self, PyObject* value)
1399 {
1400         MT_Matrix3x3 matrix;
1401         if (PyObject_IsMT_Matrix(value, 3) && PyMatTo(value, matrix))
1402         {
1403                 NodeSetLocalOrientation(matrix);
1404                 NodeUpdateGS(0.f,true);
1405                 Py_RETURN_NONE;
1406         }
1407
1408         MT_Quaternion quat;
1409         if (PyVecTo(value, quat))
1410         {
1411                 matrix.setRotation(quat);
1412                 NodeSetLocalOrientation(matrix);
1413                 NodeUpdateGS(0.f,true);
1414                 Py_RETURN_NONE;
1415         }
1416         return NULL;
1417 }
1418
1419 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* self, 
1420                                                                                   PyObject* args, 
1421                                                                                   PyObject* kwds)
1422 {
1423         PyObject* pyvect;
1424         int axis = 2; //z axis is the default
1425         float fac = 1.0;
1426         
1427         if (PyArg_ParseTuple(args,"O|if",&pyvect,&axis, &fac))
1428         {
1429                 MT_Vector3 vect;
1430                 if (PyVecTo(pyvect, vect))
1431                 {
1432                         AlignAxisToVect(vect,axis,fac);
1433                         Py_RETURN_NONE;
1434                 }
1435         }
1436         return NULL;
1437 }
1438
1439 PyObject* KX_GameObject::PyGetAxisVect(PyObject* self, PyObject* value)
1440 {
1441         MT_Vector3 vect;
1442         if (PyVecTo(value, vect))
1443         {
1444                 return PyObjectFrom(NodeGetWorldOrientation() * vect);
1445         }
1446         return NULL;
1447 }
1448
1449 PyObject* KX_GameObject::PySetPosition(PyObject* self, PyObject* value)
1450 {
1451         MT_Point3 pos;
1452         if (PyVecTo(value, pos))
1453         {
1454                 NodeSetLocalPosition(pos);
1455                 NodeUpdateGS(0.f,true);
1456                 Py_RETURN_NONE;
1457         }
1458
1459         return NULL;
1460 }
1461
1462 PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self)
1463 {
1464         KX_IPhysicsController* ctrl = GetPhysicsController();
1465         uint_ptr physid=0;
1466         if (ctrl)
1467         {
1468                 physid= (uint_ptr)ctrl->GetUserData();
1469         }
1470         return PyInt_FromLong((long)physid);
1471 }
1472
1473 PyObject* KX_GameObject::PyGetPropertyNames(PyObject* self)
1474 {
1475         return ConvertKeysToPython();
1476 }
1477
1478 KX_PYMETHODDEF_DOC(KX_GameObject, getDistanceTo,
1479 "getDistanceTo(other): get distance to another point/KX_GameObject")
1480 {
1481         MT_Point3 b;
1482         if (PyVecArgTo(args, b))
1483         {
1484                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
1485         }
1486         PyErr_Clear();
1487         
1488         PyObject *pyother;
1489         if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &pyother))
1490         {
1491                 KX_GameObject *other = static_cast<KX_GameObject*>(pyother);
1492                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
1493         }
1494         
1495         return NULL;
1496 }
1497
1498 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
1499 {
1500
1501         KX_GameObject* hitKXObj = client->m_gameobject;
1502         
1503         if (client->m_type > KX_ClientObjectInfo::ACTOR)
1504         {
1505                 // false hit
1506                 return false;
1507         }
1508
1509         if (m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
1510         {
1511                 m_pHitObject = hitKXObj;
1512                 return true;
1513         }
1514
1515         return false;
1516         
1517 }
1518
1519 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
1520 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
1521 " prop = property name that object must have; can be omitted => detect any object\n"
1522 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
1523 " other = 3-tuple or object reference")
1524 {
1525         MT_Point3 toPoint;
1526         PyObject* pyarg;
1527         float dist = 0.0f;
1528         char *propName = NULL;
1529
1530         if (!PyArg_ParseTuple(args,"O|fs", &pyarg, &dist, &propName))
1531                 return NULL;
1532
1533         if (!PyVecTo(pyarg, toPoint))
1534         {
1535                 KX_GameObject *other;
1536                 PyErr_Clear();
1537                 if (!PyType_IsSubtype(pyarg->ob_type, &KX_GameObject::Type)) {
1538                         PyErr_SetString(PyExc_TypeError, "the first argument to rayCastTo must be a vector or a KX_GameObject");
1539                         return NULL;
1540                 }
1541                 other = static_cast<KX_GameObject*>(pyarg);
1542                 toPoint = other->NodeGetWorldPosition();
1543         }
1544         MT_Point3 fromPoint = NodeGetWorldPosition();
1545         if (dist != 0.0f)
1546         {
1547                 MT_Vector3 toDir = toPoint-fromPoint;
1548                 toDir.normalize();
1549                 toPoint = fromPoint + (dist) * toDir;
1550         }
1551
1552         MT_Point3 resultPoint;
1553         MT_Vector3 resultNormal;
1554         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
1555         KX_IPhysicsController *spc = GetPhysicsController();
1556         KX_GameObject *parent = GetParent();
1557         if (!spc && parent)
1558                 spc = parent->GetPhysicsController();
1559         if (parent)
1560                 parent->Release();
1561         
1562         m_pHitObject = NULL;
1563         if (propName)
1564                 m_testPropName = propName;
1565         else
1566                 m_testPropName.SetLength(0);
1567         KX_RayCast::RayTest(spc, pe, fromPoint, toPoint, resultPoint, resultNormal, KX_RayCast::Callback<KX_GameObject>(this));
1568
1569     if (m_pHitObject)
1570         {
1571                 m_pHitObject->AddRef();
1572                 return m_pHitObject;
1573         }
1574         Py_RETURN_NONE;
1575 }
1576
1577 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
1578 "rayCast(to,from,dist,prop): cast a ray and return tuple (object,hit,normal) of contact point with object within dist that matches prop or None if no hit\n"
1579 " prop = property name that object must have; can be omitted => detect any object\n"
1580 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
1581 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
1582 "        Can None or omitted => start from self object center\n"
1583 " to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
1584 "Note: the object on which you call this method matters: the ray will ignore it if it goes through it\n")
1585 {
1586         MT_Point3 toPoint;
1587         MT_Point3 fromPoint;
1588         PyObject* pyto;
1589         PyObject* pyfrom = NULL;
1590         float dist = 0.0f;
1591         char *propName = NULL;
1592         KX_GameObject *other;
1593
1594         if (!PyArg_ParseTuple(args,"O|Ofs", &pyto, &pyfrom, &dist, &propName))
1595                 return NULL;
1596
1597         if (!PyVecTo(pyto, toPoint))
1598         {
1599                 PyErr_Clear();
1600                 if (!PyType_IsSubtype(pyto->ob_type, &KX_GameObject::Type)) {
1601                         PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
1602                         return NULL;
1603                 }
1604                 other = static_cast<KX_GameObject*>(pyto);
1605                 toPoint = other->NodeGetWorldPosition();
1606         }
1607         if (!pyfrom || pyfrom == Py_None)
1608         {
1609                 fromPoint = NodeGetWorldPosition();
1610         }
1611         else if (!PyVecTo(pyfrom, fromPoint))
1612         {
1613                 PyErr_Clear();
1614                 if (!PyType_IsSubtype(pyfrom->ob_type, &KX_GameObject::Type)) {
1615                         PyErr_SetString(PyExc_TypeError, "the second optional argument to rayCast must be a vector or a KX_GameObject");
1616                         return NULL;
1617                 }
1618                 other = static_cast<KX_GameObject*>(pyfrom);
1619                 fromPoint = other->NodeGetWorldPosition();
1620         }
1621         
1622         if (dist != 0.0f) {
1623                 MT_Vector3 toDir = toPoint-fromPoint;
1624                 if (MT_fuzzyZero(toDir.length2())) {
1625                         return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
1626                 }
1627                 toDir.normalize();
1628                 toPoint = fromPoint + (dist) * toDir;
1629         } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
1630                 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
1631         }
1632         
1633         MT_Point3 resultPoint;
1634         MT_Vector3 resultNormal;
1635         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
1636         KX_IPhysicsController *spc = GetPhysicsController();
1637         KX_GameObject *parent = GetParent();
1638         if (!spc && parent)
1639                 spc = parent->GetPhysicsController();
1640         if (parent)
1641                 parent->Release();
1642         
1643         m_pHitObject = NULL;
1644         if (propName)
1645                 m_testPropName = propName;
1646         else
1647                 m_testPropName.SetLength(0);
1648         KX_RayCast::RayTest(spc, pe, fromPoint, toPoint, resultPoint, resultNormal, KX_RayCast::Callback<KX_GameObject>(this));
1649
1650     if (m_pHitObject)
1651         {
1652                 PyObject* returnValue = PyTuple_New(3);
1653                 if (!returnValue)
1654                         return NULL;
1655                 PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->AddRef());
1656                 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(resultPoint));
1657                 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(resultNormal));
1658                 return returnValue;
1659                 //return Py_BuildValue("(O,(fff),(fff))", 
1660                 //      m_pHitObject->AddRef(),         // trick: KX_GameObject are not true Python object, they use a difference reference count system
1661                 //      resultPoint[0], resultPoint[1], resultPoint[2],
1662                 //      resultNormal[0], resultNormal[1], resultNormal[2]);
1663         }
1664         return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
1665         //Py_RETURN_NONE;
1666 }
1667
1668 /* --------------------------------------------------------------------- 
1669  * Some stuff taken from the header
1670  * --------------------------------------------------------------------- */
1671 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)        
1672 {
1673         // we will relink the sensors and actuators that use object references
1674         // if the object is part of the replicated hierarchy, use the new
1675         // object reference instead
1676         SCA_SensorList& sensorlist = GetSensors();
1677         SCA_SensorList::iterator sit;
1678         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
1679         {
1680                 (*sit)->Relink(map_parameter);
1681         }
1682         SCA_ActuatorList& actuatorlist = GetActuators();
1683         SCA_ActuatorList::iterator ait;
1684         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1685         {
1686                 (*ait)->Relink(map_parameter);
1687         }
1688 }
1689