deprecate controller.getActuator(name) and controller.getSensor(name) for
[blender.git] / source / gameengine / Expressions / PyObjectPlus.cpp
1 /**
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32
33 #ifndef NO_EXP_PYTHON_EMBEDDING
34
35 /*------------------------------
36  * PyObjectPlus cpp
37  *
38  * C++ library routines for Crawl 3.2
39  *
40  * Derived from work by
41  * David Redish
42  * graduate student
43  * Computer Science Department 
44  * Carnegie Mellon University (CMU)
45  * Center for the Neural Basis of Cognition (CNBC) 
46  * http://www.python.org/doc/PyCPP.html
47  *
48 ------------------------------*/
49 #include <MT_assert.h>
50 #include "stdlib.h"
51 #include "PyObjectPlus.h"
52 #include "STR_String.h"
53 /*------------------------------
54  * PyObjectPlus Type            -- Every class, even the abstract one should have a Type
55 ------------------------------*/
56
57
58 PyTypeObject PyObjectPlus::Type = {
59 #if (PY_VERSION_HEX >= 0x02060000)
60         PyVarObject_HEAD_INIT(NULL, 0)
61 #else
62         /* python 2.5 and below */
63         PyObject_HEAD_INIT( NULL )  /* required py macro */
64         0,                              /*ob_size*/
65 #endif
66         "PyObjectPlus",                 /*tp_name*/
67         sizeof(PyObjectPlus_Proxy),             /*tp_basicsize*/
68         0,                              /*tp_itemsize*/
69         /* methods */
70         py_base_dealloc,
71         0,
72         0,
73         0,
74         0,
75         py_base_repr,
76         0,0,0,0,0,0,
77         py_base_getattro,
78         py_base_setattro,
79         0,0,0,0,0,0,0,0,0,
80         Methods
81 };
82
83
84 PyObjectPlus::~PyObjectPlus()
85 {
86         if(m_proxy) {
87                 Py_DECREF(m_proxy);                     /* Remove own reference, python may still have 1 */
88                 BGE_PROXY_REF(m_proxy)= NULL;
89         }
90 //      assert(ob_refcnt==0);
91 }
92
93 void PyObjectPlus::py_base_dealloc(PyObject *self)                              // python wrapper
94 {
95         PyObjectPlus *self_plus= BGE_PROXY_REF(self);
96         if(self_plus) {
97                 if(BGE_PROXY_PYOWNS(self)) { /* Does python own this?, then delete it  */
98                         self_plus->m_proxy = NULL; /* Need this to stop ~PyObjectPlus from decrefing m_proxy otherwise its decref'd twice and py-debug crashes */
99                         delete self_plus;
100                 }
101                 
102                 BGE_PROXY_REF(self)= NULL; // not really needed
103         }
104         PyObject_DEL( self );
105 };
106
107 PyObjectPlus::PyObjectPlus(PyTypeObject *T)                             // constructor
108 {
109         MT_assert(T != NULL);
110         m_proxy= NULL;
111 };
112   
113 /*------------------------------
114  * PyObjectPlus Methods         -- Every class, even the abstract one should have a Methods
115 ------------------------------*/
116 PyMethodDef PyObjectPlus::Methods[] = {
117   {"isA",                (PyCFunction) sPyisA,                  METH_O},
118   {NULL, NULL}          /* Sentinel */
119 };
120
121 PyAttributeDef PyObjectPlus::Attributes[] = {
122         KX_PYATTRIBUTE_RO_FUNCTION("invalid",           PyObjectPlus, pyattr_get_invalid),
123         {NULL} //Sentinel
124 };
125
126 PyObject* PyObjectPlus::pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
127 {       
128         Py_RETURN_FALSE;
129 }
130
131 /*------------------------------
132  * PyObjectPlus Parents         -- Every class, even the abstract one should have parents
133 ------------------------------*/
134 PyParentObject PyObjectPlus::Parents[] = {&PyObjectPlus::Type, NULL};
135
136 /*------------------------------
137  * PyObjectPlus attributes      -- attributes
138 ------------------------------*/
139
140
141 /* This should be the entry in Type since it takes the C++ class from PyObjectPlus_Proxy */
142 PyObject *PyObjectPlus::py_base_getattro(PyObject * self, PyObject *attr)
143 {
144         PyObjectPlus *self_plus= BGE_PROXY_REF(self);
145         if(self_plus==NULL) {
146                 if(!strcmp("invalid", PyString_AsString(attr))) {
147                         Py_RETURN_TRUE;
148                 }
149                 PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
150                 return NULL;
151         }
152         
153         PyObject *ret= self_plus->py_getattro(attr);
154         
155         /* Attribute not found, was this a __dict__ lookup?, otherwise set an error if none is set */
156         if(ret==NULL) {
157                 char *attr_str= PyString_AsString(attr);
158                 
159                 if (strcmp(attr_str, "__dict__")==0)
160                 {
161                         /* the error string will probably not
162                          * be set but just incase clear it */
163                         PyErr_Clear(); 
164                         ret= self_plus->py_getattro_dict();
165                 }
166                 else if (!PyErr_Occurred()) {
167                         /* We looked for an attribute but it wasnt found
168                          * since py_getattro didnt set the error, set it here */
169                         PyErr_Format(PyExc_AttributeError, "'%s' object has no attribute '%s'", self->ob_type->tp_name, attr_str);
170                 }
171         }
172         return ret;
173 }
174
175 /* This should be the entry in Type since it takes the C++ class from PyObjectPlus_Proxy */
176 int PyObjectPlus::py_base_setattro(PyObject *self, PyObject *attr, PyObject *value)
177 {
178         PyObjectPlus *self_plus= BGE_PROXY_REF(self);
179         if(self_plus==NULL) {
180                 PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
181                 return -1;
182         }
183         
184         if (value==NULL)
185                 return self_plus->py_delattro(attr);
186         
187         return self_plus->py_setattro(attr, value); 
188 }
189
190 PyObject *PyObjectPlus::py_base_repr(PyObject *self)                    // This should be the entry in Type.
191 {
192         
193         PyObjectPlus *self_plus= BGE_PROXY_REF(self);
194         if(self_plus==NULL) {
195                 PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
196                 return NULL;
197         }
198         
199         return self_plus->py_repr();  
200 }
201
202 PyObject *PyObjectPlus::py_getattro(PyObject* attr)
203 {
204         PyObject *descr = PyDict_GetItem(Type.tp_dict, attr); \
205         if (descr == NULL) {
206                 return NULL; /* py_base_getattro sets the error, this way we can avoid setting the error at many levels */
207         } else {
208                 /* Copied from py_getattro_up */
209                 if (PyCObject_Check(descr)) {
210                         return py_get_attrdef((void *)this, (const PyAttributeDef*)PyCObject_AsVoidPtr(descr));
211                 } else if (descr->ob_type->tp_descr_get) {
212                         return PyCFunction_New(((PyMethodDescrObject *)descr)->d_method, this->m_proxy);
213                 } else {
214                         return NULL;
215                 }
216                 /* end py_getattro_up copy */
217         }
218 }
219
220 PyObject* PyObjectPlus::py_getattro_dict() {
221         return py_getattr_dict(NULL, Type.tp_dict);
222 }
223
224 int PyObjectPlus::py_delattro(PyObject* attr)
225 {
226         PyErr_SetString(PyExc_AttributeError, "attribute cant be deleted");
227         return 1;
228 }
229
230 int PyObjectPlus::py_setattro(PyObject *attr, PyObject* value)
231 {
232         PyErr_SetString(PyExc_AttributeError, "attribute cant be set");
233         return PY_SET_ATTR_MISSING;
234 }
235
236 PyObject *PyObjectPlus::py_get_attrdef(void *self, const PyAttributeDef *attrdef)
237 {
238         if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_DUMMY)
239         {
240                 // fake attribute, ignore
241                 return NULL;
242         }
243         if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
244         {
245                 // the attribute has no field correspondance, handover processing to function.
246                 if (attrdef->m_getFunction == NULL)
247                         return NULL;
248                 return (*attrdef->m_getFunction)(self, attrdef);
249         }
250         char *ptr = reinterpret_cast<char*>(self)+attrdef->m_offset;
251         if (attrdef->m_length > 1)
252         {
253                 PyObject* resultlist = PyList_New(attrdef->m_length);
254                 for (unsigned int i=0; i<attrdef->m_length; i++)
255                 {
256                         switch (attrdef->m_type) {
257                         case KX_PYATTRIBUTE_TYPE_BOOL:
258                                 {
259                                         bool *val = reinterpret_cast<bool*>(ptr);
260                                         ptr += sizeof(bool);
261                                         PyList_SET_ITEM(resultlist,i,PyInt_FromLong(*val));
262                                         break;
263                                 }
264                         case KX_PYATTRIBUTE_TYPE_SHORT:
265                                 {
266                                         short int *val = reinterpret_cast<short int*>(ptr);
267                                         ptr += sizeof(short int);
268                                         PyList_SET_ITEM(resultlist,i,PyInt_FromLong(*val));
269                                         break;
270                                 }
271                         case KX_PYATTRIBUTE_TYPE_ENUM:
272                                 // enum are like int, just make sure the field size is the same
273                                 if (sizeof(int) != attrdef->m_size)
274                                 {
275                                         Py_DECREF(resultlist);
276                                         return NULL;
277                                 }
278                                 // walkthrough
279                         case KX_PYATTRIBUTE_TYPE_INT:
280                                 {
281                                         int *val = reinterpret_cast<int*>(ptr);
282                                         ptr += sizeof(int);
283                                         PyList_SET_ITEM(resultlist,i,PyInt_FromLong(*val));
284                                         break;
285                                 }
286                         case KX_PYATTRIBUTE_TYPE_FLOAT:
287                                 {
288                                         float *val = reinterpret_cast<float*>(ptr);
289                                         ptr += sizeof(float);
290                                         PyList_SET_ITEM(resultlist,i,PyFloat_FromDouble(*val));
291                                         break;
292                                 }
293                         default:
294                                 // no support for array of complex data
295                                 Py_DECREF(resultlist);
296                                 return NULL;
297                         }
298                 }
299                 return resultlist;
300         }
301         else
302         {
303                 switch (attrdef->m_type) {
304                 case KX_PYATTRIBUTE_TYPE_BOOL:
305                         {
306                                 bool *val = reinterpret_cast<bool*>(ptr);
307                                 return PyInt_FromLong(*val);
308                         }
309                 case KX_PYATTRIBUTE_TYPE_SHORT:
310                         {
311                                 short int *val = reinterpret_cast<short int*>(ptr);
312                                 return PyInt_FromLong(*val);
313                         }
314                 case KX_PYATTRIBUTE_TYPE_ENUM:
315                         // enum are like int, just make sure the field size is the same
316                         if (sizeof(int) != attrdef->m_size)
317                         {
318                                 return NULL;
319                         }
320                         // walkthrough
321                 case KX_PYATTRIBUTE_TYPE_INT:
322                         {
323                                 int *val = reinterpret_cast<int*>(ptr);
324                                 return PyInt_FromLong(*val);
325                         }
326                 case KX_PYATTRIBUTE_TYPE_FLOAT:
327                         {
328                                 float *val = reinterpret_cast<float*>(ptr);
329                                 return PyFloat_FromDouble(*val);
330                         }
331                 case KX_PYATTRIBUTE_TYPE_STRING:
332                         {
333                                 STR_String *val = reinterpret_cast<STR_String*>(ptr);
334                                 return PyString_FromString(*val);
335                         }
336                 default:
337                         return NULL;
338                 }
339         }
340 }
341
342 int PyObjectPlus::py_set_attrdef(void *self, const PyAttributeDef *attrdef, PyObject *value)
343 {
344         void *undoBuffer = NULL;
345         void *sourceBuffer = NULL;
346         size_t bufferSize = 0;
347         
348         char *ptr = reinterpret_cast<char*>(self)+attrdef->m_offset;
349         if (attrdef->m_length > 1)
350         {
351                 if (!PySequence_Check(value)) 
352                 {
353                         PyErr_Format(PyExc_TypeError, "expected a sequence for attribute \"%s\"", attrdef->m_name);
354                         return 1;
355                 }
356                 if (PySequence_Size(value) != attrdef->m_length)
357                 {
358                         PyErr_Format(PyExc_TypeError, "incorrect number of elements in sequence for attribute \"%s\"", attrdef->m_name);
359                         return 1;
360                 }
361                 switch (attrdef->m_type) 
362                 {
363                 case KX_PYATTRIBUTE_TYPE_FUNCTION:
364                         if (attrdef->m_setFunction == NULL) 
365                         {
366                                 PyErr_Format(PyExc_AttributeError, "function attribute without function for attribute \"%s\", report to blender.org", attrdef->m_name);
367                                 return 1;
368                         }
369                         return (*attrdef->m_setFunction)(self, attrdef, value);
370                 case KX_PYATTRIBUTE_TYPE_BOOL:
371                         bufferSize = sizeof(bool);
372                         break;
373                 case KX_PYATTRIBUTE_TYPE_SHORT:
374                         bufferSize = sizeof(short int);
375                         break;
376                 case KX_PYATTRIBUTE_TYPE_ENUM:
377                 case KX_PYATTRIBUTE_TYPE_INT:
378                         bufferSize = sizeof(int);
379                         break;
380                 case KX_PYATTRIBUTE_TYPE_FLOAT:
381                         bufferSize = sizeof(float);
382                         break;
383                 default:
384                         // should not happen
385                         PyErr_Format(PyExc_AttributeError, "Unsupported attribute type for attribute \"%s\", report to blender.org", attrdef->m_name);
386                         return 1;
387                 }
388                 // let's implement a smart undo method
389                 bufferSize *= attrdef->m_length;
390                 undoBuffer = malloc(bufferSize);
391                 sourceBuffer = ptr;
392                 if (undoBuffer)
393                 {
394                         memcpy(undoBuffer, sourceBuffer, bufferSize);
395                 }
396                 for (int i=0; i<attrdef->m_length; i++)
397                 {
398                         PyObject *item = PySequence_GetItem(value, i); /* new ref */
399                         // we can decrement the reference immediately, the reference count
400                         // is at least 1 because the item is part of an array
401                         Py_DECREF(item);
402                         switch (attrdef->m_type) 
403                         {
404                         case KX_PYATTRIBUTE_TYPE_BOOL:
405                                 {
406                                         bool *var = reinterpret_cast<bool*>(ptr);
407                                         ptr += sizeof(bool);
408                                         if (PyInt_Check(item)) 
409                                         {
410                                                 *var = (PyInt_AsLong(item) != 0);
411                                         } 
412                                         else if (PyBool_Check(item))
413                                         {
414                                                 *var = (item == Py_True);
415                                         }
416                                         else
417                                         {
418                                                 PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
419                                                 goto UNDO_AND_ERROR;
420                                         }
421                                         break;
422                                 }
423                         case KX_PYATTRIBUTE_TYPE_SHORT:
424                                 {
425                                         short int *var = reinterpret_cast<short int*>(ptr);
426                                         ptr += sizeof(short int);
427                                         if (PyInt_Check(item)) 
428                                         {
429                                                 long val = PyInt_AsLong(item);
430                                                 if (attrdef->m_clamp)
431                                                 {
432                                                         if (val < attrdef->m_imin)
433                                                                 val = attrdef->m_imin;
434                                                         else if (val > attrdef->m_imax)
435                                                                 val = attrdef->m_imax;
436                                                 }
437                                                 else if (val < attrdef->m_imin || val > attrdef->m_imax)
438                                                 {
439                                                         PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
440                                                         goto UNDO_AND_ERROR;
441                                                 }
442                                                 *var = (short int)val;
443                                         }
444                                         else
445                                         {
446                                                 PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
447                                                 goto UNDO_AND_ERROR;
448                                         }
449                                         break;
450                                 }
451                         case KX_PYATTRIBUTE_TYPE_ENUM:
452                                 // enum are equivalent to int, just make sure that the field size matches:
453                                 if (sizeof(int) != attrdef->m_size)
454                                 {
455                                         PyErr_Format(PyExc_AttributeError, "Size check error for attribute, \"%s\", report to blender.org", attrdef->m_name);
456                                         goto UNDO_AND_ERROR;
457                                 }
458                                 // walkthrough
459                         case KX_PYATTRIBUTE_TYPE_INT:
460                                 {
461                                         int *var = reinterpret_cast<int*>(ptr);
462                                         ptr += sizeof(int);
463                                         if (PyInt_Check(item)) 
464                                         {
465                                                 long val = PyInt_AsLong(item);
466                                                 if (attrdef->m_clamp)
467                                                 {
468                                                         if (val < attrdef->m_imin)
469                                                                 val = attrdef->m_imin;
470                                                         else if (val > attrdef->m_imax)
471                                                                 val = attrdef->m_imax;
472                                                 }
473                                                 else if (val < attrdef->m_imin || val > attrdef->m_imax)
474                                                 {
475                                                         PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
476                                                         goto UNDO_AND_ERROR;
477                                                 }
478                                                 *var = (int)val;
479                                         }
480                                         else
481                                         {
482                                                 PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
483                                                 goto UNDO_AND_ERROR;
484                                         }
485                                         break;
486                                 }
487                         case KX_PYATTRIBUTE_TYPE_FLOAT:
488                                 {
489                                         float *var = reinterpret_cast<float*>(ptr);
490                                         ptr += sizeof(float);
491                                         double val = PyFloat_AsDouble(item);
492                                         if (val == -1.0 && PyErr_Occurred())
493                                         {
494                                                 PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name);
495                                                 goto UNDO_AND_ERROR;
496                                         }
497                                         else if (attrdef->m_clamp) 
498                                         {
499                                                 if (val < attrdef->m_fmin)
500                                                         val = attrdef->m_fmin;
501                                                 else if (val > attrdef->m_fmax)
502                                                         val = attrdef->m_fmax;
503                                         }
504                                         else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
505                                         {
506                                                 PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
507                                                 goto UNDO_AND_ERROR;
508                                         }
509                                         *var = (float)val;
510                                         break;
511                                 }
512                         default:
513                                 // should not happen
514                                 PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", report to blender.org", attrdef->m_name);
515                                 goto UNDO_AND_ERROR;
516                         }
517                 }
518                 // no error, call check function if any
519                 if (attrdef->m_checkFunction != NULL)
520                 {
521                         if ((*attrdef->m_checkFunction)(self, attrdef) != 0)
522                         {
523                                 // if the checing function didnt set an error then set a generic one here so we dont set an error with no exception
524                                 if (PyErr_Occurred()==0)
525                                         PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", reasion unknown", attrdef->m_name);
526                                 
527                                 // post check returned an error, restore values
528                         UNDO_AND_ERROR:
529                                 if (undoBuffer)
530                                 {
531                                         memcpy(sourceBuffer, undoBuffer, bufferSize);
532                                         free(undoBuffer);
533                                 }
534                                 return 1;
535                         }
536                 }
537                 if (undoBuffer)
538                         free(undoBuffer);
539                 return 0;
540         }
541         else    // simple attribute value
542         {
543                 if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
544                 {
545                         if (attrdef->m_setFunction == NULL)
546                         {
547                                 PyErr_Format(PyExc_AttributeError, "function attribute without function \"%s\", report to blender.org", attrdef->m_name);
548                                 return 1;
549                         }
550                         return (*attrdef->m_setFunction)(self, attrdef, value);
551                 }
552                 if (attrdef->m_checkFunction != NULL)
553                 {
554                         // post check function is provided, prepare undo buffer
555                         sourceBuffer = ptr;
556                         switch (attrdef->m_type) 
557                         {
558                         case KX_PYATTRIBUTE_TYPE_BOOL:
559                                 bufferSize = sizeof(bool);
560                                 break;
561                         case KX_PYATTRIBUTE_TYPE_SHORT:
562                                 bufferSize = sizeof(short);
563                                 break;
564                         case KX_PYATTRIBUTE_TYPE_ENUM:
565                         case KX_PYATTRIBUTE_TYPE_INT:
566                                 bufferSize = sizeof(int);
567                                 break;
568                         case KX_PYATTRIBUTE_TYPE_FLOAT:
569                                 bufferSize = sizeof(float);
570                                 break;
571                         case KX_PYATTRIBUTE_TYPE_STRING:
572                                 sourceBuffer = reinterpret_cast<STR_String*>(ptr)->Ptr();
573                                 if (sourceBuffer)
574                                         bufferSize = strlen(reinterpret_cast<char*>(sourceBuffer))+1;
575                                 break;
576                         default:
577                                 PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
578                                 return 1;
579                         }
580                         if (bufferSize)
581                         {
582                                 undoBuffer = malloc(bufferSize);
583                                 if (undoBuffer)
584                                 {
585                                         memcpy(undoBuffer, sourceBuffer, bufferSize);
586                                 }
587                         }
588                 }
589                         
590                 switch (attrdef->m_type) 
591                 {
592                 case KX_PYATTRIBUTE_TYPE_BOOL:
593                         {
594                                 bool *var = reinterpret_cast<bool*>(ptr);
595                                 if (PyInt_Check(value)) 
596                                 {
597                                         *var = (PyInt_AsLong(value) != 0);
598                                 } 
599                                 else if (PyBool_Check(value))
600                                 {
601                                         *var = (value == Py_True);
602                                 }
603                                 else
604                                 {
605                                         PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
606                                         goto FREE_AND_ERROR;
607                                 }
608                                 break;
609                         }
610                 case KX_PYATTRIBUTE_TYPE_SHORT:
611                         {
612                                 short int *var = reinterpret_cast<short int*>(ptr);
613                                 if (PyInt_Check(value)) 
614                                 {
615                                         long val = PyInt_AsLong(value);
616                                         if (attrdef->m_clamp)
617                                         {
618                                                 if (val < attrdef->m_imin)
619                                                         val = attrdef->m_imin;
620                                                 else if (val > attrdef->m_imax)
621                                                         val = attrdef->m_imax;
622                                         }
623                                         else if (val < attrdef->m_imin || val > attrdef->m_imax)
624                                         {
625                                                 PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
626                                                 goto FREE_AND_ERROR;
627                                         }
628                                         *var = (short int)val;
629                                 }
630                                 else
631                                 {
632                                         PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
633                                         goto FREE_AND_ERROR;
634                                 }
635                                 break;
636                         }
637                 case KX_PYATTRIBUTE_TYPE_ENUM:
638                         // enum are equivalent to int, just make sure that the field size matches:
639                         if (sizeof(int) != attrdef->m_size)
640                         {
641                                 PyErr_Format(PyExc_AttributeError, "attribute size check error for attribute \"%s\", report to blender.org", attrdef->m_name);
642                                 goto FREE_AND_ERROR;
643                         }
644                         // walkthrough
645                 case KX_PYATTRIBUTE_TYPE_INT:
646                         {
647                                 int *var = reinterpret_cast<int*>(ptr);
648                                 if (PyInt_Check(value)) 
649                                 {
650                                         long val = PyInt_AsLong(value);
651                                         if (attrdef->m_clamp)
652                                         {
653                                                 if (val < attrdef->m_imin)
654                                                         val = attrdef->m_imin;
655                                                 else if (val > attrdef->m_imax)
656                                                         val = attrdef->m_imax;
657                                         }
658                                         else if (val < attrdef->m_imin || val > attrdef->m_imax)
659                                         {
660                                                 PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
661                                                 goto FREE_AND_ERROR;
662                                         }
663                                         *var = (int)val;
664                                 }
665                                 else
666                                 {
667                                         PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
668                                         goto FREE_AND_ERROR;
669                                 }
670                                 break;
671                         }
672                 case KX_PYATTRIBUTE_TYPE_FLOAT:
673                         {
674                                 float *var = reinterpret_cast<float*>(ptr);
675                                 double val = PyFloat_AsDouble(value);
676                                 if (val == -1.0 && PyErr_Occurred())
677                                 {
678                                         PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name);
679                                         goto FREE_AND_ERROR;
680                                 }
681                                 else if (attrdef->m_clamp)
682                                 {
683                                         if (val < attrdef->m_fmin)
684                                                 val = attrdef->m_fmin;
685                                         else if (val > attrdef->m_fmax)
686                                                 val = attrdef->m_fmax;
687                                 }
688                                 else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
689                                 {
690                                         PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
691                                         goto FREE_AND_ERROR;
692                                 }
693                                 *var = (float)val;
694                                 break;
695                         }
696                 case KX_PYATTRIBUTE_TYPE_STRING:
697                         {
698                                 STR_String *var = reinterpret_cast<STR_String*>(ptr);
699                                 if (PyString_Check(value)) 
700                                 {
701                                         char *val = PyString_AsString(value);
702                                         if (attrdef->m_clamp)
703                                         {
704                                                 if (strlen(val) < attrdef->m_imin)
705                                                 {
706                                                         // can't increase the length of the string
707                                                         PyErr_Format(PyExc_ValueError, "string length too short for attribute \"%s\"", attrdef->m_name);
708                                                         goto FREE_AND_ERROR;
709                                                 }
710                                                 else if (strlen(val) > attrdef->m_imax)
711                                                 {
712                                                         // trim the string
713                                                         char c = val[attrdef->m_imax];
714                                                         val[attrdef->m_imax] = 0;
715                                                         *var = val;
716                                                         val[attrdef->m_imax] = c;
717                                                         break;
718                                                 }
719                                         } else if (strlen(val) < attrdef->m_imin || strlen(val) > attrdef->m_imax)
720                                         {
721                                                 PyErr_Format(PyExc_ValueError, "string length out of range for attribute \"%s\"", attrdef->m_name);
722                                                 goto FREE_AND_ERROR;
723                                         }
724                                         *var = val;
725                                 }
726                                 else
727                                 {
728                                         PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name);
729                                         goto FREE_AND_ERROR;
730                                 }
731                                 break;
732                         }
733                 default:
734                         // should not happen
735                         PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
736                         goto FREE_AND_ERROR;
737                 }
738         }
739         // check if post processing is needed
740         if (attrdef->m_checkFunction != NULL)
741         {
742                 if ((*attrdef->m_checkFunction)(self, attrdef) != 0)
743                 {
744                         // restore value
745                 RESTORE_AND_ERROR:
746                         if (undoBuffer)
747                         {
748                                 if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_STRING)
749                                 {
750                                         // special case for STR_String: restore the string
751                                         STR_String *var = reinterpret_cast<STR_String*>(ptr);
752                                         *var = reinterpret_cast<char*>(undoBuffer);
753                                 }
754                                 else
755                                 {
756                                         // other field type have direct values
757                                         memcpy(ptr, undoBuffer, bufferSize);
758                                 }
759                         }
760                 FREE_AND_ERROR:
761                         if (undoBuffer)
762                                 free(undoBuffer);
763                         return 1;
764                 }
765         }
766         if (undoBuffer)
767                 free(undoBuffer);
768         return 0;       
769 }
770
771
772
773 /*------------------------------
774  * PyObjectPlus repr            -- representations
775 ------------------------------*/
776 PyObject *PyObjectPlus::py_repr(void)
777 {
778         PyErr_SetString(PyExc_SystemError, "Representation not overridden by object.");  
779         return NULL;
780 }
781
782 /*------------------------------
783  * PyObjectPlus isA             -- the isA functions
784 ------------------------------*/
785 bool PyObjectPlus::isA(PyTypeObject *T)         // if called with a Type, use "typename"
786 {
787         int i;
788         PyParentObject  P;
789         PyParentObject *Ps = GetParents();
790
791         for (P = Ps[i=0]; P != NULL; P = Ps[i++])
792                 if (P==T)
793                         return true;
794
795         return false;
796 }
797
798
799 bool PyObjectPlus::isA(const char *mytypename)          // check typename of each parent
800 {
801         int i;
802         PyParentObject  P;
803         PyParentObject *Ps = GetParents();
804   
805         for (P = Ps[i=0]; P != NULL; P = Ps[i++])
806                 if (strcmp(P->tp_name, mytypename)==0)
807                         return true;
808
809         return false;
810 }
811
812 PyObject *PyObjectPlus::PyisA(PyObject *value)          // Python wrapper for isA
813 {
814         if (PyType_Check(value)) {
815                 return PyBool_FromLong(isA((PyTypeObject *)value));
816         } else if (PyString_Check(value)) {
817                 return PyBool_FromLong(isA(PyString_AsString(value)));
818         }
819     PyErr_SetString(PyExc_TypeError, "object.isA(value): expected a type or a string");
820     return NULL;        
821 }
822
823
824 void PyObjectPlus::ProcessReplica()
825 {
826         /* Clear the proxy, will be created again if needed with GetProxy()
827          * otherwise the PyObject will point to the wrong reference */
828         m_proxy= NULL;
829 }
830
831 /* Sometimes we might want to manually invalidate a BGE type even if
832  * it hasnt been released by the BGE, say for example when an object
833  * is removed from a scene, accessing it may cause problems.
834  * 
835  * In this case the current proxy is made invalid, disowned,
836  * and will raise an error on access. However if python can get access
837  * to this class again it will make a new proxy and work as expected.
838  */
839 void PyObjectPlus::InvalidateProxy()            // check typename of each parent
840 {
841         if(m_proxy) { 
842                 BGE_PROXY_REF(m_proxy)=NULL;
843                 Py_DECREF(m_proxy);
844                 m_proxy= NULL;
845         }
846 }
847
848 /* Utility function called by the macro py_getattro_up()
849  * for getting ob.__dict__() values from our PyObject
850  * this is used by python for doing dir() on an object, so its good
851  * if we return a list of attributes and methods.
852  * 
853  * Other then making dir() useful the value returned from __dict__() is not useful
854  * since every value is a Py_None
855  * */
856 PyObject *py_getattr_dict(PyObject *pydict, PyObject *tp_dict)
857 {
858     if(pydict==NULL) { /* incase calling __dict__ on the parent of this object raised an error */
859         PyErr_Clear();
860         pydict = PyDict_New();
861     }
862         
863         PyDict_Update(pydict, tp_dict);
864         return pydict;
865 }
866
867
868
869 PyObject *PyObjectPlus::GetProxy_Ext(PyObjectPlus *self, PyTypeObject *tp)
870 {
871         if (self->m_proxy==NULL)
872         {
873                 self->m_proxy = reinterpret_cast<PyObject *>PyObject_NEW( PyObjectPlus_Proxy, tp);
874                 BGE_PROXY_PYOWNS(self->m_proxy) = false;
875         }
876         //PyObject_Print(self->m_proxy, stdout, 0);
877         //printf("ref %d\n", self->m_proxy->ob_refcnt);
878         
879         BGE_PROXY_REF(self->m_proxy) = self; /* Its possible this was set to NULL, so set it back here */
880         Py_INCREF(self->m_proxy); /* we own one, thos ones fore the return */
881         return self->m_proxy;
882 }
883
884 PyObject *PyObjectPlus::NewProxy_Ext(PyObjectPlus *self, PyTypeObject *tp, bool py_owns)
885 {
886         if (self->m_proxy)
887         {
888                 if(py_owns)
889                 {       /* Free */
890                         BGE_PROXY_REF(self->m_proxy) = NULL;
891                         Py_DECREF(self->m_proxy);
892                         self->m_proxy= NULL;
893                 }
894                 else {
895                         Py_INCREF(self->m_proxy);
896                         return self->m_proxy;
897                 }
898                 
899         }
900         
901         GetProxy_Ext(self, tp);
902         if(py_owns) {
903                 BGE_PROXY_PYOWNS(self->m_proxy) = py_owns;
904                 Py_DECREF(self->m_proxy); /* could avoid thrashing here but for now its ok */
905         }
906         return self->m_proxy;
907 }
908
909 ///////////////////////////////////////////////////////////////////////////////////////////////
910 ///////////////////////////////////////////////////////////////////////////////////////////////
911 /* deprecation warning management */
912
913 bool PyObjectPlus::m_ignore_deprecation_warnings(false);
914 void PyObjectPlus::SetDeprecationWarnings(bool ignoreDeprecationWarnings)
915 {
916         m_ignore_deprecation_warnings = ignoreDeprecationWarnings;
917 }
918
919 void PyObjectPlus::ShowDeprecationWarning_func(const char* old_way,const char* new_way)
920 {
921         {
922                 printf("Method %s is deprecated, please use %s instead.\n", old_way, new_way);
923                 
924                 // import sys; print '\t%s:%d' % (sys._getframe(0).f_code.co_filename, sys._getframe(0).f_lineno)
925                 
926                 PyObject *getframe, *frame;
927                 PyObject *f_lineno, *f_code, *co_filename;
928                 
929                 getframe = PySys_GetObject((char *)"_getframe"); // borrowed
930                 if (getframe) {
931                         frame = PyObject_CallObject(getframe, NULL);
932                         if (frame) {
933                                 f_lineno= PyObject_GetAttrString(frame, "f_lineno");
934                                 f_code= PyObject_GetAttrString(frame, "f_code");
935                                 if (f_lineno && f_code) {
936                                         co_filename= PyObject_GetAttrString(f_code, "co_filename");
937                                         if (co_filename) {
938                                                 
939                                                 printf("\t%s:%d\n", PyString_AsString(co_filename), (int)PyInt_AsLong(f_lineno));
940                                                 
941                                                 Py_DECREF(f_lineno);
942                                                 Py_DECREF(f_code);
943                                                 Py_DECREF(co_filename);
944                                                 Py_DECREF(frame);
945                                                 return;
946                                         }
947                                 }
948                                 
949                                 Py_XDECREF(f_lineno);
950                                 Py_XDECREF(f_code);
951                                 Py_DECREF(frame);
952                         }
953                         
954                 }
955                 PyErr_Clear();
956                 printf("\tERROR - Could not access sys._getframe(0).f_lineno or sys._getframe().f_code.co_filename\n");
957         }
958 }
959
960 void PyObjectPlus::ClearDeprecationWarning()
961 {
962         WarnLink *wlink_next;
963         WarnLink *wlink = GetDeprecationWarningLinkFirst();
964         
965         while(wlink)
966         {
967                 wlink->warn_done= false; /* no need to NULL the link, its cleared before adding to the list next time round */
968                 wlink_next= reinterpret_cast<WarnLink *>(wlink->link);
969                 wlink->link= NULL;
970                 wlink= wlink_next;
971         }
972         NullDeprecationWarning();
973 }
974
975 WarnLink*               m_base_wlink_first= NULL;
976 WarnLink*               m_base_wlink_last= NULL;
977
978 WarnLink*               PyObjectPlus::GetDeprecationWarningLinkFirst(void) {return m_base_wlink_first;}
979 WarnLink*               PyObjectPlus::GetDeprecationWarningLinkLast(void) {return m_base_wlink_last;}
980 void                    PyObjectPlus::SetDeprecationWarningFirst(WarnLink* wlink) {m_base_wlink_first= wlink;}
981 void                    PyObjectPlus::SetDeprecationWarningLinkLast(WarnLink* wlink) {m_base_wlink_last= wlink;}
982 void                    PyObjectPlus::NullDeprecationWarning() {m_base_wlink_first= m_base_wlink_last= NULL;}
983
984 #endif //NO_EXP_PYTHON_EMBEDDING
985