BGE showstopper bug fix:
[blender.git] / source / gameengine / Ketsji / KX_TouchSensor.cpp
1 /**
2  * Senses touch and collision events
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "KX_TouchSensor.h"
33 #include "SCA_EventManager.h"
34 #include "SCA_LogicManager.h"
35 #include "KX_GameObject.h"
36 #include "KX_TouchEventManager.h"
37 #include "KX_SumoPhysicsController.h"
38 #include <iostream>
39 #include "PHY_IPhysicsEnvironment.h"
40
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif
44
45 /* ------------------------------------------------------------------------- */
46 /* Native functions                                                          */
47 /* ------------------------------------------------------------------------- */
48
49 void KX_TouchSensor::SynchronizeTransform()
50 {
51         // the touch sensor does not require any synchronization: it uses
52         // the same physical object which is already synchronized by Blender
53 }
54
55
56 void KX_TouchSensor::EndFrame() {
57         m_colliders->ReleaseAndRemoveAll();
58         m_hitObject = NULL;
59         m_bTriggered = false;
60 }
61
62 void KX_TouchSensor::UnregisterToManager()
63 {
64         // before unregistering the sensor, make sure we release all references
65         EndFrame();
66         m_eventmgr->RemoveSensor(this);
67 }
68
69 bool KX_TouchSensor::Evaluate(CValue* event)
70 {
71         bool result = false;
72         bool reset = m_reset && m_level;
73
74         m_reset = false;
75         if (m_bTriggered != m_bLastTriggered)
76         {
77                 m_bLastTriggered = m_bTriggered;
78                 if (!m_bTriggered)
79                         m_hitObject = NULL;
80                 result = true;
81         }
82         if (reset)
83                 // force an event
84                 result = true;
85         return result;
86 }
87
88 KX_TouchSensor::KX_TouchSensor(SCA_EventManager* eventmgr,KX_GameObject* gameobj,bool bFindMaterial,const STR_String& touchedpropname,PyTypeObject* T)
89 :SCA_ISensor(gameobj,eventmgr,T),
90 m_touchedpropname(touchedpropname),
91 m_bFindMaterial(bFindMaterial),
92 m_eventmgr(eventmgr)
93 /*m_sumoObj(sumoObj),*/
94 {
95 //      KX_TouchEventManager* touchmgr = (KX_TouchEventManager*) eventmgr;
96 //      m_resptable = touchmgr->GetResponseTable();
97         
98 //      m_solidHandle = m_sumoObj->getObjectHandle();
99
100         m_colliders = new CListValue();
101         
102         KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
103         client_info->m_gameobject = gameobj;
104         client_info->m_auxilary_info = NULL;
105         client_info->m_sensors.push_back(this);
106         
107         m_physCtrl = dynamic_cast<PHY_IPhysicsController*>(gameobj->GetPhysicsController());
108         MT_assert( !gameobj->GetPhysicsController() || m_physCtrl );
109         Init();
110 }
111
112 void KX_TouchSensor::Init()
113 {
114         m_bCollision = false;
115         m_bTriggered = false;
116         m_bLastTriggered = (m_invert)?true:false;
117         m_hitObject =  NULL;
118         m_reset = true;
119 }
120
121 KX_TouchSensor::~KX_TouchSensor()
122 {
123         //DT_ClearObjectResponse(m_resptable,m_solidHandle);
124         m_colliders->Release();
125 }
126
127 CValue* KX_TouchSensor::GetReplica() 
128 {
129         KX_TouchSensor* replica = new KX_TouchSensor(*this);
130         replica->m_colliders = new CListValue();
131         replica->Init();
132         // this will copy properties and so on...
133         CValue::AddDataToReplica(replica);
134         return replica;
135 }
136
137 void    KX_TouchSensor::ReParent(SCA_IObject* parent)
138 {
139         KX_GameObject *gameobj = static_cast<KX_GameObject *>(parent);
140         PHY_IPhysicsController *sphy = dynamic_cast<PHY_IPhysicsController*>(((KX_GameObject*)parent)->GetPhysicsController());
141         if (sphy)
142                 m_physCtrl = sphy;
143         
144 //      m_solidHandle = m_sumoObj->getObjectHandle();
145         KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
146         client_info->m_gameobject = gameobj;
147         client_info->m_auxilary_info = NULL;
148         
149         client_info->m_sensors.push_back(this);
150         SCA_ISensor::ReParent(parent);
151 }
152
153 void KX_TouchSensor::RegisterSumo(KX_TouchEventManager *touchman)
154 {
155         if (m_physCtrl)
156         {
157                 touchman->GetPhysicsEnvironment()->requestCollisionCallback(m_physCtrl);
158                 // collision
159                 // Deprecated   
160
161         }
162 }
163
164 void KX_TouchSensor::UnregisterSumo(KX_TouchEventManager* touchman)
165 {
166         if (m_physCtrl)
167         {
168                 touchman->GetPhysicsEnvironment()->removeCollisionCallback(m_physCtrl);
169         }
170 }
171
172 bool    KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_CollData* colldata)
173 {
174 //      KX_TouchEventManager* toucheventmgr = (KX_TouchEventManager*)m_eventmgr;
175         KX_GameObject* parent = (KX_GameObject*)GetParent();
176
177         // need the mapping from PHY_IPhysicsController to gameobjects now
178         
179         KX_ClientObjectInfo* client_info = static_cast<KX_ClientObjectInfo*> (object1 == m_physCtrl? 
180                                         ((PHY_IPhysicsController*)object2)->getNewClientInfo(): 
181                                         ((PHY_IPhysicsController*)object1)->getNewClientInfo());
182
183         KX_GameObject* gameobj = ( client_info ? 
184                         client_info->m_gameobject : 
185                         NULL);
186         
187         if (gameobj && (gameobj != parent) && client_info->isActor())
188         {
189                 if (!m_colliders->SearchValue(gameobj))
190                         m_colliders->Add(gameobj->AddRef());
191                 
192                 bool found = m_touchedpropname.IsEmpty();
193                 if (!found)
194                 {
195                         if (m_bFindMaterial)
196                         {
197                                 if (client_info->m_auxilary_info)
198                                 {
199                                         found = (m_touchedpropname == STR_String((char*)client_info->m_auxilary_info));
200                                 }
201                         } else
202                         {
203                                 found = (gameobj->GetProperty(m_touchedpropname) != NULL);
204                         }
205                 }
206                 if (found)
207                 {
208                         m_bTriggered = true;
209                         m_hitObject = gameobj;
210                         //printf("KX_TouchSensor::HandleCollision\n");
211                 }
212                 
213         } 
214         return DT_CONTINUE;
215 }
216
217
218 /* ------------------------------------------------------------------------- */
219 /* Python functions                                                          */
220 /* ------------------------------------------------------------------------- */
221 /* Integration hooks ------------------------------------------------------- */
222 PyTypeObject KX_TouchSensor::Type = {
223         PyObject_HEAD_INIT(&PyType_Type)
224         0,
225         "KX_TouchSensor",
226         sizeof(KX_TouchSensor),
227         0,
228         PyDestructor,
229         0,
230         __getattr,
231         __setattr,
232         0, //&MyPyCompare,
233         __repr,
234         0, //&cvalue_as_number,
235         0,
236         0,
237         0,
238         0
239 };
240
241 PyParentObject KX_TouchSensor::Parents[] = {
242         &KX_TouchSensor::Type,
243         &SCA_ISensor::Type,
244         &SCA_ILogicBrick::Type,
245         &CValue::Type,
246         NULL
247 };
248
249 PyMethodDef KX_TouchSensor::Methods[] = {
250         {"setProperty", 
251          (PyCFunction) KX_TouchSensor::sPySetProperty,      METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
252         {"getProperty", 
253          (PyCFunction) KX_TouchSensor::sPyGetProperty,      METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
254         {"getHitObject", 
255          (PyCFunction) KX_TouchSensor::sPyGetHitObject,     METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
256         {"getHitObjectList", 
257          (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_VARARGS, (PY_METHODCHAR)GetHitObjectList_doc},
258         {NULL,NULL} //Sentinel
259 };
260
261 PyObject* KX_TouchSensor::_getattr(const STR_String& attr) {
262         _getattr_up(SCA_ISensor);
263 }
264
265 /* Python API */
266
267 /* 1. setProperty */
268 const char KX_TouchSensor::SetProperty_doc[] = 
269 "setProperty(name)\n"
270 "\t- name: string\n"
271 "\tSet the property or material to collide with. Use\n"
272 "\tsetTouchMaterial() to switch between properties and\n"
273 "\tmaterials.";
274 PyObject* KX_TouchSensor::PySetProperty(PyObject* self, 
275                                                                                 PyObject* args, 
276                                                                                 PyObject* kwds) {
277         char *nameArg;
278         if (!PyArg_ParseTuple(args, "s", &nameArg)) {
279                 return NULL;
280         }
281
282         CValue* prop = GetParent()->FindIdentifier(nameArg);
283
284         if (!prop->IsError()) {
285                 m_touchedpropname = nameArg;
286         } else {
287                 ; /* not found ... */
288         }
289         prop->Release();
290         
291         Py_Return;
292 }
293 /* 2. getProperty */
294 const char KX_TouchSensor::GetProperty_doc[] = 
295 "getProperty(name)\n"
296 "\tReturns the property or material to collide with. Use\n"
297 "\tgetTouchMaterial() to find out whether this sensor\n"
298 "\tlooks for properties or materials.";
299 PyObject*  KX_TouchSensor::PyGetProperty(PyObject* self, 
300                                                                                  PyObject* args, 
301                                                                                  PyObject* kwds) {
302         return PyString_FromString(m_touchedpropname);
303 }
304
305 const char KX_TouchSensor::GetHitObject_doc[] = 
306 "getHitObject()\n"
307 ;
308 PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self, 
309                                                                                  PyObject* args, 
310                                                                                  PyObject* kwds)
311 {
312         /* to do: do Py_IncRef if the object is already known in Python */
313         /* otherwise, this leaks memory */
314         if (m_hitObject)
315         {
316                 return m_hitObject->AddRef();
317         }
318         Py_Return;
319 }
320
321 const char KX_TouchSensor::GetHitObjectList_doc[] = 
322 "getHitObjectList()\n"
323 "\tReturn a list of the objects this object collided with,\n"
324 "\tbut only those matching the property/material condition.\n";
325 PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self, 
326                                                                                  PyObject* args, 
327                                                                                  PyObject* kwds)
328 {
329
330         /* to do: do Py_IncRef if the object is already known in Python */
331         /* otherwise, this leaks memory */
332
333         if ( m_touchedpropname.IsEmpty() ) {
334                 return m_colliders->AddRef();
335         } else {
336                 CListValue* newList = new CListValue();
337                 int i = 0;
338                 while (i < m_colliders->GetCount()) {
339                         if (m_bFindMaterial) {
340                                 /* need to associate the CValues from the list to material
341                                  * names. The collider list _should_ contains only
342                                  * KX_GameObjects. I am loathe to cast them, though... The
343                                  * material name must be retrieved from Sumo. To a Sumo
344                                  * object, a client-info block is attached. This block
345                                  * contains the material name. 
346                                  * - this also doesn't work (obviously) for multi-materials... 
347                                  */
348                                 KX_GameObject* gameob = (KX_GameObject*) m_colliders->GetValue(i);
349                                 PHY_IPhysicsController* spc = dynamic_cast<PHY_IPhysicsController*>(gameob->GetPhysicsController());
350                                 
351                                 if (spc) {
352                                         KX_ClientObjectInfo* cl_inf = static_cast<KX_ClientObjectInfo*>(spc->getNewClientInfo());
353                                         
354                                         if (m_touchedpropname == ((char*)cl_inf->m_auxilary_info)) {
355                                                 newList->Add(m_colliders->GetValue(i)->AddRef());
356                                         } 
357                                 }
358                                 
359                         } else {
360                                 CValue* val = m_colliders->GetValue(i)->FindIdentifier(m_touchedpropname);
361                                 if (!val->IsError()) {
362                                         newList->Add(m_colliders->GetValue(i)->AddRef());
363                                 }
364                                 val->Release();
365                         }
366                         
367                         i++;
368                 }
369                 return newList->AddRef();
370         }
371
372 }
373
374 /* 5. getTouchMaterial */
375 const char KX_TouchSensor::GetTouchMaterial_doc[] = 
376 "getTouchMaterial()\n"
377 "\tReturns KX_TRUE if this sensor looks for a specific material,\n"
378 "\tKX_FALSE if it looks for a specific property.\n" ;
379 PyObject* KX_TouchSensor::PyGetTouchMaterial(PyObject* self, 
380                                                                                          PyObject* args, 
381                                                                                          PyObject* kwds)
382 {
383         return PyInt_FromLong(m_bFindMaterial);
384 }
385
386 /* 6. setTouchMaterial */
387 const char KX_TouchSensor::SetTouchMaterial_doc[] = 
388 "setTouchMaterial(flag)\n"
389 "\t- flag: KX_TRUE or KX_FALSE.\n"
390 "\tSet flag to KX_TRUE to switch on positive pulse mode,\n"
391 "\tKX_FALSE to switch off positive pulse mode.\n" ;
392 PyObject* KX_TouchSensor::PySetTouchMaterial(PyObject* self, PyObject* args, PyObject* kwds)
393 {
394         int pulseArg = 0;
395
396         if(!PyArg_ParseTuple(args, "i", &pulseArg)) {
397                 return NULL;
398         }
399         
400         m_bFindMaterial = pulseArg != 0;
401
402         Py_Return;
403 }
404
405
406 /* eof */