add 2 new utility functions to the BGE mesh py api.
[blender.git] / source / gameengine / Ketsji / KX_MeshProxy.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file gameengine/Ketsji/KX_MeshProxy.cpp
29  *  \ingroup ketsji
30  */
31
32
33 #ifdef WITH_PYTHON
34
35 #include "KX_MeshProxy.h"
36 #include "RAS_IPolygonMaterial.h"
37 #include "RAS_MeshObject.h"
38
39 #include "KX_VertexProxy.h"
40 #include "KX_PolyProxy.h"
41
42 #include "KX_PolygonMaterial.h"
43 #include "KX_BlenderMaterial.h"
44
45 #include "KX_PyMath.h"
46 #include "KX_ConvertPhysicsObject.h"
47
48 #include "PyObjectPlus.h" 
49
50 PyTypeObject KX_MeshProxy::Type = {
51         PyVarObject_HEAD_INIT(NULL, 0)
52         "KX_MeshProxy",
53         sizeof(PyObjectPlus_Proxy),
54         0,
55         py_base_dealloc,
56         0,
57         0,
58         0,
59         0,
60         py_base_repr,
61         0,0,0,0,0,0,0,0,0,
62         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
63         0,0,0,0,0,0,0,
64         Methods,
65         0,
66         0,
67         &CValue::Type,
68         0,0,0,0,0,0,
69         py_base_new
70 };
71
72 PyMethodDef KX_MeshProxy::Methods[] = {
73         {"getMaterialName", (PyCFunction)KX_MeshProxy::sPyGetMaterialName,METH_VARARGS},
74         {"getTextureName", (PyCFunction)KX_MeshProxy::sPyGetTextureName,METH_VARARGS},
75         {"getVertexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetVertexArrayLength,METH_VARARGS},
76         {"getVertex", (PyCFunction)KX_MeshProxy::sPyGetVertex,METH_VARARGS},
77         {"getPolygon", (PyCFunction)KX_MeshProxy::sPyGetPolygon,METH_VARARGS},
78         {"transform", (PyCFunction)KX_MeshProxy::sPyTransform,METH_VARARGS},
79         {"transform_uv", (PyCFunction)KX_MeshProxy::sPyTransformUV,METH_VARARGS},
80         //{"getIndexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetIndexArrayLength,METH_VARARGS},
81         {NULL,NULL} //Sentinel
82 };
83
84 PyAttributeDef KX_MeshProxy::Attributes[] = {
85         KX_PYATTRIBUTE_RO_FUNCTION("materials",         KX_MeshProxy, pyattr_get_materials),
86         KX_PYATTRIBUTE_RO_FUNCTION("numPolygons",       KX_MeshProxy, pyattr_get_numPolygons),
87         KX_PYATTRIBUTE_RO_FUNCTION("numMaterials",      KX_MeshProxy, pyattr_get_numMaterials),
88
89         { NULL }        //Sentinel
90 };
91
92 void KX_MeshProxy::SetMeshModified(bool v)
93 {
94         m_meshobj->SetMeshModified(v);
95 }
96
97 KX_MeshProxy::KX_MeshProxy(RAS_MeshObject* mesh)
98         : CValue(), m_meshobj(mesh)
99 {
100 }
101
102 KX_MeshProxy::~KX_MeshProxy()
103 {
104 }
105
106
107
108 // stuff for cvalue related things
109 CValue*         KX_MeshProxy::Calc(VALUE_OPERATOR op, CValue *val) { return NULL;}
110 CValue*         KX_MeshProxy::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) { return NULL;}
111
112 const STR_String &      KX_MeshProxy::GetText() {return m_meshobj->GetName();};
113 double          KX_MeshProxy::GetNumber() { return -1;}
114 STR_String&     KX_MeshProxy::GetName() { return m_meshobj->GetName();}
115 void            KX_MeshProxy::SetName(const char *name) { };
116 CValue*         KX_MeshProxy::GetReplica() { return NULL;}
117
118
119 // stuff for python integration
120
121 PyObject *KX_MeshProxy::PyGetMaterialName(PyObject *args, PyObject *kwds)
122 {
123         int matid= 1;
124         STR_String matname;
125
126         if (PyArg_ParseTuple(args,"i:getMaterialName",&matid))
127         {
128                 matname = m_meshobj->GetMaterialName(matid);
129         }
130         else {
131                 return NULL;
132         }
133
134         return PyUnicode_From_STR_String(matname);
135
136 }
137
138
139 PyObject *KX_MeshProxy::PyGetTextureName(PyObject *args, PyObject *kwds)
140 {
141         int matid= 1;
142         STR_String matname;
143
144         if (PyArg_ParseTuple(args,"i:getTextureName",&matid))
145         {
146                 matname = m_meshobj->GetTextureName(matid);
147         }
148         else {
149                 return NULL;
150         }
151
152         return PyUnicode_From_STR_String(matname);
153                 
154 }
155
156 PyObject *KX_MeshProxy::PyGetVertexArrayLength(PyObject *args, PyObject *kwds)
157 {
158         int matid= 0;
159         int length = 0;
160
161         
162         if (!PyArg_ParseTuple(args,"i:getVertexArrayLength",&matid))
163                 return NULL;
164         
165
166         RAS_MeshMaterial *mmat = m_meshobj->GetMeshMaterial(matid); /* can be NULL*/
167         
168         if (mmat)
169         {
170                 RAS_IPolyMaterial* mat = mmat->m_bucket->GetPolyMaterial();
171                 if (mat)
172                         length = m_meshobj->NumVertices(mat);
173         }
174         
175         return PyLong_FromSsize_t(length);
176 }
177
178
179 PyObject *KX_MeshProxy::PyGetVertex(PyObject *args, PyObject *kwds)
180 {
181         int vertexindex;
182         int matindex;
183
184         if (!PyArg_ParseTuple(args,"ii:getVertex",&matindex,&vertexindex))
185                 return NULL;
186         
187         RAS_TexVert* vertex = m_meshobj->GetVertex(matindex,vertexindex);
188         
189         if (vertex==NULL) {
190                 PyErr_SetString(PyExc_ValueError, "mesh.getVertex(mat_idx, vert_idx): KX_MeshProxy, could not get a vertex at the given indices");
191                 return NULL;
192         }
193         
194         return (new KX_VertexProxy(this, vertex))->NewProxy(true);
195 }
196
197 PyObject *KX_MeshProxy::PyGetPolygon(PyObject *args, PyObject *kwds)
198 {
199         int polyindex= 1;
200         PyObject *polyob = NULL;
201
202         if (!PyArg_ParseTuple(args,"i:getPolygon",&polyindex))
203                 return NULL;
204         
205         if (polyindex<0 || polyindex >= m_meshobj->NumPolygons())
206         {
207                 PyErr_SetString(PyExc_AttributeError, "mesh.getPolygon(int): KX_MeshProxy, invalid polygon index");
208                 return NULL;
209         }
210                 
211
212         RAS_Polygon* polygon = m_meshobj->GetPolygon(polyindex);
213         if (polygon)
214         {
215                 polyob = (new KX_PolyProxy(m_meshobj, polygon))->NewProxy(true);
216         }
217         else {
218                 PyErr_SetString(PyExc_AttributeError, "mesh.getPolygon(int): KX_MeshProxy, polygon is NULL, unknown reason");
219         }
220         return polyob;
221 }
222
223 PyObject *KX_MeshProxy::PyTransform(PyObject *args, PyObject *kwds)
224 {
225         int matindex;
226         PyObject *pymat;
227         bool ok = false;
228
229         MT_Matrix4x4 transform;
230
231         if (!PyArg_ParseTuple(args,"iO:transform", &matindex, &pymat) ||
232             !PyMatTo(pymat, transform))
233         {
234                 return NULL;
235         }
236
237         MT_Matrix4x4 ntransform = transform.inverse().transposed();
238         ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f;
239
240         /* transform mesh verts */
241         unsigned int mit_index = 0;
242         for (list<RAS_MeshMaterial>::iterator mit = m_meshobj->GetFirstMaterial();
243              (mit != m_meshobj->GetLastMaterial());
244              ++mit, ++mit_index)
245         {
246                 if (matindex == -1) {
247                         /* always transform */
248                 }
249                 else if (matindex == mit_index) {
250                         /* we found the right index! */
251                 }
252                 else {
253                         continue;
254                 }
255
256                 RAS_MeshSlot *slot = mit->m_baseslot;
257                 RAS_MeshSlot::iterator it;
258                 ok = true;
259
260                 for (slot->begin(it); !slot->end(it); slot->next(it)) {
261                         size_t i;
262                         for (i = it.startvertex; i < it.endvertex; i++) {
263                                 it.vertex[i].Transform(transform, ntransform);
264                         }
265                 }
266
267                 /* if we set a material index, quit when done */
268                 if (matindex == mit_index) {
269                         break;
270                 }
271         }
272
273         if (ok == false) {
274                 PyErr_Format(PyExc_ValueError,
275                              "mesh.transform(...): invalid material index %d", matindex);
276                 return NULL;
277         }
278
279         m_meshobj->SetMeshModified(true);
280
281         Py_RETURN_NONE;
282 }
283
284 PyObject *KX_MeshProxy::PyTransformUV(PyObject *args, PyObject *kwds)
285 {
286         int matindex;
287         PyObject *pymat;
288         int uvindex = -1;
289         bool ok = false;
290
291         MT_Matrix4x4 transform;
292
293         if (!PyArg_ParseTuple(args,"iO|ii:transform_uv", &matindex, &pymat, &uvindex) ||
294             !PyMatTo(pymat, transform))
295         {
296                 return NULL;
297         }
298
299         if (uvindex < -1 || uvindex > 1) {
300                 PyErr_Format(PyExc_ValueError,
301                              "mesh.transform_uv(...): invalid uv index %d", uvindex);
302                 return NULL;
303         }
304
305         /* transform mesh verts */
306         unsigned int mit_index = 0;
307         for (list<RAS_MeshMaterial>::iterator mit = m_meshobj->GetFirstMaterial();
308              (mit != m_meshobj->GetLastMaterial());
309              ++mit, ++mit_index)
310         {
311                 if (matindex == -1) {
312                         /* always transform */
313                 }
314                 else if (matindex == mit_index) {
315                         /* we found the right index! */
316                 }
317                 else {
318                         continue;
319                 }
320
321                 RAS_MeshSlot *slot = mit->m_baseslot;
322                 RAS_MeshSlot::iterator it;
323                 ok = true;
324
325                 for (slot->begin(it); !slot->end(it); slot->next(it)) {
326                         size_t i;
327
328                         for (i = it.startvertex; i < it.endvertex; i++) {
329                                 switch (uvindex) {
330                                         case 0:
331                                                 it.vertex[i].TransformUV(transform);
332                                                 break;
333                                         case 1:
334                                                 it.vertex[i].TransformUV2(transform);
335                                                 break;
336                                         case -1:
337                                                 it.vertex[i].TransformUV(transform);
338                                                 it.vertex[i].TransformUV2(transform);
339                                                 break;
340                                 }
341                         }
342                 }
343
344                 /* if we set a material index, quit when done */
345                 if (matindex == mit_index) {
346                         break;
347                 }
348         }
349
350         if (ok == false) {
351                 PyErr_Format(PyExc_ValueError,
352                              "mesh.transform_uv(...): invalid material index %d", matindex);
353                 return NULL;
354         }
355
356         m_meshobj->SetMeshModified(true);
357
358         Py_RETURN_NONE;
359 }
360
361 PyObject *KX_MeshProxy::pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
362 {
363         KX_MeshProxy* self = static_cast<KX_MeshProxy*>(self_v);
364         
365         int tot= self->m_meshobj->NumMaterials();
366         int i;
367         
368         PyObject *materials = PyList_New( tot );
369         
370         list<RAS_MeshMaterial>::iterator mit= self->m_meshobj->GetFirstMaterial();
371         
372         
373         for (i=0; i<tot; mit++, i++) {
374                 RAS_IPolyMaterial *polymat = mit->m_bucket->GetPolyMaterial();   
375                 
376                 /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject *)? - Campbell */
377                 if (polymat->GetFlag() & RAS_BLENDERMAT)         
378                 {        
379                         KX_BlenderMaterial *mat = static_cast<KX_BlenderMaterial*>(polymat);     
380                         PyList_SET_ITEM(materials, i, mat->GetProxy());
381                 }
382                 else {
383                         KX_PolygonMaterial *mat = static_cast<KX_PolygonMaterial*>(polymat);
384                         PyList_SET_ITEM(materials, i, mat->GetProxy());
385                 }
386         }
387         return materials;
388 }
389
390 PyObject * KX_MeshProxy::pyattr_get_numMaterials(void * selfv, const KX_PYATTRIBUTE_DEF * attrdef)
391 {
392         KX_MeshProxy * self = static_cast<KX_MeshProxy *> (selfv);
393         return PyLong_FromSsize_t(self->m_meshobj->NumMaterials());
394 }
395
396 PyObject * KX_MeshProxy::pyattr_get_numPolygons(void * selfv, const KX_PYATTRIBUTE_DEF * attrdef)
397 {
398         KX_MeshProxy * self = static_cast<KX_MeshProxy *> (selfv);
399         return PyLong_FromSsize_t(self->m_meshobj->NumPolygons());
400 }
401
402 /* a close copy of ConvertPythonToGameObject but for meshes */
403 bool ConvertPythonToMesh(PyObject *value, RAS_MeshObject **object, bool py_none_ok, const char *error_prefix)
404 {
405         if (value==NULL) {
406                 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
407                 *object = NULL;
408                 return false;
409         }
410                 
411         if (value==Py_None) {
412                 *object = NULL;
413                 
414                 if (py_none_ok) {
415                         return true;
416                 } else {
417                         PyErr_Format(PyExc_TypeError, "%s, expected KX_MeshProxy or a KX_MeshProxy name, None is invalid", error_prefix);
418                         return false;
419                 }
420         }
421         
422         if (PyUnicode_Check(value)) {
423                 *object = (RAS_MeshObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String( _PyUnicode_AsString(value) ));
424                 
425                 if (*object) {
426                         return true;
427                 } else {
428                         PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_MeshProxy in this scene", error_prefix, _PyUnicode_AsString(value));
429                         return false;
430                 }
431         }
432         
433         if (PyObject_TypeCheck(value, &KX_MeshProxy::Type)) {
434                 KX_MeshProxy *kx_mesh = static_cast<KX_MeshProxy*>BGE_PROXY_REF(value);
435                 
436                 /* sets the error */
437                 if (kx_mesh==NULL) {
438                         PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
439                         return false;
440                 }
441                 
442                 *object = kx_mesh->GetMesh();
443                 return true;
444         }
445         
446         *object = NULL;
447         
448         if (py_none_ok) {
449                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_MeshProxy, a string or None", error_prefix);
450         } else {
451                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_MeshProxy or a string", error_prefix);
452         }
453         
454         return false;
455 }
456
457 #endif // WITH_PYTHON