fix for [#17878] Scripts operating on blender objects don't clear memory after a...
[blender.git] / source / gameengine / GameLogic / SCA_PythonController.cpp
1 /**
2  * Execute Python scripts
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 "SCA_PythonController.h"
33 #include "SCA_LogicManager.h"
34 #include "SCA_ISensor.h"
35 #include "SCA_IActuator.h"
36 #include "PyObjectPlus.h"
37 #include "compile.h"
38 #include "eval.h"
39 #include <algorithm>
40
41
42 #ifdef HAVE_CONFIG_H
43 #include <config.h>
44 #endif
45
46 // initialize static member variables
47 SCA_PythonController* SCA_PythonController::m_sCurrentController = NULL;
48
49
50 SCA_PythonController::SCA_PythonController(SCA_IObject* gameobj,
51                                                                                    PyTypeObject* T)
52         : SCA_IController(gameobj, T),
53         m_bytecode(NULL),
54         m_bModified(true),
55         m_pythondictionary(NULL)
56 {
57 }
58
59 /*
60 //debugging
61 CValue*         SCA_PythonController::AddRef()
62 {
63         //printf("AddRef refcount = %i\n",GetRefCount());
64         return CValue::AddRef();
65 }
66 int                     SCA_PythonController::Release()
67 {
68         //printf("Release refcount = %i\n",GetRefCount());
69         return CValue::Release();
70 }
71 */
72
73
74
75 SCA_PythonController::~SCA_PythonController()
76 {
77         if (m_bytecode)
78         {
79                 //
80                 //printf("released python byte script\n");
81                 Py_DECREF(m_bytecode);
82         }
83         
84         if (m_pythondictionary)
85         {
86                 // break any circular references in the dictionary
87                 PyDict_Clear(m_pythondictionary);
88                 Py_DECREF(m_pythondictionary);
89         }
90 }
91
92
93
94 CValue* SCA_PythonController::GetReplica()
95 {
96         SCA_PythonController* replica = new SCA_PythonController(*this);
97         // Copy the compiled bytecode if possible.
98         Py_XINCREF(replica->m_bytecode);
99         replica->m_bModified = replica->m_bytecode == NULL;
100         
101         // The replica->m_pythondictionary is stolen - replace with a copy.
102         if (m_pythondictionary)
103                 replica->m_pythondictionary = PyDict_Copy(m_pythondictionary);
104                 
105         /*
106         // The other option is to incref the replica->m_pythondictionary -
107         // the replica objects can then share data.
108         if (m_pythondictionary)
109                 Py_INCREF(replica->m_pythondictionary);
110         */
111         
112         // this will copy properties and so on...
113         CValue::AddDataToReplica(replica);
114
115         return replica;
116 }
117
118
119
120 void SCA_PythonController::SetScriptText(const STR_String& text)
121
122         m_scriptText = text;
123         m_bModified = true;
124 }
125
126
127
128 void SCA_PythonController::SetScriptName(const STR_String& name)
129 {
130         m_scriptName = name;
131 }
132
133
134
135 void SCA_PythonController::SetDictionary(PyObject*      pythondictionary)
136 {
137         if (m_pythondictionary)
138         {
139                 PyDict_Clear(m_pythondictionary);
140                 Py_DECREF(m_pythondictionary);
141         }
142         m_pythondictionary = PyDict_Copy(pythondictionary); /* new reference */
143 }
144
145 int SCA_PythonController::IsTriggered(class SCA_ISensor* sensor)
146 {
147         if (std::find(m_triggeredSensors.begin(), m_triggeredSensors.end(), sensor) != 
148                 m_triggeredSensors.end())
149                 return 1;
150         return 0;
151 }
152
153 #if 0
154 static const char* sPyGetCurrentController__doc__;
155 #endif
156
157
158 PyObject* SCA_PythonController::sPyGetCurrentController(PyObject* self)
159 {
160         m_sCurrentController->AddRef();
161         return m_sCurrentController;
162 }
163
164 #if 0
165 static const char* sPyAddActiveActuator__doc__;
166 #endif
167
168 PyObject* SCA_PythonController::sPyAddActiveActuator(
169           
170                 PyObject* self, 
171                 PyObject* args)
172 {
173         
174         PyObject* ob1;
175         int activate;
176         if (!PyArg_ParseTuple(args, "Oi", &ob1,&activate))
177                 return NULL;
178
179         // for safety, todo: only allow for registered actuators (pointertable)
180         // we don't want to crash gameengine/blender by python scripts
181         std::vector<SCA_IActuator*> lacts =  m_sCurrentController->GetLinkedActuators();
182         
183         std::vector<SCA_IActuator*>::iterator it;
184         bool found = false;
185         CValue* act = (CValue*)ob1;
186
187         for(it = lacts.begin(); it!= lacts.end(); it++) {
188                 if( static_cast<SCA_IActuator*>(act) == (*it) ) {
189                         found=true;
190                         break;
191                 }
192         }
193         if(found){
194                 CValue* boolval = new CBoolValue(activate!=0);
195                 m_sCurrentLogicManager->AddActiveActuator((SCA_IActuator*)act,boolval);
196                 boolval->Release();
197         }
198         Py_RETURN_NONE;
199 }
200
201
202 const char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
203 const char* SCA_PythonController::sPyAddActiveActuator__doc__= "addActiveActuator(actuator,bool)";
204 const char SCA_PythonController::GetActuators_doc[] = "getActuator";
205
206 PyTypeObject SCA_PythonController::Type = {
207         PyObject_HEAD_INIT(&PyType_Type)
208                 0,
209                 "SCA_PythonController",
210                 sizeof(SCA_PythonController),
211                 0,
212                 PyDestructor,
213                 0,
214                 __getattr,
215                 __setattr,
216                 0, //&MyPyCompare,
217                 __repr,
218                 0, //&cvalue_as_number,
219                 0,
220                 0,
221                 0,
222                 0
223 };
224
225 PyParentObject SCA_PythonController::Parents[] = {
226         &SCA_PythonController::Type,
227         &SCA_IController::Type,
228         &CValue::Type,
229         NULL
230 };
231 PyMethodDef SCA_PythonController::Methods[] = {
232         {"getActuators", (PyCFunction) SCA_PythonController::sPyGetActuators, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetActuators_doc},
233         {"getActuator", (PyCFunction) SCA_PythonController::sPyGetActuator, METH_O, (PY_METHODCHAR)SCA_PythonController::GetActuator_doc},
234         {"getSensors", (PyCFunction) SCA_PythonController::sPyGetSensors, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetSensors_doc},
235         {"getSensor", (PyCFunction) SCA_PythonController::sPyGetSensor, METH_O, (PY_METHODCHAR)SCA_PythonController::GetSensor_doc},
236         {"getScript", (PyCFunction) SCA_PythonController::sPyGetScript, METH_NOARGS},
237         {"setScript", (PyCFunction) SCA_PythonController::sPySetScript, METH_O},
238         {"getState", (PyCFunction) SCA_PythonController::sPyGetState, METH_NOARGS},
239         {NULL,NULL} //Sentinel
240 };
241
242
243 void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
244 {
245         m_sCurrentController = this;
246         m_sCurrentLogicManager = logicmgr;
247         
248         if (m_bModified)
249         {
250                 // if a script already exists, decref it before replace the pointer to a new script
251                 if (m_bytecode)
252                 {
253                         Py_DECREF(m_bytecode);
254                         m_bytecode=NULL;
255                 }
256                 // recompile the scripttext into bytecode
257                 m_bytecode = Py_CompileString(m_scriptText.Ptr(), m_scriptName.Ptr(), Py_file_input);
258                 if (!m_bytecode)
259                 {
260                         // didn't compile, so instead of compile, complain
261                         // something is wrong, tell the user what went wrong
262                         printf("Python compile error from controller \"%s\": \n", GetName().Ptr());
263                         //PyRun_SimpleString(m_scriptText.Ptr());
264                         PyErr_Print();
265                         
266                         /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
267                          * their user count. Not to mention holding references to wrapped data.
268                          * This is especially bad when the PyObject for the wrapped data is free'd, after blender 
269                          * has alredy dealocated the pointer */
270                         PySys_SetObject( "last_traceback", Py_None);
271                         
272                         return;
273                 }
274                 m_bModified=false;
275         }
276         
277                 /*
278                  * This part here with excdict is a temporary patch
279                  * to avoid python/gameengine crashes when python
280                  * inadvertently holds references to game objects
281                  * in global variables.
282                  * 
283                  * The idea is always make a fresh dictionary, and
284                  * destroy it right after it is used to make sure
285                  * python won't hold any gameobject references.
286                  * 
287                  * Note that the PyDict_Clear _is_ necessary before
288                  * the Py_DECREF() because it is possible for the
289                  * variables inside the dictionary to hold references
290                  * to the dictionary (ie. generate a cycle), so we
291                  * break it by hand, then DECREF (which in this case
292                  * should always ensure excdict is cleared).
293                  */
294
295         PyObject *excdict= PyDict_Copy(m_pythondictionary);
296         PyObject* resultobj = PyEval_EvalCode((PyCodeObject*)m_bytecode,
297                 excdict, excdict);
298
299         if (resultobj)
300         {
301                 Py_DECREF(resultobj);
302         }
303         else
304         {
305                 // something is wrong, tell the user what went wrong
306                 printf("Python script error from controller \"%s\": \n", GetName().Ptr());
307                 PyErr_Print();
308                 
309                 /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
310                  * their user count. Not to mention holding references to wrapped data.
311                  * This is especially bad when the PyObject for the wrapped data is free'd, after blender 
312                  * has alredy dealocated the pointer */
313                 PySys_SetObject( "last_traceback", Py_None);
314                 
315                 //PyRun_SimpleString(m_scriptText.Ptr());
316         }
317
318         // clear after PyErrPrint - seems it can be using
319         // something in this dictionary and crash?
320         PyDict_Clear(excdict);
321         Py_DECREF(excdict);
322         m_triggeredSensors.erase(m_triggeredSensors.begin(), m_triggeredSensors.end());
323         m_sCurrentController = NULL;
324 }
325
326
327
328 PyObject* SCA_PythonController::_getattr(const STR_String& attr)
329 {
330         _getattr_up(SCA_IController);
331 }
332
333
334
335 PyObject* SCA_PythonController::PyGetActuators(PyObject* self)
336 {
337         PyObject* resultlist = PyList_New(m_linkedactuators.size());
338         for (unsigned int index=0;index<m_linkedactuators.size();index++)
339         {
340                 PyList_SET_ITEM(resultlist,index,m_linkedactuators[index]->AddRef());
341         }
342
343         return resultlist;
344 }
345
346 const char SCA_PythonController::GetSensor_doc[] = 
347 "GetSensor (char sensorname) return linked sensor that is named [sensorname]\n";
348 PyObject*
349 SCA_PythonController::PyGetSensor(PyObject* self, PyObject* value)
350 {
351
352         char *scriptArg = PyString_AsString(value);
353         if (scriptArg==NULL) {
354                 PyErr_SetString(PyExc_TypeError, "expected a string (sensor name)");
355                 return NULL;
356         }
357         
358         for (unsigned int index=0;index<m_linkedsensors.size();index++)
359         {
360                 SCA_ISensor* sensor = m_linkedsensors[index];
361                 STR_String realname = sensor->GetName();
362                 if (realname == scriptArg)
363                 {
364                         return sensor->AddRef();
365                 }
366         }
367         
368         char emsg[96];
369         PyOS_snprintf( emsg, sizeof( emsg ), "Unable to find requested sensor \"%s\"", scriptArg );
370         PyErr_SetString(PyExc_AttributeError, emsg);
371         return NULL;
372 }
373
374
375
376 const char SCA_PythonController::GetActuator_doc[] = 
377 "GetActuator (char sensorname) return linked actuator that is named [actuatorname]\n";
378 PyObject*
379 SCA_PythonController::PyGetActuator(PyObject* self, PyObject* value)
380 {
381
382         char *scriptArg = PyString_AsString(value);
383         if (scriptArg==NULL) {
384                 PyErr_SetString(PyExc_TypeError, "expected a string (actuator name)");
385                 return NULL;
386         }
387         
388         for (unsigned int index=0;index<m_linkedactuators.size();index++)
389         {
390                 SCA_IActuator* actua = m_linkedactuators[index];
391                 STR_String realname = actua->GetName();
392                 if (realname == scriptArg)
393                 {
394                         return actua->AddRef();
395                 }
396         }
397         
398         char emsg[96];
399         PyOS_snprintf( emsg, sizeof( emsg ), "Unable to find requested actuator \"%s\"", scriptArg );
400         PyErr_SetString(PyExc_AttributeError, emsg);
401         return NULL;
402 }
403
404
405 const char SCA_PythonController::GetSensors_doc[]   = "getSensors returns a list of all attached sensors";
406 PyObject*
407 SCA_PythonController::PyGetSensors(PyObject* self)
408 {
409         PyObject* resultlist = PyList_New(m_linkedsensors.size());
410         for (unsigned int index=0;index<m_linkedsensors.size();index++)
411         {
412                 PyList_SET_ITEM(resultlist,index,m_linkedsensors[index]->AddRef());
413         }
414         
415         return resultlist;
416 }
417
418 /* 1. getScript */
419 PyObject* SCA_PythonController::PyGetScript(PyObject* self)
420 {
421         return PyString_FromString(m_scriptText);
422 }
423
424 /* 2. setScript */
425 PyObject* SCA_PythonController::PySetScript(PyObject* self, PyObject* value)
426 {
427         char *scriptArg = PyString_AsString(value);
428         if (scriptArg==NULL) {
429                 PyErr_SetString(PyExc_TypeError, "expected a string (script name)");
430                 return NULL;
431         }
432         
433         /* set scripttext sets m_bModified to true, 
434                 so next time the script is needed, a reparse into byte code is done */
435
436         this->SetScriptText(scriptArg);
437         
438         Py_RETURN_NONE;
439 }
440
441 /* 1. getScript */
442 PyObject* SCA_PythonController::PyGetState(PyObject* self)
443 {
444         return PyInt_FromLong(m_statemask);
445 }
446
447 /* eof */