Base refactor 3/4
[blender.git] / source / blender / editors / space_view3d / view3d_draw.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) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_draw.c
28  *  \ingroup spview3d
29  */
30
31 #include <math.h>
32
33 #include "BIF_gl.h"
34 #include "BIF_glutil.h"
35
36 #include "BKE_camera.h"
37 #include "BKE_context.h"
38 #include "BKE_scene.h"
39 #include "BKE_object.h"
40 #include "BKE_paint.h"
41 #include "BKE_unit.h"
42
43 #include "BLF_api.h"
44
45 #include "BLI_math.h"
46 #include "BLI_rect.h"
47 #include "BLI_threads.h"
48
49 #include "DNA_brush_types.h"
50 #include "DNA_camera_types.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_view3d_types.h"
54 #include "DNA_windowmanager_types.h"
55
56 #include "ED_screen.h"
57 #include "ED_transform.h"
58
59 #include "GPU_matrix.h"
60 #include "GPU_immediate.h"
61 #include "GPU_material.h"
62 #include "GPU_viewport.h"
63
64 #include "MEM_guardedalloc.h"
65
66 #include "UI_interface.h"
67 #include "UI_resources.h"
68
69 #include "RE_engine.h"
70
71 #include "WM_api.h"
72
73 #include "view3d_intern.h"  /* own include */
74
75 /* prototypes */
76 static void draw_all_objects(const bContext *C, ARegion *ar, const bool only_depth, const bool use_depth);
77
78 typedef struct DrawData {
79         rcti border_rect;
80         bool render_border;
81         bool clip_border;
82         bool is_render;
83         GPUViewport *viewport;
84 } DrawData;
85
86 static void view3d_draw_data_init(const bContext *C, ARegion *ar, RegionView3D *rv3d, DrawData *draw_data)
87 {
88         Scene *scene = CTX_data_scene(C);
89         View3D *v3d = CTX_wm_view3d(C);
90
91         draw_data->is_render = (v3d->drawtype == OB_RENDER);
92
93         draw_data->render_border = ED_view3d_calc_render_border(scene, v3d, ar, &draw_data->border_rect);
94         draw_data->clip_border = (draw_data->render_border && !BLI_rcti_compare(&ar->drawrct, &draw_data->border_rect));
95
96         draw_data->viewport = rv3d->viewport;
97 }
98
99 /* ******************** general functions ***************** */
100
101 static bool use_depth_doit(Scene *scene, View3D *v3d)
102 {
103         if (v3d->drawtype > OB_WIRE)
104                 return true;
105
106         /* special case (depth for wire color) */
107         if (v3d->drawtype <= OB_WIRE) {
108                 if (scene->obedit && scene->obedit->type == OB_MESH) {
109                         Mesh *me = scene->obedit->data;
110                         if (me->drawflag & ME_DRAWEIGHT) {
111                                 return true;
112                         }
113                 }
114         }
115         return false;
116 }
117
118 static bool use_depth(const bContext *C)
119 {
120         View3D *v3d = CTX_wm_view3d(C);
121         Scene *scene = CTX_data_scene(C);
122         return use_depth_doit(scene, v3d);
123 }
124
125 /**
126  * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
127  */
128 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
129 {
130         RegionView3D *rv3d = ar->regiondata;
131
132
133         /* setup window matrices */
134         if (winmat)
135                 copy_m4_m4(rv3d->winmat, winmat);
136         else
137                 view3d_winmatrix_set(ar, v3d, NULL);
138
139         /* setup view matrix */
140         if (viewmat)
141                 copy_m4_m4(rv3d->viewmat, viewmat);
142         else
143                 view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
144
145         /* update utility matrices */
146         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
147         invert_m4_m4(rv3d->persinv, rv3d->persmat);
148         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
149
150         /* calculate GLSL view dependent values */
151
152         /* store window coordinates scaling/offset */
153         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
154                 rctf cameraborder;
155                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &cameraborder, false);
156                 rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
157                 rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
158
159                 rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
160                 rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
161         }
162         else {
163                 rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
164                 rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
165         }
166
167         /* calculate pixelsize factor once, is used for lamps and obcenters */
168         {
169                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
170                 * because of float point precision problems at large values [#23908] */
171                 float v1[3], v2[3];
172                 float len_px, len_sc;
173
174                 v1[0] = rv3d->persmat[0][0];
175                 v1[1] = rv3d->persmat[1][0];
176                 v1[2] = rv3d->persmat[2][0];
177
178                 v2[0] = rv3d->persmat[0][1];
179                 v2[1] = rv3d->persmat[1][1];
180                 v2[2] = rv3d->persmat[2][1];
181
182                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
183                 len_sc = (float)MAX2(ar->winx, ar->winy);
184
185                 rv3d->pixsize = len_px / len_sc;
186         }
187 }
188
189 static void view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
190 {
191         RegionView3D *rv3d = ar->regiondata;
192
193         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
194
195         /* set for opengl */
196         /* TODO(merwin): transition to GPU_matrix API */
197         glMatrixMode(GL_PROJECTION);
198         glLoadMatrixf(rv3d->winmat);
199         glMatrixMode(GL_MODELVIEW);
200         glLoadMatrixf(rv3d->viewmat);
201 }
202
203 static bool view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
204 {
205         wmWindow *win = CTX_wm_window(C);
206
207         if ((scene->r.scemode & R_MULTIVIEW) == 0)
208                 return false;
209
210         if (WM_stereo3d_enabled(win, true) == false)
211                 return false;
212
213         if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB)
214                 return false;
215
216         if (scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) {
217                 if (v3d->stereo3d_camera == STEREO_MONO_ID)
218                         return false;
219
220                 return BKE_scene_multiview_is_stereo3d(&scene->r);
221         }
222
223         return true;
224 }
225
226 /* setup the view and win matrices for the multiview cameras
227  *
228  * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
229  * we have no winmatrix (i.e., projection matrix) defined at that time.
230  * Since the camera and the camera shift are needed for the winmat calculation
231  * we do a small hack to replace it temporarily so we don't need to change the
232  * view3d)main_region_setup_view() code to account for that.
233  */
234 static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
235 {
236         bool is_left;
237         const char *names[2] = { STEREO_LEFT_NAME, STEREO_RIGHT_NAME };
238         const char *viewname;
239
240         /* show only left or right camera */
241         if (v3d->stereo3d_camera != STEREO_3D_ID)
242                 v3d->multiview_eye = v3d->stereo3d_camera;
243
244         is_left = v3d->multiview_eye == STEREO_LEFT_ID;
245         viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
246
247         /* update the viewport matrices with the new camera */
248         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
249                 Camera *data;
250                 float viewmat[4][4];
251                 float shiftx;
252
253                 data = (Camera *)v3d->camera->data;
254                 shiftx = data->shiftx;
255
256                 BLI_lock_thread(LOCK_VIEW3D);
257                 data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
258
259                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
260                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
261
262                 data->shiftx = shiftx;
263                 BLI_unlock_thread(LOCK_VIEW3D);
264         }
265         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
266                 float viewmat[4][4];
267                 Object *view_ob = v3d->camera;
268                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
269
270                 BLI_lock_thread(LOCK_VIEW3D);
271                 v3d->camera = camera;
272
273                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
274                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
275
276                 v3d->camera = view_ob;
277                 BLI_unlock_thread(LOCK_VIEW3D);
278         }
279 }
280
281 /* ******************** debug ***************** */
282
283 #define VIEW3D_DRAW_DEBUG 1
284 /* TODO: expand scope of this flag so UI reflects the underlying code */
285
286 #if VIEW3D_DRAW_DEBUG
287
288 static void view3d_draw_debug_store_depth(ARegion *UNUSED(ar), DrawData *draw_data)
289 {
290         GPUViewport *viewport = draw_data->viewport;
291         GLint viewport_size[4];
292         glGetIntegerv(GL_VIEWPORT, viewport_size);
293
294         const int x = viewport_size[0];
295         const int y = viewport_size[1];
296         const int w = viewport_size[2];
297         const int h = viewport_size[3];
298
299         if (GPU_viewport_debug_depth_is_valid(viewport)) {
300                 if ((GPU_viewport_debug_depth_width(viewport) != w) ||
301                         (GPU_viewport_debug_depth_height(viewport) != h))
302                 {
303                         GPU_viewport_debug_depth_free(viewport);
304                 }
305         }
306
307         if (!GPU_viewport_debug_depth_is_valid(viewport)) {
308                 char error[256];
309                 if (!GPU_viewport_debug_depth_create(viewport, w, h, error)) {
310                         fprintf(stderr, "Failed to create depth buffer for debug: %s\n", error);
311                         return;
312                 }
313         }
314
315         GPU_viewport_debug_depth_store(viewport, x, y);
316 }
317
318 static void view3d_draw_debug_post_solid(const bContext *C, ARegion *ar, DrawData *draw_data)
319 {
320         View3D *v3d = CTX_wm_view3d(C);
321
322         if ((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_SCENE_DEPTH) != 0) {
323                 view3d_draw_debug_store_depth(ar, draw_data);
324         }
325 }
326
327 static void view3d_draw_debug(const bContext *C, ARegion *ar, DrawData *draw_data)
328 {
329         View3D *v3d = CTX_wm_view3d(C);
330
331         if ((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_COMBINED_DEPTH) != 0) {
332                 /* store */
333                 view3d_draw_debug_store_depth(ar, draw_data);
334         }
335
336         if (((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_SCENE_DEPTH) != 0) ||
337                 ((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_COMBINED_DEPTH) != 0))
338         {
339                 /* draw */
340                 if (GPU_viewport_debug_depth_is_valid(draw_data->viewport)) {
341                         GPU_viewport_debug_depth_draw(draw_data->viewport, v3d->debug.znear, v3d->debug.zfar);
342                 }
343         }
344         else {
345                 /* cleanup */
346                 GPU_viewport_debug_depth_free(draw_data->viewport);
347         }
348 }
349
350 #endif /* VIEW3D_DRAW_DEBUG */
351
352 /* ******************** view border ***************** */
353
354 static void view3d_camera_border(
355         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
356         rctf *r_viewborder, const bool no_shift, const bool no_zoom)
357 {
358         CameraParams params;
359         rctf rect_view, rect_camera;
360
361         /* get viewport viewplane */
362         BKE_camera_params_init(&params);
363         BKE_camera_params_from_view3d(&params, v3d, rv3d);
364         if (no_zoom)
365                 params.zoom = 1.0f;
366         BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
367         rect_view = params.viewplane;
368
369         /* get camera viewplane */
370         BKE_camera_params_init(&params);
371         /* fallback for non camera objects */
372         params.clipsta = v3d->near;
373         params.clipend = v3d->far;
374         BKE_camera_params_from_object(&params, v3d->camera);
375         if (no_shift) {
376                 params.shiftx = 0.0f;
377                 params.shifty = 0.0f;
378         }
379         BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
380         rect_camera = params.viewplane;
381
382         /* get camera border within viewport */
383         r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
384         r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
385         r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
386         r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
387 }
388
389 void ED_view3d_calc_camera_border_size(
390         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
391         float r_size[2])
392 {
393         rctf viewborder;
394
395         view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, true, true);
396         r_size[0] = BLI_rctf_size_x(&viewborder);
397         r_size[1] = BLI_rctf_size_y(&viewborder);
398 }
399
400 void ED_view3d_calc_camera_border(
401         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
402         rctf *r_viewborder, const bool no_shift)
403 {
404         view3d_camera_border(scene, ar, v3d, rv3d, r_viewborder, no_shift, false);
405 }
406
407 static void drawviewborder_grid3(unsigned pos, float x1, float x2, float y1, float y2, float fac)
408 {
409         float x3, y3, x4, y4;
410
411         x3 = x1 + fac * (x2 - x1);
412         y3 = y1 + fac * (y2 - y1);
413         x4 = x1 + (1.0f - fac) * (x2 - x1);
414         y4 = y1 + (1.0f - fac) * (y2 - y1);
415
416         immBegin(GL_LINES, 8);
417         immVertex2f(pos, x1, y3);
418         immVertex2f(pos, x2, y3);
419
420         immVertex2f(pos, x1, y4);
421         immVertex2f(pos, x2, y4);
422
423         immVertex2f(pos, x3, y1);
424         immVertex2f(pos, x3, y2);
425
426         immVertex2f(pos, x4, y1);
427         immVertex2f(pos, x4, y2);
428         immEnd();
429 }
430
431 /* harmonious triangle */
432 static void drawviewborder_triangle(unsigned pos, float x1, float x2, float y1, float y2, const char golden, const char dir)
433 {
434         float ofs;
435         float w = x2 - x1;
436         float h = y2 - y1;
437
438         immBegin(GL_LINES, 6);
439         if (w > h) {
440                 if (golden) {
441                         ofs = w * (1.0f - (1.0f / 1.61803399f));
442                 }
443                 else {
444                         ofs = h * (h / w);
445                 }
446                 if (dir == 'B') SWAP(float, y1, y2);
447
448                 immVertex2f(pos, x1, y1);
449                 immVertex2f(pos, x2, y2);
450
451                 immVertex2f(pos, x2, y1);
452                 immVertex2f(pos, x1 + (w - ofs), y2);
453
454                 immVertex2f(pos, x1, y2);
455                 immVertex2f(pos, x1 + ofs, y1);
456         }
457         else {
458                 if (golden) {
459                         ofs = h * (1.0f - (1.0f / 1.61803399f));
460                 }
461                 else {
462                         ofs = w * (w / h);
463                 }
464                 if (dir == 'B') SWAP(float, x1, x2);
465
466                 immVertex2f(pos, x1, y1);
467                 immVertex2f(pos, x2, y2);
468
469                 immVertex2f(pos, x2, y1);
470                 immVertex2f(pos, x1, y1 + ofs);
471
472                 immVertex2f(pos, x1, y2);
473                 immVertex2f(pos, x2, y1 + (h - ofs));
474         }
475         immEnd();
476 }
477
478 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
479 {
480         float x1, x2, y1, y2;
481         float x1i, x2i, y1i, y2i;
482
483         rctf viewborder;
484         Camera *ca = NULL;
485         RegionView3D *rv3d = ar->regiondata;
486
487         if (v3d->camera == NULL)
488                 return;
489         if (v3d->camera->type == OB_CAMERA)
490                 ca = v3d->camera->data;
491
492         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
493         /* the offsets */
494         x1 = viewborder.xmin;
495         y1 = viewborder.ymin;
496         x2 = viewborder.xmax;
497         y2 = viewborder.ymax;
498
499         glLineWidth(1.0f);
500
501         /* apply offsets so the real 3D camera shows through */
502
503         /* note: quite un-scientific but without this bit extra
504          * 0.0001 on the lower left the 2D border sometimes
505          * obscures the 3D camera border */
506         /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
507          * but keep it here in case we need to remove the workaround */
508         x1i = (int)(x1 - 1.0001f);
509         y1i = (int)(y1 - 1.0001f);
510         x2i = (int)(x2 + (1.0f - 0.0001f));
511         y2i = (int)(y2 + (1.0f - 0.0001f));
512
513         /* use the same program for everything */
514         unsigned pos = add_attrib(immVertexFormat(), "pos", COMP_F32, 2, KEEP_FLOAT);
515         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
516
517         /* passepartout, specified in camera edit buttons */
518         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
519                 const float winx = (ar->winx + 1);
520                 const float winy = (ar->winy + 1);
521
522                 float alpha = 1.0f;
523
524                 if (ca->passepartalpha != 1.0f) {
525                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
526                         glEnable(GL_BLEND);
527                         alpha = ca->passepartalpha;
528                 }
529
530                 immUniformColor4f(0.0f, 0.0f, 0.0f, alpha);
531
532                 if (x1i > 0.0f)
533                         immRectf(pos, 0.0f, winy, x1i, 0.0f);
534                 if (x2i < winx)
535                         immRectf(pos, x2i, winy, winx, 0.0f);
536                 if (y2i < winy)
537                         immRectf(pos, x1i, winy, x2i, y2i);
538                 if (y2i > 0.0f)
539                         immRectf(pos, x1i, y1i, x2i, 0.0f);
540
541                 glDisable(GL_BLEND);
542         }
543
544         setlinestyle(0);
545
546         immUniformThemeColor(TH_BACK);
547         imm_draw_line_box(pos, x1i, y1i, x2i, y2i);
548
549 #ifdef VIEW3D_CAMERA_BORDER_HACK
550         if (view3d_camera_border_hack_test == true) {
551                 immUniformColor3ubv(view3d_camera_border_hack_col);
552                 imm_draw_line_box(pos, x1i + 1, y1i + 1, x2i - 1, y2i - 1);
553                 view3d_camera_border_hack_test = false;
554         }
555 #endif
556
557         setlinestyle(3);
558
559         /* outer line not to confuse with object selecton */
560         if (v3d->flag2 & V3D_LOCK_CAMERA) {
561                 immUniformThemeColor(TH_REDALERT);
562                 imm_draw_line_box(pos, x1i - 1, y1i - 1, x2i + 1, y2i + 1);
563         }
564
565         immUniformThemeColor(TH_VIEW_OVERLAY);
566         imm_draw_line_box(pos, x1i, y1i, x2i, y2i);
567
568         /* border */
569         if (scene->r.mode & R_BORDER) {
570                 float x3, y3, x4, y4;
571
572                 x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
573                 y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
574                 x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
575                 y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
576
577                 imm_cpack(0x4040FF);
578                 imm_draw_line_box(pos, x3, y3, x4, y4);
579         }
580
581         /* safety border */
582         if (ca) {
583                 if (ca->dtx & CAM_DTX_CENTER) {
584                         float x3, y3;
585
586                         x3 = x1 + 0.5f * (x2 - x1);
587                         y3 = y1 + 0.5f * (y2 - y1);
588
589                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
590                         immBegin(GL_LINES, 4);
591
592                         immVertex2f(pos, x1, y3);
593                         immVertex2f(pos, x2, y3);
594
595                         immVertex2f(pos, x3, y1);
596                         immVertex2f(pos, x3, y2);
597
598                         immEnd();
599                 }
600
601                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
602
603                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
604                         immBegin(GL_LINES, 4);
605
606                         immVertex2f(pos, x1, y1);
607                         immVertex2f(pos, x2, y2);
608
609                         immVertex2f(pos, x1, y2);
610                         immVertex2f(pos, x2, y1);
611
612                         immEnd();
613                 }
614
615                 if (ca->dtx & CAM_DTX_THIRDS) {
616                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
617                         drawviewborder_grid3(pos, x1, x2, y1, y2, 1.0f / 3.0f);
618                 }
619
620                 if (ca->dtx & CAM_DTX_GOLDEN) {
621                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
622                         drawviewborder_grid3(pos, x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
623                 }
624
625                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
626                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
627                         drawviewborder_triangle(pos, x1, x2, y1, y2, 0, 'A');
628                 }
629
630                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
631                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
632                         drawviewborder_triangle(pos, x1, x2, y1, y2, 0, 'B');
633                 }
634
635                 if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
636                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
637                         drawviewborder_triangle(pos, x1, x2, y1, y2, 1, 'A');
638                 }
639
640                 if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
641                         immUniformThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25f, 0);
642                         drawviewborder_triangle(pos, x1, x2, y1, y2, 1, 'B');
643                 }
644
645                 if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
646                         UI_draw_safe_areas(
647                                 pos, x1, x2, y1, y2,
648                                 scene->safe_areas.title,
649                                 scene->safe_areas.action);
650
651                         if (ca->flag & CAM_SHOW_SAFE_CENTER) {
652                                 UI_draw_safe_areas(
653                                         pos, x1, x2, y1, y2,
654                                         scene->safe_areas.title_center,
655                                         scene->safe_areas.action_center);
656                         }
657                 }
658
659                 if (ca->flag & CAM_SHOWSENSOR) {
660                         /* determine sensor fit, and get sensor x/y, for auto fit we
661                          * assume and square sensor and only use sensor_x */
662                         float sizex = scene->r.xsch * scene->r.xasp;
663                         float sizey = scene->r.ysch * scene->r.yasp;
664                         int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
665                         float sensor_x = ca->sensor_x;
666                         float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
667
668                         /* determine sensor plane */
669                         rctf rect;
670
671                         if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
672                                 float sensor_scale = (x2i - x1i) / sensor_x;
673                                 float sensor_height = sensor_scale * sensor_y;
674
675                                 rect.xmin = x1i;
676                                 rect.xmax = x2i;
677                                 rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
678                                 rect.ymax = rect.ymin + sensor_height;
679                         }
680                         else {
681                                 float sensor_scale = (y2i - y1i) / sensor_y;
682                                 float sensor_width = sensor_scale * sensor_x;
683
684                                 rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
685                                 rect.xmax = rect.xmin + sensor_width;
686                                 rect.ymin = y1i;
687                                 rect.ymax = y2i;
688                         }
689
690                         /* draw */
691                         float color[4];
692                         UI_GetThemeColorShade4fv(TH_VIEW_OVERLAY, 100, color);
693                         UI_draw_roundbox_gl_mode(GL_LINE_LOOP, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f, color);
694                 }
695         }
696
697         setlinestyle(0);
698
699         /* camera name - draw in highlighted text color */
700         if (ca && (ca->flag & CAM_SHOWNAME)) {
701                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
702                 BLF_draw_default(
703                         x1i, y1i - (0.7f * U.widget_unit), 0.0f,
704                         v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
705         }
706
707         immUnbindProgram();
708 }
709
710 static void drawrenderborder(ARegion *ar, View3D *v3d)
711 {
712         /* use the same program for everything */
713         unsigned pos = add_attrib(immVertexFormat(), "pos", COMP_F32, 2, KEEP_FLOAT);
714         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
715
716         glLineWidth(1.0f);
717         setlinestyle(3);
718         imm_cpack(0x4040FF);
719
720         imm_draw_line_box(
721             pos, v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
722             v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
723
724         setlinestyle(0);
725
726         immUnbindProgram();
727 }
728
729 /* ******************** offline engine ***************** */
730
731 static bool view3d_draw_render_draw(const bContext *C, Scene *scene,
732     ARegion *ar, View3D *UNUSED(v3d),
733     bool clip_border, const rcti *border_rect)
734 {
735         RegionView3D *rv3d = ar->regiondata;
736         RenderEngineType *type;
737         GLint scissor[4];
738
739         /* create render engine */
740         if (!rv3d->render_engine) {
741                 RenderEngine *engine;
742
743                 type = RE_engines_find(scene->r.engine);
744
745                 if (!(type->view_update && type->view_draw))
746                         return false;
747
748                 engine = RE_engine_create_ex(type, true);
749
750                 engine->tile_x = scene->r.tilex;
751                 engine->tile_y = scene->r.tiley;
752
753                 type->view_update(engine, C);
754
755                 rv3d->render_engine = engine;
756         }
757
758         /* background draw */
759         glMatrixMode(GL_PROJECTION);
760         glPushMatrix();
761         glMatrixMode(GL_MODELVIEW);
762         glPushMatrix();
763         ED_region_pixelspace(ar);
764
765         if (clip_border) {
766                 /* for border draw, we only need to clear a subset of the 3d view */
767                 if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
768                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
769                         glScissor(border_rect->xmin, border_rect->ymin,
770                                 BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
771                 }
772                 else {
773                         return false;
774                 }
775         }
776
777         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
778         /* don't change depth buffer */
779         glClear(GL_COLOR_BUFFER_BIT); /* is this necessary? -- merwin */
780
781         /* render result draw */
782         type = rv3d->render_engine->type;
783         type->view_draw(rv3d->render_engine, C);
784
785         if (clip_border) {
786                 /* restore scissor as it was before */
787                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
788         }
789
790         glMatrixMode(GL_PROJECTION);
791         glPopMatrix();
792         glMatrixMode(GL_MODELVIEW);
793         glPopMatrix();
794
795         return true;
796 }
797
798 /* ******************** background plates ***************** */
799
800 static void view3d_draw_background_gradient(void)
801 {
802         gpuMatrixBegin3D(); /* TODO: finish 2D API */
803
804         glClear(GL_DEPTH_BUFFER_BIT);
805
806         VertexFormat *format = immVertexFormat();
807         unsigned pos = add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
808         unsigned color = add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
809         unsigned char col_hi[3], col_lo[3];
810
811         immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
812
813         UI_GetThemeColor3ubv(TH_LOW_GRAD, col_lo);
814         UI_GetThemeColor3ubv(TH_HIGH_GRAD, col_hi);
815
816         immBegin(GL_QUADS, 4);
817         immAttrib3ubv(color, col_lo);
818         immVertex2f(pos, -1.0f, -1.0f);
819         immVertex2f(pos, 1.0f, -1.0f);
820
821         immAttrib3ubv(color, col_hi);
822         immVertex2f(pos, 1.0f, 1.0f);
823         immVertex2f(pos, -1.0f, 1.0f);
824         immEnd();
825
826         immUnbindProgram();
827
828         gpuMatrixEnd();
829 }
830
831 static void view3d_draw_background_none(void)
832 {
833         if (UI_GetThemeValue(TH_SHOW_BACK_GRAD)) {
834                 view3d_draw_background_gradient();
835         }
836         else {
837                 UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
838                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
839         }
840 }
841
842 static void view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
843 {
844         if (scene->world) {
845                 GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
846
847                 /* calculate full shader for background */
848                 GPU_material_bind(gpumat, 1, 1, 1.0f, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac, (v3d->scenelock != 0));
849
850                 if (GPU_material_bound(gpumat)) {
851
852                         glClear(GL_DEPTH_BUFFER_BIT);
853
854                         /* TODO viewport (dfelinto): GPU_material_bind relies on immediate mode,
855                         * we can't get rid of the following code without a bigger refactor
856                         * or we dropping this functionality. */
857
858                         glBegin(GL_TRIANGLE_STRIP);
859                         glVertex2f(-1.0f, -1.0f);
860                         glVertex2f(1.0f, -1.0f);
861                         glVertex2f(-1.0f, 1.0f);
862                         glVertex2f(1.0f, 1.0f);
863                         glEnd();
864
865                         GPU_material_unbind(gpumat);
866                 }
867                 else {
868                         view3d_draw_background_none();
869                 }
870         }
871         else {
872                 view3d_draw_background_none();
873         }
874 }
875
876 /* ******************** solid plates ***************** */
877
878 /**
879  * Clear the buffer and draw the proper shader
880  */
881 static void view3d_draw_background(const bContext *C)
882 {
883         Scene *scene = CTX_data_scene(C);
884         View3D *v3d = CTX_wm_view3d(C);
885         RegionView3D *rv3d = CTX_wm_region_view3d(C);
886
887         glDisable(GL_DEPTH_TEST);
888         glDepthMask(GL_TRUE);
889         /* Background functions do not read or write depth, but they do clear or completely
890          * overwrite color buffer. It's more efficient to clear color & depth in once call, so
891          * background functions do this even though they don't use depth.
892          */
893
894         switch (v3d->debug.background) {
895                 case V3D_DEBUG_BACKGROUND_WORLD:
896                         view3d_draw_background_world(scene, v3d, rv3d);
897                         break;
898                 case V3D_DEBUG_BACKGROUND_GRADIENT:
899                         view3d_draw_background_gradient();
900                         break;
901                 case V3D_DEBUG_BACKGROUND_NONE:
902                 default:
903                         view3d_draw_background_none();
904                         break;
905         }
906 }
907
908 /**
909  *
910  */
911 static void view3d_draw_render_solid_surfaces(const bContext *C, ARegion *ar, const bool UNUSED(run_screen_shaders))
912 {
913         /* TODO viewport */
914         draw_all_objects(C, ar, false, use_depth(C));
915 }
916
917 /**
918  *
919  */
920 static void view3d_draw_render_transparent_surfaces(const bContext *UNUSED(C))
921 {
922         /* TODO viewport */
923 }
924
925 /**
926  *
927  */
928 static void view3d_draw_post_draw(const bContext *UNUSED(C))
929 {
930         /* TODO viewport */
931 }
932
933 /* ******************** geometry overlay ***************** */
934
935 /**
936  * Front/back wire frames
937  */
938 static void view3d_draw_wire_plates(const bContext *UNUSED(C))
939 {
940         /* TODO viewport */
941 }
942
943 /**
944  * Special treatment for selected objects
945  */
946 static void view3d_draw_outline_plates(const bContext *UNUSED(C))
947 {
948         /* TODO viewport */
949 }
950
951 /* ******************** other elements ***************** */
952
953
954 #define DEBUG_GRID 0
955
956 static void gridline_range(double x0, double dx, double max, int* first_out, int* count_out)
957 {
958         /* determine range of gridlines that appear in this Area -- similar calc but separate ranges for x & y
959         * x0 is gridline 0, the axis in screen space
960         * Area covers [0 .. max) pixels */
961
962         int first = (int)ceil(-x0 / dx);
963         int last = (int)floor((max - x0) / dx);
964
965         if (first <= last) {
966                 *first_out = first;
967                 *count_out = last - first + 1;
968         }
969         else {
970                 *first_out = 0;
971                 *count_out = 0;
972         }
973
974 #if DEBUG_GRID
975         printf("   first %d * dx = %f\n", first, x0 + first * dx);
976         printf("   last %d * dx = %f\n", last, x0 + last * dx);
977         printf("   count = %d\n", *count_out);
978 #endif
979 }
980
981 static int gridline_count(ARegion *ar, double x0, double y0, double dx)
982 {
983         /* x0 & y0 establish the "phase" of the grid within this 2D region
984         * dx is the frequency, shared by x & y directions
985         * pass in dx of smallest (highest precision) grid we want to draw */
986
987 #if DEBUG_GRID
988         printf("  %s(%f, %f, dx:%f)\n", __FUNCTION__, x0, y0, dx);
989 #endif
990
991         int first, x_ct, y_ct;
992
993         gridline_range(x0, dx, ar->winx, &first, &x_ct);
994         gridline_range(y0, dx, ar->winy, &first, &y_ct);
995
996         int total_ct = x_ct + y_ct;
997
998 #if DEBUG_GRID
999         printf("   %d + %d = %d gridlines\n", x_ct, y_ct, total_ct);
1000 #endif
1001
1002         return total_ct;
1003 }
1004
1005 static bool drawgrid_draw(ARegion *ar, double x0, double y0, double dx, int skip_mod, unsigned pos, unsigned col, GLubyte col_value[3])
1006 {
1007         /* skip every skip_mod lines relative to each axis; they will be overlaid by another drawgrid_draw
1008         * always skip exact x0 & y0 axes; they will be drawn later in color
1009         *
1010         * set grid color once, just before the first line is drawn
1011         * it's harmless to set same color for every line, or every vertex
1012         * but if no lines are drawn, color must not be set! */
1013
1014 #if DEBUG_GRID
1015         printf("  %s(%f, %f, dx:%f, skip_mod:%d)\n", __FUNCTION__, x0, y0, dx, skip_mod);
1016 #endif
1017
1018         const float x_max = (float)ar->winx;
1019         const float y_max = (float)ar->winy;
1020
1021         int first, ct;
1022         int x_ct = 0, y_ct = 0; /* count of lines actually drawn */
1023         int lines_skipped_for_next_unit = 0;
1024
1025         /* draw vertical lines */
1026         gridline_range(x0, dx, x_max, &first, &ct);
1027
1028         for (int i = first; i < first + ct; ++i) {
1029                 if (i == 0)
1030                         continue;
1031                 else if (skip_mod && (i % skip_mod) == 0) {
1032                         ++lines_skipped_for_next_unit;
1033                         continue;
1034                 }
1035
1036                 if (x_ct == 0)
1037                         immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
1038
1039                 float x = (float)(x0 + i * dx);
1040                 immVertex2f(pos, x, 0.0f);
1041                 immVertex2f(pos, x, y_max);
1042                 ++x_ct;
1043         }
1044
1045         /* draw horizontal lines */
1046         gridline_range(y0, dx, y_max, &first, &ct);
1047
1048         for (int i = first; i < first + ct; ++i) {
1049                 if (i == 0)
1050                         continue;
1051                 else if (skip_mod && (i % skip_mod) == 0) {
1052                         ++lines_skipped_for_next_unit;
1053                         continue;
1054                 }
1055
1056                 if (x_ct + y_ct == 0)
1057                         immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
1058
1059                 float y = (float)(y0 + i * dx);
1060                 immVertex2f(pos, 0.0f, y);
1061                 immVertex2f(pos, x_max, y);
1062                 ++y_ct;
1063         }
1064
1065 #if DEBUG_GRID
1066         int total_ct = x_ct + y_ct;
1067         printf("    %d + %d = %d gridlines drawn, %d skipped for next unit\n", x_ct, y_ct, total_ct, lines_skipped_for_next_unit);
1068 #endif
1069
1070         return lines_skipped_for_next_unit > 0;
1071 }
1072
1073 #define GRID_MIN_PX_D 6.0
1074 #define GRID_MIN_PX_F 6.0f
1075
1076 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
1077 {
1078         RegionView3D *rv3d = ar->regiondata;
1079
1080 #if DEBUG_GRID
1081         printf("%s width %d, height %d\n", __FUNCTION__, ar->winx, ar->winy);
1082 #endif
1083
1084         double fx = rv3d->persmat[3][0];
1085         double fy = rv3d->persmat[3][1];
1086         double fw = rv3d->persmat[3][3];
1087
1088         const double wx = 0.5 * ar->winx;  /* use double precision to avoid rounding errors */
1089         const double wy = 0.5 * ar->winy;
1090
1091         double x = wx * fx / fw;
1092         double y = wy * fy / fw;
1093
1094         double vec4[4] = { v3d->grid, v3d->grid, 0.0, 1.0 };
1095         mul_m4_v4d(rv3d->persmat, vec4);
1096         fx = vec4[0];
1097         fy = vec4[1];
1098         fw = vec4[3];
1099
1100         double dx = fabs(x - wx * fx / fw);
1101         if (dx == 0) dx = fabs(y - wy * fy / fw);
1102
1103         x += wx;
1104         y += wy;
1105
1106         /* now x, y, and dx have their final values
1107         * (x,y) is the world origin (0,0,0) mapped to Area-relative screen space
1108         * dx is the distance in pixels between grid lines -- same for horiz or vert grid lines */
1109
1110         glLineWidth(1.0f);
1111
1112 #if 0 /* TODO: write to UI/widget depth buffer, not scene depth */
1113         glDepthMask(GL_FALSE);  /* disable write in zbuffer */
1114 #endif
1115
1116         VertexFormat* format = immVertexFormat();
1117         unsigned pos = add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1118         unsigned color = add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1119
1120         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1121
1122         unsigned char col[3], col2[3];
1123         UI_GetThemeColor3ubv(TH_GRID, col);
1124
1125         if (unit->system) {
1126                 const void *usys;
1127                 int len;
1128
1129                 bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
1130
1131                 bool first = true;
1132
1133                 if (usys) {
1134                         int i = len;
1135                         while (i--) {
1136                                 double scalar = bUnit_GetScaler(usys, i);
1137
1138                                 double dx_scalar = dx * scalar / (double)unit->scale_length;
1139                                 if (dx_scalar < (GRID_MIN_PX_D * 2.0)) {
1140                                         /* very very small grid items are less useful when dealing with units */
1141                                         continue;
1142                                 }
1143
1144                                 if (first) {
1145                                         first = false;
1146
1147                                         /* Store the smallest drawn grid size units name so users know how big each grid cell is */
1148                                         *grid_unit = bUnit_GetNameDisplay(usys, i);
1149                                         rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
1150
1151                                         int gridline_ct = gridline_count(ar, x, y, dx_scalar);
1152                                         if (gridline_ct == 0)
1153                                                 goto drawgrid_cleanup; /* nothing to draw */
1154
1155                                         immBegin(GL_LINES, gridline_ct * 2);
1156                                 }
1157
1158                                 float blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
1159                                 /* tweak to have the fade a bit nicer */
1160                                 blend_fac = (blend_fac * blend_fac) * 2.0f;
1161                                 CLAMP(blend_fac, 0.3f, 1.0f);
1162
1163                                 UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, blend_fac, col2);
1164
1165                                 const int skip_mod = (i == 0) ? 0 : (int)round(bUnit_GetScaler(usys, i - 1) / scalar);
1166 #if DEBUG_GRID
1167                                 printf("%s %f, ", bUnit_GetNameDisplay(usys, i), scalar);
1168                                 if (i > 0)
1169                                         printf("next unit is %d times larger\n", skip_mod);
1170                                 else
1171                                         printf("largest unit\n");
1172 #endif
1173                                 if (!drawgrid_draw(ar, x, y, dx_scalar, skip_mod, pos, color, col2))
1174                                         break;
1175                         }
1176                 }
1177         }
1178         else {
1179                 const double sublines = v3d->gridsubdiv;
1180                 const float  sublines_fl = v3d->gridsubdiv;
1181
1182                 int grids_to_draw = 2; /* first the faint fine grid, then the bold coarse grid */
1183
1184                 if (dx < GRID_MIN_PX_D) {
1185                         rv3d->gridview *= sublines_fl;
1186                         dx *= sublines;
1187                         if (dx < GRID_MIN_PX_D) {
1188                                 rv3d->gridview *= sublines_fl;
1189                                 dx *= sublines;
1190                                 if (dx < GRID_MIN_PX_D) {
1191                                         rv3d->gridview *= sublines_fl;
1192                                         dx *= sublines;
1193                                         grids_to_draw = (dx < GRID_MIN_PX_D) ? 0 : 1;
1194                                 }
1195                         }
1196                 }
1197                 else {
1198                         if (dx >(GRID_MIN_PX_D * 10.0)) {  /* start blending in */
1199                                 rv3d->gridview /= sublines_fl;
1200                                 dx /= sublines;
1201                                 if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
1202                                         rv3d->gridview /= sublines_fl;
1203                                         dx /= sublines;
1204                                         if (dx > (GRID_MIN_PX_D * 10.0)) {
1205                                                 grids_to_draw = 1;
1206                                         }
1207                                 }
1208                         }
1209                 }
1210
1211                 int gridline_ct = gridline_count(ar, x, y, dx);
1212                 if (gridline_ct == 0)
1213                         goto drawgrid_cleanup; /* nothing to draw */
1214
1215                 immBegin(GL_LINES, gridline_ct * 2);
1216
1217                 if (grids_to_draw == 2) {
1218                         UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0), col2);
1219                         if (drawgrid_draw(ar, x, y, dx, v3d->gridsubdiv, pos, color, col2))
1220                                 drawgrid_draw(ar, x, y, dx * sublines, 0, pos, color, col);
1221                 }
1222                 else if (grids_to_draw == 1) {
1223                         drawgrid_draw(ar, x, y, dx, 0, pos, color, col);
1224                 }
1225         }
1226
1227         /* draw visible axes */
1228         /* horizontal line */
1229         if (0 <= y && y < ar->winy) {
1230                 UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT) ? 'Y' : 'X');
1231                 immAttrib3ub(color, col2[0], col2[1], col2[2]);
1232                 immVertex2f(pos, 0.0f, y);
1233                 immVertex2f(pos, (float)ar->winx, y);
1234         }
1235
1236         /* vertical line */
1237         if (0 <= x && x < ar->winx) {
1238                 UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM) ? 'Y' : 'Z');
1239                 immAttrib3ub(color, col2[0], col2[1], col2[2]);
1240                 immVertex2f(pos, x, 0.0f);
1241                 immVertex2f(pos, x, (float)ar->winy);
1242         }
1243
1244         immEnd();
1245
1246 drawgrid_cleanup:
1247         immUnbindProgram();
1248
1249 #if 0 /* depth write is left enabled above */
1250         glDepthMask(GL_TRUE);  /* enable write in zbuffer */
1251 #endif
1252 }
1253
1254 #undef DEBUG_GRID
1255 #undef GRID_MIN_PX_D
1256 #undef GRID_MIN_PX_F
1257
1258 static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
1259 {
1260         /* draw only if there is something to draw */
1261         if (v3d->gridflag & (V3D_SHOW_FLOOR | V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
1262                 /* draw how many lines?
1263                 * trunc(v3d->gridlines / 2) * 4
1264                 * + 2 for xy axes (possibly with special colors)
1265                 * + 1 for z axis (the only line not in xy plane)
1266                 * even v3d->gridlines are honored, odd rounded down */
1267                 const int gridlines = v3d->gridlines / 2;
1268                 const float grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
1269                 const float grid = gridlines * grid_scale;
1270
1271                 const bool show_floor = (v3d->gridflag & V3D_SHOW_FLOOR) && gridlines >= 1;
1272
1273                 bool show_axis_x = v3d->gridflag & V3D_SHOW_X;
1274                 bool show_axis_y = v3d->gridflag & V3D_SHOW_Y;
1275                 bool show_axis_z = v3d->gridflag & V3D_SHOW_Z;
1276
1277                 unsigned char col_grid[3], col_axis[3];
1278
1279                 glLineWidth(1.0f);
1280
1281                 UI_GetThemeColor3ubv(TH_GRID, col_grid);
1282
1283                 if (!write_depth)
1284                         glDepthMask(GL_FALSE);
1285
1286                 if (show_floor) {
1287                         const unsigned vertex_ct = 2 * (gridlines * 4 + 2);
1288                         const int sublines = v3d->gridsubdiv;
1289
1290                         unsigned char col_bg[3], col_grid_emphasise[3], col_grid_light[3];
1291
1292                         VertexFormat* format = immVertexFormat();
1293                         unsigned pos = add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1294                         unsigned color = add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1295
1296                         immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
1297
1298                         immBegin(GL_LINES, vertex_ct);
1299
1300                         /* draw normal grid lines */
1301                         UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
1302
1303                         for (int a = 1; a <= gridlines; a++) {
1304                                 /* skip emphasised divider lines */
1305                                 if (a % sublines != 0) {
1306                                         const float line = a * grid_scale;
1307
1308                                         immAttrib3ubv(color, col_grid_light);
1309
1310                                         immVertex2f(pos, -grid, -line);
1311                                         immVertex2f(pos, +grid, -line);
1312                                         immVertex2f(pos, -grid, +line);
1313                                         immVertex2f(pos, +grid, +line);
1314
1315                                         immVertex2f(pos, -line, -grid);
1316                                         immVertex2f(pos, -line, +grid);
1317                                         immVertex2f(pos, +line, -grid);
1318                                         immVertex2f(pos, +line, +grid);
1319                                 }
1320                         }
1321
1322                         /* draw emphasised grid lines */
1323                         UI_GetThemeColor3ubv(TH_BACK, col_bg);
1324                         /* emphasise division lines lighter instead of darker, if background is darker than grid */
1325                         UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
1326                                 (col_grid[0] + col_grid[1] + col_grid[2] + 30 >
1327                                 col_bg[0] + col_bg[1] + col_bg[2]) ? 20 : -10);
1328
1329                         if (sublines <= gridlines) {
1330                                 immAttrib3ubv(color, col_grid_emphasise);
1331
1332                                 for (int a = sublines; a <= gridlines; a += sublines) {
1333                                         const float line = a * grid_scale;
1334
1335                                         immVertex2f(pos, -grid, -line);
1336                                         immVertex2f(pos, +grid, -line);
1337                                         immVertex2f(pos, -grid, +line);
1338                                         immVertex2f(pos, +grid, +line);
1339
1340                                         immVertex2f(pos, -line, -grid);
1341                                         immVertex2f(pos, -line, +grid);
1342                                         immVertex2f(pos, +line, -grid);
1343                                         immVertex2f(pos, +line, +grid);
1344                                 }
1345                         }
1346
1347                         /* draw X axis */
1348                         if (show_axis_x) {
1349                                 show_axis_x = false; /* drawing now, won't need to draw later */
1350                                 UI_make_axis_color(col_grid, col_axis, 'X');
1351                                 immAttrib3ubv(color, col_axis);
1352                         }
1353                         else
1354                                 immAttrib3ubv(color, col_grid_emphasise);
1355
1356                         immVertex2f(pos, -grid, 0.0f);
1357                         immVertex2f(pos, +grid, 0.0f);
1358
1359                         /* draw Y axis */
1360                         if (show_axis_y) {
1361                                 show_axis_y = false; /* drawing now, won't need to draw later */
1362                                 UI_make_axis_color(col_grid, col_axis, 'Y');
1363                                 immAttrib3ubv(color, col_axis);
1364                         }
1365                         else
1366                                 immAttrib3ubv(color, col_grid_emphasise);
1367
1368                         immVertex2f(pos, 0.0f, -grid);
1369                         immVertex2f(pos, 0.0f, +grid);
1370
1371                         immEnd();
1372                         immUnbindProgram();
1373
1374                         /* done with XY plane */
1375                 }
1376
1377                 if (show_axis_x || show_axis_y || show_axis_z) {
1378                         /* draw axis lines -- sometimes grid floor is off, other times we still need to draw the Z axis */
1379
1380                         VertexFormat* format = immVertexFormat();
1381                         unsigned pos = add_attrib(format, "pos", COMP_F32, 3, KEEP_FLOAT);
1382                         unsigned color = add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1383
1384                         immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
1385                         immBegin(GL_LINES, (show_axis_x + show_axis_y + show_axis_z) * 2);
1386
1387                         if (show_axis_x) {
1388                                 UI_make_axis_color(col_grid, col_axis, 'X');
1389                                 immAttrib3ubv(color, col_axis);
1390                                 immVertex3f(pos, -grid, 0.0f, 0.0f);
1391                                 immVertex3f(pos, +grid, 0.0f, 0.0f);
1392                         }
1393
1394                         if (show_axis_y) {
1395                                 UI_make_axis_color(col_grid, col_axis, 'Y');
1396                                 immAttrib3ubv(color, col_axis);
1397                                 immVertex3f(pos, 0.0f, -grid, 0.0f);
1398                                 immVertex3f(pos, 0.0f, +grid, 0.0f);
1399                         }
1400
1401                         if (show_axis_z) {
1402                                 UI_make_axis_color(col_grid, col_axis, 'Z');
1403                                 immAttrib3ubv(color, col_axis);
1404                                 immVertex3f(pos, 0.0f, 0.0f, -grid);
1405                                 immVertex3f(pos, 0.0f, 0.0f, +grid);
1406                         }
1407
1408                         immEnd();
1409                         immUnbindProgram();
1410                 }
1411
1412                 if (!write_depth)
1413                         glDepthMask(GL_TRUE);
1414         }
1415 }
1416
1417 /** could move this elsewhere, but tied into #ED_view3d_grid_scale */
1418 float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
1419 {
1420         /* apply units */
1421         if (scene->unit.system) {
1422                 const void *usys;
1423                 int len;
1424
1425                 bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
1426
1427                 if (usys) {
1428                         int i = bUnit_GetBaseUnit(usys);
1429                         if (grid_unit)
1430                                 *grid_unit = bUnit_GetNameDisplay(usys, i);
1431                         return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
1432                 }
1433         }
1434
1435         return 1.0f;
1436 }
1437
1438 float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
1439 {
1440         return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
1441 }
1442
1443
1444 static void view3d_draw_grid(const bContext *C, ARegion *ar)
1445 {
1446         /* TODO viewport
1447          * Missing is the flags to check whether to draw it
1448          * for now now we are using the flags in v3d itself.
1449          *
1450          * Also for now always assume depth is there, so we
1451          * draw on top of it.
1452          */
1453         /**
1454          * Calculate pixel-size factor once, is used for lamps and object centers.
1455          * Used by #ED_view3d_pixel_size and typically not accessed directly.
1456          *
1457          * \note #BKE_camera_params_compute_viewplane' also calculates a pixel-size value,
1458          * passed to #RE_SetPixelSize, in ortho mode this is compatible with this value,
1459          * but in perspective mode its offset by the near-clip.
1460          *
1461          * 'RegionView3D.pixsize' is used for viewport drawing, not rendering.
1462          */
1463         Scene *scene = CTX_data_scene(C);
1464         View3D *v3d = CTX_wm_view3d(C);
1465         RegionView3D *rv3d = ar->regiondata;
1466
1467         const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
1468         const char *grid_unit = NULL;
1469
1470         /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
1471          * objects if done last
1472          * needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views.
1473          */
1474         rv3d->gridview = ED_view3d_grid_scale(scene, v3d, &grid_unit);
1475
1476         glEnable(GL_DEPTH_TEST);
1477         glDepthMask(GL_FALSE); /* read & test depth, but don't alter it. TODO: separate UI depth buffer */
1478
1479         if (!draw_floor) {
1480                 ED_region_pixelspace(ar);
1481                 *(&grid_unit) = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
1482                 drawgrid(&scene->unit, ar, v3d, &grid_unit);
1483
1484                 glMatrixMode(GL_PROJECTION);
1485                 glLoadMatrixf(rv3d->winmat);
1486                 glMatrixMode(GL_MODELVIEW);
1487                 glLoadMatrixf(rv3d->viewmat);
1488         }
1489         else {
1490                 drawfloor(scene, v3d, &grid_unit, false);
1491         }
1492
1493         glDisable(GL_DEPTH_TEST);
1494 }
1495
1496 static bool is_cursor_visible(Scene *scene)
1497 {
1498         Object *ob = OBACT;
1499
1500         /* don't draw cursor in paint modes, but with a few exceptions */
1501         if (ob && ob->mode & OB_MODE_ALL_PAINT) {
1502                 /* exception: object is in weight paint and has deforming armature in pose mode */
1503                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1504                         if (BKE_object_pose_armature_get(ob) != NULL) {
1505                                 return true;
1506                         }
1507                 }
1508                 /* exception: object in texture paint mode, clone brush, use_clone_layer disabled */
1509                 else if (ob->mode & OB_MODE_TEXTURE_PAINT) {
1510                         const Paint *p = BKE_paint_get_active(scene);
1511
1512                         if (p && p->brush && p->brush->imagepaint_tool == PAINT_TOOL_CLONE) {
1513                                 if ((scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_LAYER_CLONE) == 0) {
1514                                         return true;
1515                                 }
1516                         }
1517                 }
1518
1519                 /* no exception met? then don't draw cursor! */
1520                 return false;
1521         }
1522
1523         return true;
1524 }
1525
1526 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
1527 {
1528         int co[2];
1529
1530         /* we don't want the clipping for cursor */
1531         if (ED_view3d_project_int_global(ar, ED_view3d_cursor3d_get(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1532                 const float f5 = 0.25f * U.widget_unit;
1533                 const float f10 = 0.5f * U.widget_unit;
1534                 const float f20 = U.widget_unit;
1535                 
1536                 glLineWidth(1.0f);
1537
1538                 VertexFormat* format = immVertexFormat();
1539                 unsigned pos = add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1540                 unsigned color = add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1541
1542                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1543
1544                 const int segments = 16;
1545
1546                 immBegin(GL_LINE_LOOP, segments);
1547
1548                 for (int i = 0; i < segments; ++i) {
1549                         float angle = 2 * M_PI * ((float)i / (float)segments);
1550                         float x = co[0] + f10 * cosf(angle);
1551                         float y = co[1] + f10 * sinf(angle);
1552
1553                         if (i % 2 == 0)
1554                                 immAttrib3ub(color, 255, 0, 0);
1555                         else
1556                                 immAttrib3ub(color, 255, 255, 255);
1557
1558                         immVertex2f(pos, x, y);
1559                 }
1560                 immEnd();
1561
1562                 immUnbindProgram();
1563
1564                 VertexFormat_clear(format);
1565                 pos = add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1566
1567                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1568
1569                 unsigned char crosshair_color[3];
1570                 UI_GetThemeColor3ubv(TH_VIEW_OVERLAY, crosshair_color);
1571                 immUniformColor3ubv(crosshair_color);
1572
1573                 immBegin(GL_LINES, 8);
1574                 immVertex2f(pos, co[0] - f20, co[1]);
1575                 immVertex2f(pos, co[0] - f5, co[1]);
1576                 immVertex2f(pos, co[0] + f5, co[1]);
1577                 immVertex2f(pos, co[0] + f20, co[1]);
1578                 immVertex2f(pos, co[0], co[1] - f20);
1579                 immVertex2f(pos, co[0], co[1] - f5);
1580                 immVertex2f(pos, co[0], co[1] + f5);
1581                 immVertex2f(pos, co[0], co[1] + f20);
1582                 immEnd();
1583
1584                 immUnbindProgram();
1585         }
1586 }
1587
1588 static void draw_view_axis(RegionView3D *rv3d, rcti *rect)
1589 {
1590         const float k = U.rvisize * U.pixelsize;  /* axis size */
1591         const int bright = - 20 * (10 - U.rvibright);  /* axis alpha offset (rvibright has range 0-10) */
1592
1593         const float startx = rect->xmin + k + 1.0f;  /* axis center in screen coordinates, x=y */
1594         const float starty = rect->ymin + k + 1.0f;
1595
1596         float axis_pos[3][2];
1597         unsigned char axis_col[3][4];
1598
1599         int axis_order[3] = {0, 1, 2};
1600         axis_sort_v3(rv3d->viewinv[2], axis_order);
1601
1602         for (int axis_i = 0; axis_i < 3; axis_i++) {
1603                 int i = axis_order[axis_i];
1604
1605                 /* get position of each axis tip on screen */
1606                 float vec[3] = { 0.0f };
1607                 vec[i] = 1.0f;
1608                 mul_qt_v3(rv3d->viewquat, vec);
1609                 axis_pos[i][0] = startx + vec[0] * k;
1610                 axis_pos[i][1] = starty + vec[1] * k;
1611
1612                 /* get color of each axis */
1613                 UI_GetThemeColorShade3ubv(TH_AXIS_X + i, bright, axis_col[i]); /* rgb */
1614                 axis_col[i][3] = 255 * hypotf(vec[0], vec[1]); /* alpha */
1615         }
1616
1617         /* draw axis lines */
1618         glLineWidth(2.0f);
1619         glEnable(GL_LINE_SMOOTH);
1620         glEnable(GL_BLEND);
1621         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1622
1623         VertexFormat *format = immVertexFormat();
1624         unsigned pos = add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1625         unsigned col = add_attrib(format, "color", COMP_U8, 4, NORMALIZE_INT_TO_FLOAT);
1626
1627         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1628         immBegin(GL_LINES, 6);
1629
1630         for (int axis_i = 0; axis_i < 3; axis_i++) {
1631                 int i = axis_order[axis_i];
1632
1633                 immAttrib4ubv(col, axis_col[i]);
1634                 immVertex2f(pos, startx, starty);
1635                 immVertex2fv(pos, axis_pos[i]);
1636         }
1637
1638         immEnd();
1639         immUnbindProgram();
1640         glDisable(GL_LINE_SMOOTH);
1641
1642         /* draw axis names */
1643         for (int axis_i = 0; axis_i < 3; axis_i++) {
1644                 int i = axis_order[axis_i];
1645
1646                 const char axis_text[2] = {'x' + i, '\0'};
1647                 BLF_color4ubv(BLF_default(), axis_col[i]);
1648                 BLF_draw_default_ascii(axis_pos[i][0] + 2, axis_pos[i][1] + 2, 0.0f, axis_text, 1);
1649         }
1650
1651         /* BLF_draw disabled blending for us */
1652 }
1653
1654 #ifdef WITH_INPUT_NDOF
1655 /* draw center and axis of rotation for ongoing 3D mouse navigation */
1656 static void draw_rotation_guide(RegionView3D *rv3d)
1657 {
1658         float o[3];    /* center of rotation */
1659         float end[3];  /* endpoints for drawing */
1660
1661         GLubyte color[4] = {0, 108, 255, 255};  /* bright blue so it matches device LEDs */
1662
1663         negate_v3_v3(o, rv3d->ofs);
1664
1665         glEnable(GL_BLEND);
1666         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1667         glPointSize(5.0f);
1668         glEnable(GL_POINT_SMOOTH);
1669         glDepthMask(GL_FALSE);  /* don't overwrite zbuf */
1670
1671         VertexFormat *format = immVertexFormat();
1672         unsigned pos = add_attrib(format, "pos", COMP_F32, 3, KEEP_FLOAT);
1673         unsigned col = add_attrib(format, "color", COMP_U8, 4, NORMALIZE_INT_TO_FLOAT);
1674
1675         immBindBuiltinProgram(GPU_SHADER_3D_SMOOTH_COLOR);
1676
1677         if (rv3d->rot_angle != 0.0f) {
1678                 /* -- draw rotation axis -- */
1679                 float scaled_axis[3];
1680                 const float scale = rv3d->dist;
1681                 mul_v3_v3fl(scaled_axis, rv3d->rot_axis, scale);
1682
1683
1684                 immBegin(GL_LINE_STRIP, 3);
1685                 color[3] = 0; /* more transparent toward the ends */
1686                 immAttrib4ubv(col, color);
1687                 add_v3_v3v3(end, o, scaled_axis);
1688                 immVertex3fv(pos, end);
1689
1690 #if 0
1691                 color[3] = 0.2f + fabsf(rv3d->rot_angle);  /* modulate opacity with angle */
1692                 /* ^^ neat idea, but angle is frame-rate dependent, so it's usually close to 0.2 */
1693 #endif
1694
1695                 color[3] = 127; /* more opaque toward the center */
1696                 immAttrib4ubv(col, color);
1697                 immVertex3fv(pos, o);
1698
1699                 color[3] = 0;
1700                 immAttrib4ubv(col, color);
1701                 sub_v3_v3v3(end, o, scaled_axis);
1702                 immVertex3fv(pos, end);
1703                 immEnd();
1704                 
1705                 /* -- draw ring around rotation center -- */
1706                 {
1707 #define     ROT_AXIS_DETAIL 13
1708
1709                         const float s = 0.05f * scale;
1710                         const float step = 2.0f * (float)(M_PI / ROT_AXIS_DETAIL);
1711
1712                         float q[4];  /* rotate ring so it's perpendicular to axis */
1713                         const int upright = fabsf(rv3d->rot_axis[2]) >= 0.95f;
1714                         if (!upright) {
1715                                 const float up[3] = {0.0f, 0.0f, 1.0f};
1716                                 float vis_angle, vis_axis[3];
1717
1718                                 cross_v3_v3v3(vis_axis, up, rv3d->rot_axis);
1719                                 vis_angle = acosf(dot_v3v3(up, rv3d->rot_axis));
1720                                 axis_angle_to_quat(q, vis_axis, vis_angle);
1721                         }
1722
1723                         immBegin(GL_LINE_LOOP, ROT_AXIS_DETAIL);
1724                         color[3] = 63; /* somewhat faint */
1725                         immAttrib4ubv(col, color);
1726                         float angle = 0.0f;
1727                         for (int i = 0; i < ROT_AXIS_DETAIL; ++i, angle += step) {
1728                                 float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
1729
1730                                 if (!upright) {
1731                                         mul_qt_v3(q, p);
1732                                 }
1733
1734                                 add_v3_v3(p, o);
1735                                 immVertex3fv(pos, p);
1736                         }
1737                         immEnd();
1738
1739 #undef      ROT_AXIS_DETAIL
1740                 }
1741
1742                 color[3] = 255;  /* solid dot */
1743         }
1744         else
1745                 color[3] = 127;  /* see-through dot */
1746
1747         /* -- draw rotation center -- */
1748         immBegin(GL_POINTS, 1);
1749         immAttrib4ubv(col, color);
1750         immVertex3fv(pos, o);
1751         immEnd();
1752         immUnbindProgram();
1753
1754 #if 0
1755         /* find screen coordinates for rotation center, then draw pretty icon */
1756         mul_m4_v3(rv3d->persinv, rot_center);
1757         UI_icon_draw(rot_center[0], rot_center[1], ICON_NDOF_TURN);
1758         /* ^^ just playing around, does not work */
1759 #endif
1760
1761         glDisable(GL_BLEND);
1762         glDisable(GL_POINT_SMOOTH);
1763         glDepthMask(GL_TRUE);
1764 }
1765 #endif /* WITH_INPUT_NDOF */
1766
1767 /* ******************** non-meshes ***************** */
1768
1769 static void view3d_draw_non_mesh(
1770 Scene *scene, Object *ob, BaseLegacy *base, View3D *v3d,
1771 RegionView3D *rv3d, const bool is_boundingbox, const unsigned char color[4])
1772 {
1773         glMatrixMode(GL_PROJECTION);
1774         glPushMatrix();
1775         glMatrixMode(GL_MODELVIEW);
1776         glPushMatrix();
1777
1778         /* multiply view with object matrix.
1779         * local viewmat and persmat, to calculate projections */
1780         ED_view3d_init_mats_rv3d_gl(ob, rv3d);
1781
1782         switch (ob->type) {
1783                 case OB_MESH:
1784                 case OB_FONT:
1785                 case OB_CURVE:
1786                 case OB_SURF:
1787                 case OB_MBALL:
1788                         if (is_boundingbox) {
1789                                 draw_bounding_volume(ob, ob->boundtype);
1790                         }
1791                         break;
1792                 case OB_EMPTY:
1793                         drawaxes(rv3d->viewmatob, ob->empty_drawsize, ob->empty_drawtype, color);
1794                         break;
1795                 case OB_LAMP:
1796                         drawlamp(v3d, rv3d, base, OB_SOLID, DRAW_CONSTCOLOR, color, ob == OBACT);
1797                         break;
1798                 case OB_CAMERA:
1799                         drawcamera(scene, v3d, rv3d, base, DRAW_CONSTCOLOR, color);
1800                         break;
1801                 case OB_SPEAKER:
1802                         drawspeaker(color);
1803                         break;
1804                 case OB_LATTICE:
1805                         /* TODO */
1806                         break;
1807                 case OB_ARMATURE:
1808                         /* TODO */
1809                         break;
1810                 default:
1811                 /* TODO Viewport: handle the other cases*/
1812                         break;
1813         }
1814
1815         if (ob->rigidbody_object) {
1816                 draw_rigidbody_shape(ob);
1817         }
1818
1819         ED_view3d_clear_mats_rv3d(rv3d);
1820
1821         glMatrixMode(GL_PROJECTION);
1822         glPopMatrix();
1823         glMatrixMode(GL_MODELVIEW);
1824         glPopMatrix();
1825 }
1826
1827 /* ******************** info ***************** */
1828
1829 /**
1830 * Render and camera border
1831 */
1832 static void view3d_draw_border(const bContext *C, ARegion *ar)
1833 {
1834         Scene *scene = CTX_data_scene(C);
1835         RegionView3D *rv3d = ar->regiondata;
1836         View3D *v3d = CTX_wm_view3d(C);
1837
1838         if (rv3d->persp == RV3D_CAMOB) {
1839                 drawviewborder(scene, ar, v3d);
1840         }
1841         else if (v3d->flag2 & V3D_RENDER_BORDER) {
1842                 drawrenderborder(ar, v3d);
1843         }
1844 }
1845
1846 /**
1847 * Grease Pencil
1848 */
1849 static void view3d_draw_grease_pencil(const bContext *UNUSED(C))
1850 {
1851         /* TODO viewport */
1852 }
1853
1854 /* ******************** view loop ***************** */
1855
1856 /**
1857  * Set the correct matrices
1858  */
1859 static void view3d_draw_setup_view(const bContext *C, ARegion *ar)
1860 {
1861         Scene *scene = CTX_data_scene(C);
1862         View3D *v3d = CTX_wm_view3d(C);
1863         RegionView3D *rv3d = ar->regiondata;
1864
1865         /* setup the view matrix */
1866         if (view3d_stereo3d_active(C, scene, v3d, rv3d))
1867                 view3d_stereo3d_setup(scene, v3d, ar);
1868         else
1869                 view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
1870 }
1871
1872 static void draw_all_objects(const bContext *C, ARegion *ar, const bool only_depth, const bool use_depth)
1873 {
1874         Scene *scene = CTX_data_scene(C);
1875         View3D *v3d = CTX_wm_view3d(C);
1876
1877         if (only_depth)
1878                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1879
1880         if (only_depth || use_depth) {
1881                 glEnable(GL_DEPTH_TEST);
1882                 glDepthFunc(GL_LESS);
1883                 glDepthMask(GL_TRUE);
1884                 v3d->zbuf = true;
1885         }
1886
1887         for (BaseLegacy *base = scene->base.first; base; base = base->next) {
1888                 if (v3d->lay & base->lay) {
1889                         /* dupli drawing */
1890                         if (base->object->transflag & OB_DUPLI)
1891                                 draw_dupli_objects(scene, ar, v3d, base);
1892
1893                         draw_object(scene, ar, v3d, base, 0);
1894                 }
1895         }
1896
1897         if (only_depth)
1898                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1899
1900         if (only_depth || use_depth) {
1901                 glDisable(GL_DEPTH_TEST);
1902                 v3d->zbuf = false;
1903         }
1904 }
1905
1906 /**
1907  * Draw only the scene depth buffer
1908  */
1909 static void draw_depth_buffer(const bContext *C, ARegion *ar)
1910 {
1911         draw_all_objects(C, ar, true, true);
1912 }
1913
1914 /**
1915  * Required if the shaders need it or external engines
1916  * (e.g., Cycles requires depth buffer handled separately).
1917  */
1918 static void view3d_draw_prerender_buffers(const bContext *C, ARegion *ar, DrawData *draw_data)
1919 {
1920         View3D *v3d = CTX_wm_view3d(C);
1921
1922         /* TODO viewport */
1923         if (draw_data->is_render && ((!draw_data->clip_border) || (v3d->drawtype <= OB_WIRE))) {
1924                 draw_depth_buffer(C, ar);
1925         }
1926 }
1927
1928 /**
1929  * Draw all the plates that will fill the RGBD buffer
1930  */
1931 static void view3d_draw_solid_plates(const bContext *C, ARegion *ar, DrawData *draw_data)
1932 {
1933         /* realtime plates */
1934         if ((!draw_data->is_render) || draw_data->clip_border) {
1935                 view3d_draw_background(C);
1936                 view3d_draw_render_solid_surfaces(C, ar, true);
1937                 view3d_draw_render_transparent_surfaces(C);
1938                 view3d_draw_post_draw(C);
1939         }
1940
1941         /* offline plates*/
1942         if (draw_data->is_render) {
1943                 Scene *scene = CTX_data_scene(C);
1944                 View3D *v3d = CTX_wm_view3d(C);
1945
1946                 view3d_draw_render_draw(C, scene, ar, v3d, draw_data->clip_border, &draw_data->border_rect);
1947         }
1948
1949 #if VIEW3D_DRAW_DEBUG
1950         view3d_draw_debug_post_solid(C, ar, draw_data);
1951 #endif
1952 }
1953
1954 /**
1955  * Wires, outline, ...
1956  */
1957 static void view3d_draw_geometry_overlay(const bContext *C)
1958 {
1959         view3d_draw_wire_plates(C);
1960         view3d_draw_outline_plates(C);
1961 }
1962
1963 /* drawing cameras, lamps, ... */
1964 static void view3d_draw_non_meshes(const bContext *C, ARegion *ar)
1965 {
1966         /* TODO viewport
1967          * for now we draw them all, in the near future
1968          * we filter them based on the plates/layers
1969          */
1970         Scene *scene = CTX_data_scene(C);
1971         View3D *v3d = CTX_wm_view3d(C);
1972         RegionView3D *rv3d = ar->regiondata;
1973
1974         bool is_boundingbox = ((v3d->drawtype == OB_BOUNDBOX) ||
1975                                 ((v3d->drawtype == OB_RENDER) && (v3d->prev_drawtype == OB_BOUNDBOX)));
1976
1977         glEnable(GL_DEPTH_TEST);
1978         glDepthMask(GL_TRUE);
1979         /* TODO Viewport
1980          * we are already temporarily writing to zbuffer in draw_object()
1981          * for now let's avoid writing again to zbuffer to prevent glitches
1982          */
1983
1984         for (BaseLegacy *base = scene->base.first; base; base = base->next) {
1985                 if (v3d->lay & base->lay) {
1986                         Object *ob = base->object;
1987
1988                         unsigned char ob_wire_col[4];
1989                         draw_object_wire_color(scene, base, ob_wire_col);
1990                         view3d_draw_non_mesh(scene, ob, base, v3d, rv3d, is_boundingbox, ob_wire_col);
1991                 }
1992         }
1993
1994         glDepthMask(GL_FALSE);
1995         glDisable(GL_DEPTH_TEST);
1996 }
1997
1998 /**
1999 * Parent lines, grid, ...
2000 */
2001 static void view3d_draw_other_elements(const bContext *C, ARegion *ar)
2002 {
2003         view3d_draw_grid(C, ar);
2004
2005 #ifdef WITH_INPUT_NDOF
2006         RegionView3D *rv3d = ar->regiondata;
2007
2008         if ((U.ndof_flag & NDOF_SHOW_GUIDE) && ((rv3d->viewlock & RV3D_LOCKED) == 0) && (rv3d->persp != RV3D_CAMOB))
2009                 /* TODO: draw something else (but not this) during fly mode */
2010                 draw_rotation_guide(rv3d);
2011 #endif
2012 }
2013
2014 /**
2015  * Paint brushes, armatures, ...
2016  */
2017 static void view3d_draw_tool_ui(const bContext *UNUSED(C))
2018 {
2019         /* TODO viewport */
2020 }
2021
2022 /**
2023  * Blueprint images
2024  */
2025 static void view3d_draw_reference_images(const bContext *UNUSED(C))
2026 {
2027         /* TODO viewport */
2028 }
2029
2030 /**
2031 * 3D manipulators
2032 */
2033 static void view3d_draw_manipulator(const bContext *C)
2034 {
2035         View3D *v3d = CTX_wm_view3d(C);
2036         v3d->zbuf = false;
2037         BIF_draw_manipulator(C);
2038 }
2039
2040 /**
2041 * Information drawn on top of the solid plates and composed data
2042 */
2043 static void view3d_draw_region_info(const bContext *C, ARegion *ar)
2044 {
2045         /* correct projection matrix */
2046         ED_region_pixelspace(ar);
2047
2048         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2049         rcti rect;
2050         ED_region_visible_rect(ar, &rect);
2051
2052         view3d_draw_border(C, ar);
2053         view3d_draw_grease_pencil(C);
2054
2055         Scene *scene = CTX_data_scene(C);
2056         View3D *v3d = CTX_wm_view3d(C);
2057         RegionView3D *rv3d = ar->regiondata;
2058
2059         /* 3D cursor */
2060         if (is_cursor_visible(scene)) {
2061                 drawcursor(scene, ar, v3d);
2062         }
2063
2064         if (U.uiflag & USER_SHOW_ROTVIEWICON) {
2065                 draw_view_axis(rv3d, &rect);
2066         }
2067
2068         /* TODO viewport */
2069 }
2070
2071 /**
2072  * This could run once per view, or even in parallel
2073  * for each of them. What is a "view"?
2074  * - a viewport with the camera elsewhere
2075  * - left/right stereo
2076  * - panorama / fisheye individual cubemap faces
2077  */
2078 static void view3d_draw_view(const bContext *C, ARegion *ar, DrawData *draw_data)
2079 {
2080         /* TODO - Technically this should be drawn to a few FBO, so we can handle
2081          * compositing better, but for now this will get the ball rolling (dfelinto) */
2082
2083         view3d_draw_setup_view(C, ar);
2084         view3d_draw_prerender_buffers(C, ar, draw_data);
2085         view3d_draw_solid_plates(C, ar, draw_data);
2086         view3d_draw_geometry_overlay(C);
2087         view3d_draw_non_meshes(C, ar);
2088         view3d_draw_other_elements(C, ar);
2089         view3d_draw_tool_ui(C);
2090         view3d_draw_reference_images(C);
2091         view3d_draw_manipulator(C);
2092         view3d_draw_region_info(C, ar);
2093
2094 #if VIEW3D_DRAW_DEBUG
2095         view3d_draw_debug(C, ar, draw_data);
2096 #endif
2097 }
2098
2099 static void view3d_render_pass(const bContext *C, ARegion *ar)
2100 {
2101         Scene *scene = CTX_data_scene(C);
2102         RenderEngineType *type = RE_engines_find(scene->r.engine); /* In the future we should get that from Layers */
2103
2104         if (type->flag & RE_USE_OGL_PIPELINE) {
2105                 type->view_draw(NULL, C);
2106         }
2107         else {
2108                 // Offline Render engine
2109         }
2110 }
2111
2112 static void view3d_draw_view_new(const bContext *C, ARegion *ar, DrawData *UNUSED(draw_data))
2113 {
2114
2115         view3d_draw_setup_view(C, ar);
2116
2117         /* Only 100% compliant on new spec goes bellow */
2118         view3d_render_pass(C, ar);
2119
2120         view3d_draw_grid(C, ar);
2121         view3d_draw_manipulator(C);
2122         view3d_draw_region_info(C, ar);
2123 }
2124
2125
2126 void view3d_main_region_draw(const bContext *C, ARegion *ar)
2127 {
2128         Scene *scene = CTX_data_scene(C);
2129         View3D *v3d = CTX_wm_view3d(C);
2130         RegionView3D *rv3d = ar->regiondata;
2131         /* TODO layers - In the future we should get RE from Layers */
2132         RenderEngineType *type = RE_engines_find(scene->r.engine);
2133
2134         if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_OGL_PIPELINE) == 0)) {
2135                 view3d_main_region_draw_legacy(C, ar);
2136                 return;
2137         }
2138
2139         if (!rv3d->viewport)
2140                 rv3d->viewport = GPU_viewport_create();
2141
2142         GPU_viewport_bind(rv3d->viewport, &ar->winrct);
2143
2144         /* TODO viewport - there is so much to be done, in fact a lot will need to happen in the space_view3d.c
2145          * before we even call the drawing routine, but let's move on for now (dfelinto)
2146          * but this is a provisory way to start seeing things in the viewport */
2147         DrawData draw_data;
2148         view3d_draw_data_init(C, ar, rv3d, &draw_data);
2149
2150         if (type->flag & RE_USE_OGL_PIPELINE)
2151                 view3d_draw_view_new(C, ar, &draw_data);
2152         else
2153                 view3d_draw_view(C, ar, &draw_data);
2154
2155         GPU_viewport_unbind(rv3d->viewport);
2156
2157         v3d->flag |= V3D_INVALID_BACKBUF;
2158 }
2159
2160 /* ******************** legacy interface ***************** */
2161 /**
2162  * This will be removed once the viewport gets replaced
2163  * meanwhile it should keep the old viewport working.
2164  */
2165
2166 void VP_legacy_drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
2167 {
2168         if (is_cursor_visible(scene)) {
2169                 drawcursor(scene, ar, v3d);
2170         }
2171 }
2172
2173 void VP_legacy_draw_view_axis(RegionView3D *rv3d, rcti *rect)
2174 {
2175         draw_view_axis(rv3d, rect);
2176 }
2177
2178 void VP_legacy_drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
2179 {
2180         drawgrid(unit, ar, v3d, grid_unit);
2181 }
2182
2183 void VP_legacy_drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
2184 {
2185         drawfloor(scene, v3d, grid_unit, write_depth);
2186 }
2187
2188 void VP_legacy_view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2189 {
2190         view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
2191 }
2192
2193 bool VP_legacy_view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
2194 {
2195         return view3d_stereo3d_active(C, scene, v3d, rv3d);
2196 }
2197
2198 void VP_legacy_view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
2199 {
2200         view3d_stereo3d_setup(scene, v3d, ar);
2201 }
2202
2203 bool VP_legacy_use_depth(Scene *scene, View3D *v3d)
2204 {
2205         return use_depth_doit(scene, v3d);
2206 }
2207
2208 void VP_drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
2209 {
2210         drawviewborder(scene, ar, v3d);
2211 }
2212
2213 void VP_drawrenderborder(ARegion *ar, View3D *v3d)
2214 {
2215         drawrenderborder(ar, v3d);
2216 }
2217
2218 void VP_view3d_draw_background_none(void)
2219 {
2220         view3d_draw_background_none();
2221 }
2222
2223 void VP_view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
2224 {
2225         view3d_draw_background_world(scene, v3d, rv3d);
2226 }