cyclic gc support for KX_PythonSeq
[blender.git] / source / gameengine / Ketsji / KX_PythonSeq.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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: none of this file.
24  *
25  * Contributor(s): Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Readonly sequence wrapper for lookups on logic bricks
29  */
30
31 /** \file gameengine/Ketsji/KX_PythonSeq.cpp
32  *  \ingroup ketsji
33  */
34
35
36 #ifdef WITH_PYTHON
37
38 #include "KX_PythonSeq.h"
39 #include "KX_GameObject.h"
40 #include "BL_ArmatureObject.h"
41 #include "SCA_ISensor.h"
42 #include "SCA_IController.h"
43 #include "SCA_IActuator.h"
44
45
46 PyObject *KX_PythonSeq_CreatePyObject( PyObject *base, short type )
47 {
48         KX_PythonSeq *seq = PyObject_GC_New(KX_PythonSeq, &KX_PythonSeq_Type);
49         seq->base = base;
50         Py_INCREF(base); /* so we can always access to check if its valid */
51         seq->type = type;
52         seq->iter = -1; /* init */
53         return (PyObject *)seq;
54 }
55
56 static int KX_PythonSeq_traverse(KX_PythonSeq *self, visitproc visit, void *arg)
57 {
58         Py_VISIT(self->base);
59         return 0;
60 }
61
62 static int KX_PythonSeq_clear(KX_PythonSeq *self)
63 {
64         Py_CLEAR(self->base);
65         return 0;
66 }
67
68 static void KX_PythonSeq_dealloc(KX_PythonSeq * self)
69 {
70         KX_PythonSeq_clear(self);
71         PyObject_GC_Del(self);
72 }
73
74 static Py_ssize_t KX_PythonSeq_len( PyObject * self )
75 {
76         PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
77          
78         if(self_plus==NULL) {
79                 PyErr_SetString(PyExc_SystemError, "len(seq): "BGE_PROXY_ERROR_MSG);
80                 return -1;
81         }
82         
83         switch(((KX_PythonSeq *)self)->type) {
84         case KX_PYGENSEQ_CONT_TYPE_SENSORS:
85                 return ((SCA_IController *)self_plus)->GetLinkedSensors().size();
86         case KX_PYGENSEQ_CONT_TYPE_ACTUATORS:
87                 return ((SCA_IController *)self_plus)->GetLinkedActuators().size();
88         case KX_PYGENSEQ_OB_TYPE_SENSORS:
89                 return ((KX_GameObject *)self_plus)->GetSensors().size();
90         case KX_PYGENSEQ_OB_TYPE_CONTROLLERS:
91                 return ((KX_GameObject *)self_plus)->GetControllers().size();
92         case KX_PYGENSEQ_OB_TYPE_ACTUATORS:
93                 return ((KX_GameObject *)self_plus)->GetActuators().size();
94         case KX_PYGENSEQ_OB_TYPE_CONSTRAINTS:
95                 return ((BL_ArmatureObject *)self_plus)->GetConstraintNumber();
96         case KX_PYGENSEQ_OB_TYPE_CHANNELS:
97                 return ((BL_ArmatureObject *)self_plus)->GetChannelNumber();
98         default:
99                 /* Should never happen */
100                 PyErr_SetString(PyExc_SystemError, "invalid type, internal error");
101                 return -1;
102         }
103 }
104
105 static PyObject *KX_PythonSeq_getIndex(PyObject* self, int index)
106 {
107         PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
108          
109         if(self_plus==NULL) {
110                 PyErr_SetString(PyExc_SystemError, "val = seq[i]: "BGE_PROXY_ERROR_MSG);
111                 return NULL;
112         }
113         
114         switch(((KX_PythonSeq *)self)->type) {
115                 case KX_PYGENSEQ_CONT_TYPE_SENSORS:
116                 {
117                         vector<SCA_ISensor*>& linkedsensors = ((SCA_IController *)self_plus)->GetLinkedSensors();
118                         if(index<0) index += linkedsensors.size();
119                         if(index<0 || index>= linkedsensors.size()) {
120                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
121                                 return NULL;
122                         }
123                         return linkedsensors[index]->GetProxy();
124                 }
125                 case KX_PYGENSEQ_CONT_TYPE_ACTUATORS:
126                 {
127                         vector<SCA_IActuator*>& linkedactuators = ((SCA_IController *)self_plus)->GetLinkedActuators();
128                         if(index<0) index += linkedactuators.size();
129                         if(index<0 || index>= linkedactuators.size()) {
130                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
131                                 return NULL;
132                         }
133                         return linkedactuators[index]->GetProxy();
134                 }
135                 case KX_PYGENSEQ_OB_TYPE_SENSORS:
136                 {
137                         SCA_SensorList& linkedsensors= ((KX_GameObject *)self_plus)->GetSensors();
138                         if(index<0) index += linkedsensors.size();
139                         if(index<0 || index>= linkedsensors.size()) {
140                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
141                                 return NULL;
142                         }
143                         return linkedsensors[index]->GetProxy();
144                 }
145                 case KX_PYGENSEQ_OB_TYPE_CONTROLLERS:
146                 {
147                         SCA_ControllerList& linkedcontrollers= ((KX_GameObject *)self_plus)->GetControllers();
148                         if(index<0) index += linkedcontrollers.size();
149                         if(index<0 || index>= linkedcontrollers.size()) {
150                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
151                                 return NULL;
152                         }
153                         return linkedcontrollers[index]->GetProxy();
154                 }
155                 case KX_PYGENSEQ_OB_TYPE_ACTUATORS:
156                 {
157                         SCA_ActuatorList& linkedactuators= ((KX_GameObject *)self_plus)->GetActuators();
158                         if(index<0) index += linkedactuators.size();
159                         if(index<0 || index>= linkedactuators.size()) {
160                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
161                                 return NULL;
162                         }
163                         return linkedactuators[index]->GetProxy();
164                 }
165                 case KX_PYGENSEQ_OB_TYPE_CONSTRAINTS:
166                 {
167                         int nb_constraint = ((BL_ArmatureObject *)self_plus)->GetConstraintNumber();
168                         if(index<0) 
169                                 index += nb_constraint;
170                         if(index<0 || index>= nb_constraint) {
171                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
172                                 return NULL;
173                         }
174                         return ((BL_ArmatureObject *)self_plus)->GetConstraint(index)->GetProxy();
175                 }
176                 case KX_PYGENSEQ_OB_TYPE_CHANNELS:
177                 {
178                         int nb_channel = ((BL_ArmatureObject *)self_plus)->GetChannelNumber();
179                         if(index<0) 
180                                 index += nb_channel;
181                         if(index<0 || index>= nb_channel) {
182                                 PyErr_SetString(PyExc_IndexError, "seq[i]: index out of range");
183                                 return NULL;
184                         }
185                         return ((BL_ArmatureObject *)self_plus)->GetChannel(index)->GetProxy();
186                 }
187
188         }
189         
190         PyErr_SetString(PyExc_SystemError, "invalid sequence type, this is a bug");
191         return NULL;
192 }
193
194 static PyObjectPlus * KX_PythonSeq_subscript__internal(PyObject *self, char *key)
195 {
196         PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
197         
198         switch(((KX_PythonSeq *)self)->type) {
199                 case KX_PYGENSEQ_CONT_TYPE_SENSORS:
200                 {
201                         vector<SCA_ISensor*>& linkedsensors = ((SCA_IController *)self_plus)->GetLinkedSensors();
202                         SCA_ISensor* sensor;
203                         for (unsigned int index=0;index<linkedsensors.size();index++) {
204                                 sensor = linkedsensors[index];
205                                 if (sensor->GetName() == key)
206                                         return static_cast<PyObjectPlus *>(sensor);
207                                 
208                         }
209                         break;
210                 }
211                 case KX_PYGENSEQ_CONT_TYPE_ACTUATORS:
212                 {
213                         vector<SCA_IActuator*>& linkedactuators = ((SCA_IController *)self_plus)->GetLinkedActuators();
214                         SCA_IActuator* actuator;
215                         for (unsigned int index=0;index<linkedactuators.size();index++) {
216                                 actuator = linkedactuators[index];
217                                 if (actuator->GetName() == key)
218                                         return static_cast<PyObjectPlus *>(actuator);
219                         }
220                         break;
221                 }
222                 case KX_PYGENSEQ_OB_TYPE_SENSORS:
223                 {
224                         SCA_SensorList& linkedsensors= ((KX_GameObject *)self_plus)->GetSensors();
225                         SCA_ISensor *sensor;
226                         for (unsigned int index=0;index<linkedsensors.size();index++) {
227                                 sensor= linkedsensors[index];
228                                 if (sensor->GetName() == key)
229                                         return static_cast<PyObjectPlus *>(sensor);
230                         }
231                         break;
232                 }
233                 case KX_PYGENSEQ_OB_TYPE_CONTROLLERS:
234                 {
235                         SCA_ControllerList& linkedcontrollers= ((KX_GameObject *)self_plus)->GetControllers();
236                         SCA_IController *controller;
237                         for (unsigned int index=0;index<linkedcontrollers.size();index++) {
238                                 controller= linkedcontrollers[index];
239                                 if (controller->GetName() == key)
240                                         return static_cast<PyObjectPlus *>(controller);
241                         }
242                         break;
243                 }
244                 case KX_PYGENSEQ_OB_TYPE_ACTUATORS:
245                 {
246                         SCA_ActuatorList& linkedactuators= ((KX_GameObject *)self_plus)->GetActuators();
247                         SCA_IActuator *actuator;
248                         for (unsigned int index=0;index<linkedactuators.size();index++) {
249                                 actuator= linkedactuators[index];
250                                 if (actuator->GetName() == key)
251                                         return static_cast<PyObjectPlus *>(actuator);
252                         }
253                         break;
254                 }
255                 case KX_PYGENSEQ_OB_TYPE_CONSTRAINTS:
256                 {
257                         return ((BL_ArmatureObject*)self_plus)->GetConstraint(key);
258                 }
259                 case KX_PYGENSEQ_OB_TYPE_CHANNELS:
260                 {
261                         return ((BL_ArmatureObject*)self_plus)->GetChannel(key);
262                 }
263         }
264         
265         return NULL;
266 }
267
268
269 static PyObject * KX_PythonSeq_subscript(PyObject * self, PyObject *key)
270 {
271         PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
272         
273         if(self_plus==NULL) {
274                 PyErr_SetString(PyExc_SystemError, "val = seq[key], KX_PythonSeq: "BGE_PROXY_ERROR_MSG);
275                 return NULL;
276         }
277         
278         if (PyLong_Check(key)) {
279                 return KX_PythonSeq_getIndex(self, PyLong_AsSsize_t( key ));
280         }
281         else if ( PyUnicode_Check(key) ) {
282                 char *name = _PyUnicode_AsString(key);
283                 PyObjectPlus *ret = KX_PythonSeq_subscript__internal(self, name);
284                 
285                 if(ret) {
286                         return ret->GetProxy();
287                 } else {
288                         PyErr_Format( PyExc_KeyError, "requested item \"%s\" does not exist", name);
289                         return NULL;
290                 }
291         }
292         else {
293                 PyErr_SetString( PyExc_TypeError, "expected a string or an index" );
294                 return NULL;
295         }
296 }
297
298
299 static int KX_PythonSeq_contains(PyObject *self, PyObject *key)
300 {
301         PyObjectPlus *self_plus= BGE_PROXY_REF(((KX_PythonSeq *)self)->base);
302         
303         if(self_plus==NULL) {
304                 PyErr_SetString(PyExc_SystemError, "key in seq, KX_PythonSeq: "BGE_PROXY_ERROR_MSG);
305                 return -1;
306         }
307         if(!PyUnicode_Check(key)) {
308                 PyErr_SetString(PyExc_SystemError, "key in seq, KX_PythonSeq: key must be a string");
309                 return -1;
310         }
311         
312         if(KX_PythonSeq_subscript__internal(self, _PyUnicode_AsString(key)))
313                 return 1;
314         
315         return 0;
316 }
317
318 /* Matches python dict.get(key, [default]) */
319 PyObject* KX_PythonSeq_get(PyObject * self, PyObject *args)
320 {
321         char *key;
322         PyObject* def = Py_None;
323         PyObjectPlus* ret_plus;
324
325         if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
326                 return NULL;
327         
328         if((ret_plus = KX_PythonSeq_subscript__internal(self, key)))
329                 return ret_plus->GetProxy();
330         
331         Py_INCREF(def);
332         return def;
333 }
334
335 PySequenceMethods KX_PythonSeq_as_sequence = {
336         NULL,           /* Cant set the len otherwise it can evaluate as false */
337         NULL,           /* sq_concat */
338         NULL,           /* sq_repeat */
339         NULL,           /* sq_item */
340         NULL,           /* sq_slice */
341         NULL,           /* sq_ass_item */
342         NULL,           /* sq_ass_slice */
343         (objobjproc)KX_PythonSeq_contains,      /* sq_contains */
344         (binaryfunc) NULL, /* sq_inplace_concat */
345         (ssizeargfunc) NULL, /* sq_inplace_repeat */
346 };
347
348 static PyMappingMethods KX_PythonSeq_as_mapping = {
349         KX_PythonSeq_len,       /* mp_length */
350         KX_PythonSeq_subscript, /* mp_subscript */
351         0,      /* mp_ass_subscript */
352 };
353
354 PyMethodDef KX_PythonSeq_methods[] = {
355         // dict style access for props
356         {"get",(PyCFunction) KX_PythonSeq_get, METH_VARARGS},
357         {NULL,NULL} //Sentinel
358 };
359
360 /*
361  * Initialize the interator index
362  */
363
364 static PyObject *KX_PythonSeq_getIter(KX_PythonSeq *self)
365 {
366         if(BGE_PROXY_REF(self->base)==NULL) {
367                 PyErr_SetString(PyExc_SystemError, "for i in seq: "BGE_PROXY_ERROR_MSG);
368                 return NULL;
369         }
370         
371         /* create a new iterator if were already using this one */
372         if (self->iter == -1) {
373                 self->iter = 0;
374                 Py_INCREF(self);
375                 return (PyObject *)self;
376         } else {
377                 return KX_PythonSeq_CreatePyObject(self->base, self->type);
378         }
379  }
380  
381
382 /*
383  * Return next KX_PythonSeq iter.
384  */
385  
386 static PyObject *KX_PythonSeq_nextIter(KX_PythonSeq *self)
387 {
388         PyObject *object = KX_PythonSeq_getIndex((PyObject *)self, self->iter);
389         
390         self->iter++;
391         if( object==NULL ) {
392                 self->iter= -1; /* for reuse */
393                 PyErr_SetString(PyExc_StopIteration,    "iterator at end");
394         }
395         return object; /* can be NULL for end of iterator */
396 }
397
398
399 static int KX_PythonSeq_compare( KX_PythonSeq * a, KX_PythonSeq * b )
400 {
401         return ( a->type == b->type && a->base == b->base) ? 0 : -1;    
402 }
403
404 static PyObject *KX_PythonSeq_richcmp(PyObject *a, PyObject *b, int op)
405 {
406         PyObject *res;
407         int ok= -1; /* zero is true */
408
409         if(BPy_KX_PythonSeq_Check(a) && BPy_KX_PythonSeq_Check(b))
410                 ok= KX_PythonSeq_compare((KX_PythonSeq *)a, (KX_PythonSeq *)b);
411         
412         switch (op) {
413         case Py_NE:
414                 ok = !ok; /* pass through */
415         case Py_EQ:
416                 res = ok ? Py_False : Py_True;
417                 break;
418
419         case Py_LT:
420         case Py_LE:
421         case Py_GT:
422         case Py_GE:
423                 res = Py_NotImplemented;
424                 break;
425         default:
426                 PyErr_BadArgument();
427                 return NULL;
428         }
429         
430         Py_INCREF(res);
431         return res;
432 }
433
434
435 /*
436  * repr function
437  * convert to a list and get its string value
438  */
439 static PyObject *KX_PythonSeq_repr( KX_PythonSeq * self )
440 {
441         PyObject *list = PySequence_List((PyObject *)self);
442         PyObject *repr = PyObject_Repr(list);
443         Py_DECREF(list);
444         return repr;
445 }
446
447
448 /*****************************************************************************/
449 /* Python KX_PythonSeq_Type structure definition:                               */
450 /*****************************************************************************/
451 PyTypeObject KX_PythonSeq_Type = {
452         PyVarObject_HEAD_INIT(NULL, 0)
453         /*  For printing, in format "<module>.<name>" */
454         "KX_PythonSeq",           /* char *tp_name; */
455         sizeof( KX_PythonSeq ),       /* int tp_basicsize; */
456         0,                          /* tp_itemsize;  For allocation */
457
458         /* Methods to implement standard operations */
459
460         ( destructor ) KX_PythonSeq_dealloc, /* destructor tp_dealloc; */
461         NULL,                       /* printfunc tp_print; */
462         NULL,                       /* getattrfunc tp_getattr; */
463         NULL,                       /* setattrfunc tp_setattr; */
464         NULL,                                           /* cmpfunc tp_compare; */
465         ( reprfunc ) KX_PythonSeq_repr,   /* reprfunc tp_repr; */
466
467         /* Method suites for standard classes */
468
469         NULL,                       /* PyNumberMethods *tp_as_number; */
470         &KX_PythonSeq_as_sequence,          /* PySequenceMethods *tp_as_sequence; */
471         &KX_PythonSeq_as_mapping,                       /* PyMappingMethods *tp_as_mapping; */
472
473         /* More standard operations (here for binary compatibility) */
474
475         NULL,                       /* hashfunc tp_hash; */
476         NULL,                       /* ternaryfunc tp_call; */
477         NULL,                       /* reprfunc tp_str; */
478         NULL,                       /* getattrofunc tp_getattro; */
479         NULL,                       /* setattrofunc tp_setattro; */
480
481         /* Functions to access object as input/output buffer */
482         NULL,                       /* PyBufferProcs *tp_as_buffer; */
483
484   /*** Flags to define presence of optional/expanded features ***/
485         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* long tp_flags; */
486
487         NULL,                       /*  char *tp_doc;  Documentation string */
488   /*** Assigned meaning in release 2.0 ***/
489         /* call function for all accessible objects */
490         (traverseproc)KX_PythonSeq_traverse,    /* traverseproc tp_traverse; */
491
492         /* delete references to contained objects */
493         (inquiry)KX_PythonSeq_clear,    /* inquiry tp_clear; */
494
495   /***  Assigned meaning in release 2.1 ***/
496   /*** rich comparisons ***/
497         (richcmpfunc)KX_PythonSeq_richcmp,      /* richcmpfunc tp_richcompare; */
498
499   /***  weak reference enabler ***/
500         0,                          /* long tp_weaklistoffset; */
501
502   /*** Added in release 2.2 ***/
503         /*   Iterators */
504         ( getiterfunc) KX_PythonSeq_getIter, /* getiterfunc tp_iter; */
505         ( iternextfunc ) KX_PythonSeq_nextIter, /* iternextfunc tp_iternext; */
506
507   /*** Attribute descriptor and subclassing stuff ***/
508         KX_PythonSeq_methods,       /* struct PyMethodDef *tp_methods; */
509         NULL,                       /* struct PyMemberDef *tp_members; */
510         NULL,       /* struct PyGetSetDef *tp_getset; */
511         NULL,                       /* struct _typeobject *tp_base; */
512         NULL,                       /* PyObject *tp_dict; */
513         NULL,                       /* descrgetfunc tp_descr_get; */
514         NULL,                       /* descrsetfunc tp_descr_set; */
515         0,                          /* long tp_dictoffset; */
516         NULL,                       /* initproc tp_init; */
517         NULL,                       /* allocfunc tp_alloc; */
518         NULL,                       /* newfunc tp_new; */
519         /*  Low-level free-memory routine */
520         NULL,                       /* freefunc tp_free;  */
521         /* For PyObject_IS_GC */
522         NULL,                       /* inquiry tp_is_gc;  */
523         NULL,                       /* PyObject *tp_bases; */
524         /* method resolution order */
525         NULL,                       /* PyObject *tp_mro;  */
526         NULL,                       /* PyObject *tp_cache; */
527         NULL,                       /* PyObject *tp_subclasses; */
528         NULL,                       /* PyObject *tp_weaklist; */
529         NULL
530 };
531
532 #endif // WITH_PYTHON