svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r22717:22875
[blender.git] / source / gameengine / Ketsji / KX_Camera.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Camera in the gameengine. Cameras are also used for views.
29  */
30  
31 #include "GL/glew.h"
32 #include "KX_Camera.h"
33 #include "KX_Scene.h"
34 #include "KX_PythonInit.h"
35 #include "KX_Python.h"
36 #include "KX_PyMath.h"
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 KX_Camera::KX_Camera(void* sgReplicationInfo,
42                                          SG_Callbacks callbacks,
43                                          const RAS_CameraData& camdata,
44                                          bool frustum_culling,
45                                          bool delete_node)
46                                         :
47                                         KX_GameObject(sgReplicationInfo,callbacks),
48                                         m_camdata(camdata),
49                                         m_dirty(true),
50                                         m_normalized(false),
51                                         m_frustum_culling(frustum_culling),
52                                         m_set_projection_matrix(false),
53                                         m_set_frustum_center(false),
54                                         m_delete_node(delete_node)
55 {
56         // setting a name would be nice...
57         m_name = "cam";
58         m_projection_matrix.setIdentity();
59         m_modelview_matrix.setIdentity();
60         CValue* val = new CIntValue(1);
61         SetProperty("camera",val);
62         val->Release();
63 }
64
65
66 KX_Camera::~KX_Camera()
67 {
68         if (m_delete_node && m_pSGNode)
69         {
70                 // for shadow camera, avoids memleak
71                 delete m_pSGNode;
72                 m_pSGNode = NULL;
73         }
74 }       
75
76
77 CValue* KX_Camera::GetReplica()
78 {
79         KX_Camera* replica = new KX_Camera(*this);
80         
81         // this will copy properties and so on...
82         replica->ProcessReplica();
83         
84         return replica;
85 }
86
87 void KX_Camera::ProcessReplica()
88 {
89         KX_GameObject::ProcessReplica();
90         // replicated camera are always registered in the scene
91         m_delete_node = false;
92 }
93
94 MT_Transform KX_Camera::GetWorldToCamera() const
95
96         MT_Transform camtrans;
97         camtrans.invert(MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation()));
98         
99         return camtrans;
100 }
101
102
103          
104 MT_Transform KX_Camera::GetCameraToWorld() const
105 {
106         return MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation());
107 }
108
109
110
111 void KX_Camera::CorrectLookUp(MT_Scalar speed)
112 {
113 }
114
115
116
117 const MT_Point3 KX_Camera::GetCameraLocation() const
118 {
119         /* this is the camera locatio in cam coords... */
120         //return m_trans1.getOrigin();
121         //return MT_Point3(0,0,0);   <-----
122         /* .... I want it in world coords */
123         //MT_Transform trans;
124         //trans.setBasis(NodeGetWorldOrientation());
125         
126         return NodeGetWorldPosition();          
127 }
128
129
130
131 /* I want the camera orientation as well. */
132 const MT_Quaternion KX_Camera::GetCameraOrientation() const
133 {
134         return NodeGetWorldOrientation().getRotation();
135 }
136
137
138
139 /**
140 * Sets the projection matrix that is used by the rasterizer.
141 */
142 void KX_Camera::SetProjectionMatrix(const MT_Matrix4x4 & mat)
143 {
144         m_projection_matrix = mat;
145         m_dirty = true;
146         m_set_projection_matrix = true;
147         m_set_frustum_center = false;
148 }
149
150
151
152 /**
153 * Sets the modelview matrix that is used by the rasterizer.
154 */
155 void KX_Camera::SetModelviewMatrix(const MT_Matrix4x4 & mat)
156 {
157         m_modelview_matrix = mat;
158         m_dirty = true;
159         m_set_frustum_center = false;
160 }
161
162
163
164 /**
165 * Gets the projection matrix that is used by the rasterizer.
166 */
167 const MT_Matrix4x4& KX_Camera::GetProjectionMatrix() const
168 {
169         return m_projection_matrix;
170 }
171
172
173
174 /**
175 * Gets the modelview matrix that is used by the rasterizer.
176 */
177 const MT_Matrix4x4& KX_Camera::GetModelviewMatrix() const
178 {
179         return m_modelview_matrix;
180 }
181
182
183 bool KX_Camera::hasValidProjectionMatrix() const
184 {
185         return m_set_projection_matrix;
186 }
187
188 void KX_Camera::InvalidateProjectionMatrix(bool valid)
189 {
190         m_set_projection_matrix = valid;
191 }
192
193
194 /*
195 * These getters retrieve the clip data and the focal length
196 */
197 float KX_Camera::GetLens() const
198 {
199         return m_camdata.m_lens;
200 }
201
202 float KX_Camera::GetScale() const
203 {
204         return m_camdata.m_scale;
205 }
206
207
208
209 float KX_Camera::GetCameraNear() const
210 {
211         return m_camdata.m_clipstart;
212 }
213
214
215
216 float KX_Camera::GetCameraFar() const
217 {
218         return m_camdata.m_clipend;
219 }
220
221 float KX_Camera::GetFocalLength() const
222 {
223         return m_camdata.m_focallength;
224 }
225
226
227
228 RAS_CameraData* KX_Camera::GetCameraData()
229 {
230         return &m_camdata; 
231 }
232
233 void KX_Camera::ExtractClipPlanes()
234 {
235         if (!m_dirty)
236                 return;
237
238         MT_Matrix4x4 m = m_projection_matrix * m_modelview_matrix;
239         // Left clip plane
240         m_planes[0] = m[3] + m[0];
241         // Right clip plane
242         m_planes[1] = m[3] - m[0];
243         // Top clip plane
244         m_planes[2] = m[3] - m[1];
245         // Bottom clip plane
246         m_planes[3] = m[3] + m[1];
247         // Near clip plane
248         m_planes[4] = m[3] + m[2];
249         // Far clip plane
250         m_planes[5] = m[3] - m[2];
251         
252         m_dirty = false;
253         m_normalized = false;
254 }
255
256 void KX_Camera::NormalizeClipPlanes()
257 {
258         if (m_normalized)
259                 return;
260         
261         for (unsigned int p = 0; p < 6; p++)
262         {
263                 MT_Scalar factor = sqrt(m_planes[p][0]*m_planes[p][0] + m_planes[p][1]*m_planes[p][1] + m_planes[p][2]*m_planes[p][2]);
264                 if (!MT_fuzzyZero(factor))
265                         m_planes[p] /= factor;
266         }
267         
268         m_normalized = true;
269 }
270
271 void KX_Camera::ExtractFrustumSphere()
272 {
273         if (m_set_frustum_center)
274                 return;
275
276     // compute sphere for the general case and not only symmetric frustum:
277     // the mirror code in ImageRender can use very asymmetric frustum.
278     // We will put the sphere center on the line that goes from origin to the center of the far clipping plane
279     // This is the optimal position if the frustum is symmetric or very asymmetric and probably close
280     // to optimal for the general case. The sphere center position is computed so that the distance to 
281     // the near and far extreme frustum points are equal.
282
283     // get the transformation matrix from device coordinate to camera coordinate
284         MT_Matrix4x4 clip_camcs_matrix = m_projection_matrix;
285         clip_camcs_matrix.invert();
286
287         if (m_projection_matrix[3][3] == MT_Scalar(0.0)) 
288         {
289                 // frustrum projection
290                 // detect which of the corner of the far clipping plane is the farthest to the origin
291                 MT_Vector4 nfar;    // far point in device normalized coordinate
292                 MT_Point3 farpoint; // most extreme far point in camera coordinate
293                 MT_Point3 nearpoint;// most extreme near point in camera coordinate
294                 MT_Point3 farcenter(0.,0.,0.);// center of far cliping plane in camera coordinate
295                 MT_Scalar F=-1.0, N; // square distance of far and near point to origin
296                 MT_Scalar f, n;     // distance of far and near point to z axis. f is always > 0 but n can be < 0
297                 MT_Scalar e, s;     // far and near clipping distance (<0)
298                 MT_Scalar c;        // slope of center line = distance of far clipping center to z axis / far clipping distance
299                 MT_Scalar z;        // projection of sphere center on z axis (<0)
300                 // tmp value
301                 MT_Vector4 npoint(1., 1., 1., 1.);
302                 MT_Vector4 hpoint;
303                 MT_Point3 point;
304                 MT_Scalar len;
305                 for (int i=0; i<4; i++)
306                 {
307                 hpoint = clip_camcs_matrix*npoint;
308                         point.setValue(hpoint[0]/hpoint[3], hpoint[1]/hpoint[3], hpoint[2]/hpoint[3]);
309                         len = point.dot(point);
310                         if (len > F)
311                         {
312                                 nfar = npoint;
313                                 farpoint = point;
314                                 F = len;
315                         }
316                         // rotate by 90 degree along the z axis to walk through the 4 extreme points of the far clipping plane
317                         len = npoint[0];
318                         npoint[0] = -npoint[1];
319                         npoint[1] = len;
320                         farcenter += point;
321                 }
322                 // the far center is the average of the far clipping points
323                 farcenter *= 0.25;
324                 // the extreme near point is the opposite point on the near clipping plane
325                 nfar.setValue(-nfar[0], -nfar[1], -1., 1.);
326                 nfar = clip_camcs_matrix*nfar;
327                 nearpoint.setValue(nfar[0]/nfar[3], nfar[1]/nfar[3], nfar[2]/nfar[3]);
328                 // this is a frustrum projection
329                 N = nearpoint.dot(nearpoint);
330                 e = farpoint[2];
331                 s = nearpoint[2];
332                 // projection on XY plane for distance to axis computation
333                 MT_Point2 farxy(farpoint[0], farpoint[1]);
334                 // f is forced positive by construction
335                 f = farxy.length();
336                 // get corresponding point on the near plane
337                 farxy *= s/e;
338                 // this formula preserve the sign of n
339                 n = f*s/e - MT_Point2(nearpoint[0]-farxy[0], nearpoint[1]-farxy[1]).length();
340                 c = MT_Point2(farcenter[0], farcenter[1]).length()/e;
341                 // the big formula, it simplifies to (F-N)/(2(e-s)) for the symmetric case
342                 z = (F-N)/(2.0*(e-s+c*(f-n)));
343                 m_frustum_center = MT_Point3(farcenter[0]*z/e, farcenter[1]*z/e, z);
344                 m_frustum_radius = m_frustum_center.distance(farpoint);
345         } 
346         else
347         {
348                 // orthographic projection
349                 // The most extreme points on the near and far plane. (normalized device coords)
350                 MT_Vector4 hnear(1., 1., 1., 1.), hfar(-1., -1., -1., 1.);
351                 
352                 // Transform to hom camera local space
353                 hnear = clip_camcs_matrix*hnear;
354                 hfar = clip_camcs_matrix*hfar;
355                 
356                 // Tranform to 3d camera local space.
357                 MT_Point3 nearpoint(hnear[0]/hnear[3], hnear[1]/hnear[3], hnear[2]/hnear[3]);
358                 MT_Point3 farpoint(hfar[0]/hfar[3], hfar[1]/hfar[3], hfar[2]/hfar[3]);
359                 
360                 // just use mediant point
361                 m_frustum_center = (farpoint + nearpoint)*0.5;
362                 m_frustum_radius = m_frustum_center.distance(farpoint);
363         }
364         // Transform to world space.
365         m_frustum_center = GetCameraToWorld()(m_frustum_center);
366         m_frustum_radius /= fabs(NodeGetWorldScaling()[NodeGetWorldScaling().closestAxis()]);
367         
368         m_set_frustum_center = true;
369 }
370
371 bool KX_Camera::PointInsideFrustum(const MT_Point3& x)
372 {
373         ExtractClipPlanes();
374         
375         for( unsigned int i = 0; i < 6 ; i++ )
376         {
377                 if (m_planes[i][0]*x[0] + m_planes[i][1]*x[1] + m_planes[i][2]*x[2] + m_planes[i][3] < 0.)
378                         return false;
379         }
380         return true;
381 }
382
383 int KX_Camera::BoxInsideFrustum(const MT_Point3 *box)
384 {
385         ExtractClipPlanes();
386         
387         unsigned int insideCount = 0;
388         // 6 view frustum planes
389         for( unsigned int p = 0; p < 6 ; p++ )
390         {
391                 unsigned int behindCount = 0;
392                 // 8 box verticies.
393                 for (unsigned int v = 0; v < 8 ; v++)
394                 {
395                         if (m_planes[p][0]*box[v][0] + m_planes[p][1]*box[v][1] + m_planes[p][2]*box[v][2] + m_planes[p][3] < 0.)
396                                 behindCount++;
397                 }
398                 
399                 // 8 points behind this plane
400                 if (behindCount == 8)
401                         return OUTSIDE;
402
403                 // Every box vertex is on the front side of this plane
404                 if (!behindCount)
405                         insideCount++;
406         }
407         
408         // All box verticies are on the front side of all frustum planes.
409         if (insideCount == 6)
410                 return INSIDE;
411         
412         return INTERSECT;
413 }
414
415 int KX_Camera::SphereInsideFrustum(const MT_Point3& center, const MT_Scalar &radius)
416 {
417         ExtractFrustumSphere();
418         if (center.distance2(m_frustum_center) > (radius + m_frustum_radius)*(radius + m_frustum_radius))
419                 return OUTSIDE;
420
421         unsigned int p;
422         ExtractClipPlanes();
423         NormalizeClipPlanes();
424                 
425         MT_Scalar distance;
426         int intersect = INSIDE;
427         // distance:  <-------- OUTSIDE -----|----- INTERSECT -----0----- INTERSECT -----|----- INSIDE -------->
428         //                                -radius                                      radius
429         for (p = 0; p < 6; p++)
430         {
431                 distance = m_planes[p][0]*center[0] + m_planes[p][1]*center[1] + m_planes[p][2]*center[2] + m_planes[p][3];
432                 if (fabs(distance) <= radius)
433                         intersect = INTERSECT;
434                 else if (distance < -radius)
435                         return OUTSIDE;
436         }
437         
438         return intersect;
439 }
440
441 bool KX_Camera::GetFrustumCulling() const
442 {
443         return m_frustum_culling;
444 }
445  
446 void KX_Camera::EnableViewport(bool viewport)
447 {
448         m_camdata.m_viewport = viewport;
449 }
450
451 void KX_Camera::SetViewport(int left, int bottom, int right, int top)
452 {
453         m_camdata.m_viewportleft = left;
454         m_camdata.m_viewportbottom = bottom;
455         m_camdata.m_viewportright = right;
456         m_camdata.m_viewporttop = top;
457 }
458
459 bool KX_Camera::GetViewport() const
460 {
461         return m_camdata.m_viewport;
462 }
463
464 int KX_Camera::GetViewportLeft() const
465 {
466         return m_camdata.m_viewportleft;
467 }
468
469 int KX_Camera::GetViewportBottom() const
470 {
471         return m_camdata.m_viewportbottom;
472 }
473
474 int KX_Camera::GetViewportRight() const
475 {
476         return m_camdata.m_viewportright;
477 }
478
479 int KX_Camera::GetViewportTop() const
480 {
481         return m_camdata.m_viewporttop;
482 }
483
484 //----------------------------------------------------------------------------
485 //Python
486
487
488 PyMethodDef KX_Camera::Methods[] = {
489         KX_PYMETHODTABLE(KX_Camera, sphereInsideFrustum),
490         KX_PYMETHODTABLE_O(KX_Camera, boxInsideFrustum),
491         KX_PYMETHODTABLE_O(KX_Camera, pointInsideFrustum),
492         KX_PYMETHODTABLE_NOARGS(KX_Camera, getCameraToWorld),
493         KX_PYMETHODTABLE_NOARGS(KX_Camera, getWorldToCamera),
494         KX_PYMETHODTABLE(KX_Camera, setViewport),
495         KX_PYMETHODTABLE_NOARGS(KX_Camera, setOnTop),
496         KX_PYMETHODTABLE_O(KX_Camera, getScreenPosition),
497         KX_PYMETHODTABLE(KX_Camera, getScreenVect),
498         KX_PYMETHODTABLE(KX_Camera, getScreenRay),
499         {NULL,NULL} //Sentinel
500 };
501
502 PyAttributeDef KX_Camera::Attributes[] = {
503         
504         KX_PYATTRIBUTE_BOOL_RW("frustum_culling", KX_Camera, m_frustum_culling),
505         KX_PYATTRIBUTE_RW_FUNCTION("perspective", KX_Camera, pyattr_get_perspective, pyattr_set_perspective),
506         
507         KX_PYATTRIBUTE_RW_FUNCTION("lens",      KX_Camera,      pyattr_get_lens, pyattr_set_lens),
508         KX_PYATTRIBUTE_RW_FUNCTION("near",      KX_Camera,      pyattr_get_near, pyattr_set_near),
509         KX_PYATTRIBUTE_RW_FUNCTION("far",       KX_Camera,      pyattr_get_far,  pyattr_set_far),
510         
511         KX_PYATTRIBUTE_RW_FUNCTION("useViewport",       KX_Camera,      pyattr_get_use_viewport,  pyattr_set_use_viewport),
512         
513         KX_PYATTRIBUTE_RW_FUNCTION("projection_matrix", KX_Camera,      pyattr_get_projection_matrix, pyattr_set_projection_matrix),
514         KX_PYATTRIBUTE_RO_FUNCTION("modelview_matrix",  KX_Camera,      pyattr_get_modelview_matrix),
515         KX_PYATTRIBUTE_RO_FUNCTION("camera_to_world",   KX_Camera,      pyattr_get_camera_to_world),
516         KX_PYATTRIBUTE_RO_FUNCTION("world_to_camera",   KX_Camera,      pyattr_get_world_to_camera),
517         
518         /* Grrr, functions for constants? */
519         KX_PYATTRIBUTE_RO_FUNCTION("INSIDE",    KX_Camera, pyattr_get_INSIDE),
520         KX_PYATTRIBUTE_RO_FUNCTION("OUTSIDE",   KX_Camera, pyattr_get_OUTSIDE),
521         KX_PYATTRIBUTE_RO_FUNCTION("INTERSECT", KX_Camera, pyattr_get_INTERSECT),
522         
523         { NULL }        //Sentinel
524 };
525
526 PyTypeObject KX_Camera::Type = {
527         PyVarObject_HEAD_INIT(NULL, 0)
528         "KX_Camera",
529         sizeof(PyObjectPlus_Proxy),
530         0,
531         py_base_dealloc,
532         0,
533         0,
534         0,
535         0,
536         py_base_repr,
537         0,
538         &KX_GameObject::Sequence,
539         &KX_GameObject::Mapping,
540         0,0,0,
541         NULL,
542         NULL,
543         0,
544         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
545         0,0,0,0,0,0,0,
546         Methods,
547         0,
548         0,
549         &KX_GameObject::Type,
550         0,0,0,0,0,0,
551         py_base_new
552 };
553
554 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, sphereInsideFrustum,
555 "sphereInsideFrustum(center, radius) -> Integer\n"
556 "\treturns INSIDE, OUTSIDE or INTERSECT if the given sphere is\n"
557 "\tinside/outside/intersects this camera's viewing frustum.\n\n"
558 "\tcenter = the center of the sphere (in world coordinates.)\n"
559 "\tradius = the radius of the sphere\n\n"
560 "\tExample:\n"
561 "\timport GameLogic\n\n"
562 "\tco = GameLogic.getCurrentController()\n"
563 "\tcam = co.GetOwner()\n\n"
564 "\t# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]\n"
565 "\tif (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):\n"
566 "\t\t# Sphere is inside frustum !\n"
567 "\t\t# Do something useful !\n"
568 "\telse:\n"
569 "\t\t# Sphere is outside frustum\n"
570 )
571 {
572         PyObject *pycenter;
573         float radius;
574         if (PyArg_ParseTuple(args, "Of:sphereInsideFrustum", &pycenter, &radius))
575         {
576                 MT_Point3 center;
577                 if (PyVecTo(pycenter, center))
578                 {
579                         return PyLong_FromSsize_t(SphereInsideFrustum(center, radius)); /* new ref */
580                 }
581         }
582
583         PyErr_SetString(PyExc_TypeError, "camera.sphereInsideFrustum(center, radius): KX_Camera, expected arguments: (center, radius)");
584         
585         return NULL;
586 }
587
588 KX_PYMETHODDEF_DOC_O(KX_Camera, boxInsideFrustum,
589 "boxInsideFrustum(box) -> Integer\n"
590 "\treturns INSIDE, OUTSIDE or INTERSECT if the given box is\n"
591 "\tinside/outside/intersects this camera's viewing frustum.\n\n"
592 "\tbox = a list of the eight (8) corners of the box (in world coordinates.)\n\n"
593 "\tExample:\n"
594 "\timport GameLogic\n\n"
595 "\tco = GameLogic.getCurrentController()\n"
596 "\tcam = co.GetOwner()\n\n"
597 "\tbox = []\n"
598 "\tbox.append([-1.0, -1.0, -1.0])\n"
599 "\tbox.append([-1.0, -1.0,  1.0])\n"
600 "\tbox.append([-1.0,  1.0, -1.0])\n"
601 "\tbox.append([-1.0,  1.0,  1.0])\n"
602 "\tbox.append([ 1.0, -1.0, -1.0])\n"
603 "\tbox.append([ 1.0, -1.0,  1.0])\n"
604 "\tbox.append([ 1.0,  1.0, -1.0])\n"
605 "\tbox.append([ 1.0,  1.0,  1.0])\n\n"
606 "\tif (cam.boxInsideFrustum(box) != cam.OUTSIDE):\n"
607 "\t\t# Box is inside/intersects frustum !\n"
608 "\t\t# Do something useful !\n"
609 "\telse:\n"
610 "\t\t# Box is outside the frustum !\n"
611 )
612 {
613         unsigned int num_points = PySequence_Size(value);
614         if (num_points != 8)
615         {
616                 PyErr_Format(PyExc_TypeError, "camera.boxInsideFrustum(box): KX_Camera, expected eight (8) points, got %d", num_points);
617                 return NULL;
618         }
619         
620         MT_Point3 box[8];
621         for (unsigned int p = 0; p < 8 ; p++)
622         {
623                 PyObject *item = PySequence_GetItem(value, p); /* new ref */
624                 bool error = !PyVecTo(item, box[p]);
625                 Py_DECREF(item);
626                 if (error)
627                         return NULL;
628         }
629         
630         return PyLong_FromSsize_t(BoxInsideFrustum(box)); /* new ref */
631 }
632
633 KX_PYMETHODDEF_DOC_O(KX_Camera, pointInsideFrustum,
634 "pointInsideFrustum(point) -> Bool\n"
635 "\treturns 1 if the given point is inside this camera's viewing frustum.\n\n"
636 "\tpoint = The point to test (in world coordinates.)\n\n"
637 "\tExample:\n"
638 "\timport GameLogic\n\n"
639 "\tco = GameLogic.getCurrentController()\n"
640 "\tcam = co.GetOwner()\n\n"
641 "\t# Test point [0.0, 0.0, 0.0]"
642 "\tif (cam.pointInsideFrustum([0.0, 0.0, 0.0])):\n"
643 "\t\t# Point is inside frustum !\n"
644 "\t\t# Do something useful !\n"
645 "\telse:\n"
646 "\t\t# Box is outside the frustum !\n"
647 )
648 {
649         MT_Point3 point;
650         if (PyVecTo(value, point))
651         {
652                 return PyLong_FromSsize_t(PointInsideFrustum(point)); /* new ref */
653         }
654         
655         PyErr_SetString(PyExc_TypeError, "camera.pointInsideFrustum(point): KX_Camera, expected point argument.");
656         return NULL;
657 }
658
659 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getCameraToWorld,
660 "getCameraToWorld() -> Matrix4x4\n"
661 "\treturns the camera to world transformation matrix, as a list of four lists of four values.\n\n"
662 "\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
663 )
664 {
665         return PyObjectFrom(GetCameraToWorld()); /* new ref */
666 }
667
668 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getWorldToCamera,
669 "getWorldToCamera() -> Matrix4x4\n"
670 "\treturns the world to camera transformation matrix, as a list of four lists of four values.\n\n"
671 "\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
672 )
673 {
674         return PyObjectFrom(GetWorldToCamera()); /* new ref */
675 }
676
677 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, setViewport,
678 "setViewport(left, bottom, right, top)\n"
679 "Sets this camera's viewport\n")
680 {
681         int left, bottom, right, top;
682         if (!PyArg_ParseTuple(args,"iiii:setViewport",&left, &bottom, &right, &top))
683                 return NULL;
684         
685         SetViewport(left, bottom, right, top);
686         Py_RETURN_NONE;
687 }
688
689 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, setOnTop,
690 "setOnTop()\n"
691 "Sets this camera's viewport on top\n")
692 {
693         class KX_Scene* scene = KX_GetActiveScene();
694         scene->SetCameraOnTop(this);
695         Py_RETURN_NONE;
696 }
697
698 PyObject* KX_Camera::pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
699 {
700         KX_Camera* self= static_cast<KX_Camera*>(self_v);
701         return PyBool_FromLong(self->m_camdata.m_perspective);
702 }
703
704 int KX_Camera::pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
705 {
706         KX_Camera* self= static_cast<KX_Camera*>(self_v);
707         int param = PyObject_IsTrue( value );
708         if (param == -1) {
709                 PyErr_SetString(PyExc_AttributeError, "camera.perspective = bool: KX_Camera, expected True/False or 0/1");
710                 return PY_SET_ATTR_FAIL;
711         }
712         
713         self->m_camdata.m_perspective= param;
714         return PY_SET_ATTR_SUCCESS;
715 }
716
717 PyObject* KX_Camera::pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
718 {
719         KX_Camera* self= static_cast<KX_Camera*>(self_v);
720         return PyFloat_FromDouble(self->m_camdata.m_lens);
721 }
722
723 int KX_Camera::pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
724 {
725         KX_Camera* self= static_cast<KX_Camera*>(self_v);
726         float param = PyFloat_AsDouble(value);
727         if (param == -1) {
728                 PyErr_SetString(PyExc_AttributeError, "camera.lens = float: KX_Camera, expected a float greater then zero");
729                 return PY_SET_ATTR_FAIL;
730         }
731         
732         self->m_camdata.m_lens= param;
733         self->m_set_projection_matrix = false;
734         return PY_SET_ATTR_SUCCESS;
735 }
736
737 PyObject* KX_Camera::pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
738 {
739         KX_Camera* self= static_cast<KX_Camera*>(self_v);
740         return PyFloat_FromDouble(self->m_camdata.m_clipstart);
741 }
742
743 int KX_Camera::pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
744 {
745         KX_Camera* self= static_cast<KX_Camera*>(self_v);
746         float param = PyFloat_AsDouble(value);
747         if (param == -1) {
748                 PyErr_SetString(PyExc_AttributeError, "camera.near = float: KX_Camera, expected a float greater then zero");
749                 return PY_SET_ATTR_FAIL;
750         }
751         
752         self->m_camdata.m_clipstart= param;
753         self->m_set_projection_matrix = false;
754         return PY_SET_ATTR_SUCCESS;
755 }
756
757 PyObject* KX_Camera::pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
758 {
759         KX_Camera* self= static_cast<KX_Camera*>(self_v);
760         return PyFloat_FromDouble(self->m_camdata.m_clipend);
761 }
762
763 int KX_Camera::pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
764 {
765         KX_Camera* self= static_cast<KX_Camera*>(self_v);
766         float param = PyFloat_AsDouble(value);
767         if (param == -1) {
768                 PyErr_SetString(PyExc_AttributeError, "camera.far = float: KX_Camera, expected a float greater then zero");
769                 return PY_SET_ATTR_FAIL;
770         }
771         
772         self->m_camdata.m_clipend= param;
773         self->m_set_projection_matrix = false;
774         return PY_SET_ATTR_SUCCESS;
775 }
776
777
778 PyObject* KX_Camera::pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
779 {
780         KX_Camera* self= static_cast<KX_Camera*>(self_v);
781         return PyBool_FromLong(self->GetViewport());
782 }
783
784 int KX_Camera::pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
785 {
786         KX_Camera* self= static_cast<KX_Camera*>(self_v);
787         int param = PyObject_IsTrue( value );
788         if (param == -1) {
789                 PyErr_SetString(PyExc_AttributeError, "camera.useViewport = bool: KX_Camera, expected True or False");
790                 return PY_SET_ATTR_FAIL;
791         }
792         self->EnableViewport((bool)param);
793         return PY_SET_ATTR_SUCCESS;
794 }
795
796
797 PyObject* KX_Camera::pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
798 {
799         KX_Camera* self= static_cast<KX_Camera*>(self_v);
800         return PyObjectFrom(self->GetProjectionMatrix()); 
801 }
802
803 int KX_Camera::pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
804 {
805         KX_Camera* self= static_cast<KX_Camera*>(self_v);
806         MT_Matrix4x4 mat;
807         if (!PyMatTo(value, mat)) 
808                 return PY_SET_ATTR_FAIL;
809         
810         self->SetProjectionMatrix(mat);
811         return PY_SET_ATTR_SUCCESS;
812 }
813
814 PyObject* KX_Camera::pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
815 {
816         KX_Camera* self= static_cast<KX_Camera*>(self_v);
817         return PyObjectFrom(self->GetModelviewMatrix()); 
818 }
819
820 PyObject* KX_Camera::pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
821 {
822         KX_Camera* self= static_cast<KX_Camera*>(self_v);
823         return PyObjectFrom(self->GetCameraToWorld());
824 }
825
826 PyObject* KX_Camera::pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
827 {
828         KX_Camera* self= static_cast<KX_Camera*>(self_v);
829         return PyObjectFrom(self->GetWorldToCamera()); 
830 }
831
832
833 PyObject* KX_Camera::pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
834 {       return PyLong_FromSsize_t(INSIDE); }
835 PyObject* KX_Camera::pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
836 {       return PyLong_FromSsize_t(OUTSIDE); }
837 PyObject* KX_Camera::pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
838 {       return PyLong_FromSsize_t(INTERSECT); }
839
840
841 bool ConvertPythonToCamera(PyObject * value, KX_Camera **object, bool py_none_ok, const char *error_prefix)
842 {
843         if (value==NULL) {
844                 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
845                 *object = NULL;
846                 return false;
847         }
848                 
849         if (value==Py_None) {
850                 *object = NULL;
851                 
852                 if (py_none_ok) {
853                         return true;
854                 } else {
855                         PyErr_Format(PyExc_TypeError, "%s, expected KX_Camera or a KX_Camera name, None is invalid", error_prefix);
856                         return false;
857                 }
858         }
859         
860         if (PyUnicode_Check(value)) {
861                 STR_String value_str = _PyUnicode_AsString(value);
862                 *object = KX_GetActiveScene()->FindCamera(value_str);
863                 
864                 if (*object) {
865                         return true;
866                 } else {
867                         PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_Camera in this scene", error_prefix, _PyUnicode_AsString(value));
868                         return false;
869                 }
870         }
871         
872         if (PyObject_TypeCheck(value, &KX_Camera::Type)) {
873                 *object = static_cast<KX_Camera*>BGE_PROXY_REF(value);
874                 
875                 /* sets the error */
876                 if (*object==NULL) {
877                         PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
878                         return false;
879                 }
880                 
881                 return true;
882         }
883         
884         *object = NULL;
885         
886         if (py_none_ok) {
887                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera, a string or None", error_prefix);
888         } else {
889                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera or a string", error_prefix);
890         }
891         
892         return false;
893 }
894
895 KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition,
896 "getScreenPosition()\n"
897 )
898
899 {
900         MT_Vector3 vect;
901         KX_GameObject *obj = NULL;
902
903         if (!PyVecTo(value, vect))
904         {
905                 if(ConvertPythonToGameObject(value, &obj, true, ""))
906                 {
907                         PyErr_Clear();
908                         vect = MT_Vector3(obj->NodeGetWorldPosition());
909                 }
910                 else
911                 {
912                         PyErr_SetString(PyExc_TypeError, "Error in getScreenPosition. Expected a Vector3 or a KX_GameObject or a string for a name of a KX_GameObject");
913                         return NULL;
914                 }
915         }
916
917         GLint viewport[4];
918         GLdouble win[3];
919         GLdouble modelmatrix[16];
920         GLdouble projmatrix[16];
921
922         MT_Matrix4x4 m_modelmatrix = this->GetModelviewMatrix();
923         MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();
924
925         m_modelmatrix.getValue(modelmatrix);
926         m_projmatrix.getValue(projmatrix);
927
928         glGetIntegerv(GL_VIEWPORT, viewport);
929
930         gluProject(vect[0], vect[1], vect[2], modelmatrix, projmatrix, viewport, &win[0], &win[1], &win[2]);
931
932         vect[0] =  (win[0] - viewport[0]) / viewport[2];
933         vect[1] =  (win[1] - viewport[1]) / viewport[3];
934
935         vect[1] = 1.0 - vect[1]; //to follow Blender window coordinate system (Top-Down)
936
937         PyObject* ret = PyTuple_New(2);
938         if(ret){
939                 PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0]));
940                 PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1]));
941                 return ret;
942         }
943
944         return NULL;
945 }
946
947 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect,
948 "getScreenVect()\n"
949 )
950 {
951         double x,y;
952         if (!PyArg_ParseTuple(args,"dd:getScreenVect",&x,&y))
953                 return NULL;
954
955         y = 1.0 - y; //to follow Blender window coordinate system (Top-Down)
956
957         MT_Vector3 vect;
958         MT_Point3 campos, screenpos;
959
960         GLint viewport[4];
961         GLdouble win[3];
962         GLdouble modelmatrix[16];
963         GLdouble projmatrix[16];
964
965         MT_Matrix4x4 m_modelmatrix = this->GetModelviewMatrix();
966         MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();
967
968         m_modelmatrix.getValue(modelmatrix);
969         m_projmatrix.getValue(projmatrix);
970
971         glGetIntegerv(GL_VIEWPORT, viewport);
972
973         vect[0] = x * viewport[2];
974         vect[1] = y * viewport[3];
975
976         vect[0] += viewport[0];
977         vect[1] += viewport[1];
978
979         glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &vect[2]);
980         gluUnProject(vect[0], vect[1], vect[2], modelmatrix, projmatrix, viewport, &win[0], &win[1], &win[2]);
981
982         campos = this->GetCameraLocation();
983         screenpos = MT_Point3(win[0], win[1], win[2]);
984         vect = campos-screenpos;
985
986         vect.normalize();
987         return PyObjectFrom(vect);
988 }
989
990 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay,
991 "getScreenRay()\n"
992 )
993 {
994         MT_Vector3 vect;
995         double x,y,dist;
996         char *propName = NULL;
997
998         if (!PyArg_ParseTuple(args,"ddd|s:getScreenRay",&x,&y,&dist,&propName))
999                 return NULL;
1000
1001         PyObject* argValue = PyTuple_New(2);
1002         if (argValue) {
1003                 PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x));
1004                 PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y));
1005         }
1006
1007         if(!PyVecTo(PygetScreenVect(argValue), vect))
1008         {
1009                 Py_DECREF(argValue);
1010                 PyErr_SetString(PyExc_TypeError,
1011                         "Error in getScreenRay. Invalid 2D coordinate. Expected a normalized 2D screen coordinate, a distance and an optional property argument");
1012                 return NULL;
1013         }
1014         Py_DECREF(argValue);
1015
1016         dist = -dist;
1017         vect += this->GetCameraLocation();
1018
1019         argValue = (propName?PyTuple_New(3):PyTuple_New(2));
1020         if (argValue) {
1021                 PyTuple_SET_ITEM(argValue, 0, PyObjectFrom(vect));
1022                 PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(dist));
1023                 if (propName)
1024                         PyTuple_SET_ITEM(argValue, 2, PyUnicode_FromString(propName));
1025
1026                 PyObject* ret= this->PyrayCastTo(argValue,NULL);
1027                 Py_DECREF(argValue);
1028                 return ret;
1029         }
1030
1031         return NULL;
1032 }
1033