Fix T58850: NDOF navigation guide not shown
[blender.git] / source / blender / blenkernel / intern / camera.c
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 blender/blenkernel/intern/camera.c
29  *  \ingroup bke
30  */
31
32 #include <stdlib.h>
33 #include <stddef.h>
34
35 #include "DNA_camera_types.h"
36 #include "DNA_lamp_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_view3d_types.h"
40 #include "DNA_ID.h"
41
42 #include "BLI_math.h"
43 #include "BLI_listbase.h"
44 #include "BLI_rect.h"
45 #include "BLI_string.h"
46 #include "BLI_utildefines.h"
47
48 #include "BKE_animsys.h"
49 #include "BKE_camera.h"
50 #include "BKE_object.h"
51 #include "BKE_layer.h"
52 #include "BKE_library.h"
53 #include "BKE_library_query.h"
54 #include "BKE_library_remap.h"
55 #include "BKE_main.h"
56 #include "BKE_scene.h"
57 #include "BKE_screen.h"
58
59 #include "DEG_depsgraph_query.h"
60
61 #include "MEM_guardedalloc.h"
62
63 /****************************** Camera Datablock *****************************/
64
65 void BKE_camera_init(Camera *cam)
66 {
67         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(cam, id));
68
69         cam->lens = 50.0f;
70         cam->sensor_x = DEFAULT_SENSOR_WIDTH;
71         cam->sensor_y = DEFAULT_SENSOR_HEIGHT;
72         cam->clipsta = 0.1f;
73         cam->clipend = 1000.0f;
74         cam->drawsize = 0.5f;
75         cam->ortho_scale = 6.0;
76         cam->flag |= CAM_SHOWPASSEPARTOUT;
77         cam->passepartalpha = 0.5f;
78
79         cam->gpu_dof.fstop = 128.0f;
80         cam->gpu_dof.ratio = 1.0f;
81
82         /* stereoscopy 3d */
83         cam->stereo.interocular_distance = 0.065f;
84         cam->stereo.convergence_distance = 30.f * 0.065f;
85         cam->stereo.pole_merge_angle_from = DEG2RADF(60.0f);
86         cam->stereo.pole_merge_angle_to = DEG2RADF(75.0f);
87 }
88
89 void *BKE_camera_add(Main *bmain, const char *name)
90 {
91         Camera *cam;
92
93         cam =  BKE_libblock_alloc(bmain, ID_CA, name, 0);
94
95         BKE_camera_init(cam);
96
97         return cam;
98 }
99
100 /**
101  * Only copy internal data of Camera ID from source to already allocated/initialized destination.
102  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
103  *
104  * WARNING! This function will not handle ID user count!
105  *
106  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
107  */
108 void BKE_camera_copy_data(Main *UNUSED(bmain), Camera *cam_dst, const Camera *cam_src, const int UNUSED(flag))
109 {
110         BLI_duplicatelist(&cam_dst->bg_images, &cam_src->bg_images);
111 }
112
113 Camera *BKE_camera_copy(Main *bmain, const Camera *cam)
114 {
115         Camera *cam_copy;
116         BKE_id_copy_ex(bmain, &cam->id, (ID **)&cam_copy, 0, false);
117         return cam_copy;
118 }
119
120 void BKE_camera_make_local(Main *bmain, Camera *cam, const bool lib_local)
121 {
122         BKE_id_make_local_generic(bmain, &cam->id, true, lib_local);
123 }
124
125 /** Free (or release) any data used by this camera (does not free the camera itself). */
126 void BKE_camera_free(Camera *ca)
127 {
128         BLI_freelistN(&ca->bg_images);
129
130         BKE_animdata_free((ID *)ca, false);
131 }
132
133 /******************************** Camera Usage *******************************/
134
135 /* get the camera's dof value, takes the dof object into account */
136 float BKE_camera_object_dof_distance(Object *ob)
137 {
138         Camera *cam = (Camera *)ob->data;
139         if (ob->type != OB_CAMERA)
140                 return 0.0f;
141         if (cam->dof_ob) {
142                 float view_dir[3], dof_dir[3];
143                 normalize_v3_v3(view_dir, ob->obmat[2]);
144                 sub_v3_v3v3(dof_dir, ob->obmat[3], cam->dof_ob->obmat[3]);
145                 return fabsf(dot_v3v3(view_dir, dof_dir));
146         }
147         return cam->YF_dofdist;
148 }
149
150 float BKE_camera_sensor_size(int sensor_fit, float sensor_x, float sensor_y)
151 {
152         /* sensor size used to fit to. for auto, sensor_x is both x and y. */
153         if (sensor_fit == CAMERA_SENSOR_FIT_VERT)
154                 return sensor_y;
155
156         return sensor_x;
157 }
158
159 int BKE_camera_sensor_fit(int sensor_fit, float sizex, float sizey)
160 {
161         if (sensor_fit == CAMERA_SENSOR_FIT_AUTO) {
162                 if (sizex >= sizey)
163                         return CAMERA_SENSOR_FIT_HOR;
164                 else
165                         return CAMERA_SENSOR_FIT_VERT;
166         }
167
168         return sensor_fit;
169 }
170
171 /******************************** Camera Params *******************************/
172
173 void BKE_camera_params_init(CameraParams *params)
174 {
175         memset(params, 0, sizeof(CameraParams));
176
177         /* defaults */
178         params->sensor_x = DEFAULT_SENSOR_WIDTH;
179         params->sensor_y = DEFAULT_SENSOR_HEIGHT;
180         params->sensor_fit = CAMERA_SENSOR_FIT_AUTO;
181
182         params->zoom = 1.0f;
183
184         /* fallback for non camera objects */
185         params->clipsta = 0.1f;
186         params->clipend = 100.0f;
187 }
188
189 void BKE_camera_params_from_object(CameraParams *params, const Object *ob)
190 {
191         if (!ob)
192                 return;
193
194         if (ob->type == OB_CAMERA) {
195                 /* camera object */
196                 Camera *cam = ob->data;
197
198                 if (cam->type == CAM_ORTHO)
199                         params->is_ortho = true;
200                 params->lens = cam->lens;
201                 params->ortho_scale = cam->ortho_scale;
202
203                 params->shiftx = cam->shiftx;
204                 params->shifty = cam->shifty;
205
206                 params->sensor_x = cam->sensor_x;
207                 params->sensor_y = cam->sensor_y;
208                 params->sensor_fit = cam->sensor_fit;
209
210                 params->clipsta = cam->clipsta;
211                 params->clipend = cam->clipend;
212         }
213         else if (ob->type == OB_LAMP) {
214                 /* lamp object */
215                 Lamp *la = ob->data;
216                 float fac = cosf(la->spotsize * 0.5f);
217                 float phi = acosf(fac);
218
219                 params->lens = 16.0f * fac / sinf(phi);
220                 if (params->lens == 0.0f)
221                         params->lens = 35.0f;
222
223                 params->clipsta = la->clipsta;
224                 params->clipend = la->clipend;
225         }
226         else {
227                 params->lens = 35.0f;
228         }
229 }
230
231 void BKE_camera_params_from_view3d(CameraParams *params, Depsgraph *depsgraph, const View3D *v3d, const RegionView3D *rv3d)
232 {
233         /* common */
234         params->lens = v3d->lens;
235         params->clipsta = v3d->near;
236         params->clipend = v3d->far;
237
238         if (rv3d->persp == RV3D_CAMOB) {
239                 /* camera view */
240                 const Object *ob_camera_eval = DEG_get_evaluated_object(depsgraph, v3d->camera);
241                 BKE_camera_params_from_object(params, ob_camera_eval);
242
243                 params->zoom = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
244
245                 params->offsetx = 2.0f * rv3d->camdx * params->zoom;
246                 params->offsety = 2.0f * rv3d->camdy * params->zoom;
247
248                 params->shiftx *= params->zoom;
249                 params->shifty *= params->zoom;
250
251                 params->zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB / params->zoom;
252         }
253         else if (rv3d->persp == RV3D_ORTHO) {
254                 /* orthographic view */
255                 float sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
256                 params->clipend *= 0.5f;    // otherwise too extreme low zbuffer quality
257                 params->clipsta = -params->clipend;
258
259                 params->is_ortho = true;
260                 /* make sure any changes to this match ED_view3d_radius_to_dist_ortho() */
261                 params->ortho_scale = rv3d->dist * sensor_size / v3d->lens;
262                 params->zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
263         }
264         else {
265                 /* perspective view */
266                 params->zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
267         }
268 }
269
270 void BKE_camera_params_compute_viewplane(CameraParams *params, int winx, int winy, float xasp, float yasp)
271 {
272         rctf viewplane;
273         float pixsize, viewfac, sensor_size, dx, dy;
274         int sensor_fit;
275
276         params->ycor = yasp / xasp;
277
278         if (params->is_ortho) {
279                 /* orthographic camera */
280                 /* scale == 1.0 means exact 1 to 1 mapping */
281                 pixsize = params->ortho_scale;
282         }
283         else {
284                 /* perspective camera */
285                 sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
286                 pixsize = (sensor_size * params->clipsta) / params->lens;
287         }
288
289         /* determine sensor fit */
290         sensor_fit = BKE_camera_sensor_fit(params->sensor_fit, xasp * winx, yasp * winy);
291
292         if (sensor_fit == CAMERA_SENSOR_FIT_HOR)
293                 viewfac = winx;
294         else
295                 viewfac = params->ycor * winy;
296
297         pixsize /= viewfac;
298
299         /* extra zoom factor */
300         pixsize *= params->zoom;
301
302         /* compute view plane:
303          * fully centered, zbuffer fills in jittered between -.5 and +.5 */
304         viewplane.xmin = -0.5f * (float)winx;
305         viewplane.ymin = -0.5f * params->ycor * (float)winy;
306         viewplane.xmax =  0.5f * (float)winx;
307         viewplane.ymax =  0.5f * params->ycor * (float)winy;
308
309         /* lens shift and offset */
310         dx = params->shiftx * viewfac + winx * params->offsetx;
311         dy = params->shifty * viewfac + winy * params->offsety;
312
313         viewplane.xmin += dx;
314         viewplane.ymin += dy;
315         viewplane.xmax += dx;
316         viewplane.ymax += dy;
317
318         /* the window matrix is used for clipping, and not changed during OSA steps */
319         /* using an offset of +0.5 here would give clip errors on edges */
320         viewplane.xmin *= pixsize;
321         viewplane.xmax *= pixsize;
322         viewplane.ymin *= pixsize;
323         viewplane.ymax *= pixsize;
324
325         /* Used for rendering (offset by near-clip with perspective views), passed to RE_SetPixelSize.
326          * For viewport drawing 'RegionView3D.pixsize'. */
327         params->viewdx = pixsize;
328         params->viewdy = params->ycor * pixsize;
329         params->viewplane = viewplane;
330 }
331
332 /* viewplane is assumed to be already computed */
333 void BKE_camera_params_compute_matrix(CameraParams *params)
334 {
335         rctf viewplane = params->viewplane;
336
337         /* compute projection matrix */
338         if (params->is_ortho)
339                 orthographic_m4(params->winmat, viewplane.xmin, viewplane.xmax,
340                                 viewplane.ymin, viewplane.ymax, params->clipsta, params->clipend);
341         else
342                 perspective_m4(params->winmat, viewplane.xmin, viewplane.xmax,
343                                viewplane.ymin, viewplane.ymax, params->clipsta, params->clipend);
344 }
345
346 /***************************** Camera View Frame *****************************/
347
348 void BKE_camera_view_frame_ex(
349         const Scene *scene, const Camera *camera,
350         const float drawsize, const bool do_clip, const float scale[3],
351         float r_asp[2], float r_shift[2], float *r_drawsize, float r_vec[4][3])
352 {
353         float facx, facy;
354         float depth;
355
356         /* aspect correcton */
357         if (scene) {
358                 float aspx = (float) scene->r.xsch * scene->r.xasp;
359                 float aspy = (float) scene->r.ysch * scene->r.yasp;
360                 int sensor_fit = BKE_camera_sensor_fit(camera->sensor_fit, aspx, aspy);
361
362                 if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
363                         r_asp[0] = 1.0;
364                         r_asp[1] = aspy / aspx;
365                 }
366                 else {
367                         r_asp[0] = aspx / aspy;
368                         r_asp[1] = 1.0;
369                 }
370         }
371         else {
372                 r_asp[0] = 1.0f;
373                 r_asp[1] = 1.0f;
374         }
375
376         if (camera->type == CAM_ORTHO) {
377                 facx = 0.5f * camera->ortho_scale * r_asp[0] * scale[0];
378                 facy = 0.5f * camera->ortho_scale * r_asp[1] * scale[1];
379                 r_shift[0] = camera->shiftx * camera->ortho_scale * scale[0];
380                 r_shift[1] = camera->shifty * camera->ortho_scale * scale[1];
381                 depth = do_clip ? -((camera->clipsta * scale[2]) + 0.1f) : -drawsize * camera->ortho_scale * scale[2];
382
383                 *r_drawsize = 0.5f * camera->ortho_scale;
384         }
385         else {
386                 /* that way it's always visible - clipsta+0.1 */
387                 float fac, scale_x, scale_y;
388                 float half_sensor = 0.5f * ((camera->sensor_fit == CAMERA_SENSOR_FIT_VERT) ?
389                                             (camera->sensor_y) : (camera->sensor_x));
390
391
392                 if (do_clip) {
393                         /* fixed depth, variable size (avoids exceeding clipping range) */
394                         /* r_drawsize shouldn't be used in this case, set to dummy value */
395                         *r_drawsize = 1.0f;
396                         depth = -(camera->clipsta + 0.1f) * scale[2];
397                         fac = depth / (camera->lens / (-half_sensor));
398                         scale_x = scale[0] / scale[2];
399                         scale_y = scale[1] / scale[2];
400                 }
401                 else {
402                         /* fixed size, variable depth (stays a reasonable size in the 3D view) */
403                         *r_drawsize = drawsize / ((scale[0] + scale[1] + scale[2]) / 3.0f);
404                         depth = *r_drawsize * camera->lens / (-half_sensor) * scale[2];
405                         fac = *r_drawsize;
406                         scale_x = scale[0];
407                         scale_y = scale[1];
408                 }
409
410                 facx = fac * r_asp[0] * scale_x;
411                 facy = fac * r_asp[1] * scale_y;
412                 r_shift[0] = camera->shiftx * fac * 2.0f * scale_x;
413                 r_shift[1] = camera->shifty * fac * 2.0f * scale_y;
414         }
415
416         r_vec[0][0] = r_shift[0] + facx; r_vec[0][1] = r_shift[1] + facy; r_vec[0][2] = depth;
417         r_vec[1][0] = r_shift[0] + facx; r_vec[1][1] = r_shift[1] - facy; r_vec[1][2] = depth;
418         r_vec[2][0] = r_shift[0] - facx; r_vec[2][1] = r_shift[1] - facy; r_vec[2][2] = depth;
419         r_vec[3][0] = r_shift[0] - facx; r_vec[3][1] = r_shift[1] + facy; r_vec[3][2] = depth;
420 }
421
422 void BKE_camera_view_frame(const Scene *scene, const Camera *camera, float r_vec[4][3])
423 {
424         float dummy_asp[2];
425         float dummy_shift[2];
426         float dummy_drawsize;
427         const float dummy_scale[3] = {1.0f, 1.0f, 1.0f};
428
429         BKE_camera_view_frame_ex(scene, camera, 0.0, true, dummy_scale,
430                                  dummy_asp, dummy_shift, &dummy_drawsize, r_vec);
431 }
432
433 #define CAMERA_VIEWFRAME_NUM_PLANES 4
434
435 typedef struct CameraViewFrameData {
436         float plane_tx[CAMERA_VIEWFRAME_NUM_PLANES][4];  /* 4 planes */
437         float normal_tx[CAMERA_VIEWFRAME_NUM_PLANES][3];
438         float dist_vals_sq[CAMERA_VIEWFRAME_NUM_PLANES];  /* distance squared (signed) */
439         unsigned int tot;
440
441         /* Ortho camera only. */
442         bool is_ortho;
443         float camera_no[3];
444         float dist_to_cam;
445
446         /* Not used by callbacks... */
447         float camera_rotmat[3][3];
448 } CameraViewFrameData;
449
450 static void camera_to_frame_view_cb(const float co[3], void *user_data)
451 {
452         CameraViewFrameData *data = (CameraViewFrameData *)user_data;
453         unsigned int i;
454
455         for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
456                 const float nd = dist_signed_squared_to_plane_v3(co, data->plane_tx[i]);
457                 CLAMP_MAX(data->dist_vals_sq[i], nd);
458         }
459
460         if (data->is_ortho) {
461                 const float d = dot_v3v3(data->camera_no, co);
462                 CLAMP_MAX(data->dist_to_cam, d);
463         }
464
465         data->tot++;
466 }
467
468 static void camera_frame_fit_data_init(
469         const Scene *scene, const Object *ob,
470         CameraParams *params, CameraViewFrameData *data)
471 {
472         float camera_rotmat_transposed_inversed[4][4];
473         unsigned int i;
474
475         /* setup parameters */
476         BKE_camera_params_init(params);
477         BKE_camera_params_from_object(params, ob);
478
479         /* compute matrix, viewplane, .. */
480         if (scene) {
481                 BKE_camera_params_compute_viewplane(params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
482         }
483         else {
484                 BKE_camera_params_compute_viewplane(params, 1, 1, 1.0f, 1.0f);
485         }
486         BKE_camera_params_compute_matrix(params);
487
488         /* initialize callback data */
489         copy_m3_m4(data->camera_rotmat, (float (*)[4])ob->obmat);
490         normalize_m3(data->camera_rotmat);
491         /* To transform a plane which is in its homogeneous representation (4d vector),
492          * we need the inverse of the transpose of the transform matrix... */
493         copy_m4_m3(camera_rotmat_transposed_inversed, data->camera_rotmat);
494         transpose_m4(camera_rotmat_transposed_inversed);
495         invert_m4(camera_rotmat_transposed_inversed);
496
497         /* Extract frustum planes from projection matrix. */
498         planes_from_projmat(params->winmat,
499                             /*   left              right                 top              bottom        near  far */
500                             data->plane_tx[2], data->plane_tx[0], data->plane_tx[3], data->plane_tx[1], NULL, NULL);
501
502         /* Rotate planes and get normals from them */
503         for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
504                 mul_m4_v4(camera_rotmat_transposed_inversed, data->plane_tx[i]);
505                 normalize_v3_v3(data->normal_tx[i], data->plane_tx[i]);
506         }
507
508         copy_v4_fl(data->dist_vals_sq, FLT_MAX);
509         data->tot = 0;
510         data->is_ortho = params->is_ortho;
511         if (params->is_ortho) {
512                 /* we want (0, 0, -1) transformed by camera_rotmat, this is a quicker shortcut. */
513                 negate_v3_v3(data->camera_no, data->camera_rotmat[2]);
514                 data->dist_to_cam = FLT_MAX;
515         }
516 }
517
518 static bool camera_frame_fit_calc_from_data(
519         CameraParams *params, CameraViewFrameData *data, float r_co[3], float *r_scale)
520 {
521         float plane_tx[CAMERA_VIEWFRAME_NUM_PLANES][4];
522         unsigned int i;
523
524         if (data->tot <= 1) {
525                 return false;
526         }
527
528         if (params->is_ortho) {
529                 const float *cam_axis_x = data->camera_rotmat[0];
530                 const float *cam_axis_y = data->camera_rotmat[1];
531                 const float *cam_axis_z = data->camera_rotmat[2];
532                 float dists[CAMERA_VIEWFRAME_NUM_PLANES];
533                 float scale_diff;
534
535                 /* apply the dist-from-plane's to the transformed plane points */
536                 for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
537                         dists[i] = sqrtf_signed(data->dist_vals_sq[i]);
538                 }
539
540                 if ((dists[0] + dists[2]) > (dists[1] + dists[3])) {
541                         scale_diff = (dists[1] + dists[3]) *
542                                      (BLI_rctf_size_x(&params->viewplane) / BLI_rctf_size_y(&params->viewplane));
543                 }
544                 else {
545                         scale_diff = (dists[0] + dists[2]) *
546                                      (BLI_rctf_size_y(&params->viewplane) / BLI_rctf_size_x(&params->viewplane));
547                 }
548                 *r_scale = params->ortho_scale - scale_diff;
549
550                 zero_v3(r_co);
551                 madd_v3_v3fl(r_co, cam_axis_x, (dists[2] - dists[0]) * 0.5f + params->shiftx * scale_diff);
552                 madd_v3_v3fl(r_co, cam_axis_y, (dists[1] - dists[3]) * 0.5f + params->shifty * scale_diff);
553                 madd_v3_v3fl(r_co, cam_axis_z, -(data->dist_to_cam - 1.0f - params->clipsta));
554
555                 return true;
556         }
557         else {
558                 float plane_isect_1[3], plane_isect_1_no[3], plane_isect_1_other[3];
559                 float plane_isect_2[3], plane_isect_2_no[3], plane_isect_2_other[3];
560
561                 float plane_isect_pt_1[3], plane_isect_pt_2[3];
562
563                 /* apply the dist-from-plane's to the transformed plane points */
564                 for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
565                         float co[3];
566                         mul_v3_v3fl(co, data->normal_tx[i], sqrtf_signed(data->dist_vals_sq[i]));
567                         plane_from_point_normal_v3(plane_tx[i], co, data->normal_tx[i]);
568                 }
569
570                 if ((!isect_plane_plane_v3(plane_tx[0], plane_tx[2], plane_isect_1, plane_isect_1_no)) ||
571                     (!isect_plane_plane_v3(plane_tx[1], plane_tx[3], plane_isect_2, plane_isect_2_no)))
572                 {
573                         return false;
574                 }
575
576                 add_v3_v3v3(plane_isect_1_other, plane_isect_1, plane_isect_1_no);
577                 add_v3_v3v3(plane_isect_2_other, plane_isect_2, plane_isect_2_no);
578
579                 if (isect_line_line_v3(plane_isect_1, plane_isect_1_other,
580                                        plane_isect_2, plane_isect_2_other,
581                                        plane_isect_pt_1, plane_isect_pt_2) != 0)
582                 {
583                         float cam_plane_no[3];
584                         float plane_isect_delta[3];
585                         float plane_isect_delta_len;
586
587                         float shift_fac = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y) /
588                                           params->lens;
589
590                         /* we want (0, 0, -1) transformed by camera_rotmat, this is a quicker shortcut. */
591                         negate_v3_v3(cam_plane_no, data->camera_rotmat[2]);
592
593                         sub_v3_v3v3(plane_isect_delta, plane_isect_pt_2, plane_isect_pt_1);
594                         plane_isect_delta_len = len_v3(plane_isect_delta);
595
596                         if (dot_v3v3(plane_isect_delta, cam_plane_no) > 0.0f) {
597                                 copy_v3_v3(r_co, plane_isect_pt_1);
598
599                                 /* offset shift */
600                                 normalize_v3(plane_isect_1_no);
601                                 madd_v3_v3fl(r_co, plane_isect_1_no, params->shifty * plane_isect_delta_len * shift_fac);
602                         }
603                         else {
604                                 copy_v3_v3(r_co, plane_isect_pt_2);
605
606                                 /* offset shift */
607                                 normalize_v3(plane_isect_2_no);
608                                 madd_v3_v3fl(r_co, plane_isect_2_no, params->shiftx * plane_isect_delta_len * shift_fac);
609                         }
610
611                         return true;
612                 }
613         }
614
615         return false;
616 }
617
618 /* don't move the camera, just yield the fit location */
619 /* r_scale only valid/useful for ortho cameras */
620 bool BKE_camera_view_frame_fit_to_scene(
621         Depsgraph *depsgraph, Scene *scene, Object *camera_ob, float r_co[3], float *r_scale)
622 {
623         CameraParams params;
624         CameraViewFrameData data_cb;
625
626         /* just in case */
627         *r_scale = 1.0f;
628
629         camera_frame_fit_data_init(scene, camera_ob, &params, &data_cb);
630
631         /* run callback on all visible points */
632         BKE_scene_foreach_display_point(depsgraph, camera_to_frame_view_cb, &data_cb);
633
634         return camera_frame_fit_calc_from_data(&params, &data_cb, r_co, r_scale);
635 }
636
637 bool BKE_camera_view_frame_fit_to_coords(
638         const Depsgraph *depsgraph, const float (*cos)[3], int num_cos, Object *camera_ob,
639         float r_co[3], float *r_scale)
640 {
641         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
642         Object *camera_ob_eval = DEG_get_evaluated_object(depsgraph, camera_ob);
643         CameraParams params;
644         CameraViewFrameData data_cb;
645
646         /* just in case */
647         *r_scale = 1.0f;
648
649         camera_frame_fit_data_init(scene_eval, camera_ob_eval, &params, &data_cb);
650
651         /* run callback on all given coordinates */
652         while (num_cos--) {
653                 camera_to_frame_view_cb(cos[num_cos], &data_cb);
654         }
655
656         return camera_frame_fit_calc_from_data(&params, &data_cb, r_co, r_scale);
657 }
658
659 /******************* multiview matrix functions ***********************/
660
661 static void camera_model_matrix(const Object *camera, float r_modelmat[4][4])
662 {
663         copy_m4_m4(r_modelmat, camera->obmat);
664 }
665
666 static void camera_stereo3d_model_matrix(const Object *camera, const bool is_left, float r_modelmat[4][4])
667 {
668         Camera *data = (Camera *)camera->data;
669         float interocular_distance, convergence_distance;
670         short convergence_mode, pivot;
671         float sizemat[4][4];
672
673         float fac = 1.0f;
674         float fac_signed;
675
676         interocular_distance = data->stereo.interocular_distance;
677         convergence_distance = data->stereo.convergence_distance;
678         convergence_mode = data->stereo.convergence_mode;
679         pivot = data->stereo.pivot;
680
681         if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) ||
682             ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left))
683         {
684                 camera_model_matrix(camera, r_modelmat);
685                 return;
686         }
687         else {
688                 float size[3];
689                 mat4_to_size(size, camera->obmat);
690                 size_to_mat4(sizemat, size);
691         }
692
693         if (pivot == CAM_S3D_PIVOT_CENTER)
694                 fac = 0.5f;
695
696         fac_signed = is_left ? fac : -fac;
697
698         /* rotation */
699         if (convergence_mode == CAM_S3D_TOE) {
700                 float angle;
701                 float angle_sin, angle_cos;
702                 float toeinmat[4][4];
703                 float rotmat[4][4];
704
705                 unit_m4(rotmat);
706
707                 if (pivot == CAM_S3D_PIVOT_CENTER) {
708                         fac = -fac;
709                         fac_signed = -fac_signed;
710                 }
711
712                 angle = atanf((interocular_distance * 0.5f) / convergence_distance) / fac;
713
714                 angle_cos = cosf(angle * fac_signed);
715                 angle_sin = sinf(angle * fac_signed);
716
717                 rotmat[0][0] =  angle_cos;
718                 rotmat[2][0] = -angle_sin;
719                 rotmat[0][2] =  angle_sin;
720                 rotmat[2][2] =  angle_cos;
721
722                 if (pivot == CAM_S3D_PIVOT_CENTER) {
723                         /* set the rotation */
724                         copy_m4_m4(toeinmat, rotmat);
725                         /* set the translation */
726                         toeinmat[3][0] = interocular_distance * fac_signed;
727
728                         /* transform */
729                         normalize_m4_m4(r_modelmat, camera->obmat);
730                         mul_m4_m4m4(r_modelmat, r_modelmat, toeinmat);
731
732                         /* scale back to the original size */
733                         mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
734                 }
735                 else { /* CAM_S3D_PIVOT_LEFT, CAM_S3D_PIVOT_RIGHT */
736                         /* rotate perpendicular to the interocular line */
737                         normalize_m4_m4(r_modelmat, camera->obmat);
738                         mul_m4_m4m4(r_modelmat, r_modelmat, rotmat);
739
740                         /* translate along the interocular line */
741                         unit_m4(toeinmat);
742                         toeinmat[3][0] = -interocular_distance * fac_signed;
743                         mul_m4_m4m4(r_modelmat, r_modelmat, toeinmat);
744
745                         /* rotate to toe-in angle */
746                         mul_m4_m4m4(r_modelmat, r_modelmat, rotmat);
747
748                         /* scale back to the original size */
749                         mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
750                 }
751         }
752         else {
753                 normalize_m4_m4(r_modelmat, camera->obmat);
754
755                 /* translate - no rotation in CAM_S3D_OFFAXIS, CAM_S3D_PARALLEL */
756                 translate_m4(r_modelmat, -interocular_distance * fac_signed, 0.0f, 0.0f);
757
758                 /* scale back to the original size */
759                 mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
760         }
761 }
762
763 /* the view matrix is used by the viewport drawing, it is basically the inverted model matrix */
764 void BKE_camera_multiview_view_matrix(RenderData *rd, const Object *camera, const bool is_left, float r_viewmat[4][4])
765 {
766         BKE_camera_multiview_model_matrix(rd, camera, is_left ? STEREO_LEFT_NAME : STEREO_RIGHT_NAME, r_viewmat);
767         invert_m4(r_viewmat);
768 }
769
770 /* left is the default */
771 static bool camera_is_left(const char *viewname)
772 {
773         if (viewname && viewname[0] != '\0') {
774                 return !STREQ(viewname, STEREO_RIGHT_NAME);
775         }
776         return true;
777 }
778
779 void BKE_camera_multiview_model_matrix(RenderData *rd, const Object *camera, const char *viewname, float r_modelmat[4][4])
780 {
781         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
782
783         if (!is_multiview) {
784                 camera_model_matrix(camera, r_modelmat);
785         }
786         else if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
787                 camera_model_matrix(camera, r_modelmat);
788         }
789         else { /* SCE_VIEWS_SETUP_BASIC */
790                 const bool is_left = camera_is_left(viewname);
791                 camera_stereo3d_model_matrix(camera, is_left, r_modelmat);
792         }
793         normalize_m4(r_modelmat);
794 }
795
796 bool BKE_camera_multiview_spherical_stereo(RenderData *rd, const Object *camera)
797 {
798         Camera *cam;
799         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
800
801         if (!is_multiview)
802                 return false;
803
804         if (camera->type != OB_CAMERA)
805                 return false;
806         else
807                 cam = camera->data;
808
809         if ((rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) &&
810             ELEM(cam->type, CAM_PANO, CAM_PERSP) &&
811             ((cam->stereo.flag & CAM_S3D_SPHERICAL) != 0))
812         {
813                 return true;
814         }
815
816         return false;
817 }
818
819 static Object *camera_multiview_advanced(Scene *scene, Object *camera, const char *suffix)
820 {
821         SceneRenderView *srv;
822         char name[MAX_NAME];
823         const char *camera_name = camera->id.name + 2;
824         const int len_name = strlen(camera_name);
825         int len_suffix_max = -1;
826
827         name[0] = '\0';
828
829         /* we need to take the better match, thus the len_suffix_max test */
830         for (srv = scene->r.views.first; srv; srv = srv->next) {
831                 const int len_suffix = strlen(srv->suffix);
832
833                 if ((len_suffix < len_suffix_max) || (len_name < len_suffix))
834                         continue;
835
836                 if (STREQ(camera_name + (len_name - len_suffix), srv->suffix)) {
837                         BLI_snprintf(name, sizeof(name), "%.*s%s", (len_name - len_suffix), camera_name, suffix);
838                         len_suffix_max = len_suffix;
839                 }
840         }
841
842         if (name[0] != '\0') {
843                 Object *ob = BKE_scene_object_find_by_name(scene, name);
844                 if (ob != NULL) {
845                         return ob;
846                 }
847         }
848
849         return camera;
850 }
851
852 /* returns the camera to be used for render */
853 Object *BKE_camera_multiview_render(Scene *scene, Object *camera, const char *viewname)
854 {
855         const bool is_multiview = (camera != NULL) &&  (scene->r.scemode & R_MULTIVIEW) != 0;
856
857         if (!is_multiview) {
858                 return camera;
859         }
860         else if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
861                 return camera;
862         }
863         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
864                 const char *suffix = BKE_scene_multiview_view_suffix_get(&scene->r, viewname);
865                 return camera_multiview_advanced(scene, camera, suffix);
866         }
867 }
868
869 static float camera_stereo3d_shift_x(const Object *camera, const char *viewname)
870 {
871         Camera *data = camera->data;
872         float shift = data->shiftx;
873         float interocular_distance, convergence_distance;
874         short convergence_mode, pivot;
875         bool is_left = true;
876
877         float fac = 1.0f;
878         float fac_signed;
879
880         if (viewname && viewname[0]) {
881                 is_left = STREQ(viewname, STEREO_LEFT_NAME);
882         }
883
884         interocular_distance = data->stereo.interocular_distance;
885         convergence_distance = data->stereo.convergence_distance;
886         convergence_mode = data->stereo.convergence_mode;
887         pivot = data->stereo.pivot;
888
889         if (convergence_mode != CAM_S3D_OFFAXIS)
890                 return shift;
891
892         if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) ||
893             ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left))
894         {
895                 return shift;
896         }
897
898         if (pivot == CAM_S3D_PIVOT_CENTER)
899                 fac = 0.5f;
900
901         fac_signed = is_left ? fac : -fac;
902         shift += ((interocular_distance / data->sensor_x) * (data->lens / convergence_distance)) * fac_signed;
903
904         return shift;
905 }
906
907 float BKE_camera_multiview_shift_x(RenderData *rd, const Object *camera, const char *viewname)
908 {
909         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
910         Camera *data = camera->data;
911
912         BLI_assert(camera->type == OB_CAMERA);
913
914         if (!is_multiview) {
915                 return data->shiftx;
916         }
917         else if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
918                 return data->shiftx;
919         }
920         else { /* SCE_VIEWS_SETUP_BASIC */
921                 return camera_stereo3d_shift_x(camera, viewname);
922         }
923 }
924
925 void BKE_camera_multiview_params(RenderData *rd, CameraParams *params, const Object *camera, const char *viewname)
926 {
927         if (camera->type == OB_CAMERA) {
928                 params->shiftx = BKE_camera_multiview_shift_x(rd, camera, viewname);
929         }
930 }
931
932 void BKE_camera_to_gpu_dof(struct Object *camera, struct GPUFXSettings *r_fx_settings)
933 {
934         if (camera->type == OB_CAMERA) {
935                 Camera *cam = camera->data;
936                 r_fx_settings->dof = &cam->gpu_dof;
937                 r_fx_settings->dof->focal_length = cam->lens;
938                 r_fx_settings->dof->sensor = BKE_camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
939                 r_fx_settings->dof->focus_distance = BKE_camera_object_dof_distance(camera);
940         }
941 }
942
943 CameraBGImage *BKE_camera_background_image_new(Camera *cam)
944 {
945         CameraBGImage *bgpic = MEM_callocN(sizeof(CameraBGImage), "Background Image");
946
947         bgpic->scale = 1.0f;
948         bgpic->alpha = 0.5f;
949         bgpic->iuser.ok = 1;
950         bgpic->iuser.flag |= IMA_ANIM_ALWAYS;
951         bgpic->flag |= CAM_BGIMG_FLAG_EXPANDED;
952
953         BLI_addtail(&cam->bg_images, bgpic);
954
955         return bgpic;
956 }
957
958 void BKE_camera_background_image_remove(Camera *cam, CameraBGImage *bgpic)
959 {
960         BLI_remlink(&cam->bg_images, bgpic);
961
962         MEM_freeN(bgpic);
963 }
964
965 void BKE_camera_background_image_clear(Camera *cam)
966 {
967         CameraBGImage *bgpic = cam->bg_images.first;
968
969         while (bgpic) {
970                 CameraBGImage *next_bgpic = bgpic->next;
971
972                 BKE_camera_background_image_remove(cam, bgpic);
973
974                 bgpic = next_bgpic;
975         }
976 }