Merge branch 'master' into blender2.8
authorCampbell Barton <ideasman42@gmail.com>
Tue, 23 Jan 2018 00:24:44 +0000 (11:24 +1100)
committerCampbell Barton <ideasman42@gmail.com>
Tue, 23 Jan 2018 00:24:44 +0000 (11:24 +1100)
1  2 
source/blender/editors/space_view3d/view3d_draw.c
source/blender/editors/space_view3d/view3d_intern.h
source/blender/editors/space_view3d/view3d_view.c

index cf43d65b44a01c64e9a367bb48cc27945d53f6b3,1bf334411692f22df03ff8fa921858aa2aa7e2bc..f734bb085d035dabbcae3f89e4e5347139198067
  #include "ED_keyframing.h"
  #include "ED_gpencil.h"
  #include "ED_screen.h"
 -#include "ED_space_api.h"
 -#include "ED_screen_types.h"
  #include "ED_transform.h"
  
 -#include "UI_interface.h"
 -#include "UI_interface_icons.h"
 -#include "UI_resources.h"
 +#include "DEG_depsgraph_query.h"
  
  #include "GPU_draw.h"
 -#include "GPU_framebuffer.h"
 +#include "GPU_matrix.h"
 +#include "GPU_immediate.h"
 +#include "GPU_immediate_util.h"
  #include "GPU_material.h"
 +#include "GPU_viewport.h"
  #include "GPU_compositing.h"
 -#include "GPU_extensions.h"
 -#include "GPU_select.h"
 -
 -#include "view3d_intern.h"  /* own include */
  
 -/* prototypes */
 -static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d);
 -static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar, const rcti *rect);
 -static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
 -                                            float winmat[4][4], const char *viewname);
 -
 -/* handy utility for drawing shapes in the viewport for arbitrary code.
 - * could add lines and points too */
 -// #define DEBUG_DRAW
 -#ifdef DEBUG_DRAW
 -static void bl_debug_draw(void);
 -/* add these locally when using these functions for testing */
 -extern void bl_debug_draw_quad_clear(void);
 -extern void bl_debug_draw_quad_add(const float v0[3], const float v1[3], const float v2[3], const float v3[3]);
 -extern void bl_debug_draw_edge_add(const float v0[3], const float v1[3]);
 -extern void bl_debug_color_set(const unsigned int col);
 -#endif
 +#include "MEM_guardedalloc.h"
  
 -void circf(float x, float y, float rad)
 -{
 -      GLUquadricObj *qobj = gluNewQuadric(); 
 -      
 -      gluQuadricDrawStyle(qobj, GLU_FILL); 
 -      
 -      glPushMatrix(); 
 -      
 -      glTranslatef(x, y, 0.0);
 -      
 -      gluDisk(qobj, 0.0,  rad, 32, 1);
 -      
 -      glPopMatrix(); 
 -      
 -      gluDeleteQuadric(qobj);
 -}
 +#include "UI_interface.h"
 +#include "UI_resources.h"
  
 -void circ(float x, float y, float rad)
 -{
 -      GLUquadricObj *qobj = gluNewQuadric(); 
 -      
 -      gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
 -      
 -      glPushMatrix(); 
 -      
 -      glTranslatef(x, y, 0.0);
 -      
 -      gluDisk(qobj, 0.0,  rad, 32, 1);
 -      
 -      glPopMatrix(); 
 -      
 -      gluDeleteQuadric(qobj);
 -}
 +#include "RE_engine.h"
  
 +#include "WM_api.h"
 +#include "WM_types.h"
  
 -/* ********* custom clipping *********** */
 +#include "RNA_access.h"
  
 -static void view3d_draw_clipping(RegionView3D *rv3d)
 -{
 -      BoundBox *bb = rv3d->clipbb;
 -
 -      if (bb) {
 -              const unsigned int clipping_index[6][4] = {
 -                      {0, 1, 2, 3},
 -                      {0, 4, 5, 1},
 -                      {4, 7, 6, 5},
 -                      {7, 3, 2, 6},
 -                      {1, 5, 6, 2},
 -                      {7, 4, 0, 3}
 -              };
 -
 -              /* fill in zero alpha for rendering & re-projection [#31530] */
 -              unsigned char col[4];
 -              UI_GetThemeColor4ubv(TH_V3D_CLIPPING_BORDER, col);
 -              glColor4ubv(col);
 -
 -              glEnable(GL_BLEND);
 -              glEnableClientState(GL_VERTEX_ARRAY);
 -              glVertexPointer(3, GL_FLOAT, 0, bb->vec);
 -              glDrawElements(GL_QUADS, sizeof(clipping_index) / sizeof(unsigned int), GL_UNSIGNED_INT, clipping_index);
 -              glDisableClientState(GL_VERTEX_ARRAY);
 -              glDisable(GL_BLEND);
 -      }
 -}
 +#include "IMB_imbuf.h"
 +#include "IMB_imbuf_types.h"
  
 -void ED_view3d_clipping_set(RegionView3D *rv3d)
 -{
 -      double plane[4];
 -      const unsigned int tot = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : 6;
 -      unsigned int a;
 -
 -      for (a = 0; a < tot; a++) {
 -              copy_v4db_v4fl(plane, rv3d->clip[a]);
 -              glClipPlane(GL_CLIP_PLANE0 + a, plane);
 -              glEnable(GL_CLIP_PLANE0 + a);
 -      }
 -}
 +#include "view3d_intern.h"  /* own include */
  
 -/* use these to temp disable/enable clipping when 'rv3d->rflag & RV3D_CLIPPING' is set */
 -void ED_view3d_clipping_disable(void)
 -{
 -      unsigned int a;
 +/* ******************** general functions ***************** */
  
 -      for (a = 0; a < 6; a++) {
 -              glDisable(GL_CLIP_PLANE0 + a);
 -      }
 -}
 -void ED_view3d_clipping_enable(void)
 +static bool use_depth_doit(Scene *scene, View3D *v3d)
  {
 -      unsigned int a;
 +      if (v3d->drawtype > OB_WIRE)
 +              return true;
  
 -      for (a = 0; a < 6; a++) {
 -              glEnable(GL_CLIP_PLANE0 + a);
 +      /* special case (depth for wire color) */
 +      if (v3d->drawtype <= OB_WIRE) {
 +              if (scene->obedit && scene->obedit->type == OB_MESH) {
 +                      Mesh *me = scene->obedit->data;
 +                      if (me->drawflag & ME_DRAWEIGHT) {
 +                              return true;
 +                      }
 +              }
        }
 +      return false;
  }
  
 -static bool view3d_clipping_test(const float co[3], const float clip[6][4])
 +/**
 + * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
 + */
 +void ED_view3d_update_viewmat(
 +        const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d, ARegion *ar,
 +        float viewmat[4][4], float winmat[4][4], const rcti *rect)
  {
 -      if (plane_point_side_v3(clip[0], co) > 0.0f)
 -              if (plane_point_side_v3(clip[1], co) > 0.0f)
 -                      if (plane_point_side_v3(clip[2], co) > 0.0f)
 -                              if (plane_point_side_v3(clip[3], co) > 0.0f)
 -                                      return false;
 +      const Depsgraph *depsgraph = eval_ctx->depsgraph;
 +      RegionView3D *rv3d = ar->regiondata;
  
 -      return true;
 -}
 +      /* setup window matrices */
 +      if (winmat)
 +              copy_m4_m4(rv3d->winmat, winmat);
 +      else
 +              view3d_winmatrix_set(depsgraph, ar, v3d, rect);
  
 -/* for 'local' ED_view3d_clipping_local must run first
 - * then all comparisons can be done in localspace */
 -bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], const bool is_local)
 -{
 -      return view3d_clipping_test(co, is_local ? rv3d->clip_local : rv3d->clip);
 -}
 +      /* setup view matrix */
-       if (viewmat)
++      if (viewmat) {
 +              copy_m4_m4(rv3d->viewmat, viewmat);
-       else
-               view3d_viewmatrix_set(eval_ctx, scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
++      }
++      else {
++              float rect_scale[2];
++              if (rect) {
++                      rect_scale[0] = (float)BLI_rcti_size_x(rect) / (float)ar->winx;
++                      rect_scale[1] = (float)BLI_rcti_size_y(rect) / (float)ar->winy;
++              }
++              /* note: calls BKE_object_where_is_calc for camera... */
++              view3d_viewmatrix_set(eval_ctx, scene, v3d, rv3d, rect ? rect_scale : NULL);
++      }
 +      /* update utility matrices */
 +      mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
 +      invert_m4_m4(rv3d->persinv, rv3d->persmat);
 +      invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
 +
 +      /* calculate GLSL view dependent values */
  
 -/* ********* end custom clipping *********** */
 +      /* store window coordinates scaling/offset */
 +      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 +              rctf cameraborder;
 +              ED_view3d_calc_camera_border(scene, eval_ctx->depsgraph, ar, v3d, rv3d, &cameraborder, false);
 +              rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
 +              rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
  
 +              rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
 +              rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
 +      }
 +      else {
 +              rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
 +              rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
 +      }
  
 -static void drawgrid_draw(ARegion *ar, double wx, double wy, double x, double y, double dx)
 -{     
 -      double verts[2][2];
 +      /* calculate pixelsize factor once, is used for lamps and obcenters */
 +      {
 +              /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
 +               * because of float point precision problems at large values [#23908] */
 +              float v1[3], v2[3];
 +              float len_px, len_sc;
  
 -      x += (wx);
 -      y += (wy);
 +              v1[0] = rv3d->persmat[0][0];
 +              v1[1] = rv3d->persmat[1][0];
 +              v1[2] = rv3d->persmat[2][0];
  
 -      /* set fixed 'Y' */
 -      verts[0][1] = 0.0f;
 -      verts[1][1] = (double)ar->winy;
 +              v2[0] = rv3d->persmat[0][1];
 +              v2[1] = rv3d->persmat[1][1];
 +              v2[2] = rv3d->persmat[2][1];
  
 -      /* iter over 'X' */
 -      verts[0][0] = verts[1][0] = x - dx * floor(x / dx);
 -      glEnableClientState(GL_VERTEX_ARRAY);
 -      glVertexPointer(2, GL_DOUBLE, 0, verts);
 +              len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
 +              len_sc = (float)MAX2(ar->winx, ar->winy);
  
 -      while (verts[0][0] < ar->winx) {
 -              glDrawArrays(GL_LINES, 0, 2);
 -              verts[0][0] = verts[1][0] = verts[0][0] + dx;
 +              rv3d->pixsize = len_px / len_sc;
        }
 +}
  
 -      /* set fixed 'X' */
 -      verts[0][0] = 0.0f;
 -      verts[1][0] = (double)ar->winx;
 +static void view3d_main_region_setup_view(
 +        const EvaluationContext *eval_ctx, Scene *scene,
 +        View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
  
 -      /* iter over 'Y' */
 -      verts[0][1] = verts[1][1] = y - dx * floor(y / dx);
 -      while (verts[0][1] < ar->winy) {
 -              glDrawArrays(GL_LINES, 0, 2);
 -              verts[0][1] = verts[1][1] = verts[0][1] + dx;
 -      }
 +      ED_view3d_update_viewmat(eval_ctx, scene, v3d, ar, viewmat, winmat, rect);
  
 -      glDisableClientState(GL_VERTEX_ARRAY);
 +      /* set for opengl */
 +      gpuLoadProjectionMatrix(rv3d->winmat);
 +      gpuLoadMatrix(rv3d->viewmat);
  }
  
 -#define GRID_MIN_PX_D   6.0
 -#define GRID_MIN_PX_F 6.0f
 -
 -static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
 +static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
  {
 -      /* extern short bgpicmode; */
 -      RegionView3D *rv3d = ar->regiondata;
 -      double wx, wy, x, y, fw, fx, fy, dx;
 -      double vec4[4];
 -      unsigned char col[3], col2[3];
 +      if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 +              return false;
 +      }
  
 -      fx = rv3d->persmat[3][0];
 -      fy = rv3d->persmat[3][1];
 -      fw = rv3d->persmat[3][3];
 +      if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
 +              return false;
 +      }
  
 -      wx = (ar->winx / 2.0); /* because of rounding errors, grid at wrong location */
 -      wy = (ar->winy / 2.0);
 +      switch (v3d->stereo3d_camera) {
 +              case STEREO_MONO_ID:
 +                      return false;
 +                      break;
 +              case STEREO_3D_ID:
 +                      /* win will be NULL when calling this from the selection or draw loop. */
 +                      if ((win == NULL) || (WM_stereo3d_enabled(win, true) == false)) {
 +                              return false;
 +                      }
 +                      if (((scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) != 0) &&
 +                          !BKE_scene_multiview_is_stereo3d(&scene->r))
 +                      {
 +                              return false;
 +                      }
 +                      break;
 +              /* We always need the stereo calculation for left and right cameras. */
 +              case STEREO_LEFT_ID:
 +              case STEREO_RIGHT_ID:
 +              default:
 +                      break;
 +      }
 +      return true;
 +}
  
 -      x = (wx) * fx / fw;
 -      y = (wy) * fy / fw;
  
 -      vec4[0] = vec4[1] = v3d->grid;
 +/* setup the view and win matrices for the multiview cameras
 + *
 + * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
 + * we have no winmatrix (i.e., projection matrix) defined at that time.
 + * Since the camera and the camera shift are needed for the winmat calculation
 + * we do a small hack to replace it temporarily so we don't need to change the
 + * view3d)main_region_setup_view() code to account for that.
 + */
 +static void view3d_stereo3d_setup(
 +        const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d, ARegion *ar, const rcti *rect)
 +{
 +      bool is_left;
 +      const char *names[2] = { STEREO_LEFT_NAME, STEREO_RIGHT_NAME };
 +      const char *viewname;
  
 -      vec4[2] = 0.0;
 -      vec4[3] = 1.0;
 -      mul_m4_v4d(rv3d->persmat, vec4);
 -      fx = vec4[0];
 -      fy = vec4[1];
 -      fw = vec4[3];
 +      /* show only left or right camera */
 +      if (v3d->stereo3d_camera != STEREO_3D_ID)
 +              v3d->multiview_eye = v3d->stereo3d_camera;
  
 -      dx = fabs(x - (wx) * fx / fw);
 -      if (dx == 0) dx = fabs(y - (wy) * fy / fw);
 -      
 -      glLineWidth(1.0f);
 +      is_left = v3d->multiview_eye == STEREO_LEFT_ID;
 +      viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
  
 -      glDepthMask(GL_FALSE);     /* disable write in zbuffer */
 +      /* update the viewport matrices with the new camera */
 +      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 +              Camera *data;
 +              float viewmat[4][4];
 +              float shiftx;
  
 -      /* check zoom out */
 -      UI_ThemeColor(TH_GRID);
 -      
 -      if (unit->system) {
 -              /* Use GRID_MIN_PX * 2 for units because very very small grid
 -               * items are less useful when dealing with units */
 -              const void *usys;
 -              int len, i;
 -              double dx_scalar;
 -              float blend_fac;
 +              data = (Camera *)v3d->camera->data;
 +              shiftx = data->shiftx;
  
 -              bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
 +              BLI_lock_thread(LOCK_VIEW3D);
 +              data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
  
 -              if (usys) {
 -                      i = len;
 -                      while (i--) {
 -                              double scalar = bUnit_GetScaler(usys, i);
 +              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 +              view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, NULL, rect);
  
 -                              dx_scalar = dx * scalar / (double)unit->scale_length;
 -                              if (dx_scalar < (GRID_MIN_PX_D * 2.0))
 -                                      continue;
 +              data->shiftx = shiftx;
 +              BLI_unlock_thread(LOCK_VIEW3D);
 +      }
 +      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 +              float viewmat[4][4];
 +              Object *view_ob = v3d->camera;
 +              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
  
 -                              /* Store the smallest drawn grid size units name so users know how big each grid cell is */
 -                              if (*grid_unit == NULL) {
 -                                      *grid_unit = bUnit_GetNameDisplay(usys, i);
 -                                      rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
 -                              }
 -                              blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
 +              BLI_lock_thread(LOCK_VIEW3D);
 +              v3d->camera = camera;
  
 -                              /* tweak to have the fade a bit nicer */
 -                              blend_fac = (blend_fac * blend_fac) * 2.0f;
 -                              CLAMP(blend_fac, 0.3f, 1.0f);
 +              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 +              view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, NULL, rect);
  
 +              v3d->camera = view_ob;
 +              BLI_unlock_thread(LOCK_VIEW3D);
 +      }
 +}
  
 -                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, blend_fac);
 +/**
 + * Set the correct matrices
 + */
 +void ED_view3d_draw_setup_view(
 +        wmWindow *win, const EvaluationContext *eval_ctx, Scene *scene, ARegion *ar, View3D *v3d,
 +        float viewmat[4][4], float winmat[4][4], const rcti *rect)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
  
 -                              drawgrid_draw(ar, wx, wy, x, y, dx_scalar);
 -                      }
 -              }
 +      /* Setup the view matrix. */
 +      if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
 +              view3d_stereo3d_setup(eval_ctx, scene, v3d, ar, rect);
        }
        else {
 -              const double sublines    = v3d->gridsubdiv;
 -              const float  sublines_fl = v3d->gridsubdiv;
 +              view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, winmat, rect);
 +      }
 +}
  
 -              if (dx < GRID_MIN_PX_D) {
 -                      rv3d->gridview *= sublines_fl;
 -                      dx *= sublines;
 +/* ******************** view border ***************** */
  
 -                      if (dx < GRID_MIN_PX_D) {
 -                              rv3d->gridview *= sublines_fl;
 -                              dx *= sublines;
 -
 -                              if (dx < GRID_MIN_PX_D) {
 -                                      rv3d->gridview *= sublines_fl;
 -                                      dx *= sublines;
 -                                      if (dx < GRID_MIN_PX_D) {
 -                                              /* pass */
 -                                      }
 -                                      else {
 -                                              UI_ThemeColor(TH_GRID);
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                      }
 -                              }
 -                              else {  /* start blending out */
 -                                      UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                                      drawgrid_draw(ar, wx, wy, x, y, dx);
 +static void view3d_camera_border(
 +        const Scene *scene, const struct Depsgraph *depsgraph,
 +        const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 +        rctf *r_viewborder, const bool no_shift, const bool no_zoom)
 +{
 +      CameraParams params;
 +      rctf rect_view, rect_camera;
  
 -                                      UI_ThemeColor(TH_GRID);
 -                                      drawgrid_draw(ar, wx, wy, x, y, sublines * dx);
 -                              }
 -                      }
 -                      else {  /* start blending out (GRID_MIN_PX < dx < (GRID_MIN_PX * 10)) */
 -                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                              drawgrid_draw(ar, wx, wy, x, y, dx);
 +      /* get viewport viewplane */
 +      BKE_camera_params_init(&params);
 +      BKE_camera_params_from_view3d(&params, depsgraph, v3d, rv3d);
 +      if (no_zoom)
 +              params.zoom = 1.0f;
 +      BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
 +      rect_view = params.viewplane;
  
 -                              UI_ThemeColor(TH_GRID);
 -                              drawgrid_draw(ar, wx, wy, x, y, sublines * dx);
 -                      }
 -              }
 -              else {
 -                      if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 -                              rv3d->gridview /= sublines_fl;
 -                              dx /= sublines;
 -                              if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 -                                      rv3d->gridview /= sublines_fl;
 -                                      dx /= sublines;
 -                                      if (dx > (GRID_MIN_PX_D * 10.0)) {
 -                                              UI_ThemeColor(TH_GRID);
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                      }
 -                                      else {
 -                                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                              UI_ThemeColor(TH_GRID);
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
 -                                      }
 -                              }
 -                              else {
 -                                      UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                                      drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                      UI_ThemeColor(TH_GRID);
 -                                      drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
 -                              }
 -                      }
 -                      else {
 -                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                              UI_ThemeColor(TH_GRID);
 -                              drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
 -                      }
 -              }
 +      /* get camera viewplane */
 +      BKE_camera_params_init(&params);
 +      /* fallback for non camera objects */
 +      params.clipsta = v3d->near;
 +      params.clipend = v3d->far;
 +      BKE_camera_params_from_object(&params, v3d->camera);
 +      if (no_shift) {
 +              params.shiftx = 0.0f;
 +              params.shifty = 0.0f;
        }
 +      BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
 +      rect_camera = params.viewplane;
  
 -
 -      x += (wx);
 -      y += (wy);
 -      UI_GetThemeColor3ubv(TH_GRID, col);
 -
 -      setlinestyle(0);
 -      
 -      /* center cross */
 -      /* horizontal line */
 -      if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
 -              UI_make_axis_color(col, col2, 'Y');
 -      else UI_make_axis_color(col, col2, 'X');
 -      glColor3ubv(col2);
 -      
 -      fdrawline(0.0,  y,  (float)ar->winx,  y); 
 -      
 -      /* vertical line */
 -      if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
 -              UI_make_axis_color(col, col2, 'Y');
 -      else UI_make_axis_color(col, col2, 'Z');
 -      glColor3ubv(col2);
 -
 -      fdrawline(x, 0.0, x, (float)ar->winy); 
 -
 -      glDepthMask(GL_TRUE);  /* enable write in zbuffer */
 +      /* get camera border within viewport */
 +      r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
 +      r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
 +      r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
 +      r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
  }
 -#undef GRID_MIN_PX
  
 -/** could move this elsewhere, but tied into #ED_view3d_grid_scale */
 -float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
 +void ED_view3d_calc_camera_border_size(
 +        const Scene *scene, const Depsgraph *depsgraph,
 +        const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 +        float r_size[2])
  {
 -      /* apply units */
 -      if (scene->unit.system) {
 -              const void *usys;
 -              int len;
 -
 -              bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
 -
 -              if (usys) {
 -                      int i = bUnit_GetBaseUnit(usys);
 -                      if (grid_unit)
 -                              *grid_unit = bUnit_GetNameDisplay(usys, i);
 -                      return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
 -              }
 -      }
 +      rctf viewborder;
  
 -      return 1.0f;
 +      view3d_camera_border(scene, depsgraph, ar, v3d, rv3d, &viewborder, true, true);
 +      r_size[0] = BLI_rctf_size_x(&viewborder);
 +      r_size[1] = BLI_rctf_size_y(&viewborder);
  }
  
 -float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
 +void ED_view3d_calc_camera_border(
 +        const Scene *scene, const Depsgraph *depsgraph,
 +        const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 +        rctf *r_viewborder, const bool no_shift)
  {
 -      return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
 +      view3d_camera_border(scene, depsgraph, ar, v3d, rv3d, r_viewborder, no_shift, false);
  }
  
 -static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
 +static void drawviewborder_grid3(uint shdr_pos, float x1, float x2, float y1, float y2, float fac)
  {
 -      float grid, grid_scale;
 -      unsigned char col_grid[3];
 -      const int gridlines = v3d->gridlines / 2;
 -
 -      if (v3d->gridlines < 3) return;
 -      
 -      /* use 'grid_scale' instead of 'v3d->grid' from now on */
 -      grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
 -      grid = gridlines * grid_scale;
 +      float x3, y3, x4, y4;
  
 -      if (!write_depth)
 -              glDepthMask(GL_FALSE);
 +      x3 = x1 + fac * (x2 - x1);
 +      y3 = y1 + fac * (y2 - y1);
 +      x4 = x1 + (1.0f - fac) * (x2 - x1);
 +      y4 = y1 + (1.0f - fac) * (y2 - y1);
  
 -      UI_GetThemeColor3ubv(TH_GRID, col_grid);
 +      immBegin(GWN_PRIM_LINES, 8);
  
 -      glLineWidth(1);
 +      immVertex2f(shdr_pos, x1, y3);
 +      immVertex2f(shdr_pos, x2, y3);
  
 -      /* draw the Y axis and/or grid lines */
 -      if (v3d->gridflag & V3D_SHOW_FLOOR) {
 -              const int sublines = v3d->gridsubdiv;
 -              float vert[4][3] = {{0.0f}};
 -              unsigned char col_bg[3];
 -              unsigned char col_grid_emphasise[3], col_grid_light[3];
 -              int a;
 -              int prev_emphasise = -1;
 +      immVertex2f(shdr_pos, x1, y4);
 +      immVertex2f(shdr_pos, x2, y4);
  
 -              UI_GetThemeColor3ubv(TH_BACK, col_bg);
 +      immVertex2f(shdr_pos, x3, y1);
 +      immVertex2f(shdr_pos, x3, y2);
  
 -              /* emphasise division lines lighter instead of darker, if background is darker than grid */
 -              UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
 -              UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
 -                                      (((col_grid[0] + col_grid[1] + col_grid[2]) + 30) >
 -                                       (col_bg[0] + col_bg[1] + col_bg[2])) ? 20 : -10);
 +      immVertex2f(shdr_pos, x4, y1);
 +      immVertex2f(shdr_pos, x4, y2);
  
 -              /* set fixed axis */
 -              vert[0][0] = vert[2][1] = grid;
 -              vert[1][0] = vert[3][1] = -grid;
 +      immEnd();
 +}
  
 -              glEnableClientState(GL_VERTEX_ARRAY);
 -              glVertexPointer(3, GL_FLOAT, 0, vert);
 +/* harmonious triangle */
 +static void drawviewborder_triangle(
 +        uint shdr_pos, float x1, float x2, float y1, float y2, const char golden, const char dir)
 +{
 +      float ofs;
 +      float w = x2 - x1;
 +      float h = y2 - y1;
  
 -              for (a = -gridlines; a <= gridlines; a++) {
 -                      const float line = a * grid_scale;
 -                      const int is_emphasise = (a % sublines) == 0;
 +      immBegin(GWN_PRIM_LINES, 6);
  
 -                      if (is_emphasise != prev_emphasise) {
 -                              glColor3ubv(is_emphasise ? col_grid_emphasise : col_grid_light);
 -                              prev_emphasise = is_emphasise;
 -                      }
 +      if (w > h) {
 +              if (golden) {
 +                      ofs = w * (1.0f - (1.0f / 1.61803399f));
 +              }
 +              else {
 +                      ofs = h * (h / w);
 +              }
 +              if (dir == 'B') SWAP(float, y1, y2);
  
 -                      /* set variable axis */
 -                      vert[0][1] = vert[1][1] = vert[2][0] = vert[3][0] = line;
 +              immVertex2f(shdr_pos, x1, y1);
 +              immVertex2f(shdr_pos, x2, y2);
  
 -                      glDrawArrays(GL_LINES, 0, 4);
 -              }
 +              immVertex2f(shdr_pos, x2, y1);
 +              immVertex2f(shdr_pos, x1 + (w - ofs), y2);
  
 -              glDisableClientState(GL_VERTEX_ARRAY);
 +              immVertex2f(shdr_pos, x1, y2);
 +              immVertex2f(shdr_pos, x1 + ofs, y1);
        }
 -      
 -      /* draw the Z axis line */
 -      /* check for the 'show Z axis' preference */
 -      if (v3d->gridflag & (V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
 -              glBegin(GL_LINES);
 -              int axis;
 -              for (axis = 0; axis < 3; axis++) {
 -                      if (v3d->gridflag & (V3D_SHOW_X << axis)) {
 -                              float vert[3];
 -                              unsigned char tcol[3];
 -
 -                              UI_make_axis_color(col_grid, tcol, 'X' + axis);
 -                              glColor3ubv(tcol);
 -
 -                              zero_v3(vert);
 -                              vert[axis] = grid;
 -                              glVertex3fv(vert);
 -                              vert[axis] = -grid;
 -                              glVertex3fv(vert);
 -                      }
 +      else {
 +              if (golden) {
 +                      ofs = h * (1.0f - (1.0f / 1.61803399f));
                }
 -              glEnd();
 -      }
 -      
 -      glDepthMask(GL_TRUE);
 -}
 +              else {
 +                      ofs = w * (w / h);
 +              }
 +              if (dir == 'B') SWAP(float, x1, x2);
  
 +              immVertex2f(shdr_pos, x1, y1);
 +              immVertex2f(shdr_pos, x2, y2);
  
 -static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      int co[2];
 +              immVertex2f(shdr_pos, x2, y1);
 +              immVertex2f(shdr_pos, x1, y1 + ofs);
  
 -      /* we don't want the clipping for cursor */
 -      if (ED_view3d_project_int_global(ar, ED_view3d_cursor3d_get(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
 -              const float f5 = 0.25f * U.widget_unit;
 -              const float f10 = 0.5f * U.widget_unit;
 -              const float f20 = U.widget_unit;
 -              
 -              glLineWidth(1);
 -              setlinestyle(0); 
 -              cpack(0xFF);
 -              circ((float)co[0], (float)co[1], f10);
 -              setlinestyle(4);
 -              cpack(0xFFFFFF);
 -              circ((float)co[0], (float)co[1], f10);
 -              setlinestyle(0);
 -
 -              UI_ThemeColor(TH_VIEW_OVERLAY);
 -              sdrawline(co[0] - f20, co[1], co[0] - f5, co[1]);
 -              sdrawline(co[0] + f5, co[1], co[0] + f20, co[1]);
 -              sdrawline(co[0], co[1] - f20, co[0], co[1] - f5);
 -              sdrawline(co[0], co[1] + f5, co[0], co[1] + f20);
 +              immVertex2f(shdr_pos, x1, y2);
 +              immVertex2f(shdr_pos, x2, y1 + (h - ofs));
        }
 +
 +      immEnd();
  }
  
 -/* Draw a live substitute of the view icon, which is always shown
 - * colors copied from transform_manipulator.c, we should keep these matching. */
 -static void draw_view_axis(RegionView3D *rv3d, rcti *rect)
 +static void drawviewborder(Scene *scene, const Depsgraph *depsgraph, ARegion *ar, View3D *v3d)
  {
 -      const float k = U.rvisize * U.pixelsize;   /* axis size */
 -      const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
 -      float startx = k + 1.0f; /* axis center in screen coordinates, x=y */
 -      float starty = k + 1.0f;
 -      float ydisp = 0.0;          /* vertical displacement to allow obj info text */
 -      int bright = - 20 * (10 - U.rvibright); /* axis alpha offset (rvibright has range 0-10) */
 -      float vec[3];
 -      float dx, dy;
 +      float x1, x2, y1, y2;
 +      float x1i, x2i, y1i, y2i;
  
 -      int axis_order[3] = {0, 1, 2};
 -      int axis_i;
 +      rctf viewborder;
 +      Camera *ca = NULL;
 +      RegionView3D *rv3d = ar->regiondata;
 +
 +      if (v3d->camera == NULL)
 +              return;
 +      if (v3d->camera->type == OB_CAMERA)
 +              ca = v3d->camera->data;
 +      
 +      ED_view3d_calc_camera_border(scene, depsgraph, ar, v3d, rv3d, &viewborder, false);
 +      /* the offsets */
 +      x1 = viewborder.xmin;
 +      y1 = viewborder.ymin;
 +      x2 = viewborder.xmax;
 +      y2 = viewborder.ymax;
 +      
 +      glLineWidth(1.0f);
  
 -      startx += rect->xmin;
 -      starty += rect->ymin;
 +      /* apply offsets so the real 3D camera shows through */
  
 -      axis_sort_v3(rv3d->viewinv[2], axis_order);
 +      /* note: quite un-scientific but without this bit extra
 +       * 0.0001 on the lower left the 2D border sometimes
 +       * obscures the 3D camera border */
 +      /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
 +       * but keep it here in case we need to remove the workaround */
 +      x1i = (int)(x1 - 1.0001f);
 +      y1i = (int)(y1 - 1.0001f);
 +      x2i = (int)(x2 + (1.0f - 0.0001f));
 +      y2i = (int)(y2 + (1.0f - 0.0001f));
  
 -      /* thickness of lines is proportional to k */
 -      glLineWidth(2);
 +      uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
  
 -      glEnable(GL_BLEND);
 -      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 +      /* First, solid lines. */
 +      {
 +              immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
  
 -      for (axis_i = 0; axis_i < 3; axis_i++) {
 -              int i = axis_order[axis_i];
 -              const char axis_text[2] = {'x' + i, '\0'};
 +              /* passepartout, specified in camera edit buttons */
 +              if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
 +                      const float winx = (ar->winx + 1);
 +                      const float winy = (ar->winy + 1);
  
 -              zero_v3(vec);
 -              vec[i] = 1.0f;
 -              mul_qt_v3(rv3d->viewquat, vec);
 -              dx = vec[0] * k;
 -              dy = vec[1] * k;
 +                      float alpha = 1.0f;
  
 -              UI_ThemeColorShadeAlpha(TH_AXIS_X + i, 0, bright);
 -              glBegin(GL_LINES);
 -              glVertex2f(startx, starty + ydisp);
 -              glVertex2f(startx + dx, starty + dy + ydisp);
 -              glEnd();
 +                      if (ca->passepartalpha != 1.0f) {
 +                              glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 +                              glEnable(GL_BLEND);
 +                              alpha = ca->passepartalpha;
 +                      }
 +
 +                      immUniformColor4f(0.0f, 0.0f, 0.0f, alpha);
  
 -              if (fabsf(dx) > toll || fabsf(dy) > toll) {
 -                      BLF_draw_default_ascii(startx + dx + 2, starty + dy + ydisp + 2, 0.0f, axis_text, 1);
 +                      if (x1i > 0.0f)
 +                              immRectf(shdr_pos, 0.0f, winy, x1i, 0.0f);
 +                      if (x2i < winx)
 +                              immRectf(shdr_pos, x2i, winy, winx, 0.0f);
 +                      if (y2i < winy)
 +                              immRectf(shdr_pos, x1i, winy, x2i, y2i);
 +                      if (y2i > 0.0f)
 +                              immRectf(shdr_pos, x1i, y1i, x2i, 0.0f);
  
 -                      /* BLF_draw_default disables blending */
 -                      glEnable(GL_BLEND);
 +                      glDisable(GL_BLEND);
                }
 -      }
  
 -      glDisable(GL_BLEND);
 -}
 +              immUniformThemeColor(TH_BACK);
 +              imm_draw_box_wire_2d(shdr_pos, x1i, y1i, x2i, y2i);
  
 -#ifdef WITH_INPUT_NDOF
 -/* draw center and axis of rotation for ongoing 3D mouse navigation */
 -static void draw_rotation_guide(RegionView3D *rv3d)
 -{
 -      float o[3];    /* center of rotation */
 -      float end[3];  /* endpoints for drawing */
 +#ifdef VIEW3D_CAMERA_BORDER_HACK
 +              if (view3d_camera_border_hack_test == true) {
 +                      immUniformColor3ubv(view3d_camera_border_hack_col);
 +                      imm_draw_box_wire_2d(shdr_pos, x1i + 1, y1i + 1, x2i - 1, y2i - 1);
 +                      view3d_camera_border_hack_test = false;
 +              }
 +#endif
  
 -      float color[4] = {0.0f, 0.4235f, 1.0f, 1.0f};  /* bright blue so it matches device LEDs */
 +              immUnbindProgram();
 +      }
  
 -      negate_v3_v3(o, rv3d->ofs);
 +      /* And now, the dashed lines! */
 +      immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
  
 -      glEnable(GL_BLEND);
 -      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 -      glPointSize(5);
 -      glEnable(GL_POINT_SMOOTH);
 -      glDepthMask(0);  /* don't overwrite zbuf */
 +      {
 +              float viewport_size[4];
 +              glGetFloatv(GL_VIEWPORT, viewport_size);
 +              immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
  
 -      if (rv3d->rot_angle != 0.0f) {
 -              /* -- draw rotation axis -- */
 -              float scaled_axis[3];
 -              const float scale = rv3d->dist;
 -              mul_v3_v3fl(scaled_axis, rv3d->rot_axis, scale);
 +              immUniform1i("num_colors", 0);  /* "simple" mode */
 +              immUniform1f("dash_width", 6.0f);
 +              immUniform1f("dash_factor", 0.5f);
  
 +              /* outer line not to confuse with object selection */
 +              if (v3d->flag2 & V3D_LOCK_CAMERA) {
 +                      immUniformThemeColor(TH_REDALERT);
 +                      imm_draw_box_wire_2d(shdr_pos, x1i - 1, y1i - 1, x2i + 1, y2i + 1);
 +              }
  
 -              glBegin(GL_LINE_STRIP);
 -              color[3] = 0.0f;  /* more transparent toward the ends */
 -              glColor4fv(color);
 -              add_v3_v3v3(end, o, scaled_axis);
 -              glVertex3fv(end);
 +              immUniformThemeColor(TH_VIEW_OVERLAY);
 +              imm_draw_box_wire_2d(shdr_pos, x1i, y1i, x2i, y2i);
 +      }
  
 -#if 0
 -              color[3] = 0.2f + fabsf(rv3d->rot_angle);  /* modulate opacity with angle */
 -              /* ^^ neat idea, but angle is frame-rate dependent, so it's usually close to 0.2 */
 -#endif
 +      /* border */
 +      if (scene->r.mode & R_BORDER) {
 +              float x3, y3, x4, y4;
  
 -              color[3] = 0.5f;  /* more opaque toward the center */
 -              glColor4fv(color);
 -              glVertex3fv(o);
 +              x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
 +              y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
 +              x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
 +              y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
  
 -              color[3] = 0.0f;
 -              glColor4fv(color);
 -              sub_v3_v3v3(end, o, scaled_axis);
 -              glVertex3fv(end);
 -              glEnd();
 -              
 -              /* -- draw ring around rotation center -- */
 -              {
 -#define     ROT_AXIS_DETAIL 13
 +              immUniformColor3f(1.0f, 0.25f, 0.25f);
 +              imm_draw_box_wire_2d(shdr_pos, x3, y3, x4, y4);
 +      }
  
 -                      const float s = 0.05f * scale;
 -                      const float step = 2.0f * (float)(M_PI / ROT_AXIS_DETAIL);
 -                      float angle;
 -                      int i;
 +      /* safety border */
 +      if (ca) {
 +              immUniformThemeColorBlend(TH_VIEW_OVERLAY, TH_BACK, 0.25f);
  
 -                      float q[4];  /* rotate ring so it's perpendicular to axis */
 -                      const int upright = fabsf(rv3d->rot_axis[2]) >= 0.95f;
 -                      if (!upright) {
 -                              const float up[3] = {0.0f, 0.0f, 1.0f};
 -                              float vis_angle, vis_axis[3];
 +              if (ca->dtx & CAM_DTX_CENTER) {
 +                      float x3, y3;
  
 -                              cross_v3_v3v3(vis_axis, up, rv3d->rot_axis);
 -                              vis_angle = acosf(dot_v3v3(up, rv3d->rot_axis));
 -                              axis_angle_to_quat(q, vis_axis, vis_angle);
 -                      }
 +                      x3 = x1 + 0.5f * (x2 - x1);
 +                      y3 = y1 + 0.5f * (y2 - y1);
  
 -                      color[3] = 0.25f;  /* somewhat faint */
 -                      glColor4fv(color);
 -                      glBegin(GL_LINE_LOOP);
 -                      for (i = 0, angle = 0.0f; i < ROT_AXIS_DETAIL; ++i, angle += step) {
 -                              float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
 +                      immBegin(GWN_PRIM_LINES, 4);
  
 -                              if (!upright) {
 -                                      mul_qt_v3(q, p);
 -                              }
 +                      immVertex2f(shdr_pos, x1, y3);
 +                      immVertex2f(shdr_pos, x2, y3);
  
 -                              add_v3_v3(p, o);
 -                              glVertex3fv(p);
 -                      }
 -                      glEnd();
 +                      immVertex2f(shdr_pos, x3, y1);
 +                      immVertex2f(shdr_pos, x3, y2);
  
 -#undef      ROT_AXIS_DETAIL
 +                      immEnd();
                }
  
 -              color[3] = 1.0f;  /* solid dot */
 -      }
 -      else
 -              color[3] = 0.5f;  /* see-through dot */
 +              if (ca->dtx & CAM_DTX_CENTER_DIAG) {
 +                      immBegin(GWN_PRIM_LINES, 4);
  
 -      /* -- draw rotation center -- */
 -      glColor4fv(color);
 -      glBegin(GL_POINTS);
 -      glVertex3fv(o);
 -      glEnd();
 +                      immVertex2f(shdr_pos, x1, y1);
 +                      immVertex2f(shdr_pos, x2, y2);
  
 -#if 0
 -      /* find screen coordinates for rotation center, then draw pretty icon */
 -      mul_m4_v3(rv3d->persinv, rot_center);
 -      UI_icon_draw(rot_center[0], rot_center[1], ICON_NDOF_TURN);
 -      /* ^^ just playing around, does not work */
 -#endif
 -
 -      glDisable(GL_BLEND);
 -      glDisable(GL_POINT_SMOOTH);
 -      glDepthMask(1);
 -}
 -#endif /* WITH_INPUT_NDOF */
 +                      immVertex2f(shdr_pos, x1, y2);
 +                      immVertex2f(shdr_pos, x2, y1);
  
 -static void draw_view_icon(RegionView3D *rv3d, rcti *rect)
 -{
 -      BIFIconID icon;
 -      
 -      if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
 -              icon = ICON_AXIS_TOP;
 -      else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK))
 -              icon = ICON_AXIS_FRONT;
 -      else if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
 -              icon = ICON_AXIS_SIDE;
 -      else return;
 -      
 -      glEnable(GL_BLEND);
 -      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
 -      
 -      UI_icon_draw(5.0 + rect->xmin, 5.0 + rect->ymin, icon);
 -      
 -      glDisable(GL_BLEND);
 -}
 +                      immEnd();
 +              }
  
 -static const char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
 -{
 -      const char *name = NULL;
 -      
 -      switch (rv3d->view) {
 -              case RV3D_VIEW_FRONT:
 -                      if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Front Ortho");
 -                      else name = IFACE_("Front Persp");
 -                      break;
 -              case RV3D_VIEW_BACK:
 -                      if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Back Ortho");
 -                      else name = IFACE_("Back Persp");
 -                      break;
 -              case RV3D_VIEW_TOP:
 -                      if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Top Ortho");
 -                      else name = IFACE_("Top Persp");
 -                      break;
 -              case RV3D_VIEW_BOTTOM:
 -                      if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Bottom Ortho");
 -                      else name = IFACE_("Bottom Persp");
 -                      break;
 -              case RV3D_VIEW_RIGHT:
 -                      if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Right Ortho");
 -                      else name = IFACE_("Right Persp");
 -                      break;
 -              case RV3D_VIEW_LEFT:
 -                      if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Left Ortho");
 -                      else name = IFACE_("Left Persp");
 -                      break;
 -                      
 -              default:
 -                      if (rv3d->persp == RV3D_CAMOB) {
 -                              if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
 -                                      Camera *cam;
 -                                      cam = v3d->camera->data;
 -                                      if (cam->type == CAM_PERSP) {
 -                                              name = IFACE_("Camera Persp");
 -                                      }
 -                                      else if (cam->type == CAM_ORTHO) {
 -                                              name = IFACE_("Camera Ortho");
 -                                      }
 -                                      else {
 -                                              BLI_assert(cam->type == CAM_PANO);
 -                                              name = IFACE_("Camera Pano");
 -                                      }
 -                              }
 -                              else {
 -                                      name = IFACE_("Object as Camera");
 -                              }
 -                      }
 -                      else {
 -                              name = (rv3d->persp == RV3D_ORTHO) ? IFACE_("User Ortho") : IFACE_("User Persp");
 -                      }
 -                      break;
 -      }
 -      
 -      return name;
 -}
 +              if (ca->dtx & CAM_DTX_THIRDS) {
 +                      drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f / 3.0f);
 +              }
  
 -static void draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      const char *name = view3d_get_name(v3d, rv3d);
 -      /* increase size for unicode languages (Chinese in utf-8...) */
 -#ifdef WITH_INTERNATIONAL
 -      char tmpstr[96];
 -#else
 -      char tmpstr[32];
 -#endif
 +              if (ca->dtx & CAM_DTX_GOLDEN) {
 +                      drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
 +              }
  
 -      if (v3d->localvd) {
 -              BLI_snprintf(tmpstr, sizeof(tmpstr), IFACE_("%s (Local)"), name);
 -              name = tmpstr;
 -      }
 +              if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
 +                      drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'A');
 +              }
  
 -      UI_ThemeColor(TH_TEXT_HI);
 -#ifdef WITH_INTERNATIONAL
 -      BLF_draw_default(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
 -#else
 -      BLF_draw_default_ascii(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
 -#endif
 -}
 +              if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
 +                      drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'B');
 +              }
  
 -/* draw info beside axes in bottom left-corner: 
 - * framenum, object name, bone name (if available), marker name (if available)
 - */
 +              if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
 +                      drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'A');
 +              }
  
 -static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
 -{
 -      const int cfra = CFRA;
 -      const char *msg_pin = " (Pinned)";
 -      const char *msg_sep = " : ";
 +              if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
 +                      drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'B');
 +              }
  
 -      char info[300];
 -      const char *markern;
 -      char *s = info;
 -      short offset = 1.5f * UI_UNIT_X + rect->xmin;
 +              if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
 +                      UI_draw_safe_areas(
 +                              shdr_pos, x1, x2, y1, y2,
 +                              scene->safe_areas.title, scene->safe_areas.action);
  
 -      s += sprintf(s, "(%d)", cfra);
 +                      if (ca->flag & CAM_SHOW_SAFE_CENTER) {
 +                              UI_draw_safe_areas(
 +                                      shdr_pos, x1, x2, y1, y2,
 +                                      scene->safe_areas.title_center, scene->safe_areas.action_center);
 +                      }
 +              }
  
 -      /* 
 -       * info can contain:
 -       * - a frame (7 + 2)
 -       * - 3 object names (MAX_NAME)
 -       * - 2 BREAD_CRUMB_SEPARATORs (6)
 -       * - a SHAPE_KEY_PINNED marker and a trailing '\0' (9+1) - translated, so give some room!
 -       * - a marker name (MAX_NAME + 3)
 -       */
 +              if (ca->flag & CAM_SHOWSENSOR) {
 +                      /* determine sensor fit, and get sensor x/y, for auto fit we
 +                       * assume and square sensor and only use sensor_x */
 +                      float sizex = scene->r.xsch * scene->r.xasp;
 +                      float sizey = scene->r.ysch * scene->r.yasp;
 +                      int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
 +                      float sensor_x = ca->sensor_x;
 +                      float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
  
 -      /* get name of marker on current frame (if available) */
 -      markern = BKE_scene_find_marker_name(scene, cfra);
 -      
 -      /* check if there is an object */
 -      if (ob) {
 -              *s++ = ' ';
 -              s += BLI_strcpy_rlen(s, ob->id.name + 2);
 +                      /* determine sensor plane */
 +                      rctf rect;
  
 -              /* name(s) to display depends on type of object */
 -              if (ob->type == OB_ARMATURE) {
 -                      bArmature *arm = ob->data;
 -                      
 -                      /* show name of active bone too (if possible) */
 -                      if (arm->edbo) {
 -                              if (arm->act_edbone) {
 -                                      s += BLI_strcpy_rlen(s, msg_sep);
 -                                      s += BLI_strcpy_rlen(s, arm->act_edbone->name);
 -                              }
 -                      }
 -                      else if (ob->mode & OB_MODE_POSE) {
 -                              if (arm->act_bone) {
 +                      if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
 +                              float sensor_scale = (x2i - x1i) / sensor_x;
 +                              float sensor_height = sensor_scale * sensor_y;
  
 -                                      if (arm->act_bone->layer & arm->layer) {
 -                                              s += BLI_strcpy_rlen(s, msg_sep);
 -                                              s += BLI_strcpy_rlen(s, arm->act_bone->name);
 -                                      }
 -                              }
 +                              rect.xmin = x1i;
 +                              rect.xmax = x2i;
 +                              rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
 +                              rect.ymax = rect.ymin + sensor_height;
                        }
 -              }
 -              else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
 -                      Key *key = NULL;
 -                      KeyBlock *kb = NULL;
 -
 -                      /* try to display active bone and active shapekey too (if they exist) */
 +                      else {
 +                              float sensor_scale = (y2i - y1i) / sensor_y;
 +                              float sensor_width = sensor_scale * sensor_x;
  
 -                      if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
 -                              Object *armobj = BKE_object_pose_armature_get(ob);
 -                              if (armobj  && armobj->mode & OB_MODE_POSE) {
 -                                      bArmature *arm = armobj->data;
 -                                      if (arm->act_bone) {
 -                                              if (arm->act_bone->layer & arm->layer) {
 -                                                      s += BLI_strcpy_rlen(s, msg_sep);
 -                                                      s += BLI_strcpy_rlen(s, arm->act_bone->name);
 -                                              }
 -                                      }
 -                              }
 +                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 +                              rect.xmax = rect.xmin + sensor_width;
 +                              rect.ymin = y1i;
 +                              rect.ymax = y2i;
                        }
  
 -                      key = BKE_key_from_object(ob);
 -                      if (key) {
 -                              kb = BLI_findlink(&key->block, ob->shapenr - 1);
 -                              if (kb) {
 -                                      s += BLI_strcpy_rlen(s, msg_sep);
 -                                      s += BLI_strcpy_rlen(s, kb->name);
 -                                      if (ob->shapeflag & OB_SHAPE_LOCK) {
 -                                              s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
 -                                      }
 -                              }
 -                      }
 +                      /* draw */
 +                      immUniformThemeColorShade(TH_VIEW_OVERLAY, 100);
 +                      
 +                      /* TODO Was using UI_draw_roundbox_4fv(false, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f, color).
 +                       * We'll probably need a new imm_draw_line_roundbox_dashed dor that - though in practice the
 +                       * 2.0f round corner effect was nearly not visible anyway... */
 +                      imm_draw_box_wire_2d(shdr_pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
                }
 -              
 -              /* color depends on whether there is a keyframe */
 -              if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
 -                      UI_ThemeColor(TH_TIME_KEYFRAME);
 -              else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
 -                      UI_ThemeColor(TH_TIME_GP_KEYFRAME);
 -              else
 -                      UI_ThemeColor(TH_TEXT_HI);
 -      }
 -      else {
 -              /* no object */
 -              if (ED_gpencil_has_keyframe_v3d(scene, NULL, cfra))
 -                      UI_ThemeColor(TH_TIME_GP_KEYFRAME);
 -              else
 -                      UI_ThemeColor(TH_TEXT_HI);
        }
  
 -      if (markern) {
 -              s += sprintf(s, " <%s>", markern);
 -      }
 -      
 -      if (U.uiflag & USER_SHOW_ROTVIEWICON)
 -              offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
 +      immUnbindProgram();
 +      /* end dashed lines */
  
 -      BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
 +      /* camera name - draw in highlighted text color */
 +      if (ca && (ca->flag & CAM_SHOWNAME)) {
 +              UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
 +              BLF_draw_default(
 +                      x1i, y1i - (0.7f * U.widget_unit), 0.0f,
 +                      v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
 +      }
  }
  
 -static void view3d_camera_border(
 -        const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 -        rctf *r_viewborder, const bool no_shift, const bool no_zoom)
 +static void drawrenderborder(ARegion *ar, View3D *v3d)
  {
 -      CameraParams params;
 -      rctf rect_view, rect_camera;
 +      /* use the same program for everything */
 +      uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
  
 -      /* get viewport viewplane */
 -      BKE_camera_params_init(&params);
 -      BKE_camera_params_from_view3d(&params, v3d, rv3d);
 -      if (no_zoom)
 -              params.zoom = 1.0f;
 -      BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
 -      rect_view = params.viewplane;
 +      glLineWidth(1.0f);
  
 -      /* get camera viewplane */
 -      BKE_camera_params_init(&params);
 -      /* fallback for non camera objects */
 -      params.clipsta = v3d->near;
 -      params.clipend = v3d->far;
 -      BKE_camera_params_from_object(&params, v3d->camera);
 -      if (no_shift) {
 -              params.shiftx = 0.0f;
 -              params.shifty = 0.0f;
 -      }
 -      BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
 -      rect_camera = params.viewplane;
 +      immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
  
 -      /* get camera border within viewport */
 -      r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
 -      r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
 -      r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
 -      r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
 -}
 +      float viewport_size[4];
 +      glGetFloatv(GL_VIEWPORT, viewport_size);
 +      immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
  
 -void ED_view3d_calc_camera_border_size(
 -        const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 -        float r_size[2])
 -{
 -      rctf viewborder;
 +      immUniform1i("num_colors", 0);  /* "simple" mode */
 +      immUniform4f("color", 1.0f, 0.25f, 0.25f, 1.0f);
 +      immUniform1f("dash_width", 6.0f);
 +      immUniform1f("dash_factor", 0.5f);
  
 -      view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, true, true);
 -      r_size[0] = BLI_rctf_size_x(&viewborder);
 -      r_size[1] = BLI_rctf_size_y(&viewborder);
 -}
 +      imm_draw_box_wire_2d(shdr_pos,
 +                        v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
 +                        v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
  
 -void ED_view3d_calc_camera_border(
 -        const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 -        rctf *r_viewborder, const bool no_shift)
 -{
 -      view3d_camera_border(scene, ar, v3d, rv3d, r_viewborder, no_shift, false);
 +      immUnbindProgram();
  }
  
 -static void drawviewborder_grid3(float x1, float x2, float y1, float y2, float fac)
 +void ED_view3d_draw_depth(
 +        const EvaluationContext *eval_ctx, struct Depsgraph *graph,
 +        ARegion *ar, View3D *v3d, bool alphaoverride)
  {
 -      float x3, y3, x4, y4;
 -
 -      x3 = x1 + fac * (x2 - x1);
 -      y3 = y1 + fac * (y2 - y1);
 -      x4 = x1 + (1.0f - fac) * (x2 - x1);
 -      y4 = y1 + (1.0f - fac) * (y2 - y1);
 -
 -      glBegin(GL_LINES);
 -      glVertex2f(x1, y3);
 -      glVertex2f(x2, y3);
 +      struct bThemeState theme_state;
 +      Scene *scene = DEG_get_evaluated_scene(graph);
 +      RegionView3D *rv3d = ar->regiondata;
  
 -      glVertex2f(x1, y4);
 -      glVertex2f(x2, y4);
 +      short zbuf = v3d->zbuf;
 +      short flag = v3d->flag;
 +      float glalphaclip = U.glalphaclip;
 +      int obcenter_dia = U.obcenter_dia;
 +      /* temp set drawtype to solid */
 +      /* Setting these temporarily is not nice */
 +      v3d->flag &= ~V3D_SELECT_OUTLINE;
 +      U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
 +      U.obcenter_dia = 0;
  
 -      glVertex2f(x3, y1);
 -      glVertex2f(x3, y2);
 +      /* Tools may request depth outside of regular drawing code. */
 +      UI_Theme_Store(&theme_state);
 +      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
  
 -      glVertex2f(x4, y1);
 -      glVertex2f(x4, y2);
 -      glEnd();
 -}
 +      ED_view3d_draw_setup_view(NULL, eval_ctx, scene, ar, v3d, NULL, NULL, NULL);
  
 -/* harmonious triangle */
 -static void drawviewborder_triangle(float x1, float x2, float y1, float y2, const char golden, const char dir)
 -{
 -      float ofs;
 -      float w = x2 - x1;
 -      float h = y2 - y1;
 +      glClear(GL_DEPTH_BUFFER_BIT);
  
 -      glBegin(GL_LINES);
 -      if (w > h) {
 -              if (golden) {
 -                      ofs = w * (1.0f - (1.0f / 1.61803399f));
 -              }
 -              else {
 -                      ofs = h * (h / w);
 -              }
 -              if (dir == 'B') SWAP(float, y1, y2);
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_set(rv3d);
 +      }
 +      /* get surface depth without bias */
 +      rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
  
 -              glVertex2f(x1, y1);
 -              glVertex2f(x2, y2);
 +      v3d->zbuf = true;
 +      glEnable(GL_DEPTH_TEST);
  
 -              glVertex2f(x2, y1);
 -              glVertex2f(x1 + (w - ofs), y2);
 +#ifdef WITH_OPENGL_LEGACY
 +      if (IS_VIEWPORT_LEGACY(vc->v3d)) {
 +              /* temp, calls into view3d_draw_legacy.c */
 +              ED_view3d_draw_depth_loop(scene, ar, v3d);
 +      }
 +      else
 +#endif /* WITH_OPENGL_LEGACY */
 +      {
 +              DRW_draw_depth_loop(graph, ar, v3d);
 +      }
  
 -              glVertex2f(x1, y2);
 -              glVertex2f(x1 + ofs, y1);
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_disable();
        }
 -      else {
 -              if (golden) {
 -                      ofs = h * (1.0f - (1.0f / 1.61803399f));
 -              }
 -              else {
 -                      ofs = w * (w / h);
 -              }
 -              if (dir == 'B') SWAP(float, x1, x2);
 +      rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
  
 -              glVertex2f(x1, y1);
 -              glVertex2f(x2, y2);
 +      v3d->zbuf = zbuf;
 +      if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
  
 -              glVertex2f(x2, y1);
 -              glVertex2f(x1, y1 + ofs);
 +      U.glalphaclip = glalphaclip;
 +      v3d->flag = flag;
 +      U.obcenter_dia = obcenter_dia;
  
 -              glVertex2f(x1, y2);
 -              glVertex2f(x2, y1 + (h - ofs));
 -      }
 -      glEnd();
 +      UI_Theme_Restore(&theme_state);
  }
  
 -static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      float x1, x2, y1, y2;
 -      float x1i, x2i, y1i, y2i;
 +/* ******************** background plates ***************** */
  
 -      rctf viewborder;
 -      Camera *ca = NULL;
 -      RegionView3D *rv3d = ar->regiondata;
 +static void view3d_draw_background_gradient(void)
 +{
 +      /* TODO: finish 2D API & draw background with that */
  
 -      if (v3d->camera == NULL)
 -              return;
 -      if (v3d->camera->type == OB_CAMERA)
 -              ca = v3d->camera->data;
 -      
 -      ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
 -      /* the offsets */
 -      x1 = viewborder.xmin;
 -      y1 = viewborder.ymin;
 -      x2 = viewborder.xmax;
 -      y2 = viewborder.ymax;
 -      
 -      glLineWidth(1.0f);
 +      Gwn_VertFormat *format = immVertexFormat();
 +      unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +      unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
 +      unsigned char col_hi[3], col_lo[3];
  
 -      /* apply offsets so the real 3D camera shows through */
 +      immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
  
 -      /* note: quite un-scientific but without this bit extra
 -       * 0.0001 on the lower left the 2D border sometimes
 -       * obscures the 3D camera border */
 -      /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
 -       * but keep it here in case we need to remove the workaround */
 -      x1i = (int)(x1 - 1.0001f);
 -      y1i = (int)(y1 - 1.0001f);
 -      x2i = (int)(x2 + (1.0f - 0.0001f));
 -      y2i = (int)(y2 + (1.0f - 0.0001f));
 -      
 -      /* passepartout, specified in camera edit buttons */
 -      if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
 -              const float winx = (ar->winx + 1);
 -              const float winy = (ar->winy + 1);
 +      UI_GetThemeColor3ubv(TH_LOW_GRAD, col_lo);
 +      UI_GetThemeColor3ubv(TH_HIGH_GRAD, col_hi);
  
 -              if (ca->passepartalpha == 1.0f) {
 -                      glColor3f(0, 0, 0);
 -              }
 -              else {
 -                      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 -                      glEnable(GL_BLEND);
 -                      glColor4f(0, 0, 0, ca->passepartalpha);
 -              }
 +      immBegin(GWN_PRIM_TRI_FAN, 4);
 +      immAttrib3ubv(color, col_lo);
 +      immVertex2f(pos, -1.0f, -1.0f);
 +      immVertex2f(pos, 1.0f, -1.0f);
  
 -              if (x1i > 0.0f)
 -                      glRectf(0.0, winy, x1i, 0.0);
 -              if (x2i < winx)
 -                      glRectf(x2i, winy, winx, 0.0);
 -              if (y2i < winy)
 -                      glRectf(x1i, winy, x2i, y2i);
 -              if (y2i > 0.0f)
 -                      glRectf(x1i, y1i, x2i, 0.0);
 -              
 -              glDisable(GL_BLEND);
 -      }
 +      immAttrib3ubv(color, col_hi);
 +      immVertex2f(pos, 1.0f, 1.0f);
 +      immVertex2f(pos, -1.0f, 1.0f);
 +      immEnd();
  
 -      setlinestyle(0);
 +      immUnbindProgram();
 +}
  
 -      UI_ThemeColor(TH_BACK);
 -              
 -      fdrawbox(x1i, y1i, x2i, y2i);
 +static void view3d_draw_background_none(void)
 +{
 +      UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
 +      glClear(GL_COLOR_BUFFER_BIT);
 +}
  
 -#ifdef VIEW3D_CAMERA_BORDER_HACK
 -      if (view3d_camera_border_hack_test == true) {
 -              glColor3ubv(view3d_camera_border_hack_col);
 -              fdrawbox(x1i + 1, y1i + 1, x2i - 1, y2i - 1);
 -              view3d_camera_border_hack_test = false;
 -      }
 -#endif
 +static void view3d_draw_background_world(Scene *scene, RegionView3D *rv3d)
 +{
 +      if (scene->world) {
 +              GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
  
 -      setlinestyle(3);
 +              /* calculate full shader for background */
 +              GPU_material_bind(gpumat, 1, 1, 1.0f, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac);
 +
 +              if (GPU_material_bound(gpumat)) {
 +                      /* TODO viewport (dfelinto): GPU_material_bind relies on immediate mode,
 +                       * we can't get rid of the following code without a bigger refactor
 +                       * or we dropping this functionality. */
 +
 +                      glBegin(GL_TRIANGLE_STRIP);
 +                      glVertex2f(-1.0f, -1.0f);
 +                      glVertex2f(1.0f, -1.0f);
 +                      glVertex2f(-1.0f, 1.0f);
 +                      glVertex2f(1.0f, 1.0f);
 +                      glEnd();
  
 -      /* outer line not to confuse with object selecton */
 -      if (v3d->flag2 & V3D_LOCK_CAMERA) {
 -              UI_ThemeColor(TH_REDALERT);
 -              fdrawbox(x1i - 1, y1i - 1, x2i + 1, y2i + 1);
 +                      GPU_material_unbind(gpumat);
 +                      return;
 +              }
        }
  
 -      UI_ThemeColor(TH_VIEW_OVERLAY);
 -      fdrawbox(x1i, y1i, x2i, y2i);
 +      /* if any of the above fails */
 +      view3d_draw_background_none();
 +}
  
 -      /* border */
 -      if (scene->r.mode & R_BORDER) {
 -              float x3, y3, x4, y4;
 +/* ******************** other elements ***************** */
  
 -              x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
 -              y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
 -              x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
 -              y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
  
 -              cpack(0x4040FF);
 -              sdrawbox(x3,  y3,  x4,  y4);
 -      }
 +#define DEBUG_GRID 0
  
 -      /* safety border */
 -      if (ca) {
 -              if (ca->dtx & CAM_DTX_CENTER) {
 -                      float x3, y3;
 +static void gridline_range(double x0, double dx, double max, int *r_first, int *r_count)
 +{
 +      /* determine range of gridlines that appear in this Area -- similar calc but separate ranges for x & y
 +       * x0 is gridline 0, the axis in screen space
 +       * Area covers [0 .. max) pixels */
  
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 +      int first = (int)ceil(-x0 / dx);
 +      int last = (int)floor((max - x0) / dx);
  
 -                      x3 = x1 + 0.5f * (x2 - x1);
 -                      y3 = y1 + 0.5f * (y2 - y1);
 +      if (first <= last) {
 +              *r_first = first;
 +              *r_count = last - first + 1;
 +      }
 +      else {
 +              *r_first = 0;
 +              *r_count = 0;
 +      }
  
 -                      glBegin(GL_LINES);
 -                      glVertex2f(x1, y3);
 -                      glVertex2f(x2, y3);
 +#if DEBUG_GRID
 +      printf("   first %d * dx = %f\n", first, x0 + first * dx);
 +      printf("   last %d * dx = %f\n", last, x0 + last * dx);
 +      printf("   count = %d\n", *count_out);
 +#endif
 +}
  
 -                      glVertex2f(x3, y1);
 -                      glVertex2f(x3, y2);
 -                      glEnd();
 -              }
 +static int gridline_count(ARegion *ar, double x0, double y0, double dx)
 +{
 +      /* x0 & y0 establish the "phase" of the grid within this 2D region
 +       * dx is the frequency, shared by x & y directions
 +       * pass in dx of smallest (highest precision) grid we want to draw */
  
 -              if (ca->dtx & CAM_DTX_CENTER_DIAG) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 +#if DEBUG_GRID
 +      printf("  %s(%f, %f, dx:%f)\n", __FUNCTION__, x0, y0, dx);
 +#endif
  
 -                      glBegin(GL_LINES);
 -                      glVertex2f(x1, y1);
 -                      glVertex2f(x2, y2);
 +      int first, x_ct, y_ct;
  
 -                      glVertex2f(x1, y2);
 -                      glVertex2f(x2, y1);
 -                      glEnd();
 -              }
 +      gridline_range(x0, dx, ar->winx, &first, &x_ct);
 +      gridline_range(y0, dx, ar->winy, &first, &y_ct);
  
 -              if (ca->dtx & CAM_DTX_THIRDS) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_grid3(x1, x2, y1, y2, 1.0f / 3.0f);
 -              }
 +      int total_ct = x_ct + y_ct;
  
 -              if (ca->dtx & CAM_DTX_GOLDEN) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_grid3(x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
 -              }
 +#if DEBUG_GRID
 +      printf("   %d + %d = %d gridlines\n", x_ct, y_ct, total_ct);
 +#endif
  
 -              if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 0, 'A');
 -              }
 +      return total_ct;
 +}
  
 -              if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 0, 'B');
 -              }
 +static bool drawgrid_draw(ARegion *ar, double x0, double y0, double dx, int skip_mod, unsigned pos, unsigned col, GLubyte col_value[3])
 +{
 +      /* skip every skip_mod lines relative to each axis; they will be overlaid by another drawgrid_draw
 +       * always skip exact x0 & y0 axes; they will be drawn later in color
 +       *
 +       * set grid color once, just before the first line is drawn
 +       * it's harmless to set same color for every line, or every vertex
 +       * but if no lines are drawn, color must not be set! */
  
 -              if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 1, 'A');
 -              }
 +#if DEBUG_GRID
 +      printf("  %s(%f, %f, dx:%f, skip_mod:%d)\n", __FUNCTION__, x0, y0, dx, skip_mod);
 +#endif
  
 -              if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 1, 'B');
 -              }
 +      const float x_max = (float)ar->winx;
 +      const float y_max = (float)ar->winy;
  
 -              if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
 -                      UI_draw_safe_areas(
 -                              x1, x2, y1, y2,
 -                              scene->safe_areas.title,
 -                              scene->safe_areas.action);
 +      int first, ct;
 +      int x_ct = 0, y_ct = 0; /* count of lines actually drawn */
 +      int lines_skipped_for_next_unit = 0;
  
 -                      if (ca->flag & CAM_SHOW_SAFE_CENTER) {
 -                              UI_draw_safe_areas(
 -                                      x1, x2, y1, y2,
 -                                      scene->safe_areas.title_center,
 -                                      scene->safe_areas.action_center);
 -                      }
 +      /* draw vertical lines */
 +      gridline_range(x0, dx, x_max, &first, &ct);
 +
 +      for (int i = first; i < first + ct; ++i) {
 +              if (i == 0)
 +                      continue;
 +              else if (skip_mod && (i % skip_mod) == 0) {
 +                      ++lines_skipped_for_next_unit;
 +                      continue;
                }
  
 -              if (ca->flag & CAM_SHOWSENSOR) {
 -                      /* determine sensor fit, and get sensor x/y, for auto fit we
 -                       * assume and square sensor and only use sensor_x */
 -                      float sizex = scene->r.xsch * scene->r.xasp;
 -                      float sizey = scene->r.ysch * scene->r.yasp;
 -                      int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
 -                      float sensor_x = ca->sensor_x;
 -                      float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
 +              if (x_ct == 0)
 +                      immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
  
 -                      /* determine sensor plane */
 -                      rctf rect;
 +              float x = (float)(x0 + i * dx);
 +              immVertex2f(pos, x, 0.0f);
 +              immVertex2f(pos, x, y_max);
 +              ++x_ct;
 +      }
  
 -                      if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
 -                              float sensor_scale = (x2i - x1i) / sensor_x;
 -                              float sensor_height = sensor_scale * sensor_y;
 +      /* draw horizontal lines */
 +      gridline_range(y0, dx, y_max, &first, &ct);
  
 -                              rect.xmin = x1i;
 -                              rect.xmax = x2i;
 -                              rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
 -                              rect.ymax = rect.ymin + sensor_height;
 -                      }
 -                      else {
 -                              float sensor_scale = (y2i - y1i) / sensor_y;
 -                              float sensor_width = sensor_scale * sensor_x;
 +      for (int i = first; i < first + ct; ++i) {
 +              if (i == 0)
 +                      continue;
 +              else if (skip_mod && (i % skip_mod) == 0) {
 +                      ++lines_skipped_for_next_unit;
 +                      continue;
 +              }
  
 -                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 -                              rect.xmax = rect.xmin + sensor_width;
 -                              rect.ymin = y1i;
 -                              rect.ymax = y2i;
 -                      }
 +              if (x_ct + y_ct == 0)
 +                      immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
  
 -                      /* draw */
 -                      UI_ThemeColorShade(TH_VIEW_OVERLAY, 100);
 -                      UI_draw_roundbox_gl_mode(GL_LINE_LOOP, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f);
 -              }
 +              float y = (float)(y0 + i * dx);
 +              immVertex2f(pos, 0.0f, y);
 +              immVertex2f(pos, x_max, y);
 +              ++y_ct;
        }
  
 -      setlinestyle(0);
 +#if DEBUG_GRID
 +      int total_ct = x_ct + y_ct;
 +      printf("    %d + %d = %d gridlines drawn, %d skipped for next unit\n", x_ct, y_ct, total_ct, lines_skipped_for_next_unit);
 +#endif
  
 -      /* camera name - draw in highlighted text color */
 -      if (ca && (ca->flag & CAM_SHOWNAME)) {
 -              UI_ThemeColor(TH_TEXT_HI);
 -              BLF_draw_default(
 -                      x1i, y1i - (0.7f * U.widget_unit), 0.0f,
 -                      v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
 -      }
 +      return lines_skipped_for_next_unit > 0;
  }
  
 -/* *********************** backdraw for selection *************** */
 +#define GRID_MIN_PX_D 6.0
 +#define GRID_MIN_PX_F 6.0f
  
 -static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d)
 +static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
  {
        RegionView3D *rv3d = ar->regiondata;
 -      struct Base *base = scene->basact;
 -      int multisample_enabled;
  
 -      BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
 +#if DEBUG_GRID
 +      printf("%s width %d, height %d\n", __FUNCTION__, ar->winx, ar->winy);
 +#endif
  
 -      if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
 -                   BKE_paint_select_face_test(base->object)))
 -      {
 -              /* do nothing */
 -      }
 -      /* texture paint mode sampling */
 -      else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
 -               (v3d->drawtype > OB_WIRE))
 -      {
 -              /* do nothing */
 -      }
 -      else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
 -               V3D_IS_ZBUF(v3d))
 -      {
 -              /* do nothing */
 -      }
 -      else if (scene->obedit &&
 -               V3D_IS_ZBUF(v3d))
 -      {
 -              /* do nothing */
 -      }
 -      else {
 -              v3d->flag &= ~V3D_INVALID_BACKBUF;
 -              return;
 -      }
 +      double fx = rv3d->persmat[3][0];
 +      double fy = rv3d->persmat[3][1];
 +      double fw = rv3d->persmat[3][3];
  
 -      if (!(v3d->flag & V3D_INVALID_BACKBUF))
 -              return;
 +      const double wx = 0.5 * ar->winx;  /* use double precision to avoid rounding errors */
 +      const double wy = 0.5 * ar->winy;
  
 -#if 0
 -      if (test) {
 -              if (qtest()) {
 -                      addafterqueue(ar->win, BACKBUFDRAW, 1);
 -                      return;
 -              }
 -      }
 -#endif
 +      double x = wx * fx / fw;
 +      double y = wy * fy / fw;
  
 -      if (v3d->drawtype > OB_WIRE) v3d->zbuf = true;
 -      
 -      /* dithering and AA break color coding, so disable */
 -      glDisable(GL_DITHER);
 -
 -      multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
 -      if (multisample_enabled)
 -              glDisable(GL_MULTISAMPLE);
 -
 -      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 -              /* for multisample we use an offscreen FBO. multisample drawing can fail
 -               * with color coded selection drawing, and reading back depths from such
 -               * a buffer can also cause a few seconds freeze on OS X / NVidia. */
 -              int w = BLI_rcti_size_x(&ar->winrct);
 -              int h = BLI_rcti_size_y(&ar->winrct);
 -              char error[256];
 -
 -              if (rv3d->gpuoffscreen) {
 -                      if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
 -                          GPU_offscreen_height(rv3d->gpuoffscreen) != h)
 -                      {
 -                              GPU_offscreen_free(rv3d->gpuoffscreen);
 -                              rv3d->gpuoffscreen = NULL;
 -                      }
 -              }
 +      double vec4[4] = { v3d->grid, v3d->grid, 0.0, 1.0 };
 +      mul_m4_v4d(rv3d->persmat, vec4);
 +      fx = vec4[0];
 +      fy = vec4[1];
 +      fw = vec4[3];
  
 -              if (!rv3d->gpuoffscreen) {
 -                      rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
 +      double dx = fabs(x - wx * fx / fw);
 +      if (dx == 0) dx = fabs(y - wy * fy / fw);
  
 -                      if (!rv3d->gpuoffscreen)
 -                              fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
 -              }
 -      }
 +      x += wx;
 +      y += wy;
  
 -      if (rv3d->gpuoffscreen)
 -              GPU_offscreen_bind(rv3d->gpuoffscreen, true);
 -      else
 -              glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
 +      /* now x, y, and dx have their final values
 +       * (x,y) is the world origin (0,0,0) mapped to Area-relative screen space
 +       * dx is the distance in pixels between grid lines -- same for horiz or vert grid lines */
  
 -      glClearColor(0.0, 0.0, 0.0, 0.0);
 -      if (v3d->zbuf) {
 -              glEnable(GL_DEPTH_TEST);
 -              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -      }
 -      else {
 -              glClear(GL_COLOR_BUFFER_BIT);
 -              glDisable(GL_DEPTH_TEST);
 -      }
 -      
 -      if (rv3d->rflag & RV3D_CLIPPING)
 -              ED_view3d_clipping_set(rv3d);
 -      
 -      G.f |= G_BACKBUFSEL;
 -      
 -      if (base && (base->lay & v3d->lay))
 -              draw_object_backbufsel(scene, v3d, rv3d, base->object);
 -      
 -      if (rv3d->gpuoffscreen)
 -              GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
 -      else
 -              ar->swap = 0; /* mark invalid backbuf for wm draw */
 -
 -      v3d->flag &= ~V3D_INVALID_BACKBUF;
 -
 -      G.f &= ~G_BACKBUFSEL;
 -      v3d->zbuf = false;
 -      glDisable(GL_DEPTH_TEST);
 -      glEnable(GL_DITHER);
 -      if (multisample_enabled)
 -              glEnable(GL_MULTISAMPLE);
 -
 -      if (rv3d->rflag & RV3D_CLIPPING)
 -              ED_view3d_clipping_disable();
 -}
 +      glLineWidth(1.0f);
  
 -void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 +#if 0 /* TODO: write to UI/widget depth buffer, not scene depth */
 +      glDepthMask(GL_FALSE);  /* disable write in zbuffer */
 +#endif
  
 -      if (rv3d->gpuoffscreen) {
 -              GPU_offscreen_bind(rv3d->gpuoffscreen, true);
 -              glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
 -              glReadPixels(x, y, w, h, format, type, data);
 -              GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
 -      }
 -      else {
 -              glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 -      }
 -}
 +      Gwn_VertFormat *format = immVertexFormat();
 +      unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +      unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
  
 -/* XXX depth reading exception, for code not using gpu offscreen */
 -static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
 -{
 +      immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
  
 -      glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 -}
 +      unsigned char col[3], col2[3];
 +      UI_GetThemeColor3ubv(TH_GRID, col);
  
 -void ED_view3d_backbuf_validate(ViewContext *vc)
 -{
 -      if (vc->v3d->flag & V3D_INVALID_BACKBUF)
 -              backdrawview3d(vc->scene, vc->win, vc->ar, vc->v3d);
 -}
 +      if (unit->system) {
 +              const void *usys;
 +              int len;
  
 -/**
 - * allow for small values [0.5 - 2.5],
 - * and large values, FLT_MAX by clamping by the area size
 - */
 -int ED_view3d_backbuf_sample_size_clamp(ARegion *ar, const float dist)
 -{
 -      return (int)min_ff(ceilf(dist), (float)max_ii(ar->winx, ar->winx));
 -}
 +              bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
  
 -/* samples a single pixel (copied from vpaint) */
 -unsigned int ED_view3d_backbuf_sample(ViewContext *vc, int x, int y)
 -{
 -      unsigned int col;
 -      
 -      if (x >= vc->ar->winx || y >= vc->ar->winy) {
 -              return 0;
 -      }
 +              bool first = true;
  
 -      ED_view3d_backbuf_validate(vc);
 +              if (usys) {
 +                      int i = len;
 +                      while (i--) {
 +                              double scalar = bUnit_GetScaler(usys, i);
  
 -      view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
 -      glReadBuffer(GL_BACK);
 -      
 -      if (ENDIAN_ORDER == B_ENDIAN) {
 -              BLI_endian_switch_uint32(&col);
 -      }
 -      
 -      return GPU_select_to_index(col);
 -}
 +                              double dx_scalar = dx * scalar / (double)unit->scale_length;
 +                              if (dx_scalar < (GRID_MIN_PX_D * 2.0)) {
 +                                      /* very very small grid items are less useful when dealing with units */
 +                                      continue;
 +                              }
  
 -/* reads full rect, converts indices */
 -ImBuf *ED_view3d_backbuf_read(ViewContext *vc, int xmin, int ymin, int xmax, int ymax)
 -{
 -      struct ImBuf *ibuf_clip;
 -      /* clip */
 -      const rcti clip = {
 -          max_ii(xmin, 0), min_ii(xmax, vc->ar->winx - 1),
 -          max_ii(ymin, 0), min_ii(ymax, vc->ar->winy - 1)};
 -      const int size_clip[2] = {
 -          BLI_rcti_size_x(&clip) + 1,
 -          BLI_rcti_size_y(&clip) + 1};
 -
 -      if (UNLIKELY((clip.xmin > clip.xmax) ||
 -                   (clip.ymin > clip.ymax)))
 -      {
 -              return NULL;
 -      }
 +                              if (first) {
 +                                      first = false;
  
 -      ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
 +                                      /* Store the smallest drawn grid size units name so users know how big each grid cell is */
 +                                      *grid_unit = bUnit_GetNameDisplay(usys, i);
 +                                      rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
  
 -      ED_view3d_backbuf_validate(vc);
 +                                      int gridline_ct = gridline_count(ar, x, y, dx_scalar);
 +                                      if (gridline_ct == 0)
 +                                              goto drawgrid_cleanup; /* nothing to draw */
  
 -      view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
 +                                      immBegin(GWN_PRIM_LINES, gridline_ct * 2);
 +                              }
  
 -      glReadBuffer(GL_BACK);
 +                              float blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
 +                              /* tweak to have the fade a bit nicer */
 +                              blend_fac = (blend_fac * blend_fac) * 2.0f;
 +                              CLAMP(blend_fac, 0.3f, 1.0f);
  
 -      if (ENDIAN_ORDER == B_ENDIAN) {
 -              IMB_convert_rgba_to_abgr(ibuf_clip);
 -      }
 +                              UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, blend_fac, col2);
  
 -      GPU_select_to_index_array(ibuf_clip->rect, size_clip[0] * size_clip[1]);
 -      
 -      if ((clip.xmin == xmin) &&
 -          (clip.xmax == xmax) &&
 -          (clip.ymin == ymin) &&
 -          (clip.ymax == ymax))
 -      {
 -              return ibuf_clip;
 +                              const int skip_mod = (i == 0) ? 0 : (int)round(bUnit_GetScaler(usys, i - 1) / scalar);
 +#if DEBUG_GRID
 +                              printf("%s %f, ", bUnit_GetNameDisplay(usys, i), scalar);
 +                              if (i > 0)
 +                                      printf("next unit is %d times larger\n", skip_mod);
 +                              else
 +                                      printf("largest unit\n");
 +#endif
 +                              if (!drawgrid_draw(ar, x, y, dx_scalar, skip_mod, pos, color, col2))
 +                                      break;
 +                      }
 +              }
        }
        else {
 -              /* put clipped result into a non-clipped buffer */
 -              struct ImBuf *ibuf_full;
 -              const int size[2] = {
 -                  (xmax - xmin + 1),
 -                  (ymax - ymin + 1)};
 -
 -              ibuf_full = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
 -
 -              IMB_rectcpy(
 -                      ibuf_full, ibuf_clip,
 -                      clip.xmin - xmin, clip.ymin - ymin,
 -                      0, 0,
 -                      size_clip[0], size_clip[1]);
 -              IMB_freeImBuf(ibuf_clip);
 -              return ibuf_full;
 -      }
 -}
 -
 -/* smart function to sample a rect spiralling outside, nice for backbuf selection */
 -unsigned int ED_view3d_backbuf_sample_rect(
 -        ViewContext *vc, const int mval[2], int size,
 -        unsigned int min, unsigned int max, float *r_dist)
 -{
 -      struct ImBuf *buf;
 -      const unsigned int *bufmin, *bufmax, *tbuf;
 -      int minx, miny;
 -      int a, b, rc, nr, amount, dirvec[4][2];
 -      unsigned int index = 0;
 -
 -      amount = (size - 1) / 2;
 +              const double sublines = v3d->gridsubdiv;
 +              const float  sublines_fl = v3d->gridsubdiv;
  
 -      minx = mval[0] - (amount + 1);
 -      miny = mval[1] - (amount + 1);
 -      buf = ED_view3d_backbuf_read(vc, minx, miny, minx + size - 1, miny + size - 1);
 -      if (!buf) return 0;
 +              int grids_to_draw = 2; /* first the faint fine grid, then the bold coarse grid */
  
 -      rc = 0;
 -      
 -      dirvec[0][0] = 1; dirvec[0][1] = 0;
 -      dirvec[1][0] = 0; dirvec[1][1] = -size;
 -      dirvec[2][0] = -1; dirvec[2][1] = 0;
 -      dirvec[3][0] = 0; dirvec[3][1] = size;
 -      
 -      bufmin = buf->rect;
 -      tbuf = buf->rect;
 -      bufmax = buf->rect + size * size;
 -      tbuf += amount * size + amount;
 -      
 -      for (nr = 1; nr <= size; nr++) {
 -              
 -              for (a = 0; a < 2; a++) {
 -                      for (b = 0; b < nr; b++) {
 -                              if (*tbuf && *tbuf >= min && *tbuf < max) {
 -                                      /* we got a hit */
 -
 -                                      /* get x,y pixel coords from the offset
 -                                       * (manhatten distance in keeping with other screen-based selection) */
 -                                      *r_dist = (float)(
 -                                              abs(((int)(tbuf - buf->rect) % size) - (size / 2)) +
 -                                              abs(((int)(tbuf - buf->rect) / size) - (size / 2)));
 -
 -                                      /* indices start at 1 here */
 -                                      index = (*tbuf - min) + 1;
 -                                      goto exit;
 +              if (dx < GRID_MIN_PX_D) {
 +                      rv3d->gridview *= sublines_fl;
 +                      dx *= sublines;
 +                      if (dx < GRID_MIN_PX_D) {
 +                              rv3d->gridview *= sublines_fl;
 +                              dx *= sublines;
 +                              if (dx < GRID_MIN_PX_D) {
 +                                      rv3d->gridview *= sublines_fl;
 +                                      dx *= sublines;
 +                                      grids_to_draw = (dx < GRID_MIN_PX_D) ? 0 : 1;
                                }
 -                              
 -                              tbuf += (dirvec[rc][0] + dirvec[rc][1]);
 -                              
 -                              if (tbuf < bufmin || tbuf >= bufmax) {
 -                                      goto exit;
 +                      }
 +              }
 +              else {
 +                      if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 +                              rv3d->gridview /= sublines_fl;
 +                              dx /= sublines;
 +                              if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 +                                      rv3d->gridview /= sublines_fl;
 +                                      dx /= sublines;
 +                                      if (dx > (GRID_MIN_PX_D * 10.0)) {
 +                                              grids_to_draw = 1;
 +                                      }
                                }
                        }
 -                      rc++;
 -                      rc &= 3;
                }
 -      }
 -
 -exit:
 -      IMB_freeImBuf(buf);
 -      return index;
 -}
 -
  
 -/* ************************************************************* */
 +              int gridline_ct = gridline_count(ar, x, y, dx);
 +              if (gridline_ct == 0)
 +                      goto drawgrid_cleanup; /* nothing to draw */
  
 -static void view3d_stereo_bgpic_setup(Scene *scene, View3D *v3d, Image *ima, ImageUser *iuser)
 -{
 -      if (BKE_image_is_stereo(ima)) {
 -              iuser->flag |= IMA_SHOW_STEREO;
 +              immBegin(GWN_PRIM_LINES, gridline_ct * 2);
  
 -              if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 -                      iuser->multiview_eye = STEREO_LEFT_ID;
 +              if (grids_to_draw == 2) {
 +                      UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0), col2);
 +                      if (drawgrid_draw(ar, x, y, dx, v3d->gridsubdiv, pos, color, col2))
 +                              drawgrid_draw(ar, x, y, dx * sublines, 0, pos, color, col);
                }
 -              else if (v3d->stereo3d_camera != STEREO_3D_ID) {
 -                      /* show only left or right camera */
 -                      iuser->multiview_eye = v3d->stereo3d_camera;
 +              else if (grids_to_draw == 1) {
 +                      drawgrid_draw(ar, x, y, dx, 0, pos, color, col);
                }
 +      }
  
 -              BKE_image_multiview_index(ima, iuser);
 +      /* draw visible axes */
 +      /* horizontal line */
 +      if (0 <= y && y < ar->winy) {
 +              UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT) ? 'Y' : 'X');
 +              immAttrib3ub(color, col2[0], col2[1], col2[2]);
 +              immVertex2f(pos, 0.0f, y);
 +              immVertex2f(pos, (float)ar->winx, y);
        }
 -      else {
 -              iuser->flag &= ~IMA_SHOW_STEREO;
 +
 +      /* vertical line */
 +      if (0 <= x && x < ar->winx) {
 +              UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM) ? 'Y' : 'Z');
 +              immAttrib3ub(color, col2[0], col2[1], col2[2]);
 +              immVertex2f(pos, x, 0.0f);
 +              immVertex2f(pos, x, (float)ar->winy);
        }
 +
 +      immEnd();
 +
 +drawgrid_cleanup:
 +      immUnbindProgram();
 +
 +#if 0 /* depth write is left enabled above */
 +      glDepthMask(GL_TRUE);  /* enable write in zbuffer */
 +#endif
  }
  
 -static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
 -                              const bool do_foreground, const bool do_camera_frame)
 +#undef DEBUG_GRID
 +#undef GRID_MIN_PX_D
 +#undef GRID_MIN_PX_F
 +
 +static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
  {
 -      RegionView3D *rv3d = ar->regiondata;
 -      BGpic *bgpic;
 -      int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
 +      /* draw only if there is something to draw */
 +      if (v3d->gridflag & (V3D_SHOW_FLOOR | V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
 +              /* draw how many lines?
 +               * trunc(v3d->gridlines / 2) * 4
 +               * + 2 for xy axes (possibly with special colors)
 +               * + 1 for z axis (the only line not in xy plane)
 +               * even v3d->gridlines are honored, odd rounded down */
 +              const int gridlines = v3d->gridlines / 2;
 +              const float grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
 +              const float grid = gridlines * grid_scale;
  
 -      for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
 -              bgpic->iuser.scene = scene;  /* Needed for render results. */
 +              const bool show_floor = (v3d->gridflag & V3D_SHOW_FLOOR) && gridlines >= 1;
  
 -              if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
 -                      continue;
 +              bool show_axis_x = v3d->gridflag & V3D_SHOW_X;
 +              bool show_axis_y = v3d->gridflag & V3D_SHOW_Y;
 +              bool show_axis_z = v3d->gridflag & V3D_SHOW_Z;
  
 -              if ((bgpic->view == 0) || /* zero for any */
 -                  (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
 -                  (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
 -              {
 -                      float image_aspect[2];
 -                      float fac, asp, zoomx, zoomy;
 -                      float x1, y1, x2, y2, centx, centy;
 -
 -                      ImBuf *ibuf = NULL, *freeibuf, *releaseibuf;
 -                      void *lock;
 -                      rctf clip_rect;
 -
 -                      Image *ima = NULL;
 -                      MovieClip *clip = NULL;
 -
 -                      /* disable individual images */
 -                      if ((bgpic->flag & V3D_BGPIC_DISABLED))
 -                              continue;
 -
 -                      freeibuf = NULL;
 -                      releaseibuf = NULL;
 -                      if (bgpic->source == V3D_BGPIC_IMAGE) {
 -                              ima = bgpic->ima;
 -                              if (ima == NULL)
 -                                      continue;
 -                              BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
 -                              if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
 -                                      ibuf = NULL; /* frame is out of range, dont show */
 -                              }
 -                              else {
 -                                      view3d_stereo_bgpic_setup(scene, v3d, ima, &bgpic->iuser);
 -                                      ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, &lock);
 -                                      releaseibuf = ibuf;
 -                              }
 +              unsigned char col_grid[3], col_axis[3];
  
 -                              image_aspect[0] = ima->aspx;
 -                              image_aspect[1] = ima->aspy;
 -                      }
 -                      else if (bgpic->source == V3D_BGPIC_MOVIE) {
 -                              /* TODO: skip drawing when out of frame range (as image sequences do above) */
 +              glLineWidth(1.0f);
  
 -                              if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
 -                                      if (scene->camera)
 -                                              clip = BKE_object_movieclip_get(scene, scene->camera, true);
 -                              }
 -                              else {
 -                                      clip = bgpic->clip;
 -                              }
 +              UI_GetThemeColor3ubv(TH_GRID, col_grid);
  
 -                              if (clip == NULL)
 -                                      continue;
 +              if (!write_depth)
 +                      glDepthMask(GL_FALSE);
  
 -                              BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
 -                              ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
 +              if (show_floor) {
 +                      const unsigned vertex_ct = 2 * (gridlines * 4 + 2);
 +                      const int sublines = v3d->gridsubdiv;
  
 -                              image_aspect[0] = clip->aspx;
 -                              image_aspect[1] = clip->aspy;
 +                      unsigned char col_bg[3], col_grid_emphasise[3], col_grid_light[3];
  
 -                              /* working with ibuf from image and clip has got different workflow now.
 -                               * ibuf acquired from clip is referenced by cache system and should
 -                               * be dereferenced after usage. */
 -                              freeibuf = ibuf;
 -                      }
 -                      else {
 -                              /* perhaps when loading future files... */
 -                              BLI_assert(0);
 -                              copy_v2_fl(image_aspect, 1.0f);
 -                      }
 +                      Gwn_VertFormat *format = immVertexFormat();
 +                      unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +                      unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
  
 -                      if (ibuf == NULL)
 -                              continue;
 +                      immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
  
 -                      if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
 -                              if (freeibuf)
 -                                      IMB_freeImBuf(freeibuf);
 -                              if (releaseibuf)
 -                                      BKE_image_release_ibuf(ima, releaseibuf, lock);
 +                      immBegin(GWN_PRIM_LINES, vertex_ct);
  
 -                              continue;
 -                      }
 +                      /* draw normal grid lines */
 +                      UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
  
 -                      if (ibuf->rect == NULL)
 -                              IMB_rect_from_float(ibuf);
 +                      for (int a = 1; a <= gridlines; a++) {
 +                              /* skip emphasised divider lines */
 +                              if (a % sublines != 0) {
 +                                      const float line = a * grid_scale;
  
 -                      if (rv3d->persp == RV3D_CAMOB) {
 +                                      immAttrib3ubv(color, col_grid_light);
  
 -                              if (do_camera_frame) {
 -                                      rctf vb;
 -                                      ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
 -                                      x1 = vb.xmin;
 -                                      y1 = vb.ymin;
 -                                      x2 = vb.xmax;
 -                                      y2 = vb.ymax;
 -                              }
 -                              else {
 -                                      x1 = ar->winrct.xmin;
 -                                      y1 = ar->winrct.ymin;
 -                                      x2 = ar->winrct.xmax;
 -                                      y2 = ar->winrct.ymax;
 -                              }
 +                                      immVertex2f(pos, -grid, -line);
 +                                      immVertex2f(pos, +grid, -line);
 +                                      immVertex2f(pos, -grid, +line);
 +                                      immVertex2f(pos, +grid, +line);
  
 -                              /* apply offset last - camera offset is different to offset in blender units */
 -                              /* so this has some sane way of working - this matches camera's shift _exactly_ */
 -                              {
 -                                      const float max_dim = max_ff(x2 - x1, y2 - y1);
 -                                      const float xof_scale = bgpic->xof * max_dim;
 -                                      const float yof_scale = bgpic->yof * max_dim;
 -
 -                                      x1 += xof_scale;
 -                                      y1 += yof_scale;
 -                                      x2 += xof_scale;
 -                                      y2 += yof_scale;
 +                                      immVertex2f(pos, -line, -grid);
 +                                      immVertex2f(pos, -line, +grid);
 +                                      immVertex2f(pos, +line, -grid);
 +                                      immVertex2f(pos, +line, +grid);
                                }
 +                      }
  
 -                              centx = (x1 + x2) / 2.0f;
 -                              centy = (y1 + y2) / 2.0f;
 +                      /* draw emphasised grid lines */
 +                      UI_GetThemeColor3ubv(TH_BACK, col_bg);
 +                      /* emphasise division lines lighter instead of darker, if background is darker than grid */
 +                      UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
 +                              (col_grid[0] + col_grid[1] + col_grid[2] + 30 >
 +                              col_bg[0] + col_bg[1] + col_bg[2]) ? 20 : -10);
  
 -                              /* aspect correction */
 -                              if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
 -                                      /* apply aspect from clip */
 -                                      const float w_src = ibuf->x * image_aspect[0];
 -                                      const float h_src = ibuf->y * image_aspect[1];
 +                      if (sublines <= gridlines) {
 +                              immAttrib3ubv(color, col_grid_emphasise);
  
 -                                      /* destination aspect is already applied from the camera frame */
 -                                      const float w_dst = x1 - x2;
 -                                      const float h_dst = y1 - y2;
 +                              for (int a = sublines; a <= gridlines; a += sublines) {
 +                                      const float line = a * grid_scale;
  
 -                                      const float asp_src = w_src / h_src;
 -                                      const float asp_dst = w_dst / h_dst;
 +                                      immVertex2f(pos, -grid, -line);
 +                                      immVertex2f(pos, +grid, -line);
 +                                      immVertex2f(pos, -grid, +line);
 +                                      immVertex2f(pos, +grid, +line);
  
 -                                      if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
 -                                              if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
 -                                                      /* fit X */
 -                                                      const float div = asp_src / asp_dst;
 -                                                      x1 = ((x1 - centx) * div) + centx;
 -                                                      x2 = ((x2 - centx) * div) + centx;
 -                                              }
 -                                              else {
 -                                                      /* fit Y */
 -                                                      const float div = asp_dst / asp_src;
 -                                                      y1 = ((y1 - centy) * div) + centy;
 -                                                      y2 = ((y2 - centy) * div) + centy;
 -                                              }
 -                                      }
 +                                      immVertex2f(pos, -line, -grid);
 +                                      immVertex2f(pos, -line, +grid);
 +                                      immVertex2f(pos, +line, -grid);
 +                                      immVertex2f(pos, +line, +grid);
                                }
                        }
 -                      else {
 -                              float tvec[3];
 -                              float sco[2];
 -                              const float mval_f[2] = {1.0f, 0.0f};
 -                              const float co_zero[3] = {0};
 -                              float zfac;
 -
 -                              /* calc window coord */
 -                              zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
 -                              ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
 -                              fac = max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
 -                              fac = 1.0f / fac;
 -
 -                              asp = (float)ibuf->y / (float)ibuf->x;
 -
 -                              zero_v3(tvec);
 -                              ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
 -
 -                              x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
 -                              y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
 -                              x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
 -                              y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
 -
 -                              centx = (x1 + x2) / 2.0f;
 -                              centy = (y1 + y2) / 2.0f;
 -                      }
  
 -                      /* complete clip? */
 -                      BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
 -                      if (bgpic->rotation) {
 -                              BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
 +                      /* draw X axis */
 +                      if (show_axis_x) {
 +                              show_axis_x = false; /* drawing now, won't need to draw later */
 +                              UI_make_axis_color(col_grid, col_axis, 'X');
 +                              immAttrib3ubv(color, col_axis);
                        }
 +                      else
 +                              immAttrib3ubv(color, col_grid_emphasise);
  
 -                      if (clip_rect.xmax < 0 || clip_rect.ymax < 0 || clip_rect.xmin > ar->winx || clip_rect.ymin > ar->winy) {
 -                              if (freeibuf)
 -                                      IMB_freeImBuf(freeibuf);
 -                              if (releaseibuf)
 -                                      BKE_image_release_ibuf(ima, releaseibuf, lock);
 +                      immVertex2f(pos, -grid, 0.0f);
 +                      immVertex2f(pos, +grid, 0.0f);
  
 -                              continue;
 +                      /* draw Y axis */
 +                      if (show_axis_y) {
 +                              show_axis_y = false; /* drawing now, won't need to draw later */
 +                              UI_make_axis_color(col_grid, col_axis, 'Y');
 +                              immAttrib3ubv(color, col_axis);
                        }
 +                      else
 +                              immAttrib3ubv(color, col_grid_emphasise);
  
 -                      zoomx = (x2 - x1) / ibuf->x;
 -                      zoomy = (y2 - y1) / ibuf->y;
 +                      immVertex2f(pos, 0.0f, -grid);
 +                      immVertex2f(pos, 0.0f, +grid);
  
 -                      /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
 -                      if (zoomx < 1.0f || zoomy < 1.0f) {
 -                              float tzoom = min_ff(zoomx, zoomy);
 -                              int mip = 0;
 +                      immEnd();
 +                      immUnbindProgram();
  
 -                              if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
 -                                      IMB_remakemipmap(ibuf, 0);
 -                                      ibuf->userflags &= ~IB_MIPMAP_INVALID;
 -                              }
 -                              else if (ibuf->mipmap[0] == NULL)
 -                                      IMB_makemipmap(ibuf, 0);
 -
 -                              while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
 -                                      tzoom *= 2.0f;
 -                                      zoomx *= 2.0f;
 -                                      zoomy *= 2.0f;
 -                                      mip++;
 -                              }
 -                              if (mip > 0)
 -                                      ibuf = ibuf->mipmap[mip - 1];
 -                      }
 -
 -                      if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
 -                      glDepthMask(0);
 +                      /* done with XY plane */
 +              }
  
 -                      glEnable(GL_BLEND);
 -                      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
 +              if (show_axis_x || show_axis_y || show_axis_z) {
 +                      /* draw axis lines -- sometimes grid floor is off, other times we still need to draw the Z axis */
  
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      ED_region_pixelspace(ar);
 +                      Gwn_VertFormat *format = immVertexFormat();
 +                      unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT);
 +                      unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
  
 -                      glTranslatef(centx, centy, 0.0);
 -                      glRotatef(RAD2DEGF(-bgpic->rotation), 0.0f, 0.0f, 1.0f);
 +                      immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
 +                      immBegin(GWN_PRIM_LINES, (show_axis_x + show_axis_y + show_axis_z) * 2);
  
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_X) {
 -                              zoomx *= -1.0f;
 -                              x1 = x2;
 +                      if (show_axis_x) {
 +                              UI_make_axis_color(col_grid, col_axis, 'X');
 +                              immAttrib3ubv(color, col_axis);
 +                              immVertex3f(pos, -grid, 0.0f, 0.0f);
 +                              immVertex3f(pos, +grid, 0.0f, 0.0f);
                        }
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
 -                              zoomy *= -1.0f;
 -                              y1 = y2;
 -                      }
 -                      glPixelZoom(zoomx, zoomy);
 -                      glColor4f(1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend);
 -
 -                      /* could not use glaDrawPixelsAuto because it could fallback to
 -                       * glaDrawPixelsSafe in some cases, which will end up in missing
 -                       * alpha transparency for the background image (sergey)
 -                       */
 -                      glaDrawPixelsTex(x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect);
  
 -                      glPixelZoom(1.0, 1.0);
 -                      glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
 -
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 -
 -                      glDisable(GL_BLEND);
 +                      if (show_axis_y) {
 +                              UI_make_axis_color(col_grid, col_axis, 'Y');
 +                              immAttrib3ubv(color, col_axis);
 +                              immVertex3f(pos, 0.0f, -grid, 0.0f);
 +                              immVertex3f(pos, 0.0f, +grid, 0.0f);
 +                      }
  
 -                      glDepthMask(1);
 -                      if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 +                      if (show_axis_z) {
 +                              UI_make_axis_color(col_grid, col_axis, 'Z');
 +                              immAttrib3ubv(color, col_axis);
 +                              immVertex3f(pos, 0.0f, 0.0f, -grid);
 +                              immVertex3f(pos, 0.0f, 0.0f, +grid);
 +                      }
  
 -                      if (freeibuf)
 -                              IMB_freeImBuf(freeibuf);
 -                      if (releaseibuf)
 -                              BKE_image_release_ibuf(ima, releaseibuf, lock);
 +                      immEnd();
 +                      immUnbindProgram();
                }
 +
 +              if (!write_depth)
 +                      glDepthMask(GL_TRUE);
        }
  }
  
index df2e5315c3952c8189bf3bc56c66601348ea0300,b1ccb508e508ccc64044ac9a9132073c0129c9ce..1e4e4dbc177ea722282d3b4a7316faaee75a3133
@@@ -276,8 -247,8 +276,12 @@@ void ED_view3d_smooth_view_force_finish
          struct bContext *C,
          struct View3D *v3d, struct ARegion *ar);
  
- void view3d_winmatrix_set(const struct Depsgraph *depsgraph, ARegion *ar, const View3D *v3d, const rcti *rect);
- void view3d_viewmatrix_set(const struct EvaluationContext *eval_ctx, Scene *scene, const View3D *v3d, RegionView3D *rv3d);
 -void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rcti *rect);
 -void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2]);
++void view3d_winmatrix_set(
++        const struct Depsgraph *depsgraph,
++        ARegion *ar, const View3D *v3d, const rcti *rect);
++void view3d_viewmatrix_set(
++        const struct EvaluationContext *eval_ctx, Scene *scene,
++        const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2]);
  
  void fly_modal_keymap(struct wmKeyConfig *keyconf);
  void walk_modal_keymap(struct wmKeyConfig *keyconf);
index 1d984ad9f4b3172fc3cbaaf1dcc0db8f9275f931,36ef4508058666c6966c0b17aaadc02dac0f74b2..c555358f4c30e0441e796a804f33fbe42f89ebc7
@@@ -1113,8 -1117,18 +1113,21 @@@ bool ED_view3d_lock(RegionView3D *rv3d
        return ED_view3d_quat_from_axis_view(rv3d->view, rv3d->viewquat);
  }
  
- /* don't set windows active in here, is used by renderwin too */
- void view3d_viewmatrix_set(const EvaluationContext *eval_ctx, Scene *scene, const View3D *v3d, RegionView3D *rv3d)
+ /**
+  * Sets #RegionView3D.viewmat
+  *
++ * \param eval_ctx: Context.
+  * \param scene: Scene for camera and cursor location.
+  * \param v3d: View 3D space data.
+  * \param rv3d: 3D region which stores the final matrices.
+  * \param rect_scale: Optional 2D scale argument,
+  * Use when displaying a sub-region, eg: when #view3d_winmatrix_set takes a 'rect' argument.
+  *
+  * \note don't set windows active in here, is used by renderwin too.
 - * */
 -void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2])
++ */
++void view3d_viewmatrix_set(
++        const EvaluationContext *eval_ctx, Scene *scene,
++        const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2])
  {
        if (rv3d->persp == RV3D_CAMOB) {      /* obs/camera */
                if (v3d->camera) {