Copying scripts from 2.4x without 2.5x changes
[blender.git] / source / gameengine / Expressions / ListValue.cpp
1 // ListValue.cpp: implementation of the CListValue class.
2 //
3 //////////////////////////////////////////////////////////////////////
4 /*
5  * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
6  *
7  * Permission to use, copy, modify, distribute and sell this software
8  * and its documentation for any purpose is hereby granted without fee,
9  * provided that the above copyright notice appear in all copies and
10  * that both that copyright notice and this permission notice appear
11  * in supporting documentation.  Erwin Coumans makes no
12  * representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied warranty.
14  *
15  */
16
17 #include "ListValue.h"
18 #include "StringValue.h"
19 #include "VoidValue.h"
20 #include <algorithm>
21 #include "BoolValue.h"
22
23 #include "BLO_sys_types.h" /* for intptr_t support */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #if  ((PY_MAJOR_VERSION == 2) &&(PY_MINOR_VERSION < 5))
30 #define Py_ssize_t int
31 #endif
32
33 Py_ssize_t listvalue_bufferlen(PyObject* self)
34 {
35         CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
36         if (list==NULL)
37                 return 0;
38         
39         return (Py_ssize_t)list->GetCount();
40 }
41
42 PyObject* listvalue_buffer_item(PyObject* self, Py_ssize_t index)
43 {
44         CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
45         CValue *cval;
46         
47         if (list==NULL) {
48                 PyErr_SetString(PyExc_SystemError, "val = CList[i], "BGE_PROXY_ERROR_MSG);
49                 return NULL;
50         }
51         
52         int count = list->GetCount();
53         
54         if (index < 0)
55                 index = count+index;
56         
57         if (index < 0 || index >= count) {
58                 PyErr_SetString(PyExc_IndexError, "CList[i]: Python ListIndex out of range in CValueList");
59                 return NULL;
60         }
61         
62         cval= list->GetValue(index);
63         
64         PyObject* pyobj = cval->ConvertValueToPython();
65         if (pyobj)
66                 return pyobj;
67         else
68                 return cval->GetProxy();
69 }
70
71 PyObject* listvalue_mapping_subscript(PyObject* self, PyObject* pyindex)
72 {
73         CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
74         if (list==NULL) {
75                 PyErr_SetString(PyExc_SystemError, "value = CList[i], "BGE_PROXY_ERROR_MSG);
76                 return NULL;
77         }
78         
79         if (PyUnicode_Check(pyindex))
80         {
81                 CValue *item = ((CListValue*) list)->FindValue(_PyUnicode_AsString(pyindex));
82                 if (item) {
83                         PyObject* pyobj = item->ConvertValueToPython();
84                         if(pyobj)
85                                 return pyobj;
86                         else
87                                 return item->GetProxy();
88                 }
89         }
90         else if (PyLong_Check(pyindex))
91         {
92                 int index = PyLong_AsSsize_t(pyindex);
93                 return listvalue_buffer_item(self, index); /* wont add a ref */
94         }
95         
96         PyObject *pyindex_str = PyObject_Repr(pyindex); /* new ref */
97         PyErr_Format(PyExc_KeyError, "CList[key]: '%s' key not in list", _PyUnicode_AsString(pyindex_str));
98         Py_DECREF(pyindex_str);
99         return NULL;
100 }
101
102
103 /* just slice it into a python list... */
104 PyObject* listvalue_buffer_slice(PyObject* self,Py_ssize_t ilow, Py_ssize_t ihigh)
105 {
106         CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
107         if (list==NULL) {
108                 PyErr_SetString(PyExc_SystemError, "val = CList[i:j], "BGE_PROXY_ERROR_MSG);
109                 return NULL;
110         }
111         
112         int i, j;
113         PyObject *newlist;
114
115         if (ilow < 0) ilow = 0;
116
117         int n = ((CListValue*) list)->GetCount();
118
119         if (ihigh >= n)
120                 ihigh = n;
121     if (ihigh < ilow)
122         ihigh = ilow;
123
124         newlist = PyList_New(ihigh - ilow);
125         if (!newlist)
126                 return NULL;
127
128         for (i = ilow, j = 0; i < ihigh; i++, j++)
129         {
130                 PyObject* pyobj = list->GetValue(i)->ConvertValueToPython();
131                 if (!pyobj)
132                         pyobj = list->GetValue(i)->GetProxy();
133                 PyList_SET_ITEM(newlist, i, pyobj);
134         }       
135         return newlist;
136 }
137
138
139 /* clist + list, return a list that python owns */
140 static PyObject *listvalue_buffer_concat(PyObject * self, PyObject * other)
141 {
142         CListValue *listval= static_cast<CListValue *>(BGE_PROXY_REF(self));
143         int i, numitems, numitems_orig;
144         
145         if (listval==NULL) {
146                 PyErr_SetString(PyExc_SystemError, "CList+other, "BGE_PROXY_ERROR_MSG);
147                 return NULL;
148         }
149         
150         numitems_orig= listval->GetCount();
151         
152         // for now, we support CListValue concatenated with items
153         // and CListValue concatenated to Python Lists
154         // and CListValue concatenated with another CListValue
155         
156         /* Shallow copy, dont use listval->GetReplica(), it will screw up with KX_GameObjects */
157         CListValue* listval_new = new CListValue();
158         
159         if (PyList_Check(other))
160         {
161                 CValue* listitemval;
162                 bool error = false;
163                 
164                 numitems = PyList_Size(other);
165                 
166                 /* copy the first part of the list */
167                 listval_new->Resize(numitems_orig + numitems);
168                 for (i=0;i<numitems_orig;i++)
169                         listval_new->SetValue(i, listval->GetValue(i)->AddRef());
170                 
171                 for (i=0;i<numitems;i++)
172                 {
173                         listitemval = listval->ConvertPythonToValue(PyList_GetItem(other,i), "cList + pyList: CListValue, ");
174                         
175                         if (listitemval) {
176                                 listval_new->SetValue(i+numitems_orig, listitemval);
177                         } else {
178                                 error= true;
179                                 break;
180                         }
181                 }
182                 
183                 if (error) {
184                         listval_new->Resize(numitems_orig+i); /* resize so we dont try release NULL pointers */
185                         listval_new->Release();
186                         return NULL; /* ConvertPythonToValue above sets the error */ 
187                 }
188         
189         }
190         else if (PyObject_TypeCheck(other, &CListValue::Type)) {
191                 // add items from otherlist to this list
192                 CListValue* otherval = static_cast<CListValue *>(BGE_PROXY_REF(other));
193                 if(otherval==NULL) {
194                         listval_new->Release();
195                         PyErr_SetString(PyExc_SystemError, "CList+other, "BGE_PROXY_ERROR_MSG);
196                         return NULL;
197                 }
198                 
199                 numitems = otherval->GetCount();
200                 
201                 /* copy the first part of the list */
202                 listval_new->Resize(numitems_orig + numitems); /* resize so we dont try release NULL pointers */
203                 for (i=0;i<numitems_orig;i++)
204                         listval_new->SetValue(i, listval->GetValue(i)->AddRef());
205                 
206                 /* now copy the other part of the list */
207                 for (i=0;i<numitems;i++)
208                         listval_new->SetValue(i+numitems_orig, otherval->GetValue(i)->AddRef());
209                 
210         }
211         return listval_new->NewProxy(true); /* python owns this list */
212 }
213
214 static int listvalue_buffer_contains(PyObject *self_v, PyObject *value)
215 {
216         CListValue *self= static_cast<CListValue *>(BGE_PROXY_REF(self_v));
217         
218         if (self==NULL) {
219                 PyErr_SetString(PyExc_SystemError, "val in CList, "BGE_PROXY_ERROR_MSG);
220                 return -1;
221         }
222         
223         if (PyUnicode_Check(value)) {
224                 if (self->FindValue((const char *)_PyUnicode_AsString(value))) {
225                         return 1;
226                 }
227         }
228         else if (PyObject_TypeCheck(value, &CValue::Type)) { /* not dict like at all but this worked before __contains__ was used */
229                 CValue *item= static_cast<CValue *>(BGE_PROXY_REF(value));
230                 for (int i=0; i < self->GetCount(); i++)
231                         if (self->GetValue(i) == item) // Com
232                                 return 1;
233                 
234         } // not using CheckEqual
235         
236         return 0;
237 }
238
239
240 static  PySequenceMethods listvalue_as_sequence = {
241         listvalue_bufferlen,//(inquiry)buffer_length, /*sq_length*/
242         listvalue_buffer_concat, /*sq_concat*/
243         NULL, /*sq_repeat*/
244         listvalue_buffer_item, /*sq_item*/
245 // TODO, slicing in py3
246         NULL, // listvalue_buffer_slice, /*sq_slice*/
247         NULL, /*sq_ass_item*/
248         NULL, /*sq_ass_slice*/
249         (objobjproc)listvalue_buffer_contains,  /* sq_contains */
250 };
251
252
253
254 /* Is this one used ? */
255 static  PyMappingMethods instance_as_mapping = {
256         listvalue_bufferlen, /*mp_length*/
257         listvalue_mapping_subscript, /*mp_subscript*/
258         NULL /*mp_ass_subscript*/
259 };
260
261
262
263 PyTypeObject CListValue::Type = {
264         PyVarObject_HEAD_INIT(NULL, 0)
265         "CListValue",                   /*tp_name*/
266         sizeof(PyObjectPlus_Proxy), /*tp_basicsize*/
267         0,                              /*tp_itemsize*/
268         /* methods */
269         py_base_dealloc,                        /*tp_dealloc*/
270         0,                              /*tp_print*/
271         0,                      /*tp_getattr*/
272         0,                      /*tp_setattr*/
273         0,                              /*tp_compare*/
274         py_base_repr,                           /*tp_repr*/
275         0,                              /*tp_as_number*/
276         &listvalue_as_sequence, /*tp_as_sequence*/
277         &instance_as_mapping,           /*tp_as_mapping*/
278         0,                              /*tp_hash*/
279         0,                              /*tp_call */
280         0,
281         NULL,
282         NULL,
283         0,
284         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
285         0,0,0,0,0,0,0,
286         Methods,
287         0,
288         0,
289         &CValue::Type,
290         0,0,0,0,0,0,
291         py_base_new
292 };
293
294 PyMethodDef CListValue::Methods[] = {
295         /* List style access */
296         {"append", (PyCFunction)CListValue::sPyappend,METH_O},
297         {"reverse", (PyCFunction)CListValue::sPyreverse,METH_NOARGS},
298         {"index", (PyCFunction)CListValue::sPyindex,METH_O},
299         {"count", (PyCFunction)CListValue::sPycount,METH_O},
300         
301         /* Dict style access */
302         {"get", (PyCFunction)CListValue::sPyget,METH_VARARGS},
303         
304         /* Own cvalue funcs */
305         {"from_id", (PyCFunction)CListValue::sPyfrom_id,METH_O},
306         
307         {NULL,NULL} //Sentinel
308 };
309
310 PyAttributeDef CListValue::Attributes[] = {
311         { NULL }        //Sentinel
312 };
313
314 //////////////////////////////////////////////////////////////////////
315 // Construction/Destruction
316 //////////////////////////////////////////////////////////////////////
317
318 CListValue::CListValue()
319 : CPropValue()
320 {
321         m_bReleaseContents=true;        
322 }
323
324
325
326 CListValue::~CListValue()
327 {
328
329         if (m_bReleaseContents) {
330                 for (unsigned int i=0;i<m_pValueArray.size();i++) {
331                         m_pValueArray[i]->Release();
332                 }
333         }
334 }
335
336
337 static STR_String gstrListRep=STR_String("List");
338
339 const STR_String & CListValue::GetText()
340 {
341         gstrListRep = "[";
342         STR_String commastr = "";
343
344         for (int i=0;i<GetCount();i++)
345         {
346                 gstrListRep += commastr;
347                 gstrListRep += GetValue(i)->GetText();
348                 commastr = ",";
349         }
350         gstrListRep += "]";
351
352         return gstrListRep;
353 }
354
355
356
357 CValue* CListValue::GetReplica() { 
358         CListValue* replica = new CListValue(*this);
359
360         replica->ProcessReplica();
361
362         replica->m_bReleaseContents=true; // for copy, complete array is copied for now...
363         // copy all values
364         int numelements = m_pValueArray.size();
365         unsigned int i=0;
366         replica->m_pValueArray.resize(numelements);
367         for (i=0;i<m_pValueArray.size();i++)
368                 replica->m_pValueArray[i] = m_pValueArray[i]->GetReplica();
369
370
371         return replica;
372 };
373
374
375
376 void CListValue::SetValue(int i, CValue *val)
377 {
378         assertd(i < m_pValueArray.size());
379         m_pValueArray[i]=val;
380 }
381
382
383
384 void CListValue::Resize(int num)
385 {
386         m_pValueArray.resize(num);
387 }
388
389
390
391 void CListValue::Remove(int i)
392 {
393         assertd(i<m_pValueArray.size());
394         m_pValueArray.erase(m_pValueArray.begin()+i);
395 }
396
397
398
399 void CListValue::ReleaseAndRemoveAll()
400 {
401         for (unsigned int i=0;i<m_pValueArray.size();i++)
402                 m_pValueArray[i]->Release();
403         m_pValueArray.clear();//.Clear();
404 }
405
406
407
408 CValue* CListValue::FindValue(const STR_String & name)
409 {
410         for (int i=0; i < GetCount(); i++)
411                 if (GetValue(i)->GetName() == name)
412                         return GetValue(i);
413         
414         return NULL;
415 }
416
417 CValue* CListValue::FindValue(const char * name)
418 {
419         for (int i=0; i < GetCount(); i++)
420                 if (GetValue(i)->GetName() == name)
421                         return GetValue(i);
422         
423         return NULL;
424 }
425
426 bool CListValue::SearchValue(CValue *val)
427 {
428         for (int i=0;i<GetCount();i++)
429                 if (val == GetValue(i))
430                         return true;
431         return false;
432 }
433
434
435
436 void CListValue::SetReleaseOnDestruct(bool bReleaseContents)
437 {
438         m_bReleaseContents = bReleaseContents;
439 }
440
441
442
443 bool CListValue::RemoveValue(CValue *val)
444 {
445         bool result=false;
446
447         for (int i=GetCount()-1;i>=0;i--)
448                 if (val == GetValue(i))
449                 {
450                         Remove(i);
451                         result=true;
452                 }
453         return result;
454 }
455
456
457
458 void CListValue::MergeList(CListValue *otherlist)
459 {
460
461         int numelements = this->GetCount();
462         int numotherelements = otherlist->GetCount();
463
464
465         Resize(numelements+numotherelements);
466
467         for (int i=0;i<numotherelements;i++)
468         {
469                 SetValue(i+numelements,otherlist->GetValue(i)->AddRef());
470         }
471 }
472
473
474 PyObject* CListValue::Pyappend(PyObject* value)
475 {
476         CValue* objval = ConvertPythonToValue(value, "CList.append(i): CValueList, ");
477
478         if (!objval) /* ConvertPythonToValue sets the error */
479                 return NULL;
480         
481         if (!BGE_PROXY_PYOWNS(m_proxy)) {
482                 PyErr_SetString(PyExc_TypeError, "CList.append(i): this CValueList is used internally for the game engine and can't be modified");
483                 return NULL;
484         }
485         
486         Add(objval);
487         
488         Py_RETURN_NONE;
489 }
490
491
492
493 PyObject* CListValue::Pyreverse()
494 {
495         std::reverse(m_pValueArray.begin(),m_pValueArray.end());
496         Py_RETURN_NONE;
497 }
498
499
500
501 bool CListValue::CheckEqual(CValue* first,CValue* second)
502 {
503         bool result = false;
504         
505         CValue* eqval =  ((CValue*)first)->Calc(VALUE_EQL_OPERATOR,(CValue*)second);
506         
507         if (eqval==NULL)
508                 return false;
509         const STR_String& text = eqval->GetText();
510         if (&text==&CBoolValue::sTrueString)
511         {
512                 result = true;
513         }
514         eqval->Release();
515         return result;
516
517 }
518
519
520
521 PyObject* CListValue::Pyindex(PyObject *value)
522 {
523         PyObject* result = NULL;
524
525         CValue* checkobj = ConvertPythonToValue(value, "val = cList[i]: CValueList, ");
526         if (checkobj==NULL)
527                 return NULL; /* ConvertPythonToValue sets the error */
528
529         int numelem = GetCount();
530         for (int i=0;i<numelem;i++)
531         {
532                 CValue* elem =                  GetValue(i);
533                 if (checkobj==elem || CheckEqual(checkobj,elem))
534                 {
535                         result = PyLong_FromSsize_t(i);
536                         break;
537                 }
538         }
539         checkobj->Release();
540
541         if (result==NULL) {
542                 PyErr_SetString(PyExc_ValueError, "CList.index(x): x not in CListValue");
543         }
544         return result;
545         
546 }
547
548
549
550 PyObject* CListValue::Pycount(PyObject* value)
551 {
552         int numfound = 0;
553
554         CValue* checkobj = ConvertPythonToValue(value, ""); /* error ignored */
555         
556         if (checkobj==NULL) { /* in this case just return that there are no items in the list */
557                 PyErr_Clear();
558                 return PyLong_FromSsize_t(0);
559         }
560
561         int numelem = GetCount();
562         for (int i=0;i<numelem;i++)
563         {
564                 CValue* elem =                  GetValue(i);
565                 if (checkobj==elem || CheckEqual(checkobj,elem))
566                 {
567                         numfound ++;
568                 }
569         }
570         checkobj->Release();
571
572         return PyLong_FromSsize_t(numfound);
573 }
574
575 /* Matches python dict.get(key, [default]) */
576 PyObject* CListValue::Pyget(PyObject *args)
577 {
578         char *key;
579         PyObject* def = Py_None;
580
581         if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
582                 return NULL;
583         
584         CValue *item = FindValue((const char *)key);
585         if (item) {     
586                 PyObject* pyobj = item->ConvertValueToPython();
587                 if (pyobj)
588                         return pyobj;
589                 else
590                         return item->GetProxy();
591         }
592         Py_INCREF(def);
593         return def;
594 }
595
596
597 PyObject* CListValue::Pyfrom_id(PyObject* value)
598 {
599         uintptr_t id= (uintptr_t)PyLong_AsVoidPtr(value);
600         
601         if (PyErr_Occurred())
602                 return NULL;
603
604         int numelem = GetCount();
605         for (int i=0;i<numelem;i++)
606         {
607                 if (reinterpret_cast<uintptr_t>(m_pValueArray[i]->m_proxy) == id)
608                         return GetValue(i)->GetProxy();
609         }
610         PyErr_SetString(PyExc_IndexError, "from_id(#): id not found in CValueList");
611         return NULL;    
612
613 }
614
615
616 /* --------------------------------------------------------------------- 
617  * Some stuff taken from the header
618  * --------------------------------------------------------------------- */
619 CValue* CListValue::Calc(VALUE_OPERATOR op,CValue *val) 
620 {
621         //assert(false); // todo: implement me!
622         static int error_printed =  0;
623         if (error_printed==0) {
624                 fprintf(stderr, "CValueList::Calc not yet implimented\n");
625                 error_printed = 1;
626         }
627         return NULL;
628 }
629
630 CValue* CListValue::CalcFinal(VALUE_DATA_TYPE dtype,
631                                                           VALUE_OPERATOR op, 
632                                                           CValue* val) 
633 {
634         //assert(false); // todo: implement me!
635         static int error_printed =  0;
636         if (error_printed==0) {
637                 fprintf(stderr, "CValueList::CalcFinal not yet implimented\n");
638                 error_printed = 1;
639         }
640         return NULL;
641 }
642
643
644
645 void CListValue::Add(CValue* value)
646 {
647         m_pValueArray.push_back(value);
648 }
649
650
651
652 double CListValue::GetNumber()
653 {
654         return -1;
655 }
656
657
658
659 void CListValue::SetModified(bool bModified)
660 {       
661         CValue::SetModified(bModified);
662         int numels = GetCount();
663
664         for (int i=0;i<numels;i++)
665                 GetValue(i)->SetModified(bModified);
666 }
667
668
669
670 bool CListValue::IsModified()
671 {
672         bool bmod = CValue::IsModified(); //normal own flag
673         int numels = GetCount();
674
675         for (int i=0;i<numels;i++)
676                 bmod = bmod || GetValue(i)->IsModified();
677
678         return bmod;
679 }