Merge branch 'master' into blender2.8
authorBastien Montagne <montagne29@wanadoo.fr>
Mon, 25 Jun 2018 10:50:32 +0000 (12:50 +0200)
committerBastien Montagne <montagne29@wanadoo.fr>
Mon, 25 Jun 2018 10:50:32 +0000 (12:50 +0200)
Conflicts:
source/blender/editors/sculpt_paint/paint_image.c
source/blender/editors/space_view3d/view3d_draw.c
source/blender/editors/space_view3d/view3d_view.c
source/blender/gpu/GPU_draw.h
source/blender/gpu/GPU_material.h
source/blender/gpu/intern/gpu_draw.c
source/blender/gpu/intern/gpu_material.c
source/blender/makesrna/intern/rna_userdef.c
source/blender/windowmanager/intern/wm_files_link.c
source/blender/windowmanager/intern/wm_init_exit.c
source/creator/creator_args.c
source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
source/gameengine/Ketsji/KX_PythonInit.cpp
source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp

14 files changed:
1  2 
source/blender/draw/intern/draw_manager.c
source/blender/editors/sculpt_paint/paint_image.c
source/blender/editors/space_outliner/outliner_edit.c
source/blender/editors/space_view3d/view3d_draw.c
source/blender/gpu/GPU_draw.h
source/blender/gpu/GPU_material.h
source/blender/gpu/intern/gpu_draw.c
source/blender/gpu/intern/gpu_material.c
source/blender/makesrna/intern/rna_userdef.c
source/blender/nodes/composite/node_composite_tree.c
source/blender/nodes/intern/node_exec.c
source/blender/windowmanager/WM_api.h
source/blender/windowmanager/intern/wm_draw.c
source/blender/windowmanager/intern/wm_init_exit.c

index 7a6771ae058a000c1662a70dbdd37da65cc6a12d,0000000000000000000000000000000000000000..002333e5d3436b7dc5d31054b9a87962f268ccd0
mode 100644,000000..100644
--- /dev/null
@@@ -1,2239 -1,0 +1,2239 @@@
-               WM_init_opengl();
 +/*
 + * Copyright 2016, Blender Foundation.
 + *
 + * This program is free software; you can redistribute it and/or
 + * modify it under the terms of the GNU General Public License
 + * as published by the Free Software Foundation; either version 2
 + * of the License, or (at your option) any later version.
 + *
 + * This program is distributed in the hope that it will be useful,
 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 + * GNU General Public License for more details.
 + *
 + * You should have received a copy of the GNU General Public License
 + * along with this program; if not, write to the Free Software Foundation,
 + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 + *
 + * Contributor(s): Blender Institute
 + *
 + */
 +
 +/** \file blender/draw/intern/draw_manager.c
 + *  \ingroup draw
 + */
 +
 +#include <stdio.h>
 +
 +#include "BLI_listbase.h"
 +#include "BLI_mempool.h"
 +#include "BLI_rect.h"
 +#include "BLI_string.h"
 +#include "BLI_threads.h"
 +
 +#include "BLF_api.h"
 +
 +#include "BKE_global.h"
 +#include "BKE_mesh.h"
 +#include "BKE_object.h"
 +#include "BKE_particle.h"
 +#include "BKE_pointcache.h"
 +#include "BKE_workspace.h"
 +
 +#include "draw_manager.h"
 +#include "DNA_camera_types.h"
 +#include "DNA_mesh_types.h"
 +#include "DNA_meshdata_types.h"
 +
 +#include "ED_space_api.h"
 +#include "ED_screen.h"
 +#include "ED_particle.h"
 +#include "ED_view3d.h"
 +
 +#include "GPU_draw.h"
 +#include "GPU_extensions.h"
 +#include "GPU_framebuffer.h"
 +#include "GPU_immediate.h"
 +#include "GPU_uniformbuffer.h"
 +#include "GPU_viewport.h"
 +#include "GPU_matrix.h"
 +
 +#include "IMB_colormanagement.h"
 +
 +#include "RE_engine.h"
 +#include "RE_pipeline.h"
 +
 +#include "UI_interface.h"
 +#include "UI_resources.h"
 +
 +#include "WM_api.h"
 +#include "wm_window.h"
 +
 +#include "draw_manager_text.h"
 +#include "draw_manager_profiling.h"
 +
 +/* only for callbacks */
 +#include "draw_cache_impl.h"
 +
 +#include "draw_mode_engines.h"
 +#include "engines/eevee/eevee_engine.h"
 +#include "engines/basic/basic_engine.h"
 +#include "engines/workbench/workbench_engine.h"
 +#include "engines/external/external_engine.h"
 +
 +#include "../../../intern/gawain/gawain/gwn_context.h"
 +
 +#include "DEG_depsgraph.h"
 +#include "DEG_depsgraph_query.h"
 +
 +#ifdef USE_GPU_SELECT
 +#  include "GPU_select.h"
 +#endif
 +
 +/** Render State: No persistent data between draw calls. */
 +DRWManager DST = {NULL};
 +
 +ListBase DRW_engines = {NULL, NULL};
 +
 +extern struct GPUUniformBuffer *view_ubo; /* draw_manager_exec.c */
 +
 +static void drw_state_prepare_clean_for_draw(DRWManager *dst)
 +{
 +      memset(dst, 0x0, offsetof(DRWManager, gl_context));
 +}
 +
 +/* This function is used to reset draw manager to a state
 + * where we don't re-use data by accident across different
 + * draw calls.
 + */
 +#ifdef DEBUG
 +static void drw_state_ensure_not_reused(DRWManager *dst)
 +{
 +      memset(dst, 0xff, offsetof(DRWManager, gl_context));
 +}
 +#endif
 +
 +/* -------------------------------------------------------------------- */
 +
 +void DRW_draw_callbacks_pre_scene(void)
 +{
 +      RegionView3D *rv3d = DST.draw_ctx.rv3d;
 +
 +      gpuLoadProjectionMatrix(rv3d->winmat);
 +      gpuLoadMatrix(rv3d->viewmat);
 +}
 +
 +void DRW_draw_callbacks_post_scene(void)
 +{
 +      RegionView3D *rv3d = DST.draw_ctx.rv3d;
 +
 +      gpuLoadProjectionMatrix(rv3d->winmat);
 +      gpuLoadMatrix(rv3d->viewmat);
 +}
 +
 +struct DRWTextStore *DRW_text_cache_ensure(void)
 +{
 +      BLI_assert(DST.text_store_p);
 +      if (*DST.text_store_p == NULL) {
 +              *DST.text_store_p = DRW_text_cache_create();
 +      }
 +      return *DST.text_store_p;
 +}
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Settings
 + * \{ */
 +
 +bool DRW_object_is_renderable(Object *ob)
 +{
 +      BLI_assert(BKE_object_is_visible(ob, OB_VISIBILITY_CHECK_UNKNOWN_RENDER_MODE));
 +
 +      if (ob->type == OB_MESH) {
 +              if ((ob == DST.draw_ctx.object_edit) || BKE_object_is_in_editmode(ob)) {
 +                      View3D *v3d = DST.draw_ctx.v3d;
 +                      const int mask = (V3D_OVERLAY_EDIT_OCCLUDE_WIRE | V3D_OVERLAY_EDIT_WEIGHT);
 +
 +                      if (v3d && v3d->overlay.edit_flag & mask) {
 +                              return false;
 +                      }
 +              }
 +      }
 +
 +      return true;
 +}
 +
 +/**
 + * Return whether this object is visible depending if
 + * we are rendering or drawing in the viewport.
 + */
 +bool DRW_check_object_visible_within_active_context(Object *ob)
 +{
 +      const eObjectVisibilityCheck mode = DRW_state_is_scene_render() ?
 +                                           OB_VISIBILITY_CHECK_FOR_RENDER :
 +                                           OB_VISIBILITY_CHECK_FOR_VIEWPORT;
 +      return BKE_object_is_visible(ob, mode);
 +}
 +
 +bool DRW_object_is_flat_normal(const Object *ob)
 +{
 +      if (ob->type == OB_MESH) {
 +              const Mesh *me = ob->data;
 +              if (me->mpoly && me->mpoly[0].flag & ME_SMOOTH) {
 +                      return false;
 +              }
 +      }
 +      return true;
 +}
 +
 +bool DRW_check_psys_visible_within_active_context(
 +        Object *object,
 +        struct ParticleSystem *psys)
 +{
 +      const DRWContextState *draw_ctx = DRW_context_state_get();
 +      const Scene *scene = draw_ctx->scene;
 +      if (object == draw_ctx->object_edit) {
 +              return false;
 +      }
 +      const ParticleSettings *part = psys->part;
 +      const ParticleEditSettings *pset = &scene->toolsettings->particle;
 +      if (object->mode == OB_MODE_PARTICLE_EDIT) {
 +              if (psys_in_edit_mode(draw_ctx->depsgraph, psys)) {
 +                      if ((pset->flag & PE_DRAW_PART) == 0) {
 +                              return false;
 +                      }
 +                      if ((part->childtype == 0) &&
 +                          (psys->flag & PSYS_HAIR_DYNAMICS &&
 +                           psys->pointcache->flag & PTCACHE_BAKED) == 0)
 +                      {
 +                              return false;
 +                      }
 +              }
 +      }
 +      return true;
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Color Management
 + * \{ */
 +
 +/* Use color management profile to draw texture to framebuffer */
 +void DRW_transform_to_display(GPUTexture *tex)
 +{
 +      drw_state_set(DRW_STATE_WRITE_COLOR);
 +
 +      Gwn_VertFormat *vert_format = immVertexFormat();
 +      uint pos = GWN_vertformat_attr_add(vert_format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +      uint texco = GWN_vertformat_attr_add(vert_format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +
 +      const float dither = 1.0f;
 +
 +      bool use_ocio = false;
 +
 +      /* View transform is already applied for offscreen, don't apply again, see: T52046 */
 +      if (!(DST.options.is_image_render && !DST.options.is_scene_render)) {
 +              Scene *scene = DST.draw_ctx.scene;
 +              use_ocio = IMB_colormanagement_setup_glsl_draw_from_space(
 +                      &scene->view_settings, &scene->display_settings, NULL, dither, false);
 +      }
 +
 +      if (!use_ocio) {
 +              /* View transform is already applied for offscreen, don't apply again, see: T52046 */
 +              if (DST.options.is_image_render && !DST.options.is_scene_render) {
 +                      immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_COLOR);
 +                      immUniformColor4f(1.0f, 1.0f, 1.0f, 1.0f);
 +              }
 +              else {
 +                      immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_LINEAR_TO_SRGB);
 +              }
 +              immUniform1i("image", 0);
 +      }
 +
 +      GPU_texture_bind(tex, 0); /* OCIO texture bind point is 0 */
 +
 +      float mat[4][4];
 +      unit_m4(mat);
 +      immUniformMatrix4fv("ModelViewProjectionMatrix", mat);
 +
 +      /* Full screen triangle */
 +      immBegin(GWN_PRIM_TRIS, 3);
 +      immAttrib2f(texco, 0.0f, 0.0f);
 +      immVertex2f(pos, -1.0f, -1.0f);
 +
 +      immAttrib2f(texco, 2.0f, 0.0f);
 +      immVertex2f(pos, 3.0f, -1.0f);
 +
 +      immAttrib2f(texco, 0.0f, 2.0f);
 +      immVertex2f(pos, -1.0f, 3.0f);
 +      immEnd();
 +
 +      GPU_texture_unbind(tex);
 +
 +      if (use_ocio) {
 +              IMB_colormanagement_finish_glsl_draw();
 +      }
 +      else {
 +              immUnbindProgram();
 +      }
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Multisample Resolve
 + * \{ */
 +
 +/* Use manual multisample resolve pass.
 + * Much quicker than blitting back and forth.
 + * Assume destination fb is bound*/
 +void DRW_multisamples_resolve(GPUTexture *src_depth, GPUTexture *src_color)
 +{
 +      drw_state_set(DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND_PREMUL |
 +                    DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL);
 +
 +      int samples = GPU_texture_samples(src_depth);
 +
 +      BLI_assert(samples > 0);
 +      BLI_assert(GPU_texture_samples(src_color) == samples);
 +
 +      Gwn_Batch *geom = DRW_cache_fullscreen_quad_get();
 +
 +      int builtin;
 +      switch (samples) {
 +              case 2:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2; break;
 +              case 4:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_4; break;
 +              case 8:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_8; break;
 +              case 16: builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_16; break;
 +              default:
 +                      BLI_assert(0);
 +                      builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2;
 +                      break;
 +      }
 +
 +      GWN_batch_program_set_builtin(geom, builtin);
 +
 +      GPU_texture_bind(src_depth, 0);
 +      GPU_texture_bind(src_color, 1);
 +      GWN_batch_uniform_1i(geom, "depthMulti", 0);
 +      GWN_batch_uniform_1i(geom, "colorMulti", 1);
 +
 +      float mat[4][4];
 +      unit_m4(mat);
 +      GWN_batch_uniform_mat4(geom, "ModelViewProjectionMatrix", mat);
 +
 +      /* avoid gpuMatrix calls */
 +      GWN_batch_program_use_begin(geom);
 +      GWN_batch_draw_range_ex(geom, 0, 0, false);
 +      GWN_batch_program_use_end(geom);
 +}
 +
 +/** \} */
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Viewport (DRW_viewport)
 + * \{ */
 +
 +void *drw_viewport_engine_data_ensure(void *engine_type)
 +{
 +      void *data = GPU_viewport_engine_data_get(DST.viewport, engine_type);
 +
 +      if (data == NULL) {
 +              data = GPU_viewport_engine_data_create(DST.viewport, engine_type);
 +      }
 +      return data;
 +}
 +
 +void DRW_engine_viewport_data_size_get(
 +        const void *engine_type_v,
 +        int *r_fbl_len, int *r_txl_len, int *r_psl_len, int *r_stl_len)
 +{
 +      const DrawEngineType *engine_type = engine_type_v;
 +
 +      if (r_fbl_len) {
 +              *r_fbl_len = engine_type->vedata_size->fbl_len;
 +      }
 +      if (r_txl_len) {
 +              *r_txl_len = engine_type->vedata_size->txl_len;
 +      }
 +      if (r_psl_len) {
 +              *r_psl_len = engine_type->vedata_size->psl_len;
 +      }
 +      if (r_stl_len) {
 +              *r_stl_len = engine_type->vedata_size->stl_len;
 +      }
 +}
 +
 +const float *DRW_viewport_size_get(void)
 +{
 +      return DST.size;
 +}
 +
 +const float *DRW_viewport_invert_size_get(void)
 +{
 +      return DST.inv_size;
 +}
 +
 +const float *DRW_viewport_screenvecs_get(void)
 +{
 +      return &DST.screenvecs[0][0];
 +}
 +
 +const float *DRW_viewport_pixelsize_get(void)
 +{
 +      return &DST.pixsize;
 +}
 +
 +static void drw_viewport_cache_resize(void)
 +{
 +      /* Release the memiter before clearing the mempools that references them */
 +      GPU_viewport_cache_release(DST.viewport);
 +
 +      if (DST.vmempool != NULL) {
 +              BLI_mempool_clear_ex(DST.vmempool->calls, BLI_mempool_len(DST.vmempool->calls));
 +              BLI_mempool_clear_ex(DST.vmempool->states, BLI_mempool_len(DST.vmempool->states));
 +              BLI_mempool_clear_ex(DST.vmempool->shgroups, BLI_mempool_len(DST.vmempool->shgroups));
 +              BLI_mempool_clear_ex(DST.vmempool->uniforms, BLI_mempool_len(DST.vmempool->uniforms));
 +              BLI_mempool_clear_ex(DST.vmempool->passes, BLI_mempool_len(DST.vmempool->passes));
 +      }
 +
 +      DRW_instance_data_list_free_unused(DST.idatalist);
 +      DRW_instance_data_list_resize(DST.idatalist);
 +}
 +
 +/* Not a viewport variable, we could split this out. */
 +static void drw_context_state_init(void)
 +{
 +      if (DST.draw_ctx.obact) {
 +              DST.draw_ctx.object_mode = DST.draw_ctx.obact->mode;
 +      }
 +      else {
 +              DST.draw_ctx.object_mode = OB_MODE_OBJECT;
 +      }
 +
 +      /* Edit object. */
 +      if (DST.draw_ctx.object_mode & OB_MODE_EDIT) {
 +              DST.draw_ctx.object_edit = DST.draw_ctx.obact;
 +      }
 +      else {
 +              DST.draw_ctx.object_edit = NULL;
 +      }
 +
 +      /* Pose object. */
 +      if (DST.draw_ctx.object_mode & OB_MODE_POSE) {
 +              DST.draw_ctx.object_pose = DST.draw_ctx.obact;
 +      }
 +      else if (DST.draw_ctx.object_mode & OB_MODE_WEIGHT_PAINT) {
 +              DST.draw_ctx.object_pose = BKE_object_pose_armature_get(DST.draw_ctx.obact);
 +      }
 +      else {
 +              DST.draw_ctx.object_pose = NULL;
 +      }
 +}
 +
 +/* It also stores viewport variable to an immutable place: DST
 + * This is because a cache uniform only store reference
 + * to its value. And we don't want to invalidate the cache
 + * if this value change per viewport */
 +static void drw_viewport_var_init(void)
 +{
 +      RegionView3D *rv3d = DST.draw_ctx.rv3d;
 +      /* Refresh DST.size */
 +      if (DST.viewport) {
 +              int size[2];
 +              GPU_viewport_size_get(DST.viewport, size);
 +              DST.size[0] = size[0];
 +              DST.size[1] = size[1];
 +              DST.inv_size[0] = 1.0f / size[0];
 +              DST.inv_size[1] = 1.0f / size[1];
 +
 +              DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
 +              DST.default_framebuffer = fbl->default_fb;
 +
 +              DST.vmempool = GPU_viewport_mempool_get(DST.viewport);
 +
 +              if (DST.vmempool->calls == NULL) {
 +                      DST.vmempool->calls = BLI_mempool_create(sizeof(DRWCall), 0, 512, 0);
 +              }
 +              if (DST.vmempool->states == NULL) {
 +                      DST.vmempool->states = BLI_mempool_create(sizeof(DRWCallState), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
 +              }
 +              if (DST.vmempool->shgroups == NULL) {
 +                      DST.vmempool->shgroups = BLI_mempool_create(sizeof(DRWShadingGroup), 0, 256, 0);
 +              }
 +              if (DST.vmempool->uniforms == NULL) {
 +                      DST.vmempool->uniforms = BLI_mempool_create(sizeof(DRWUniform), 0, 512, 0);
 +              }
 +              if (DST.vmempool->passes == NULL) {
 +                      DST.vmempool->passes = BLI_mempool_create(sizeof(DRWPass), 0, 64, 0);
 +              }
 +
 +              DST.idatalist = GPU_viewport_instance_data_list_get(DST.viewport);
 +              DRW_instance_data_list_reset(DST.idatalist);
 +      }
 +      else {
 +              DST.size[0] = 0;
 +              DST.size[1] = 0;
 +
 +              DST.inv_size[0] = 0;
 +              DST.inv_size[1] = 0;
 +
 +              DST.default_framebuffer = NULL;
 +              DST.vmempool = NULL;
 +      }
 +
 +      if (rv3d != NULL) {
 +              /* Refresh DST.screenvecs */
 +              copy_v3_v3(DST.screenvecs[0], rv3d->viewinv[0]);
 +              copy_v3_v3(DST.screenvecs[1], rv3d->viewinv[1]);
 +              normalize_v3(DST.screenvecs[0]);
 +              normalize_v3(DST.screenvecs[1]);
 +
 +              /* Refresh DST.pixelsize */
 +              DST.pixsize = rv3d->pixsize;
 +
 +              copy_m4_m4(DST.original_mat.mat[DRW_MAT_PERS], rv3d->persmat);
 +              copy_m4_m4(DST.original_mat.mat[DRW_MAT_PERSINV], rv3d->persinv);
 +              copy_m4_m4(DST.original_mat.mat[DRW_MAT_VIEW], rv3d->viewmat);
 +              copy_m4_m4(DST.original_mat.mat[DRW_MAT_VIEWINV], rv3d->viewinv);
 +              copy_m4_m4(DST.original_mat.mat[DRW_MAT_WIN], rv3d->winmat);
 +              invert_m4_m4(DST.original_mat.mat[DRW_MAT_WININV], rv3d->winmat);
 +
 +              memcpy(DST.view_data.matstate.mat, DST.original_mat.mat, sizeof(DST.original_mat.mat));
 +
 +              copy_v4_v4(DST.view_data.viewcamtexcofac, rv3d->viewcamtexcofac);
 +      }
 +      else {
 +              copy_v4_fl4(DST.view_data.viewcamtexcofac, 1.0f, 1.0f, 0.0f, 0.0f);
 +      }
 +
 +      /* Reset facing */
 +      DST.frontface = GL_CCW;
 +      DST.backface = GL_CW;
 +      glFrontFace(DST.frontface);
 +
 +      if (DST.draw_ctx.object_edit) {
 +              ED_view3d_init_mats_rv3d(DST.draw_ctx.object_edit, rv3d);
 +      }
 +
 +      /* Alloc array of texture reference. */
 +      if (DST.RST.bound_texs == NULL) {
 +              DST.RST.bound_texs = MEM_callocN(sizeof(GPUTexture *) * GPU_max_textures(), "Bound GPUTexture refs");
 +      }
 +      if (DST.RST.bound_tex_slots == NULL) {
 +              DST.RST.bound_tex_slots = MEM_callocN(sizeof(char) * GPU_max_textures(), "Bound Texture Slots");
 +      }
 +      if (DST.RST.bound_ubos == NULL) {
 +              DST.RST.bound_ubos = MEM_callocN(sizeof(GPUUniformBuffer *) * GPU_max_ubo_binds(), "Bound GPUUniformBuffer refs");
 +      }
 +      if (DST.RST.bound_ubo_slots == NULL) {
 +              DST.RST.bound_ubo_slots = MEM_callocN(sizeof(char) * GPU_max_ubo_binds(), "Bound Ubo Slots");
 +      }
 +
 +      if (view_ubo == NULL) {
 +              view_ubo = DRW_uniformbuffer_create(sizeof(ViewUboStorage), NULL);
 +      }
 +
 +      DST.override_mat = 0;
 +      DST.dirty_mat = true;
 +      DST.state_cache_id = 1;
 +
 +      DST.clipping.updated = false;
 +
 +      memset(DST.object_instance_data, 0x0, sizeof(DST.object_instance_data));
 +}
 +
 +void DRW_viewport_matrix_get(float mat[4][4], DRWViewportMatrixType type)
 +{
 +      BLI_assert(type >= 0 && type < DRW_MAT_COUNT);
 +      /* Can't use this in render mode. */
 +      BLI_assert(((DST.override_mat & (1 << type)) != 0) || DST.draw_ctx.rv3d != NULL);
 +
 +      copy_m4_m4(mat, DST.view_data.matstate.mat[type]);
 +}
 +
 +void DRW_viewport_matrix_get_all(DRWMatrixState *state)
 +{
 +      memcpy(state, DST.view_data.matstate.mat, sizeof(DRWMatrixState));
 +}
 +
 +void DRW_viewport_matrix_override_set(const float mat[4][4], DRWViewportMatrixType type)
 +{
 +      BLI_assert(type < DRW_MAT_COUNT);
 +      copy_m4_m4(DST.view_data.matstate.mat[type], mat);
 +      DST.override_mat |= (1 << type);
 +      DST.dirty_mat = true;
 +      DST.clipping.updated = false;
 +}
 +
 +void DRW_viewport_matrix_override_unset(DRWViewportMatrixType type)
 +{
 +      BLI_assert(type < DRW_MAT_COUNT);
 +      copy_m4_m4(DST.view_data.matstate.mat[type], DST.original_mat.mat[type]);
 +      DST.override_mat &= ~(1 << type);
 +      DST.dirty_mat = true;
 +      DST.clipping.updated = false;
 +}
 +
 +void DRW_viewport_matrix_override_set_all(DRWMatrixState *state)
 +{
 +      memcpy(DST.view_data.matstate.mat, state, sizeof(DRWMatrixState));
 +      DST.override_mat = 0xFFFFFF;
 +      DST.dirty_mat = true;
 +      DST.clipping.updated = false;
 +}
 +
 +void DRW_viewport_matrix_override_unset_all(void)
 +{
 +      memcpy(DST.view_data.matstate.mat, DST.original_mat.mat, sizeof(DRWMatrixState));
 +      DST.override_mat = 0;
 +      DST.dirty_mat = true;
 +      DST.clipping.updated = false;
 +}
 +
 +bool DRW_viewport_is_persp_get(void)
 +{
 +      RegionView3D *rv3d = DST.draw_ctx.rv3d;
 +      if (rv3d) {
 +              return rv3d->is_persp;
 +      }
 +      else {
 +              return DST.view_data.matstate.mat[DRW_MAT_WIN][3][3] == 0.0f;
 +      }
 +}
 +
 +float DRW_viewport_near_distance_get(void)
 +{
 +      float projmat[4][4];
 +      DRW_viewport_matrix_get(projmat, DRW_MAT_WIN);
 +
 +      if (DRW_viewport_is_persp_get()) {
 +              return -projmat[3][2] / (projmat[2][2] - 1.0f);
 +      }
 +      else {
 +              return -(projmat[3][2] + 1.0f) / projmat[2][2];
 +      }
 +}
 +
 +float DRW_viewport_far_distance_get(void)
 +{
 +      float projmat[4][4];
 +      DRW_viewport_matrix_get(projmat, DRW_MAT_WIN);
 +
 +      if (DRW_viewport_is_persp_get()) {
 +              return -projmat[3][2] / (projmat[2][2] + 1.0f);
 +      }
 +      else {
 +              return -(projmat[3][2] - 1.0f) / projmat[2][2];
 +      }
 +}
 +
 +DefaultFramebufferList *DRW_viewport_framebuffer_list_get(void)
 +{
 +      return GPU_viewport_framebuffer_list_get(DST.viewport);
 +}
 +
 +DefaultTextureList *DRW_viewport_texture_list_get(void)
 +{
 +      return GPU_viewport_texture_list_get(DST.viewport);
 +}
 +
 +void DRW_viewport_request_redraw(void)
 +{
 +      GPU_viewport_tag_update(DST.viewport);
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +/** \name ViewLayers (DRW_scenelayer)
 + * \{ */
 +
 +void *DRW_view_layer_engine_data_get(DrawEngineType *engine_type)
 +{
 +      for (ViewLayerEngineData *sled = DST.draw_ctx.view_layer->drawdata.first; sled; sled = sled->next) {
 +              if (sled->engine_type == engine_type) {
 +                      return sled->storage;
 +              }
 +      }
 +      return NULL;
 +}
 +
 +void **DRW_view_layer_engine_data_ensure_ex(
 +        ViewLayer *view_layer, DrawEngineType *engine_type, void (*callback)(void *storage))
 +{
 +      ViewLayerEngineData *sled;
 +
 +      for (sled = view_layer->drawdata.first; sled; sled = sled->next) {
 +              if (sled->engine_type == engine_type) {
 +                      return &sled->storage;
 +              }
 +      }
 +
 +      sled = MEM_callocN(sizeof(ViewLayerEngineData), "ViewLayerEngineData");
 +      sled->engine_type = engine_type;
 +      sled->free = callback;
 +      BLI_addtail(&view_layer->drawdata, sled);
 +
 +      return &sled->storage;
 +}
 +
 +void **DRW_view_layer_engine_data_ensure(DrawEngineType *engine_type, void (*callback)(void *storage))
 +{
 +      return DRW_view_layer_engine_data_ensure_ex(DST.draw_ctx.view_layer, engine_type, callback);
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Objects (DRW_object)
 + * \{ */
 +
 +ObjectEngineData *DRW_object_engine_data_get(Object *ob, DrawEngineType *engine_type)
 +{
 +      for (ObjectEngineData *oed = ob->drawdata.first; oed; oed = oed->next) {
 +              if (oed->engine_type == engine_type) {
 +                      return oed;
 +              }
 +      }
 +      return NULL;
 +}
 +
 +ObjectEngineData *DRW_object_engine_data_ensure(
 +        Object *ob,
 +        DrawEngineType *engine_type,
 +        size_t size,
 +        ObjectEngineDataInitCb init_cb,
 +        ObjectEngineDataFreeCb free_cb)
 +{
 +      BLI_assert(size >= sizeof(ObjectEngineData));
 +      /* Try to re-use existing data. */
 +      ObjectEngineData *oed = DRW_object_engine_data_get(ob, engine_type);
 +      if (oed != NULL) {
 +              return oed;
 +      }
 +      /* Allocate new data. */
 +      if ((ob->base_flag & BASE_FROMDUPLI) != 0) {
 +              /* NOTE: data is not persistent in this case. It is reset each redraw. */
 +              BLI_assert(free_cb == NULL); /* No callback allowed. */
 +              /* Round to sizeof(float) for DRW_instance_data_request(). */
 +              const size_t t = sizeof(float) - 1;
 +              size = (size + t) & ~t;
 +              size_t fsize = size / sizeof(float);
 +              BLI_assert(fsize < MAX_INSTANCE_DATA_SIZE);
 +              if (DST.object_instance_data[fsize] == NULL) {
 +                      DST.object_instance_data[fsize] = DRW_instance_data_request(DST.idatalist, fsize);
 +              }
 +              oed = (ObjectEngineData *)DRW_instance_data_next(DST.object_instance_data[fsize]);
 +              memset(oed, 0, size);
 +      }
 +      else {
 +              oed = MEM_callocN(size, "ObjectEngineData");
 +      }
 +      oed->engine_type = engine_type;
 +      oed->free = free_cb;
 +      /* Perform user-side initialization, if needed. */
 +      if (init_cb != NULL) {
 +              init_cb(oed);
 +      }
 +      /* Register in the list. */
 +      BLI_addtail(&ob->drawdata, oed);
 +      return oed;
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Rendering (DRW_engines)
 + * \{ */
 +
 +static void drw_engines_init(void)
 +{
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +              PROFILE_START(stime);
 +
 +              if (engine->engine_init) {
 +                      engine->engine_init(data);
 +              }
 +
 +              PROFILE_END_UPDATE(data->init_time, stime);
 +      }
 +}
 +
 +static void drw_engines_cache_init(void)
 +{
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +
 +              if (data->text_draw_cache) {
 +                      DRW_text_cache_destroy(data->text_draw_cache);
 +                      data->text_draw_cache = NULL;
 +              }
 +              if (DST.text_store_p == NULL) {
 +                      DST.text_store_p = &data->text_draw_cache;
 +              }
 +
 +              if (engine->cache_init) {
 +                      engine->cache_init(data);
 +              }
 +      }
 +}
 +
 +static void drw_engines_cache_populate(Object *ob)
 +{
 +      DST.ob_state = NULL;
 +
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +
 +              if (engine->id_update) {
 +                      engine->id_update(data, &ob->id);
 +              }
 +
 +              if (engine->cache_populate) {
 +                      engine->cache_populate(data, ob);
 +              }
 +      }
 +}
 +
 +static void drw_engines_cache_finish(void)
 +{
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +
 +              if (engine->cache_finish) {
 +                      engine->cache_finish(data);
 +              }
 +      }
 +}
 +
 +static void drw_engines_draw_background(void)
 +{
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +
 +              if (engine->draw_background) {
 +                      PROFILE_START(stime);
 +
 +                      DRW_stats_group_start(engine->idname);
 +                      engine->draw_background(data);
 +                      DRW_stats_group_end();
 +
 +                      PROFILE_END_UPDATE(data->background_time, stime);
 +                      return;
 +              }
 +      }
 +
 +      /* No draw_background found, doing default background */
 +      if (DRW_state_draw_background()) {
 +              DRW_draw_background();
 +      }
 +}
 +
 +static void drw_engines_draw_scene(void)
 +{
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +              PROFILE_START(stime);
 +
 +              if (engine->draw_scene) {
 +                      DRW_stats_group_start(engine->idname);
 +                      engine->draw_scene(data);
 +                      /* Restore for next engine */
 +                      if (DRW_state_is_fbo()) {
 +                              GPU_framebuffer_bind(DST.default_framebuffer);
 +                      }
 +                      DRW_stats_group_end();
 +              }
 +
 +              PROFILE_END_UPDATE(data->render_time, stime);
 +      }
 +}
 +
 +static void drw_engines_draw_text(void)
 +{
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +              PROFILE_START(stime);
 +
 +              if (data->text_draw_cache) {
 +                      DRW_text_cache_draw(data->text_draw_cache, DST.draw_ctx.v3d, DST.draw_ctx.ar, false);
 +              }
 +
 +              PROFILE_END_UPDATE(data->render_time, stime);
 +      }
 +}
 +
 +#define MAX_INFO_LINES 10
 +
 +/**
 + * Returns the offset required for the drawing of engines info.
 + */
 +int DRW_draw_region_engine_info_offset(void)
 +{
 +      int lines = 0;
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +
 +              /* Count the number of lines. */
 +              if (data->info[0] != '\0') {
 +                      lines++;
 +                      char *c = data->info;
 +                      while (*c++ != '\0') {
 +                              if (*c == '\n') {
 +                                      lines++;
 +                              }
 +                      }
 +              }
 +      }
 +      return MIN2(MAX_INFO_LINES, lines) * UI_UNIT_Y;
 +}
 +
 +/**
 + * Actual drawing;
 + */
 +void DRW_draw_region_engine_info(void)
 +{
 +      const char *info_array_final[MAX_INFO_LINES + 1];
 +      /* This should be maxium number of engines running at the same time. */
 +      char info_array[MAX_INFO_LINES][GPU_INFO_SIZE];
 +      int i = 0;
 +
 +      const DRWContextState *draw_ctx = DRW_context_state_get();
 +      ARegion *ar = draw_ctx->ar;
 +      float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
 +
 +      UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
 +      mul_v3_fl(fill_color, fill_color[3]);
 +
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
 +
 +              if (data->info[0] != '\0') {
 +                      char *chr_current = data->info;
 +                      char *chr_start = chr_current;
 +                      int line_len = 0;
 +
 +                      while (*chr_current++ != '\0') {
 +                              line_len++;
 +                              if (*chr_current == '\n') {
 +                                      BLI_strncpy(info_array[i++], chr_start, line_len + 1);
 +                                      /* Re-start counting. */
 +                                      chr_start = chr_current + 1;
 +                                      line_len = -1;
 +                              }
 +                      }
 +
 +                      BLI_strncpy(info_array[i++], chr_start, line_len + 1);
 +
 +                      if (i >= MAX_INFO_LINES) {
 +                              break;
 +                      }
 +              }
 +      }
 +
 +      for (int j = 0; j < i; j++) {
 +              info_array_final[j] = info_array[j];
 +      }
 +      info_array_final[i] = NULL;
 +
 +      if (info_array[0] != NULL) {
 +              ED_region_info_draw_multiline(ar, info_array_final, fill_color, true);
 +      }
 +}
 +
 +#undef MAX_INFO_LINES
 +
 +static void use_drw_engine(DrawEngineType *engine)
 +{
 +      LinkData *ld = MEM_callocN(sizeof(LinkData), "enabled engine link data");
 +      ld->data = engine;
 +      BLI_addtail(&DST.enabled_engines, ld);
 +}
 +
 +/**
 + * Use for external render engines.
 + */
 +static void drw_engines_enable_external(void)
 +{
 +      use_drw_engine(DRW_engine_viewport_external_type.draw_engine);
 +}
 +
 +/* TODO revisit this when proper layering is implemented */
 +/* Gather all draw engines needed and store them in DST.enabled_engines
 + * That also define the rendering order of engines */
 +static void drw_engines_enable_from_engine(RenderEngineType *engine_type, int drawtype, int shading_flags)
 +{
 +      switch (drawtype) {
 +              case OB_WIRE:
 +                      break;
 +
 +              case OB_SOLID:
 +                      if (shading_flags & V3D_SHADING_XRAY) {
 +                              use_drw_engine(&draw_engine_workbench_transparent);
 +                      }
 +                      else {
 +                              use_drw_engine(&draw_engine_workbench_solid);
 +                      }
 +                      break;
 +
 +              case OB_MATERIAL:
 +              case OB_RENDER:
 +              default:
 +                      /* TODO layers */
 +                      if (engine_type->draw_engine != NULL) {
 +                              use_drw_engine(engine_type->draw_engine);
 +                      }
 +
 +                      if ((engine_type->flag & RE_INTERNAL) == 0) {
 +                              drw_engines_enable_external();
 +                      }
 +                      break;
 +      }
 +}
 +
 +static void drw_engines_enable_from_object_mode(void)
 +{
 +      use_drw_engine(&draw_engine_object_type);
 +      /* TODO(fclem) remove this, it does not belong to it's own engine. */
 +      use_drw_engine(&draw_engine_motion_path_type);
 +}
 +
 +static void drw_engines_enable_from_mode(int mode)
 +{
 +      switch (mode) {
 +              case CTX_MODE_EDIT_MESH:
 +                      use_drw_engine(&draw_engine_edit_mesh_type);
 +                      break;
 +              case CTX_MODE_EDIT_CURVE:
 +                      use_drw_engine(&draw_engine_edit_curve_type);
 +                      break;
 +              case CTX_MODE_EDIT_SURFACE:
 +                      use_drw_engine(&draw_engine_edit_surface_type);
 +                      break;
 +              case CTX_MODE_EDIT_TEXT:
 +                      use_drw_engine(&draw_engine_edit_text_type);
 +                      break;
 +              case CTX_MODE_EDIT_ARMATURE:
 +                      use_drw_engine(&draw_engine_edit_armature_type);
 +                      break;
 +              case CTX_MODE_EDIT_METABALL:
 +                      use_drw_engine(&draw_engine_edit_metaball_type);
 +                      break;
 +              case CTX_MODE_EDIT_LATTICE:
 +                      use_drw_engine(&draw_engine_edit_lattice_type);
 +                      break;
 +              case CTX_MODE_POSE:
 +                      use_drw_engine(&draw_engine_pose_type);
 +                      break;
 +              case CTX_MODE_SCULPT:
 +                      use_drw_engine(&draw_engine_sculpt_type);
 +                      break;
 +              case CTX_MODE_PAINT_WEIGHT:
 +                      use_drw_engine(&draw_engine_pose_type);
 +                      use_drw_engine(&draw_engine_paint_weight_type);
 +                      break;
 +              case CTX_MODE_PAINT_VERTEX:
 +                      use_drw_engine(&draw_engine_paint_vertex_type);
 +                      break;
 +              case CTX_MODE_PAINT_TEXTURE:
 +                      use_drw_engine(&draw_engine_paint_texture_type);
 +                      break;
 +              case CTX_MODE_PARTICLE:
 +                      use_drw_engine(&draw_engine_particle_type);
 +                      break;
 +              case CTX_MODE_OBJECT:
 +                      break;
 +              default:
 +                      BLI_assert(!"Draw mode invalid");
 +                      break;
 +      }
 +}
 +
 +static void drw_engines_enable_from_overlays(int overlay_flag)
 +{
 +      if (overlay_flag) {
 +              use_drw_engine(&draw_engine_overlay_type);
 +      }
 +}
 +/**
 + * Use for select and depth-drawing.
 + */
 +static void drw_engines_enable_basic(void)
 +{
 +      use_drw_engine(DRW_engine_viewport_basic_type.draw_engine);
 +}
 +
 +static void drw_engines_enable(ViewLayer *view_layer, RenderEngineType *engine_type)
 +{
 +      Object *obact = OBACT(view_layer);
 +      const int mode = CTX_data_mode_enum_ex(DST.draw_ctx.object_edit, obact, DST.draw_ctx.object_mode);
 +      View3D * v3d = DST.draw_ctx.v3d;
 +      const int drawtype = v3d->drawtype;
 +
 +      drw_engines_enable_from_engine(engine_type, drawtype, v3d->shading.flag);
 +
 +      if (DRW_state_draw_support()) {
 +              drw_engines_enable_from_overlays(v3d->overlay.flag);
 +              drw_engines_enable_from_object_mode();
 +              drw_engines_enable_from_mode(mode);
 +      }
 +}
 +
 +static void drw_engines_disable(void)
 +{
 +      BLI_freelistN(&DST.enabled_engines);
 +}
 +
 +static uint DRW_engines_get_hash(void)
 +{
 +      uint hash = 0;
 +      /* The cache depends on enabled engines */
 +      /* FIXME : if collision occurs ... segfault */
 +      for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +              DrawEngineType *engine = link->data;
 +              hash += BLI_ghashutil_strhash_p(engine->idname);
 +      }
 +
 +      return hash;
 +}
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name View Update
 + * \{ */
 +
 +void DRW_notify_view_update(const DRWUpdateContext *update_ctx)
 +{
 +      RenderEngineType *engine_type = update_ctx->engine_type;
 +      ARegion *ar = update_ctx->ar;
 +      View3D *v3d = update_ctx->v3d;
 +      RegionView3D *rv3d = ar->regiondata;
 +      Depsgraph *depsgraph = update_ctx->depsgraph;
 +      Scene *scene = update_ctx->scene;
 +      ViewLayer *view_layer = update_ctx->view_layer;
 +
 +      /* Separate update for each stereo view. */
 +      for (int view = 0; view < 2; view++) {
 +              GPUViewport *viewport = WM_draw_region_get_viewport(ar, view);
 +              if (!viewport) {
 +                      continue;
 +              }
 +
 +              /* XXX Really nasty locking. But else this could
 +               * be executed by the material previews thread
 +               * while rendering a viewport. */
 +              BLI_mutex_lock(&DST.gl_context_mutex);
 +
 +              /* Reset before using it. */
 +              drw_state_prepare_clean_for_draw(&DST);
 +
 +              DST.viewport = viewport;
 +              DST.draw_ctx = (DRWContextState){
 +                      .ar = ar, .rv3d = rv3d, .v3d = v3d,
 +                      .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
 +                      .engine_type = engine_type,
 +                      .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
 +              };
 +
 +              drw_engines_enable(view_layer, engine_type);
 +
 +              for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
 +                      DrawEngineType *draw_engine = link->data;
 +                      ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine);
 +
 +                      if (draw_engine->view_update) {
 +                              draw_engine->view_update(data);
 +                      }
 +              }
 +
 +              DST.viewport = NULL;
 +
 +              drw_engines_disable();
 +
 +              BLI_mutex_unlock(&DST.gl_context_mutex);
 +      }
 +}
 +
 +/** \} */
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Main Draw Loops (DRW_draw)
 + * \{ */
 +
 +/* Everything starts here.
 + * This function takes care of calling all cache and rendering functions
 + * for each relevant engine / mode engine. */
 +void DRW_draw_view(const bContext *C)
 +{
 +      Depsgraph *depsgraph = CTX_data_depsgraph(C);
 +      ARegion *ar = CTX_wm_region(C);
 +      View3D *v3d = CTX_wm_view3d(C);
 +      Scene *scene = DEG_get_evaluated_scene(depsgraph);
 +      RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
 +      GPUViewport *viewport = WM_draw_region_get_bound_viewport(ar);
 +
 +      /* Reset before using it. */
 +      drw_state_prepare_clean_for_draw(&DST);
 +      DST.options.draw_text = (
 +              (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0 &&
 +              (v3d->overlay.flag & V3D_OVERLAY_HIDE_TEXT) != 0);
 +      DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, viewport, C);
 +}
 +
 +/**
 + * Used for both regular and off-screen drawing.
 + * Need to reset DST before calling this function
 + */
 +void DRW_draw_render_loop_ex(
 +        struct Depsgraph *depsgraph,
 +        RenderEngineType *engine_type,
 +        ARegion *ar, View3D *v3d,
 +        GPUViewport *viewport,
 +        const bContext *evil_C)
 +{
 +
 +      Scene *scene = DEG_get_evaluated_scene(depsgraph);
 +      ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
 +      RegionView3D *rv3d = ar->regiondata;
 +
 +      DST.draw_ctx.evil_C = evil_C;
 +
 +      DST.viewport = viewport;
 +      v3d->zbuf = true;
 +
 +      /* Setup viewport */
 +      GPU_viewport_engines_data_validate(DST.viewport, DRW_engines_get_hash());
 +
 +      DST.draw_ctx = (DRWContextState){
 +          .ar = ar, .rv3d = rv3d, .v3d = v3d,
 +          .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
 +          .engine_type = engine_type,
 +          .depsgraph = depsgraph,
 +
 +          /* reuse if caller sets */
 +          .evil_C = DST.draw_ctx.evil_C,
 +      };
 +      drw_context_state_init();
 +      drw_viewport_var_init();
 +
 +      /* Get list of enabled engines */
 +      drw_engines_enable(view_layer, engine_type);
 +
 +      /* Update ubos */
 +      DRW_globals_update();
 +
 +      drw_debug_init();
 +      DRW_hair_init();
 +
 +      /* No framebuffer allowed before drawing. */
 +      BLI_assert(GPU_framebuffer_current_get() == 0);
 +
 +      /* Init engines */
 +      drw_engines_init();
 +
 +      /* Cache filling */
 +      {
 +              PROFILE_START(stime);
 +              drw_engines_cache_init();
 +
 +              DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob)
 +              {
 +                      drw_engines_cache_populate(ob);
 +              }
 +              DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END;
 +
 +              drw_engines_cache_finish();
 +
 +              DRW_render_instance_buffer_finish();
 +
 +#ifdef USE_PROFILE
 +              double *cache_time = GPU_viewport_cache_time_get(DST.viewport);
 +              PROFILE_END_UPDATE(*cache_time, stime);
 +#endif
 +      }
 +
 +      DRW_stats_begin();
 +
 +      GPU_framebuffer_bind(DST.default_framebuffer);
 +
 +      /* Start Drawing */
 +      DRW_state_reset();
 +
 +      DRW_hair_update();
 +
 +      drw_engines_draw_background();
 +
 +      /* WIP, single image drawn over the camera view (replace) */
 +      bool do_bg_image = false;
 +      if (rv3d->persp == RV3D_CAMOB) {
 +              Object *cam_ob = v3d->camera;
 +              if (cam_ob && cam_ob->type == OB_CAMERA) {
 +                      Camera *cam = cam_ob->data;
 +                      if (!BLI_listbase_is_empty(&cam->bg_images)) {
 +                              do_bg_image = true;
 +                      }
 +              }
 +      }
 +
 +      if (do_bg_image) {
 +              ED_view3d_draw_bgpic_test(scene, depsgraph, ar, v3d, false, true);
 +      }
 +
 +
 +      DRW_draw_callbacks_pre_scene();
 +      if (DST.draw_ctx.evil_C) {
 +              ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_PRE_VIEW);
 +      }
 +
 +      drw_engines_draw_scene();
 +
 +      DRW_draw_callbacks_post_scene();
 +      if (DST.draw_ctx.evil_C) {
 +              ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_POST_VIEW);
 +      }
 +
 +      DRW_state_reset();
 +
 +      drw_debug_draw();
 +
 +      glDisable(GL_DEPTH_TEST);
 +      drw_engines_draw_text();
 +      glEnable(GL_DEPTH_TEST);
 +
 +      if (DST.draw_ctx.evil_C) {
 +              /* needed so manipulator isn't obscured */
 +              if (((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
 +                  ((v3d->twflag & V3D_MANIPULATOR_DRAW) != 0))
 +              {
 +                      glDisable(GL_DEPTH_TEST);
 +                      DRW_draw_manipulator_3d();
 +              }
 +
 +              DRW_draw_region_info();
 +
 +              if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
 +                      /* Draw 2D after region info so we can draw on top of the camera passepartout overlay.
 +                       * 'DRW_draw_region_info' sets the projection in pixel-space. */
 +                      DRW_draw_manipulator_2d();
 +                      glEnable(GL_DEPTH_TEST);
 +              }
 +      }
 +
 +      DRW_stats_reset();
 +
 +      if (do_bg_image) {
 +              ED_view3d_draw_bgpic_test(scene, depsgraph, ar, v3d, true, true);
 +      }
 +
 +      if (G.debug_value > 20) {
 +              glDisable(GL_DEPTH_TEST);
 +              rcti rect; /* local coordinate visible rect inside region, to accomodate overlapping ui */
 +              ED_region_visible_rect(DST.draw_ctx.ar, &rect);
 +              DRW_stats_draw(&rect);
 +              glEnable(GL_DEPTH_TEST);
 +      }
 +
 +      if (WM_draw_region_get_bound_viewport(ar)) {
 +              /* Don't unbind the framebuffer yet in this case and let
 +               * GPU_viewport_unbind do it, so that we can still do further
 +               * drawing of action zones on top. */
 +      }
 +      else {
 +              GPU_framebuffer_restore();
 +      }
 +
 +      DRW_state_reset();
 +      drw_engines_disable();
 +
 +      drw_viewport_cache_resize();
 +
 +#ifdef DEBUG
 +      /* Avoid accidental reuse. */
 +      drw_state_ensure_not_reused(&DST);
 +#endif
 +}
 +
 +void DRW_draw_render_loop(
 +        struct Depsgraph *depsgraph,
 +        ARegion *ar, View3D *v3d,
 +        GPUViewport *viewport)
 +{
 +      /* Reset before using it. */
 +      drw_state_prepare_clean_for_draw(&DST);
 +
 +      Scene *scene = DEG_get_evaluated_scene(depsgraph);
 +      RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
 +
 +      DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, viewport, NULL);
 +}
 +
 +/* @viewport CAN be NULL, in this case we create one. */
 +void DRW_draw_render_loop_offscreen(
 +        struct Depsgraph *depsgraph, RenderEngineType *engine_type,
 +        ARegion *ar, View3D *v3d,
 +        const bool draw_background, GPUOffScreen *ofs,
 +        GPUViewport *viewport)
 +{
 +      /* Create temporary viewport if needed. */
 +      GPUViewport *render_viewport = viewport;
 +      if (viewport == NULL) {
 +              render_viewport = GPU_viewport_create_from_offscreen(ofs);
 +      }
 +
 +      GPU_framebuffer_restore();
 +
 +      /* Reset before using it. */
 +      drw_state_prepare_clean_for_draw(&DST);
 +      DST.options.is_image_render = true;
 +      DST.options.draw_background = draw_background;
 +      DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, render_viewport, NULL);
 +
 +      /* Free temporary viewport. */
 +      if (viewport == NULL) {
 +              /* don't free data owned by 'ofs' */
 +              GPU_viewport_clear_from_offscreen(render_viewport);
 +              GPU_viewport_free(render_viewport);
 +      }
 +
 +      /* we need to re-bind (annoying!) */
 +      GPU_offscreen_bind(ofs, false);
 +}
 +
 +void DRW_render_to_image(RenderEngine *engine, struct Depsgraph *depsgraph)
 +{
 +      Scene *scene = DEG_get_evaluated_scene(depsgraph);
 +      ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
 +      RenderEngineType *engine_type = engine->type;
 +      DrawEngineType *draw_engine_type = engine_type->draw_engine;
 +      RenderData *r = &scene->r;
 +      Render *render = engine->re;
 +
 +      if (G.background && DST.gl_context == NULL) {
++              WM_init_opengl(G_MAIN);
 +      }
 +
 +      void *re_gl_context = RE_gl_context_get(render);
 +      void *re_gwn_context = NULL;
 +
 +      /* Changing Context */
 +      if (re_gl_context != NULL) {
 +              /* TODO get rid of the blocking. Only here because of the static global DST. */
 +              BLI_mutex_lock(&DST.gl_context_mutex);
 +              WM_opengl_context_activate(re_gl_context);
 +              re_gwn_context = RE_gwn_context_get(render);
 +              if (GWN_context_active_get() == NULL) {
 +                      GWN_context_active_set(re_gwn_context);
 +              }
 +              DRW_shape_cache_reset(); /* XXX fix that too. */
 +      }
 +      else {
 +              DRW_opengl_context_enable();
 +      }
 +
 +      /* IMPORTANT: We dont support immediate mode in render mode!
 +       * This shall remain in effect until immediate mode supports
 +       * multiple threads. */
 +
 +      /* Reset before using it. */
 +      drw_state_prepare_clean_for_draw(&DST);
 +      DST.options.is_image_render = true;
 +      DST.options.is_scene_render = true;
 +      DST.options.draw_background = scene->r.alphamode == R_ADDSKY;
 +
 +      DST.draw_ctx = (DRWContextState){
 +          .scene = scene, .view_layer = view_layer,
 +          .engine_type = engine_type,
 +          .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
 +      };
 +      drw_context_state_init();
 +
 +      DST.viewport = GPU_viewport_create();
 +      const int size[2] = {(r->size * r->xsch) / 100, (r->size * r->ysch) / 100};
 +      GPU_viewport_size_set(DST.viewport, size);
 +
 +      drw_viewport_var_init();
 +
 +      ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine_type);
 +
 +      /* set default viewport */
 +      glViewport(0, 0, size[0], size[1]);
 +
 +      /* Main rendering. */
 +      rctf view_rect;
 +      rcti render_rect;
 +      RE_GetViewPlane(render, &view_rect, &render_rect);
 +      if (BLI_rcti_is_empty(&render_rect)) {
 +              BLI_rcti_init(&render_rect, 0, size[0], 0, size[1]);
 +      }
 +
 +      /* Init render result. */
 +      RenderResult *render_result = RE_engine_begin_result(
 +              engine,
 +              0,
 +              0,
 +              (int)size[0],
 +              (int)size[1],
 +              view_layer->name,
 +              /* RR_ALL_VIEWS */ NULL);
 +
 +      RenderLayer *render_layer = render_result->layers.first;
 +      for (RenderView *render_view = render_result->views.first;
 +           render_view != NULL;
 +           render_view = render_view->next)
 +      {
 +              RE_SetActiveRenderView(render, render_view->name);
 +              engine_type->draw_engine->render_to_image(data, engine, render_layer, &render_rect);
 +              DST.buffer_finish_called = false;
 +      }
 +
 +      RE_engine_end_result(engine, render_result, false, false, false);
 +
 +      /* Force cache to reset. */
 +      drw_viewport_cache_resize();
 +
 +      /* TODO grease pencil */
 +
 +      GPU_viewport_free(DST.viewport);
 +      GPU_framebuffer_restore();
 +
 +#ifdef DEBUG
 +      /* Avoid accidental reuse. */
 +      drw_state_ensure_not_reused(&DST);
 +#endif
 +
 +      /* Changing Context */
 +      if (re_gl_context != NULL) {
 +              DRW_shape_cache_reset(); /* XXX fix that too. */
 +              glFlush();
 +              GWN_context_active_set(NULL);
 +              WM_opengl_context_release(re_gl_context);
 +              /* TODO get rid of the blocking. */
 +              BLI_mutex_unlock(&DST.gl_context_mutex);
 +      }
 +      else {
 +              DRW_opengl_context_disable();
 +      }
 +}
 +
 +void DRW_render_object_iter(
 +      void *vedata, RenderEngine *engine, struct Depsgraph *depsgraph,
 +      void (*callback)(void *vedata, Object *ob, RenderEngine *engine, struct Depsgraph *depsgraph))
 +{
 +      DRW_hair_init();
 +
 +      DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob)
 +      {
 +              DST.ob_state = NULL;
 +              callback(vedata, ob, engine, depsgraph);
 +      }
 +      DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END
 +}
 +
 +static struct DRWSelectBuffer {
 +      struct GPUFrameBuffer *framebuffer;
 +      struct GPUTexture *texture_depth;
 +} g_select_buffer = {NULL};
 +
 +static void draw_select_framebuffer_setup(const rcti *rect)
 +{
 +      if (g_select_buffer.framebuffer == NULL) {
 +              g_select_buffer.framebuffer = GPU_framebuffer_create();
 +      }
 +
 +      /* If size mismatch recreate the texture. */
 +      if ((g_select_buffer.texture_depth != NULL) &&
 +          ((GPU_texture_width(g_select_buffer.texture_depth) != BLI_rcti_size_x(rect)) ||
 +           (GPU_texture_height(g_select_buffer.texture_depth) != BLI_rcti_size_y(rect))))
 +      {
 +              GPU_texture_free(g_select_buffer.texture_depth);
 +              g_select_buffer.texture_depth = NULL;
 +      }
 +
 +      if (g_select_buffer.texture_depth == NULL) {
 +              g_select_buffer.texture_depth = GPU_texture_create_2D(
 +                      BLI_rcti_size_x(rect), BLI_rcti_size_y(rect), GPU_DEPTH_COMPONENT24, NULL, NULL);
 +
 +              GPU_framebuffer_texture_attach(g_select_buffer.framebuffer, g_select_buffer.texture_depth, 0, 0);
 +
 +              if (!GPU_framebuffer_check_valid(g_select_buffer.framebuffer, NULL)) {
 +                      printf("Error invalid selection framebuffer\n");
 +              }
 +      }
 +}
 +
 +/* Must run after all instance datas have been added. */
 +void DRW_render_instance_buffer_finish(void)
 +{
 +      BLI_assert(!DST.buffer_finish_called && "DRW_render_instance_buffer_finish called twice!");
 +      DST.buffer_finish_called = true;
 +      DRW_instance_buffer_finish(DST.idatalist);
 +}
 +
 +/**
 + * object mode select-loop, see: ED_view3d_draw_select_loop (legacy drawing).
 + */
 +void DRW_draw_select_loop(
 +        struct Depsgraph *depsgraph,
 +        ARegion *ar, View3D *v3d,
 +        bool UNUSED(use_obedit_skip), bool UNUSED(use_nearest), const rcti *rect,
 +        DRW_SelectPassFn select_pass_fn, void *select_pass_user_data,
 +        DRW_ObjectFilterFn object_filter_fn, void *object_filter_user_data)
 +{
 +      Scene *scene = DEG_get_evaluated_scene(depsgraph);
 +      RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
 +      ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
 +      Object *obact = OBACT(view_layer);
 +      Object *obedit = OBEDIT_FROM_OBACT(obact);
 +#ifndef USE_GPU_SELECT
 +      UNUSED_VARS(vc, scene, view_layer, v3d, ar, rect);
 +#else
 +      RegionView3D *rv3d = ar->regiondata;
 +
 +      /* Reset before using it. */
 +      drw_state_prepare_clean_for_draw(&DST);
 +
 +      bool use_obedit = false;
 +      int obedit_mode = 0;
 +      if (obedit != NULL) {
 +              if (obedit->type == OB_MBALL) {
 +                      use_obedit = true;
 +                      obedit_mode = CTX_MODE_EDIT_METABALL;
 +              }
 +              else if (obedit->type == OB_ARMATURE) {
 +                      use_obedit = true;
 +                      obedit_mode = CTX_MODE_EDIT_ARMATURE;
 +              }
 +      }
 +      if (v3d->overlay.flag & V3D_OVERLAY_BONE_SELECTION) {
 +              if (!(v3d->flag2 & V3D_RENDER_OVERRIDE)) {
 +                      Object *obpose = OBPOSE_FROM_OBACT(obact);
 +                      if (obpose) {
 +                              use_obedit = true;
 +                              obedit_mode = CTX_MODE_POSE;
 +                      }
 +              }
 +      }
 +
 +      struct GPUViewport *viewport = GPU_viewport_create();
 +      GPU_viewport_size_set(viewport, (const int[2]){BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)});
 +
 +      DST.viewport = viewport;
 +      v3d->zbuf = true;
 +
 +      DST.options.is_select = true;
 +
 +      /* Get list of enabled engines */
 +      if (use_obedit) {
 +              drw_engines_enable_from_mode(obedit_mode);
 +      }
 +      else {
 +              drw_engines_enable_basic();
 +              drw_engines_enable_from_object_mode();
 +      }
 +
 +      /* Setup viewport */
 +
 +      /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
 +      DST.draw_ctx = (DRWContextState){
 +              .ar = ar, .rv3d = rv3d, .v3d = v3d,
 +              .scene = scene, .view_layer = view_layer, .obact = obact,
 +              .engine_type = engine_type,
 +              .depsgraph = depsgraph,
 +      };
 +      drw_context_state_init();
 +      drw_viewport_var_init();
 +
 +      /* Update ubos */
 +      DRW_globals_update();
 +
 +      /* Init engines */
 +      drw_engines_init();
 +      DRW_hair_init();
 +
 +      {
 +              drw_engines_cache_init();
 +
 +              if (use_obedit) {
 +#if 0
 +                      drw_engines_cache_populate(obact);
 +#else
 +                      FOREACH_OBJECT_IN_MODE_BEGIN (view_layer, obact->mode, ob_iter) {
 +                              drw_engines_cache_populate(ob_iter);
 +                      }
 +                      FOREACH_OBJECT_IN_MODE_END;
 +#endif
 +              }
 +              else {
 +                      bool filter_exclude = false;
 +                      DEG_OBJECT_ITER_BEGIN(
 +                              depsgraph, ob,
 +                              DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
 +                              DEG_ITER_OBJECT_FLAG_VISIBLE |
 +                              DEG_ITER_OBJECT_FLAG_DUPLI)
 +                      {
 +                              if ((ob->base_flag & BASE_SELECTABLED) != 0) {
 +
 +                                      if (object_filter_fn != NULL) {
 +                                              if (ob->base_flag & BASE_FROMDUPLI) {
 +                                                      /* pass (use previous filter_exclude value) */
 +                                              }
 +                                              else {
 +                                                      filter_exclude = (object_filter_fn(ob, object_filter_user_data) == false);
 +                                              }
 +                                              if (filter_exclude) {
 +                                                      continue;
 +                                              }
 +                                      }
 +
 +                                      /* This relies on dupli instances being after their instancing object. */
 +                                      if ((ob->base_flag & BASE_FROMDUPLI) == 0) {
 +                                              Object *ob_orig = DEG_get_original_object(ob);
 +                                              DRW_select_load_id(ob_orig->select_color);
 +                                      }
 +                                      drw_engines_cache_populate(ob);
 +                              }
 +                      }
 +                      DEG_OBJECT_ITER_END;
 +              }
 +
 +              drw_engines_cache_finish();
 +
 +              DRW_render_instance_buffer_finish();
 +      }
 +
 +      /* Setup framebuffer */
 +      draw_select_framebuffer_setup(rect);
 +      GPU_framebuffer_bind(g_select_buffer.framebuffer);
 +      GPU_framebuffer_clear_depth(g_select_buffer.framebuffer, 1.0f);
 +
 +      /* Start Drawing */
 +      DRW_state_reset();
 +      DRW_draw_callbacks_pre_scene();
 +
 +      DRW_hair_update();
 +
 +      DRW_state_lock(
 +              DRW_STATE_WRITE_DEPTH |
 +              DRW_STATE_DEPTH_ALWAYS |
 +              DRW_STATE_DEPTH_LESS_EQUAL |
 +              DRW_STATE_DEPTH_EQUAL |
 +              DRW_STATE_DEPTH_GREATER |
 +              DRW_STATE_DEPTH_ALWAYS);
 +
 +      /* Only 1-2 passes. */
 +      while (true) {
 +              if (!select_pass_fn(DRW_SELECT_PASS_PRE, select_pass_user_data)) {
 +                      break;
 +              }
 +
 +              drw_engines_draw_scene();
 +
 +              if (!select_pass_fn(DRW_SELECT_PASS_POST, select_pass_user_data)) {
 +                      break;
 +              }
 +      }
 +
 +      DRW_state_lock(0);
 +
 +      DRW_draw_callbacks_post_scene();
 +
 +      DRW_state_reset();
 +      drw_engines_disable();
 +
 +#ifdef DEBUG
 +      /* Avoid accidental reuse. */
 +      drw_state_ensure_not_reused(&DST);
 +#endif
 +      GPU_framebuffer_restore();
 +
 +      /* Cleanup for selection state */
 +      GPU_viewport_free(viewport);
 +#endif  /* USE_GPU_SELECT */
 +}
 +
 +static void draw_depth_texture_to_screen(GPUTexture *texture)
 +{
 +      const float w = (float)GPU_texture_width(texture);
 +      const float h = (float)GPU_texture_height(texture);
 +
 +      Gwn_VertFormat *format = immVertexFormat();
 +      uint texcoord = GWN_vertformat_attr_add(format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +      uint pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +
 +      immBindBuiltinProgram(GPU_SHADER_3D_IMAGE_DEPTH_COPY);
 +
 +      GPU_texture_bind(texture, 0);
 +
 +      immUniform1i("image", 0); /* default GL_TEXTURE0 unit */
 +
 +      immBegin(GWN_PRIM_TRI_STRIP, 4);
 +
 +      immAttrib2f(texcoord, 0.0f, 0.0f);
 +      immVertex2f(pos, 0.0f, 0.0f);
 +
 +      immAttrib2f(texcoord, 1.0f, 0.0f);
 +      immVertex2f(pos, w, 0.0f);
 +
 +      immAttrib2f(texcoord, 0.0f, 1.0f);
 +      immVertex2f(pos, 0.0f, h);
 +
 +      immAttrib2f(texcoord, 1.0f, 1.0f);
 +      immVertex2f(pos, w, h);
 +
 +      immEnd();
 +
 +      GPU_texture_unbind(texture);
 +
 +      immUnbindProgram();
 +}
 +
 +/**
 + * object mode select-loop, see: ED_view3d_draw_depth_loop (legacy drawing).
 + */
 +void DRW_draw_depth_loop(
 +        Depsgraph *depsgraph,
 +        ARegion *ar, View3D *v3d)
 +{
 +      Scene *scene = DEG_get_evaluated_scene(depsgraph);
 +      RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
 +      ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
 +      RegionView3D *rv3d = ar->regiondata;
 +
 +      DRW_opengl_context_enable();
 +
 +      /* Reset before using it. */
 +      drw_state_prepare_clean_for_draw(&DST);
 +
 +      struct GPUViewport *viewport = GPU_viewport_create();
 +      GPU_viewport_size_set(viewport, (const int[2]){ar->winx, ar->winy});
 +
 +      /* Setup framebuffer */
 +      draw_select_framebuffer_setup(&ar->winrct);
 +      GPU_framebuffer_bind(g_select_buffer.framebuffer);
 +      GPU_framebuffer_clear_depth(g_select_buffer.framebuffer, 1.0f);
 +
 +      bool cache_is_dirty;
 +      DST.viewport = viewport;
 +      v3d->zbuf = true;
 +
 +      DST.options.is_depth = true;
 +
 +      /* Get list of enabled engines */
 +      {
 +              drw_engines_enable_basic();
 +              drw_engines_enable_from_object_mode();
 +      }
 +
 +      /* Setup viewport */
 +      cache_is_dirty = true;
 +
 +      /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
 +      DST.draw_ctx = (DRWContextState){
 +              .ar = ar, .rv3d = rv3d, .v3d = v3d,
 +              .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
 +              .engine_type = engine_type,
 +              .depsgraph = depsgraph,
 +      };
 +      drw_context_state_init();
 +      drw_viewport_var_init();
 +
 +      /* Update ubos */
 +      DRW_globals_update();
 +
 +      /* Init engines */
 +      drw_engines_init();
 +      DRW_hair_init();
 +
 +      /* TODO : tag to refresh by the dependency graph */
 +      /* ideally only refresh when objects are added/removed */
 +      /* or render properties / materials change */
 +      if (cache_is_dirty) {
 +              drw_engines_cache_init();
 +
 +              DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob)
 +              {
 +                      drw_engines_cache_populate(ob);
 +              }
 +              DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END;
 +
 +              drw_engines_cache_finish();
 +
 +              DRW_render_instance_buffer_finish();
 +      }
 +
 +      /* Start Drawing */
 +      DRW_state_reset();
 +
 +      DRW_hair_update();
 +
 +      DRW_draw_callbacks_pre_scene();
 +      drw_engines_draw_scene();
 +      DRW_draw_callbacks_post_scene();
 +
 +      DRW_state_reset();
 +      drw_engines_disable();
 +
 +#ifdef DEBUG
 +      /* Avoid accidental reuse. */
 +      drw_state_ensure_not_reused(&DST);
 +#endif
 +
 +      /* TODO: Reading depth for operators should be done here. */
 +
 +      GPU_framebuffer_restore();
 +
 +      /* Cleanup for selection state */
 +      GPU_viewport_free(viewport);
 +
 +      /* Changin context */
 +      DRW_opengl_context_disable();
 +
 +      /* XXX Drawing the resulting buffer to the BACK_BUFFER */
 +      gpuPushMatrix();
 +      gpuPushProjectionMatrix();
 +      wmOrtho2_region_pixelspace(ar);
 +      gpuLoadIdentity();
 +
 +      glEnable(GL_DEPTH_TEST); /* Cannot write to depth buffer without testing */
 +      glDepthFunc(GL_ALWAYS);
 +      draw_depth_texture_to_screen(g_select_buffer.texture_depth);
 +      glDepthFunc(GL_LEQUAL);
 +
 +      gpuPopMatrix();
 +      gpuPopProjectionMatrix();
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Draw Manager State (DRW_state)
 + * \{ */
 +
 +void DRW_state_dfdy_factors_get(float dfdyfac[2])
 +{
 +      GPU_get_dfdy_factors(dfdyfac);
 +}
 +
 +/**
 + * When false, drawing doesn't output to a pixel buffer
 + * eg: Occlusion queries, or when we have setup a context to draw in already.
 + */
 +bool DRW_state_is_fbo(void)
 +{
 +      return ((DST.default_framebuffer != NULL) || DST.options.is_image_render);
 +}
 +
 +/**
 + * For when engines need to know if this is drawing for selection or not.
 + */
 +bool DRW_state_is_select(void)
 +{
 +      return DST.options.is_select;
 +}
 +
 +bool DRW_state_is_depth(void)
 +{
 +      return DST.options.is_depth;
 +}
 +
 +/**
 + * Whether we are rendering for an image
 + */
 +bool DRW_state_is_image_render(void)
 +{
 +      return DST.options.is_image_render;
 +}
 +
 +/**
 + * Whether we are rendering only the render engine,
 + * or if we should also render the mode engines.
 + */
 +bool DRW_state_is_scene_render(void)
 +{
 +      BLI_assert(DST.options.is_scene_render ?
 +                 DST.options.is_image_render : true);
 +      return DST.options.is_scene_render;
 +}
 +
 +/**
 +* Whether we are rendering simple opengl render
 +*/
 +bool DRW_state_is_opengl_render(void)
 +{
 +      return DST.options.is_image_render && !DST.options.is_scene_render;
 +}
 +
 +/**
 + * Should text draw in this mode?
 + */
 +bool DRW_state_show_text(void)
 +{
 +      return (DST.options.is_select) == 0 &&
 +             (DST.options.is_depth) == 0 &&
 +             (DST.options.is_scene_render) == 0 &&
 +             (DST.options.draw_text) == 0;
 +}
 +
 +/**
 + * Should draw support elements
 + * Objects center, selection outline, probe data, ...
 + */
 +bool DRW_state_draw_support(void)
 +{
 +      View3D *v3d = DST.draw_ctx.v3d;
 +      return (DRW_state_is_scene_render() == false) &&
 +              (v3d != NULL) &&
 +              ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0);
 +}
 +
 +/**
 + * Whether we should render the background
 + */
 +bool DRW_state_draw_background(void)
 +{
 +      if (DRW_state_is_image_render() == false) {
 +              return true;
 +      }
 +      return DST.options.draw_background;
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Context State (DRW_context_state)
 + * \{ */
 +
 +const DRWContextState *DRW_context_state_get(void)
 +{
 +      return &DST.draw_ctx;
 +}
 +
 +/** \} */
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Init/Exit (DRW_engines)
 + * \{ */
 +
 +bool DRW_engine_render_support(DrawEngineType *draw_engine_type)
 +{
 +      return draw_engine_type->render_to_image;
 +}
 +
 +void DRW_engine_register(DrawEngineType *draw_engine_type)
 +{
 +      BLI_addtail(&DRW_engines, draw_engine_type);
 +}
 +
 +void DRW_engines_register(void)
 +{
 +      RE_engines_register(&DRW_engine_viewport_eevee_type);
 +      RE_engines_register(&DRW_engine_viewport_workbench_type);
 +
 +      DRW_engine_register(&draw_engine_workbench_solid);
 +      DRW_engine_register(&draw_engine_workbench_transparent);
 +
 +      DRW_engine_register(&draw_engine_object_type);
 +      DRW_engine_register(&draw_engine_edit_armature_type);
 +      DRW_engine_register(&draw_engine_edit_curve_type);
 +      DRW_engine_register(&draw_engine_edit_lattice_type);
 +      DRW_engine_register(&draw_engine_edit_mesh_type);
 +      DRW_engine_register(&draw_engine_edit_metaball_type);
 +      DRW_engine_register(&draw_engine_edit_surface_type);
 +      DRW_engine_register(&draw_engine_edit_text_type);
 +      DRW_engine_register(&draw_engine_motion_path_type);
 +      DRW_engine_register(&draw_engine_overlay_type);
 +      DRW_engine_register(&draw_engine_paint_texture_type);
 +      DRW_engine_register(&draw_engine_paint_vertex_type);
 +      DRW_engine_register(&draw_engine_paint_weight_type);
 +      DRW_engine_register(&draw_engine_particle_type);
 +      DRW_engine_register(&draw_engine_pose_type);
 +      DRW_engine_register(&draw_engine_sculpt_type);
 +
 +      /* setup callbacks */
 +      {
 +              /* BKE: mball.c */
 +              extern void *BKE_mball_batch_cache_dirty_cb;
 +              extern void *BKE_mball_batch_cache_free_cb;
 +              /* BKE: curve.c */
 +              extern void *BKE_curve_batch_cache_dirty_cb;
 +              extern void *BKE_curve_batch_cache_free_cb;
 +              /* BKE: mesh.c */
 +              extern void *BKE_mesh_batch_cache_dirty_cb;
 +              extern void *BKE_mesh_batch_cache_free_cb;
 +              /* BKE: lattice.c */
 +              extern void *BKE_lattice_batch_cache_dirty_cb;
 +              extern void *BKE_lattice_batch_cache_free_cb;
 +              /* BKE: particle.c */
 +              extern void *BKE_particle_batch_cache_dirty_cb;
 +              extern void *BKE_particle_batch_cache_free_cb;
 +
 +              BKE_mball_batch_cache_dirty_cb = DRW_mball_batch_cache_dirty;
 +              BKE_mball_batch_cache_free_cb = DRW_mball_batch_cache_free;
 +
 +              BKE_curve_batch_cache_dirty_cb = DRW_curve_batch_cache_dirty;
 +              BKE_curve_batch_cache_free_cb = DRW_curve_batch_cache_free;
 +
 +              BKE_mesh_batch_cache_dirty_cb = DRW_mesh_batch_cache_dirty;
 +              BKE_mesh_batch_cache_free_cb = DRW_mesh_batch_cache_free;
 +
 +              BKE_lattice_batch_cache_dirty_cb = DRW_lattice_batch_cache_dirty;
 +              BKE_lattice_batch_cache_free_cb = DRW_lattice_batch_cache_free;
 +
 +              BKE_particle_batch_cache_dirty_cb = DRW_particle_batch_cache_dirty;
 +              BKE_particle_batch_cache_free_cb = DRW_particle_batch_cache_free;
 +      }
 +}
 +
 +extern struct Gwn_VertFormat *g_pos_format; /* draw_shgroup.c */
 +extern struct GPUUniformBuffer *globals_ubo; /* draw_common.c */
 +extern struct GPUTexture *globals_ramp; /* draw_common.c */
 +void DRW_engines_free(void)
 +{
 +      DRW_opengl_context_enable();
 +
 +      DRW_TEXTURE_FREE_SAFE(g_select_buffer.texture_depth);
 +      GPU_FRAMEBUFFER_FREE_SAFE(g_select_buffer.framebuffer);
 +
 +      DRW_hair_free();
 +      DRW_shape_cache_free();
 +      DRW_stats_free();
 +      DRW_globals_free();
 +
 +      DrawEngineType *next;
 +      for (DrawEngineType *type = DRW_engines.first; type; type = next) {
 +              next = type->next;
 +              BLI_remlink(&R_engines, type);
 +
 +              if (type->engine_free) {
 +                      type->engine_free();
 +              }
 +      }
 +
 +      DRW_UBO_FREE_SAFE(globals_ubo);
 +      DRW_UBO_FREE_SAFE(view_ubo);
 +      DRW_TEXTURE_FREE_SAFE(globals_ramp);
 +      MEM_SAFE_FREE(g_pos_format);
 +
 +      MEM_SAFE_FREE(DST.RST.bound_texs);
 +      MEM_SAFE_FREE(DST.RST.bound_tex_slots);
 +      MEM_SAFE_FREE(DST.RST.bound_ubos);
 +      MEM_SAFE_FREE(DST.RST.bound_ubo_slots);
 +
 +      DRW_opengl_context_disable();
 +}
 +
 +/** \} */
 +
 +/** \name Init/Exit (DRW_opengl_ctx)
 + * \{ */
 +
 +void DRW_opengl_context_create(void)
 +{
 +      BLI_assert(DST.gl_context == NULL); /* Ensure it's called once */
 +
 +      BLI_mutex_init(&DST.gl_context_mutex);
 +      if (!G.background) {
 +              immDeactivate();
 +      }
 +      /* This changes the active context. */
 +      DST.gl_context = WM_opengl_context_create();
 +      /* Make the context active for this thread (main thread) */
 +      WM_opengl_context_activate(DST.gl_context);
 +      /* Be sure to create gawain.context too. */
 +      DST.gwn_context = GWN_context_create();
 +      if (!G.background) {
 +              immActivate();
 +      }
 +      /* Set default Blender OpenGL state */
 +      GPU_state_init();
 +      /* So we activate the window's one afterwards. */
 +      wm_window_reset_drawable();
 +}
 +
 +void DRW_opengl_context_destroy(void)
 +{
 +      BLI_assert(BLI_thread_is_main());
 +      if (DST.gl_context != NULL) {
 +              WM_opengl_context_activate(DST.gl_context);
 +              GWN_context_active_set(DST.gwn_context);
 +              GWN_context_discard(DST.gwn_context);
 +              WM_opengl_context_dispose(DST.gl_context);
 +              BLI_mutex_end(&DST.gl_context_mutex);
 +      }
 +}
 +
 +void DRW_opengl_context_enable(void)
 +{
 +      if (DST.gl_context != NULL) {
 +              /* IMPORTANT: We dont support immediate mode in render mode!
 +               * This shall remain in effect until immediate mode supports
 +               * multiple threads. */
 +              BLI_mutex_lock(&DST.gl_context_mutex);
 +              if (BLI_thread_is_main()) {
 +                      if (!G.background) {
 +                              immDeactivate();
 +                      }
 +              }
 +              WM_opengl_context_activate(DST.gl_context);
 +              GWN_context_active_set(DST.gwn_context);
 +              if (BLI_thread_is_main()) {
 +                      if (!G.background) {
 +                              immActivate();
 +                      }
 +                      BLF_batch_reset();
 +              }
 +      }
 +}
 +
 +void DRW_opengl_context_disable(void)
 +{
 +      if (DST.gl_context != NULL) {
 +#ifdef __APPLE__
 +              /* Need to flush before disabling draw context, otherwise it does not
 +               * always finish drawing and viewport can be empty or partially drawn */
 +              glFlush();
 +#endif
 +
 +              if (BLI_thread_is_main()) {
 +                      wm_window_reset_drawable();
 +              }
 +              else {
 +                      WM_opengl_context_release(DST.gl_context);
 +                      GWN_context_active_set(NULL);
 +              }
 +
 +              BLI_mutex_unlock(&DST.gl_context_mutex);
 +      }
 +}
 +
 +/** \} */
index cdb7a3bcce65275055ea957edd6583875a76376c,2ada62b028b30d10377ee4e3c80f45a8f42f8b3a..4342778a5d1c460aff2e0f29201e216afbc53ceb
@@@ -1053,7 -1024,7 +1053,8 @@@ static int texture_paint_toggle_poll(bC
  
  static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
  {
 +      struct wmMsgBus *mbus = CTX_wm_message_bus(C);
+       Main *bmain = CTX_data_main(C);
        Scene *scene = CTX_data_scene(C);
        Object *ob = CTX_data_active_object(C);
        const int mode_flag = OB_MODE_TEXTURE_PAINT;
index a0d0529086fa148804555423eb386671054747e5,d547b419d48e1343b4d234e2d71819d07b519969..990d50ae42a9fe7f6035220fcc54e615b60d27d6
@@@ -539,10 -432,10 +539,10 @@@ static int outliner_id_remap_exec(bCont
        BKE_main_lib_objects_recalc_all(bmain);
  
        /* recreate dependency graph to include new objects */
 -      DAG_scene_relations_rebuild(bmain, scene);
 +      DEG_relations_tag_update(bmain);
  
        /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */
-       GPU_materials_free();
+       GPU_materials_free(bmain);
  
        WM_event_add_notifier(C, NC_WINDOW, NULL);
  
index fd2f604651b3d9ba5dfdd26895107cfa9bf4571a,fbf2bd33638589338188e58954f1aea44df771c7..964317f695e26167c596c30571bea55adad3f6ca
   *  \ingroup spview3d
   */
  
 -#include <string.h>
 -#include <stdio.h>
  #include <math.h>
  
 -#include "DNA_armature_types.h"
 -#include "DNA_camera_types.h"
 -#include "DNA_customdata_types.h"
 -#include "DNA_object_types.h"
 -#include "DNA_group_types.h"
 -#include "DNA_mesh_types.h"
 -#include "DNA_key_types.h"
 -#include "DNA_lamp_types.h"
 -#include "DNA_scene_types.h"
 -#include "DNA_world_types.h"
 -#include "DNA_brush_types.h"
 -
 -#include "MEM_guardedalloc.h"
 -
 -#include "BLI_blenlib.h"
 +#include "BLI_listbase.h"
  #include "BLI_math.h"
 -#include "BLI_jitter_2d.h"
 -#include "BLI_utildefines.h"
 -#include "BLI_endian_switch.h"
 +#include "BLI_rect.h"
 +#include "BLI_string.h"
  #include "BLI_threads.h"
 +#include "BLI_jitter_2d.h"
 +
 +#include "BIF_gl.h"
 +#include "BIF_glutil.h"
  
 -#include "BKE_anim.h"
  #include "BKE_camera.h"
  #include "BKE_context.h"
 -#include "BKE_customdata.h"
 -#include "BKE_DerivedMesh.h"
 -#include "BKE_image.h"
 +#include "BKE_global.h"
  #include "BKE_key.h"
+ #include "BKE_main.h"
 +#include "BKE_scene.h"
  #include "BKE_object.h"
 -#include "BKE_global.h"
  #include "BKE_paint.h"
 -#include "BKE_scene.h"
 -#include "BKE_screen.h"
  #include "BKE_unit.h"
 -#include "BKE_movieclip.h"
 -
 -#include "RE_engine.h"
  
 -#include "IMB_imbuf_types.h"
 -#include "IMB_imbuf.h"
 -#include "IMB_colormanagement.h"
 +#include "BLF_api.h"
  
 -#include "BIF_gl.h"
 -#include "BIF_glutil.h"
 +#include "BLT_translation.h"
  
 -#include "WM_api.h"
 +#include "DNA_armature_types.h"
 +#include "DNA_brush_types.h"
 +#include "DNA_camera_types.h"
 +#include "DNA_key_types.h"
 +#include "DNA_mesh_types.h"
 +#include "DNA_object_types.h"
 +#include "DNA_view3d_types.h"
 +#include "DNA_windowmanager_types.h"
  
 -#include "BLF_api.h"
 -#include "BLT_translation.h"
 +#include "DRW_engine.h"
  
  #include "ED_armature.h"
  #include "ED_keyframing.h"
@@@ -1174,369 -964,3017 +1175,368 @@@ static void draw_selected_name(Scene *s
                s += sprintf(s, " <%s>", markern);
        }
  
 -      if (U.uiflag & USER_SHOW_ROTVIEWICON)
 -              offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
 -
 -      BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
 +      BLF_draw_default(rect->xmin + UI_UNIT_X, rect->ymax - (2 * U.widget_unit), 0.0f, info, sizeof(info));
  }
  
 -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)
 +/* ******************** view loop ***************** */
 +
 +/**
 +* Information drawn on top of the solid plates and composed data
 +*/
 +void view3d_draw_region_info(const bContext *C, ARegion *ar, const int offset)
  {
 -      CameraParams params;
 -      rctf rect_view, rect_camera;
 +      RegionView3D *rv3d = ar->regiondata;
 +      View3D *v3d = CTX_wm_view3d(C);
 +      Scene *scene = CTX_data_scene(C);
 +      wmWindowManager *wm = CTX_wm_manager(C);
  
 -      /* 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;
 +      /* correct projection matrix */
 +      ED_region_pixelspace(ar);
  
 -      /* 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;
 +      /* local coordinate visible rect inside region, to accomodate overlapping ui */
 +      rcti rect;
 +      ED_region_visible_rect(ar, &rect);
  
-       /* Leave room for previously drawn info. */
-       rect.ymax -= offset;
 -      /* 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;
 -}
 -
 -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;
 -
 -      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);
 -}
 -
 -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);
 -}
 -
 -static void drawviewborder_grid3(float x1, float x2, float y1, float y2, float fac)
 -{
 -      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);
 -
 -      glVertex2f(x1, y4);
 -      glVertex2f(x2, y4);
 -
 -      glVertex2f(x3, y1);
 -      glVertex2f(x3, y2);
 -
 -      glVertex2f(x4, y1);
 -      glVertex2f(x4, y2);
 -      glEnd();
 -}
 -
 -/* 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;
 -
 -      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);
 -
 -              glVertex2f(x1, y1);
 -              glVertex2f(x2, y2);
 -
 -              glVertex2f(x2, y1);
 -              glVertex2f(x1 + (w - ofs), y2);
 -
 -              glVertex2f(x1, y2);
 -              glVertex2f(x1 + ofs, y1);
 -      }
 -      else {
 -              if (golden) {
 -                      ofs = h * (1.0f - (1.0f / 1.61803399f));
 -              }
 -              else {
 -                      ofs = w * (w / h);
 -              }
 -              if (dir == 'B') SWAP(float, x1, x2);
 -
 -              glVertex2f(x1, y1);
 -              glVertex2f(x2, y2);
 -
 -              glVertex2f(x2, y1);
 -              glVertex2f(x1, y1 + ofs);
 -
 -              glVertex2f(x1, y2);
 -              glVertex2f(x2, y1 + (h - ofs));
 -      }
 -      glEnd();
 -}
 -
 -static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      float x1, x2, y1, y2;
 -      float x1i, x2i, y1i, y2i;
 -
 -      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, ar, v3d, rv3d, &viewborder, false);
 -      /* the offsets */
 -      x1 = viewborder.xmin;
 -      y1 = viewborder.ymin;
 -      x2 = viewborder.xmax;
 -      y2 = viewborder.ymax;
 -
 -      glLineWidth(1.0f);
 -
 -      /* apply offsets so the real 3D camera shows through */
 -
 -      /* 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);
 -
 -              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);
 -              }
 -
 -              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);
 -      }
 -
 -      setlinestyle(0);
 -
 -      UI_ThemeColor(TH_BACK);
 -
 -      fdrawbox(x1i, y1i, x2i, y2i);
 -
 -#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
 -
 -      setlinestyle(3);
 -
 -      /* 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);
 -      }
 -
 -      UI_ThemeColor(TH_VIEW_OVERLAY);
 -      fdrawbox(x1i, y1i, x2i, y2i);
 -
 -      /* border */
 -      if (scene->r.mode & R_BORDER) {
 -              float x3, y3, x4, y4;
 -
 -              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);
 -      }
 -
 -      /* safety border */
 -      if (ca) {
 -              if (ca->dtx & CAM_DTX_CENTER) {
 -                      float x3, y3;
 -
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -
 -                      x3 = x1 + 0.5f * (x2 - x1);
 -                      y3 = y1 + 0.5f * (y2 - y1);
 -
 -                      glBegin(GL_LINES);
 -                      glVertex2f(x1, y3);
 -                      glVertex2f(x2, y3);
 -
 -                      glVertex2f(x3, y1);
 -                      glVertex2f(x3, y2);
 -                      glEnd();
 -              }
 -
 -              if (ca->dtx & CAM_DTX_CENTER_DIAG) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -
 -                      glBegin(GL_LINES);
 -                      glVertex2f(x1, y1);
 -                      glVertex2f(x2, y2);
 -
 -                      glVertex2f(x1, y2);
 -                      glVertex2f(x2, y1);
 -                      glEnd();
 -              }
 -
 -              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);
 -              }
 -
 -              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 (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');
 -              }
 -
 -              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');
 -              }
 -
 -              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 (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');
 -              }
 -
 -              if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
 -                      UI_draw_safe_areas(
 -                              x1, x2, y1, y2,
 -                              scene->safe_areas.title,
 -                              scene->safe_areas.action);
 -
 -                      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);
 -                      }
 -              }
 -
 -              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;
 -
 -                      /* determine sensor plane */
 -                      rctf rect;
 -
 -                      if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
 -                              float sensor_scale = (x2i - x1i) / sensor_x;
 -                              float sensor_height = sensor_scale * sensor_y;
 -
 -                              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;
 -
 -                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 -                              rect.xmax = rect.xmin + sensor_width;
 -                              rect.ymin = y1i;
 -                              rect.ymax = y2i;
 -                      }
 -
 -                      /* 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);
 -              }
 -      }
 -
 -      setlinestyle(0);
 -
 -      /* 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);
 -      }
 -}
 -
 -/* *********************** backdraw for selection *************** */
 -
 -static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d, Object *obact, Object *obedit)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      int multisample_enabled;
 -
 -      BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
 -
 -      if (obact && (obact->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
 -                   BKE_paint_select_face_test(obact)))
 -      {
 -              /* do nothing */
 -      }
 -      /* texture paint mode sampling */
 -      else if (obact && (obact->mode & OB_MODE_TEXTURE_PAINT) &&
 -               (v3d->drawtype > OB_WIRE))
 -      {
 -              /* do nothing */
 -      }
 -      else if ((obact && (obact->mode & OB_MODE_PARTICLE_EDIT)) &&
 -               V3D_IS_ZBUF(v3d))
 -      {
 -              /* do nothing */
 -      }
 -      else if (obedit &&
 -               V3D_IS_ZBUF(v3d))
 -      {
 -              /* do nothing */
 -      }
 -      else {
 -              v3d->flag &= ~V3D_INVALID_BACKBUF;
 -              return;
 -      }
 -
 -      if (!(v3d->flag & V3D_INVALID_BACKBUF))
 -              return;
 -
 -#if 0
 -      if (test) {
 -              if (qtest()) {
 -                      addafterqueue(ar->win, BACKBUFDRAW, 1);
 -                      return;
 -              }
 -      }
 -#endif
 -
 -      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;
 -                      }
 -              }
 -
 -              if (!rv3d->gpuoffscreen) {
 -                      rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
 -
 -                      if (!rv3d->gpuoffscreen)
 -                              fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
 -              }
 -      }
 -
 -      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));
 -
 -      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 (obact && (obact->lay & v3d->lay)) {
 -              draw_object_backbufsel(scene, v3d, rv3d, obact);
 -      }
 -
 -      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();
 -}
 -
 -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 (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);
 -      }
 -}
 -
 -/* 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)
 -{
 -
 -      glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 -}
 -
 -void ED_view3d_backbuf_validate(ViewContext *vc)
 -{
 -      if (vc->v3d->flag & V3D_INVALID_BACKBUF) {
 -              backdrawview3d(vc->scene, vc->win, vc->ar, vc->v3d, vc->obact, vc->obedit);
 -      }
 -}
 -
 -/**
 - * 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));
 -}
 -
 -/* 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;
 -      }
 -
 -      ED_view3d_backbuf_validate(vc);
 -
 -      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);
 -}
 -
 -/* 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;
 -      }
 -
 -      ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
 -
 -      ED_view3d_backbuf_validate(vc);
 -
 -      view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
 -
 -      glReadBuffer(GL_BACK);
 -
 -      if (ENDIAN_ORDER == B_ENDIAN) {
 -              IMB_convert_rgba_to_abgr(ibuf_clip);
 -      }
 -
 -      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;
 -      }
 -      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 rectangle spiral ling outside, nice for backbuf selection
 - */
 -uint 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;
 -
 -      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;
 -
 -      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;
 -                              }
 -
 -                              tbuf += (dirvec[rc][0] + dirvec[rc][1]);
 -
 -                              if (tbuf < bufmin || tbuf >= bufmax) {
 -                                      goto exit;
 -                              }
 -                      }
 -                      rc++;
 -                      rc &= 3;
 -              }
 -      }
 -
 -exit:
 -      IMB_freeImBuf(buf);
 -      return index;
 -}
 -
 -
 -/* ************************************************************* */
 -
 -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;
 -
 -              if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 -                      iuser->multiview_eye = STEREO_LEFT_ID;
 -              }
 -              else if (v3d->stereo3d_camera != STEREO_3D_ID) {
 -                      /* show only left or right camera */
 -                      iuser->multiview_eye = v3d->stereo3d_camera;
 -              }
 -
 -              BKE_image_multiview_index(ima, iuser);
 -      }
 -      else {
 -              iuser->flag &= ~IMA_SHOW_STEREO;
 -      }
 -}
 -
 -static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
 -                              const bool do_foreground, const bool do_camera_frame)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      BGpic *bgpic;
 -      int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
 -
 -      for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
 -              bgpic->iuser.scene = scene;  /* Needed for render results. */
 -
 -              if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
 -                      continue;
 -
 -              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;
 -                              }
 -
 -                              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) */
 -
 -                              if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
 -                                      if (scene->camera)
 -                                              clip = BKE_object_movieclip_get(scene, scene->camera, true);
 -                              }
 -                              else {
 -                                      clip = bgpic->clip;
 -                              }
 -
 -                              if (clip == NULL)
 -                                      continue;
 -
 -                              BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
 -                              ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
 -
 -                              image_aspect[0] = clip->aspx;
 -                              image_aspect[1] = clip->aspy;
 -
 -                              /* 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);
 -                      }
 -
 -                      if (ibuf == NULL)
 -                              continue;
 -
 -                      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);
 -
 -                              continue;
 -                      }
 -
 -                      if (ibuf->rect == NULL)
 -                              IMB_rect_from_float(ibuf);
 -
 -                      if (rv3d->persp == RV3D_CAMOB) {
 -
 -                              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;
 -                              }
 -
 -                              /* 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;
 -                              }
 -
 -                              centx = (x1 + x2) / 2.0f;
 -                              centy = (y1 + y2) / 2.0f;
 -
 -                              /* 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];
 -
 -                                      /* destination aspect is already applied from the camera frame */
 -                                      const float w_dst = x1 - x2;
 -                                      const float h_dst = y1 - y2;
 -
 -                                      const float asp_src = w_src / h_src;
 -                                      const float asp_dst = w_dst / h_dst;
 -
 -                                      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;
 -                                              }
 -                                      }
 -                              }
 -                      }
 -                      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);
 -                      }
 -
 -                      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);
 -
 -                              continue;
 -                      }
 -
 -                      zoomx = (x2 - x1) / ibuf->x;
 -                      zoomy = (y2 - y1) / ibuf->y;
 -
 -                      /* 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;
 -
 -                              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);
 -
 -                      glEnable(GL_BLEND);
 -                      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
 -
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      ED_region_pixelspace(ar);
 -
 -                      glTranslatef(centx, centy, 0.0);
 -                      glRotatef(RAD2DEGF(-bgpic->rotation), 0.0f, 0.0f, 1.0f);
 -
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_X) {
 -                              zoomx *= -1.0f;
 -                              x1 = x2;
 -                      }
 -                      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);
 -
 -                      glDepthMask(1);
 -                      if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 -
 -                      if (freeibuf)
 -                              IMB_freeImBuf(freeibuf);
 -                      if (releaseibuf)
 -                              BKE_image_release_ibuf(ima, releaseibuf, lock);
 -              }
 -      }
 -}
 -
 -static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
 -                                   const bool do_foreground, const bool do_camera_frame)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      if ((v3d->flag & V3D_DISPBGPICS) == 0)
 -              return;
 -
 -      /* disabled - mango request, since footage /w only render is quite useful
 -       * and this option is easy to disable all background images at once */
 -#if 0
 -      if (v3d->flag2 & V3D_RENDER_OVERRIDE)
 -              return;
 -#endif
 -
 -      if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
 -              if (rv3d->persp == RV3D_CAMOB) {
 -                      view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
 -              }
 -      }
 -      else {
 -              view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
 -      }
 -}
 -
 -/* ****************** View3d afterdraw *************** */
 -
 -typedef struct View3DAfter {
 -      struct View3DAfter *next, *prev;
 -      struct Base *base;
 -      short dflag;
 -} View3DAfter;
 -
 -/* temp storage of Objects that need to be drawn as last */
 -void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
 -{
 -      View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
 -      BLI_assert((base->flag & OB_FROMDUPLI) == 0);
 -      BLI_addtail(lb, v3da);
 -      v3da->base = base;
 -      v3da->dflag = dflag;
 -}
 -
 -/* disables write in zbuffer and draws it over */
 -static void view3d_draw_transp(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      View3DAfter *v3da;
 -
 -      glDepthMask(GL_FALSE);
 -      v3d->transp = true;
 -
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
 -              draw_object(bmain, scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 -      v3d->transp = false;
 -
 -      glDepthMask(GL_TRUE);
 -
 -}
 -
 -/* clears zbuffer and draws it over */
 -static void view3d_draw_xray(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
 -{
 -      View3DAfter *v3da;
 -
 -      if (*clear && v3d->zbuf) {
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -              *clear = false;
 -      }
 -
 -      v3d->xray = true;
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -              draw_object(bmain, scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 -      v3d->xray = false;
 -}
 -
 -
 -/* clears zbuffer and draws it over */
 -static void view3d_draw_xraytransp(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d, const bool clear)
 -{
 -      View3DAfter *v3da;
 -
 -      if (clear && v3d->zbuf)
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -
 -      v3d->xray = true;
 -      v3d->transp = true;
 -
 -      glDepthMask(GL_FALSE);
 -
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 -              draw_object(bmain, scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 -
 -      v3d->transp = false;
 -      v3d->xray = false;
 -
 -      glDepthMask(GL_TRUE);
 -}
 -
 -/* clears zbuffer and draws it over,
 - * note that in the select version we don't care about transparent flag as with regular drawing */
 -static void view3d_draw_xray_select(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
 -{
 -      /* Not ideal, but we need to read from the previous depths before clearing
 -       * otherwise we could have a function to load the depths after drawing.
 -       *
 -       * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
 -       */
 -      if (U.gpu_select_pick_deph) {
 -              GPU_select_load_id(-1);
 -      }
 -
 -      View3DAfter *v3da;
 -      if (*clear && v3d->zbuf) {
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -              *clear = false;
 -      }
 -
 -      v3d->xray = true;
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -              if (GPU_select_load_id(v3da->base->selcol)) {
 -                      draw_object_select(bmain, scene, ar, v3d, v3da->base, v3da->dflag);
 -              }
 -              MEM_freeN(v3da);
 -      }
 -      v3d->xray = false;
 -}
 -
 -/* *********************** */
 -
 -/*
 - * In most cases call draw_dupli_objects,
 - * draw_dupli_objects_color was added because when drawing set dupli's
 - * we need to force the color
 - */
 -
 -#if 0
 -int dupli_ob_sort(void *arg1, void *arg2)
 -{
 -      void *p1 = ((DupliObject *)arg1)->ob;
 -      void *p2 = ((DupliObject *)arg2)->ob;
 -      int val = 0;
 -      if (p1 < p2) val = -1;
 -      else if (p1 > p2) val = 1;
 -      return val;
 -}
 -#endif
 -
 -
 -static DupliObject *dupli_step(DupliObject *dob)
 -{
 -      while (dob && dob->no_draw)
 -              dob = dob->next;
 -      return dob;
 -}
 -
 -static void draw_dupli_objects_color(
 -        Main *bmain, Scene *scene, ARegion *ar, View3D *v3d, Base *base,
 -        const short dflag, const int color)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      ListBase *lb;
 -      LodLevel *savedlod;
 -      DupliObject *dob_prev = NULL, *dob, *dob_next = NULL;
 -      Base tbase = {NULL};
 -      BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
 -      GLuint displist = 0;
 -      unsigned char color_rgb[3];
 -      const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
 -      short transflag;
 -      bool use_displist = false;  /* -1 is initialize */
 -      char dt;
 -      short dtx;
 -      DupliApplyData *apply_data;
 -
 -      if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
 -      if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
 -
 -      if (dflag & DRAW_CONSTCOLOR) {
 -              BLI_assert(color == TH_UNDEFINED);
 -      }
 -      else {
 -              UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
 -      }
 -
 -      tbase.flag = OB_FROMDUPLI | base->flag;
 -      lb = object_duplilist(bmain, bmain->eval_ctx, scene, base->object);
 -      // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
 -
 -      apply_data = duplilist_apply(base->object, scene, lb);
 -
 -      dob = dupli_step(lb->first);
 -      if (dob) dob_next = dupli_step(dob->next);
 -
 -      for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
 -              bool testbb = false;
 -
 -              tbase.object = dob->ob;
 -
 -              /* Make sure lod is updated from dupli's position */
 -              savedlod = dob->ob->currentlod;
 -
 -#ifdef WITH_GAMEENGINE
 -              if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
 -                      BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
 -              }
 -#endif
 -
 -              /* extra service: draw the duplicator in drawtype of parent, minimum taken
 -               * to allow e.g. boundbox box objects in groups for LOD */
 -              dt = tbase.object->dt;
 -              tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
 -
 -              /* inherit draw extra, but not if a boundbox under the assumption that this
 -               * is intended to speed up drawing, and drawing extra (especially wire) can
 -               * slow it down too much */
 -              dtx = tbase.object->dtx;
 -              if (tbase.object->dt != OB_BOUNDBOX)
 -                      tbase.object->dtx = base->object->dtx;
 -
 -              /* negative scale flag has to propagate */
 -              transflag = tbase.object->transflag;
 -
 -              if (is_negative_m4(dob->mat))
 -                      tbase.object->transflag |= OB_NEG_SCALE;
 -              else
 -                      tbase.object->transflag &= ~OB_NEG_SCALE;
 -
 -              /* should move outside the loop but possible color is set in draw_object still */
 -              if ((dflag & DRAW_CONSTCOLOR) == 0) {
 -                      glColor3ubv(color_rgb);
 -              }
 -
 -              /* generate displist, test for new object */
 -              if (dob_prev && dob_prev->ob != dob->ob) {
 -                      if (use_displist == true)
 -                              glDeleteLists(displist, 1);
 -
 -                      use_displist = false;
 -              }
 -
 -              if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
 -                      bb = *bb_tmp; /* must make a copy  */
 -                      testbb = true;
 -              }
 -
 -              if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
 -                      /* generate displist */
 -                      if (use_displist == false) {
 -
 -                              /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
 -                               * however this is very slow, it was probably needed for the NLA
 -                               * offset feature (used in group-duplicate.blend but no longer works in 2.5)
 -                               * so for now it should be ok to - campbell */
 -
 -                              if ( /* if this is the last no need  to make a displist */
 -                                   (dob_next == NULL || dob_next->ob != dob->ob) ||
 -                                   /* lamp drawing messes with matrices, could be handled smarter... but this works */
 -                                   (dob->ob->type == OB_LAMP) ||
 -                                   (dob->type == OB_DUPLIGROUP && dob->animated) ||
 -                                   !bb_tmp ||
 -                                   draw_glsl_material(scene, dob->ob, v3d, dt) ||
 -                                   check_object_draw_texture(scene, v3d, dt) ||
 -                                   (v3d->flag2 & V3D_SOLID_MATCAP) != 0)
 -                              {
 -                                      // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name + 2);
 -                                      use_displist = false;
 -                              }
 -                              else {
 -                                      // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name + 2);
 -
 -                                      /* disable boundbox check for list creation */
 -                                      BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 1);
 -                                      /* need this for next part of code */
 -                                      unit_m4(dob->ob->obmat);    /* obmat gets restored */
 -
 -                                      displist = glGenLists(1);
 -                                      glNewList(displist, GL_COMPILE);
 -                                      draw_object(bmain, scene, ar, v3d, &tbase, dflag_dupli);
 -                                      glEndList();
 -
 -                                      use_displist = true;
 -                                      BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 0);
 -                              }
 -                      }
 -
 -                      if (use_displist) {
 -                              glPushMatrix();
 -                              glMultMatrixf(dob->mat);
 -                              glCallList(displist);
 -                              glPopMatrix();
 -                      }
 -                      else {
 -                              copy_m4_m4(dob->ob->obmat, dob->mat);
 -                              GPU_begin_dupli_object(dob);
 -                              draw_object(bmain, scene, ar, v3d, &tbase, dflag_dupli);
 -                              GPU_end_dupli_object();
 -                      }
 -              }
 -
 -              tbase.object->dt = dt;
 -              tbase.object->dtx = dtx;
 -              tbase.object->transflag = transflag;
 -              tbase.object->currentlod = savedlod;
 -      }
 -
 -      if (apply_data) {
 -              duplilist_restore(lb, apply_data);
 -              duplilist_free_apply_data(apply_data);
 -      }
 -
 -      free_object_duplilist(lb);
 -
 -      if (use_displist)
 -              glDeleteLists(displist, 1);
 -}
 -
 -static void draw_dupli_objects(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d, Base *base)
 -{
 -      /* define the color here so draw_dupli_objects_color can be called
 -       * from the set loop */
 -
 -      int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
 -      /* debug */
 -      if (base->object->dup_group && base->object->dup_group->id.us < 1)
 -              color = TH_REDALERT;
 -
 -      draw_dupli_objects_color(bmain, scene, ar, v3d, base, 0, color);
 -}
 -
 -/* XXX warning, not using gpu offscreen here */
 -void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
 -{
 -      int x, y, w, h;
 -      rcti r;
 -      /* clamp rect by region */
 -
 -      r.xmin = 0;
 -      r.xmax = ar->winx - 1;
 -      r.ymin = 0;
 -      r.ymax = ar->winy - 1;
 -
 -      /* Constrain rect to depth bounds */
 -      BLI_rcti_isect(&r, rect, rect);
 -
 -      /* assign values to compare with the ViewDepths */
 -      x = rect->xmin;
 -      y = rect->ymin;
 -
 -      w = BLI_rcti_size_x(rect);
 -      h = BLI_rcti_size_y(rect);
 -
 -      if (w <= 0 || h <= 0) {
 -              if (d->depths)
 -                      MEM_freeN(d->depths);
 -              d->depths = NULL;
 -
 -              d->damaged = false;
 -      }
 -      else if (d->w != w ||
 -               d->h != h ||
 -               d->x != x ||
 -               d->y != y ||
 -               d->depths == NULL
 -               )
 -      {
 -              d->x = x;
 -              d->y = y;
 -              d->w = w;
 -              d->h = h;
 -
 -              if (d->depths)
 -                      MEM_freeN(d->depths);
 -
 -              d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
 -
 -              d->damaged = true;
 -      }
 -
 -      if (d->damaged) {
 -              /* XXX using special function here, it doesn't use the gpu offscreen system */
 -              view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
 -              glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
 -              d->damaged = false;
 -      }
 -}
 -
 -/* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
 -void ED_view3d_depth_update(ARegion *ar)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      /* Create storage for, and, if necessary, copy depth buffer */
 -      if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
 -      if (rv3d->depths) {
 -              ViewDepths *d = rv3d->depths;
 -              if (d->w != ar->winx ||
 -                  d->h != ar->winy ||
 -                  !d->depths)
 -              {
 -                      d->w = ar->winx;
 -                      d->h = ar->winy;
 -                      if (d->depths)
 -                              MEM_freeN(d->depths);
 -                      d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
 -                      d->damaged = true;
 -              }
 -
 -              if (d->damaged) {
 -                      view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
 -                      glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
 -
 -                      d->damaged = false;
 -              }
 -      }
 -}
 -
 -/* utility function to find the closest Z value, use for autodepth */
 -float view3d_depth_near(ViewDepths *d)
 -{
 -      /* convert to float for comparisons */
 -      const float near = (float)d->depth_range[0];
 -      const float far_real = (float)d->depth_range[1];
 -      float far = far_real;
 -
 -      const float *depths = d->depths;
 -      float depth = FLT_MAX;
 -      int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
 -
 -      /* far is both the starting 'far' value
 -       * and the closest value found. */
 -      while (i--) {
 -              depth = *depths++;
 -              if ((depth < far) && (depth > near)) {
 -                      far = depth;
 -              }
 -      }
 -
 -      return far == far_real ? FLT_MAX : far;
 -}
 -
 -void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      short zbuf = v3d->zbuf;
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      /* Setup view matrix. */
 -      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->viewmat, rv3d->winmat, NULL);
 -
 -      glClear(GL_DEPTH_BUFFER_BIT);
 -
 -      v3d->zbuf = true;
 -      glEnable(GL_DEPTH_TEST);
 -
 -      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 -              ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
 -      }
 -
 -      v3d->zbuf = zbuf;
 -}
 -
 -static void view3d_draw_depth_loop(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      Base *base;
 -
 -      /* no need for color when drawing depth buffer */
 -      const short dflag_depth = DRAW_CONSTCOLOR;
 -
 -      /* draw set first */
 -      if (scene->set) {
 -              Scene *sce_iter;
 -              for (SETLOOPER(scene->set, sce_iter, base)) {
 -                      if (v3d->lay & base->lay) {
 -                              draw_object(bmain, scene, ar, v3d, base, 0);
 -                              if (base->object->transflag & OB_DUPLI) {
 -                                      draw_dupli_objects_color(bmain, scene, ar, v3d, base, dflag_depth, TH_UNDEFINED);
 -                              }
 -                      }
 -              }
 -      }
 -
 -      for (base = scene->base.first; base; base = base->next) {
 -              if (v3d->lay & base->lay) {
 -                      /* dupli drawing */
 -                      if (base->object->transflag & OB_DUPLI) {
 -                              draw_dupli_objects_color(bmain, scene, ar, v3d, base, dflag_depth, TH_UNDEFINED);
 -                      }
 -                      draw_object(bmain, scene, ar, v3d, base, dflag_depth);
 -              }
 -      }
 -
 -      /* this isn't that nice, draw xray objects as if they are normal */
 -      if (v3d->afterdraw_transp.first ||
 -          v3d->afterdraw_xray.first ||
 -          v3d->afterdraw_xraytransp.first)
 -      {
 -              View3DAfter *v3da;
 -              int mask_orig;
 -
 -              v3d->xray = true;
 -
 -              /* transp materials can change the depth mask, see #21388 */
 -              glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
 -
 -
 -              if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
 -                      glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
 -                      for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
 -                              draw_object(bmain, scene, ar, v3d, v3da->base, dflag_depth);
 -                      }
 -                      glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
 -              }
 -
 -              /* draw 3 passes, transp/xray/xraytransp */
 -              v3d->xray = false;
 -              v3d->transp = true;
 -              while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
 -                      draw_object(bmain, scene, ar, v3d, v3da->base, dflag_depth);
 -                      MEM_freeN(v3da);
 -              }
 -
 -              v3d->xray = true;
 -              v3d->transp = false;
 -              while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -                      draw_object(bmain, scene, ar, v3d, v3da->base, dflag_depth);
 -                      MEM_freeN(v3da);
 -              }
 -
 -              v3d->xray = true;
 -              v3d->transp = true;
 -              while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 -                      draw_object(bmain, scene, ar, v3d, v3da->base, dflag_depth);
 -                      MEM_freeN(v3da);
 -              }
 -
 -
 -              v3d->xray = false;
 -              v3d->transp = false;
 -
 -              glDepthMask(mask_orig);
 -      }
 -}
 -
 -void ED_view3d_draw_depth(Main *bmain, Scene *scene, ARegion *ar, View3D *v3d, bool alphaoverride)
 -{
 -      struct bThemeState theme_state;
 -      RegionView3D *rv3d = ar->regiondata;
 -      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;
 -
 -      /* Tools may request depth outside of regular drawing code. */
 -      UI_Theme_Store(&theme_state);
 -      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
 -
 -      /* Setup view matrix. */
 -      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->viewmat, rv3d->winmat, NULL);
 -
 -      glClear(GL_DEPTH_BUFFER_BIT);
 -
 -      if (rv3d->rflag & RV3D_CLIPPING) {
 -              ED_view3d_clipping_set(rv3d);
 -      }
 -      /* get surface depth without bias */
 -      rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
 -
 -      v3d->zbuf = true;
 -      glEnable(GL_DEPTH_TEST);
 -
 -      view3d_draw_depth_loop(bmain, scene, ar, v3d);
 -
 -      if (rv3d->rflag & RV3D_CLIPPING) {
 -              ED_view3d_clipping_disable();
 -      }
 -      rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
 -
 -      v3d->zbuf = zbuf;
 -      if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
 -
 -      U.glalphaclip = glalphaclip;
 -      v3d->flag = flag;
 -      U.obcenter_dia = obcenter_dia;
 -
 -      UI_Theme_Restore(&theme_state);
 -}
 -
 -void ED_view3d_draw_select_loop(
 -        ViewContext *vc, Scene *scene, View3D *v3d, ARegion *ar,
 -        bool use_obedit_skip, bool use_nearest)
 -{
 -      short code = 1;
 -      const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
 -
 -      if (vc->obedit && vc->obedit->type == OB_MBALL) {
 -              draw_object(vc->bmain, scene, ar, v3d, BASACT, dflag);
 -      }
 -      else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
 -              /* if not drawing sketch, draw bones */
 -              if (!BDR_drawSketchNames(vc)) {
 -                      draw_object(vc->bmain, scene, ar, v3d, BASACT, dflag);
 -              }
 -      }
 -      else {
 -              Base *base;
 -
 -              for (base = scene->base.first; base; base = base->next) {
 -                      if (base->lay & v3d->lay) {
 -
 -                              if ((base->object->restrictflag & OB_RESTRICT_SELECT) ||
 -                                  (use_obedit_skip && (scene->obedit->data == base->object->data)))
 -                              {
 -                                      base->selcol = 0;
 -                              }
 -                              else {
 -                                      base->selcol = code;
 -
 -                                      if (use_nearest && (base->object->dtx & OB_DRAWXRAY)) {
 -                                              ED_view3d_after_add(&v3d->afterdraw_xray, base, dflag);
 -                                      }
 -                                      else {
 -                                              if (GPU_select_load_id(code)) {
 -                                                      draw_object_select(vc->bmain, scene, ar, v3d, base, dflag);
 -                                              }
 -                                      }
 -                                      code++;
 -                              }
 -                      }
 -              }
 -
 -              if (use_nearest) {
 -                      bool xrayclear = true;
 -                      if (v3d->afterdraw_xray.first) {
 -                              view3d_draw_xray_select(vc->bmain, scene, ar, v3d, &xrayclear);
 -                      }
 -              }
 -      }
 -}
 -
 -typedef struct View3DShadow {
 -      struct View3DShadow *next, *prev;
 -      GPULamp *lamp;
 -} View3DShadow;
 -
 -static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
 -                                   Object *ob, Object *par,
 -                                   float obmat[4][4], unsigned int lay,
 -                                   ListBase *shadows, SceneRenderLayer *srl)
 -{
 -      GPULamp *lamp;
 -      Lamp *la = (Lamp *)ob->data;
 -      View3DShadow *shadow;
 -      unsigned int layers;
 -
 -      lamp = GPU_lamp_from_blender(scene, ob, par);
 -
 -      if (lamp) {
 -              GPU_lamp_update(lamp, lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
 -              GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
 -
 -              layers = lay & v3d->lay;
 -              if (srl)
 -                      layers &= srl->lay;
 -
 -              if (layers &&
 -                  GPU_lamp_has_shadow_buffer(lamp) &&
 -                  /* keep last, may do string lookup */
 -                  GPU_lamp_visible(lamp, srl, NULL))
 -              {
 -                      shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
 -                      shadow->lamp = lamp;
 -                      BLI_addtail(shadows, shadow);
 -              }
 -      }
 -}
 -
 -static void gpu_update_lamps_shadows_world(Main *bmain, Scene *scene, View3D *v3d)
 -{
 -      ListBase shadows;
 -      View3DShadow *shadow;
 -      Scene *sce_iter;
 -      Base *base;
 -      Object *ob;
 -      World *world = scene->world;
 -      SceneRenderLayer *srl = v3d->scenelock ? BLI_findlink(&scene->r.layers, scene->r.actlay) : NULL;
 -
 -      BLI_listbase_clear(&shadows);
 -
 -      /* update lamp transform and gather shadow lamps */
 -      for (SETLOOPER(scene, sce_iter, base)) {
 -              ob = base->object;
 -
 -              if (ob->type == OB_LAMP)
 -                      gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, ob->lay, &shadows, srl);
 -
 -              if (ob->transflag & OB_DUPLI) {
 -                      DupliObject *dob;
 -                      ListBase *lb = object_duplilist(bmain, bmain->eval_ctx, scene, ob);
 -
 -                      for (dob = lb->first; dob; dob = dob->next)
 -                              if (dob->ob->type == OB_LAMP)
 -                                      gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, ob->lay, &shadows, srl);
 -
 -                      free_object_duplilist(lb);
 -              }
 -      }
 -
 -      /* render shadows after updating all lamps, nested object_duplilist
 -       * don't work correct since it's replacing object matrices */
 -      for (shadow = shadows.first; shadow; shadow = shadow->next) {
 -              /* this needs to be done better .. */
 -              float viewmat[4][4], winmat[4][4];
 -              int drawtype, lay, winsize, flag2 = v3d->flag2;
 -              ARegion ar = {NULL};
 -              RegionView3D rv3d = {{{0}}};
 -
 -              drawtype = v3d->drawtype;
 -              lay = v3d->lay;
 -
 -              v3d->drawtype = OB_SOLID;
 -              v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
 -              v3d->flag2 &= ~(V3D_SOLID_TEX | V3D_SHOW_SOLID_MATCAP);
 -              v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
 -
 -              GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
 -
 -              ar.regiondata = &rv3d;
 -              ar.regiontype = RGN_TYPE_WINDOW;
 -              rv3d.persp = RV3D_CAMOB;
 -              copy_m4_m4(rv3d.winmat, winmat);
 -              copy_m4_m4(rv3d.viewmat, viewmat);
 -              invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
 -              mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
 -              invert_m4_m4(rv3d.persinv, rv3d.viewinv);
 -
 -              /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
 -              ED_view3d_draw_offscreen(
 -                          bmain, scene, v3d, &ar, winsize, winsize, viewmat, winmat,
 -                          false, false, true,
 -                          NULL, NULL, NULL, NULL);
 -              GPU_lamp_shadow_buffer_unbind(shadow->lamp);
 -
 -              v3d->drawtype = drawtype;
 -              v3d->lay = lay;
 -              v3d->flag2 = flag2;
 -      }
 -
 -      BLI_freelistN(&shadows);
 -
 -      /* update world values */
 -      if (world) {
 -              GPU_mist_update_enable(world->mode & WO_MIST);
 -              GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr);
 -              GPU_horizon_update_color(&world->horr);
 -              GPU_ambient_update_color(&world->ambr);
 -              GPU_zenith_update_color(&world->zenr);
 -      }
 -}
 -
 -/* *********************** customdata **************** */
 -
 -CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d)
 -{
 -      CustomDataMask mask = 0;
 -      const int drawtype = view3d_effective_drawtype(v3d);
 -
 -      if (ELEM(drawtype, OB_TEXTURE, OB_MATERIAL) ||
 -          ((drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
 -      {
 -              mask |= CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
 -
 -              if (BKE_scene_use_new_shading_nodes(scene)) {
 -                      if (drawtype == OB_MATERIAL)
 -                              mask |= CD_MASK_ORCO;
 -              }
 -              else {
 -                      if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) ||
 -                          (drawtype == OB_MATERIAL))
 -                      {
 -                              mask |= CD_MASK_ORCO;
 -                      }
 -              }
 -      }
 -
 -      return mask;
 -}
 -
 -/* goes over all modes and view3d settings */
 -CustomDataMask ED_view3d_screen_datamask(const bScreen *screen)
 -{
 -      const Scene *scene = screen->scene;
 -      CustomDataMask mask = CD_MASK_BAREMESH;
 -      const ScrArea *sa;
 -
 -      /* check if we need tfaces & mcols due to view mode */
 -      for (sa = screen->areabase.first; sa; sa = sa->next) {
 -              if (sa->spacetype == SPACE_VIEW3D) {
 -                      mask |= ED_view3d_datamask(scene, sa->spacedata.first);
 -              }
 -      }
 -
 -      return mask;
 -}
 -
 -/**
 - * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
 - */
 -void ED_view3d_update_viewmat(
 -        Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      /* setup window matrices */
 -      if (winmat)
 -              copy_m4_m4(rv3d->winmat, winmat);
 -      else
 -              view3d_winmatrix_set(ar, v3d, rect);
 -
 -      /* setup view matrix */
 -      if (viewmat) {
 -              copy_m4_m4(rv3d->viewmat, viewmat);
 -      }
 -      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;
 -              }
 -              view3d_viewmatrix_set(scene, v3d, rv3d, rect ? rect_scale : NULL);  /* note: calls BKE_object_where_is_calc for camera... */
 -      }
 -
 -      /* 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 */
 -
 -      /* store window coordinates scaling/offset */
 -      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 -              rctf cameraborder;
 -              ED_view3d_calc_camera_border(scene, 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;
 -      }
 -
 -      /**
 -       * Calculate pixel-size factor once, is used for lamps and object centers.
 -       * Used by #ED_view3d_pixel_size and typically not accessed directly.
 -       *
 -       * \note #BKE_camera_params_compute_viewplane' also calculates a pixel-size value,
 -       * passed to #RE_SetPixelSize, in ortho mode this is compatible with this value,
 -       * but in perspective mode its offset by the near-clip.
 -       *
 -       * 'RegionView3D.pixsize' is used for viewport drawing, not rendering.
 -       */
 -      {
 -              /* 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;
 -
 -              v1[0] = rv3d->persmat[0][0];
 -              v1[1] = rv3d->persmat[1][0];
 -              v1[2] = rv3d->persmat[2][0];
 -
 -              v2[0] = rv3d->persmat[0][1];
 -              v2[1] = rv3d->persmat[1][1];
 -              v2[2] = rv3d->persmat[2][1];
 -
 -              len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
 -              len_sc = (float)MAX2(ar->winx, ar->winy);
 -
 -              rv3d->pixsize = len_px / len_sc;
 -      }
 -}
 -
 -/**
 - * Shared by #ED_view3d_draw_offscreen and #view3d_main_region_draw_objects
 - *
 - * \note \a C and \a grid_unit will be NULL when \a draw_offscreen is set.
 - * \note Drawing lamps and opengl render uses this, so dont do grease pencil or view widgets here.
 - */
 -static void view3d_draw_objects(
 -        const bContext *C,
 -        Main *bmain,
 -        Scene *scene, View3D *v3d, ARegion *ar,
 -        const char **grid_unit,
 -        const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
 -{
 -      if (bmain == NULL) {
 -              bmain = CTX_data_main(C);
 -      }
 -      RegionView3D *rv3d = ar->regiondata;
 -      Base *base;
 -      const bool do_camera_frame = !draw_offscreen;
 -      const bool draw_grids = !draw_offscreen && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0;
 -      const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
 -      /* only draw grids after in solid modes, else it hovers over mesh wires */
 -      const bool draw_grids_after = draw_grids && draw_floor && (v3d->drawtype > OB_WIRE) && fx;
 -      bool do_composite_xray = false;
 -      bool xrayclear = true;
 -
 -      if (!draw_offscreen) {
 -              ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
 -      }
 -
 -      if (rv3d->rflag & RV3D_CLIPPING)
 -              view3d_draw_clipping(rv3d);
 -
 -      /* set zbuffer after we draw clipping region */
 -      if (v3d->drawtype > OB_WIRE) {
 -              v3d->zbuf = true;
 -      }
 -      else {
 -              v3d->zbuf = false;
 -      }
 -
 -      /* 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) {
 -                              v3d->zbuf = true;
 -                      }
 -              }
 -      }
 -
 -      if (v3d->zbuf) {
 -              glEnable(GL_DEPTH_TEST);
 -      }
 -
 -      /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
 -       * objects if done last */
 -      if (draw_grids) {
 -              /* needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views. */
 -              rv3d->gridview = ED_view3d_grid_scale(scene, v3d, grid_unit);
 -
 -              if (!draw_floor) {
 -                      ED_region_pixelspace(ar);
 -                      *grid_unit = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
 -                      drawgrid(&scene->unit, ar, v3d, grid_unit);
 -                      /* XXX make function? replaces persp(1) */
 -                      glMatrixMode(GL_PROJECTION);
 -                      glLoadMatrixf(rv3d->winmat);
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glLoadMatrixf(rv3d->viewmat);
 -              }
 -              else if (!draw_grids_after) {
 -                      drawfloor(scene, v3d, grid_unit, true);
 -              }
 -      }
 -
 -      /* important to do before clipping */
 -      if (do_bgpic) {
 -              view3d_draw_bgpic_test(scene, ar, v3d, false, do_camera_frame);
 -      }
 -
 -      if (rv3d->rflag & RV3D_CLIPPING) {
 -              ED_view3d_clipping_set(rv3d);
 -      }
 -
 -      /* draw set first */
 -      if (scene->set) {
 -              const short dflag = DRAW_CONSTCOLOR | DRAW_SCENESET;
 -              Scene *sce_iter;
 -              for (SETLOOPER(scene->set, sce_iter, base)) {
 -                      if (v3d->lay & base->lay) {
 -                              UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
 -                              draw_object(bmain, scene, ar, v3d, base, dflag);
 -
 -                              if (base->object->transflag & OB_DUPLI) {
 -                                      draw_dupli_objects_color(bmain, scene, ar, v3d, base, dflag, TH_UNDEFINED);
 -                              }
 -                      }
 -              }
 -
 -              /* Transp and X-ray afterdraw stuff for sets is done later */
 -      }
 -
 -
 -      if (draw_offscreen) {
 -              for (base = scene->base.first; base; base = base->next) {
 -                      if (v3d->lay & base->lay) {
 -                              /* dupli drawing */
 -                              if (base->object->transflag & OB_DUPLI)
 -                                      draw_dupli_objects(bmain, scene, ar, v3d, base);
 -
 -                              draw_object(bmain, scene, ar, v3d, base, 0);
 -                      }
 -              }
 -      }
 -      else {
 -              unsigned int lay_used = 0;
 -
 -              /* then draw not selected and the duplis, but skip editmode object */
 -              for (base = scene->base.first; base; base = base->next) {
 -                      lay_used |= base->lay;
 -
 -                      if (v3d->lay & base->lay) {
 -
 -                              /* dupli drawing */
 -                              if (base->object->transflag & OB_DUPLI) {
 -                                      draw_dupli_objects(bmain, scene, ar, v3d, base);
 -                              }
 -                              if ((base->flag & SELECT) == 0) {
 -                                      if (base->object != scene->obedit)
 -                                              draw_object(bmain, scene, ar, v3d, base, 0);
 -                              }
 -                      }
 -              }
 -
 -              /* mask out localview */
 -              v3d->lay_used = lay_used & ((1 << 20) - 1);
 -
 -              /* draw selected and editmode */
 -              for (base = scene->base.first; base; base = base->next) {
 -                      if (v3d->lay & base->lay) {
 -                              if (base->object == scene->obedit || (base->flag & SELECT)) {
 -                                      draw_object(bmain, scene, ar, v3d, base, 0);
 -                              }
 -                      }
 -              }
 -      }
 -
 -      /* perspective floor goes last to use scene depth and avoid writing to depth buffer */
 -      if (draw_grids_after) {
 -              drawfloor(scene, v3d, grid_unit, false);
 -      }
 -
 -      /* must be before xray draw which clears the depth buffer */
 -      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 -              wmWindowManager *wm = (C != NULL) ? CTX_wm_manager(C) : NULL;
 -
 -              /* must be before xray draw which clears the depth buffer */
 -              if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
 -              ED_gpencil_draw_view3d(wm, scene, v3d, ar, true);
 -              if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 -      }
 -
 -      /* transp and X-ray afterdraw stuff */
 -      if (v3d->afterdraw_transp.first)     view3d_draw_transp(bmain, scene, ar, v3d);
 -
 -      /* always do that here to cleanup depth buffers if none needed */
 -      if (fx) {
 -              do_composite_xray = v3d->zbuf && (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first);
 -              GPU_fx_compositor_setup_XRay_pass(fx, do_composite_xray);
 -      }
 -
 -      if (v3d->afterdraw_xray.first)       view3d_draw_xray(bmain, scene, ar, v3d, &xrayclear);
 -      if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(bmain, scene, ar, v3d, xrayclear);
 -
 -      if (fx && do_composite_xray) {
 -              GPU_fx_compositor_XRay_resolve(fx);
 -      }
 -
 -      if (!draw_offscreen) {
 -              ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
 -      }
 -
 -      if (rv3d->rflag & RV3D_CLIPPING)
 -              ED_view3d_clipping_disable();
 -
 -      /* important to do after clipping */
 -      if (do_bgpic) {
 -              view3d_draw_bgpic_test(scene, ar, v3d, true, do_camera_frame);
 -      }
 -
 -      if (!draw_offscreen) {
 -              BIF_draw_manipulator(C);
 -      }
 -
 -      /* cleanup */
 -      if (v3d->zbuf) {
 -              v3d->zbuf = false;
 -              glDisable(GL_DEPTH_TEST);
 -      }
 -
 -      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 -              GPU_free_images_old(bmain);
 -      }
 -}
 -
 -static void view3d_main_region_setup_view(
 -        Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat, rect);
 -
 -      /* set for opengl */
 -      glMatrixMode(GL_PROJECTION);
 -      glLoadMatrixf(rv3d->winmat);
 -      glMatrixMode(GL_MODELVIEW);
 -      glLoadMatrixf(rv3d->viewmat);
 -}
 -
 -/**
 - * Store values from #RegionView3D, set when drawing.
 - * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
 - *
 - * Values set by #ED_view3d_update_viewmat should be handled here.
 - */
 -struct RV3DMatrixStore {
 -      float winmat[4][4];
 -      float viewmat[4][4];
 -      float viewinv[4][4];
 -      float persmat[4][4];
 -      float persinv[4][4];
 -      float viewcamtexcofac[4];
 -      float pixsize;
 -};
 -
 -struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
 -{
 -      struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
 -      copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
 -      copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
 -      copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
 -      copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
 -      copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
 -      copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
 -      rv3dmat->pixsize = rv3d->pixsize;
 -      return (void *)rv3dmat;
 -}
 -
 -void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat)
 -{
 -      copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
 -      copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
 -      copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
 -      copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
 -      copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
 -      copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
 -      rv3d->pixsize = rv3dmat->pixsize;
 -}
 -
 -void ED_view3d_draw_offscreen_init(Main *bmain, Scene *scene, View3D *v3d)
 -{
 -      /* shadow buffers, before we setup matrices */
 -      if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
 -              gpu_update_lamps_shadows_world(bmain, scene, v3d);
 -}
 -
 -/*
 - * Function to clear the view
 - */
 -static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
 -{
 -      if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) {
 -              RegionView3D *rv3d = ar->regiondata;
 -              GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
 -
 -              /* calculate full shader for background */
 -              GPU_material_bind(gpumat, 1, 1, 1.0, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac, (v3d->scenelock != 0));
 -
 -              bool material_not_bound = !GPU_material_bound(gpumat);
 -
 -              if (material_not_bound) {
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -                      glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
 -              }
 -
 -              /* Draw world */
 -              glEnable(GL_DEPTH_TEST);
 -              glDepthFunc(GL_ALWAYS);
 -              glBegin(GL_TRIANGLE_STRIP);
 -              glVertex3f(-1.0, -1.0, 1.0);
 -              glVertex3f(1.0, -1.0, 1.0);
 -              glVertex3f(-1.0, 1.0, 1.0);
 -              glVertex3f(1.0, 1.0, 1.0);
 -              glEnd();
 -
 -              if (material_not_bound) {
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 -              }
 -
 -              GPU_material_unbind(gpumat);
 -
 -              glDepthFunc(GL_LEQUAL);
 -              glDisable(GL_DEPTH_TEST);
 -      }
 -      else {
 -              if (UI_GetThemeValue(TH_SHOW_BACK_GRAD)) {
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -
 -                      glEnable(GL_DEPTH_TEST);
 -                      glDepthFunc(GL_ALWAYS);
 -                      glBegin(GL_QUADS);
 -                      UI_ThemeColor(TH_LOW_GRAD);
 -                      glVertex3f(-1.0, -1.0, 1.0);
 -                      glVertex3f(1.0, -1.0, 1.0);
 -                      UI_ThemeColor(TH_HIGH_GRAD);
 -                      glVertex3f(1.0, 1.0, 1.0);
 -                      glVertex3f(-1.0, 1.0, 1.0);
 -                      glEnd();
 -                      glDepthFunc(GL_LEQUAL);
 -                      glDisable(GL_DEPTH_TEST);
 -
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 -              }
 -              else {
 -                      UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
 -                      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -              }
 -      }
 -}
 -
 -/* ED_view3d_draw_offscreen_init should be called before this to initialize
 - * stuff like shadow buffers
 - */
 -void ED_view3d_draw_offscreen(
 -        Main *bmain, Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy,
 -        float viewmat[4][4], float winmat[4][4],
 -        bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
 -        GPUFX *fx, GPUFXSettings *fx_settings,
 -        GPUOffScreen *ofs)
 -{
 -      struct bThemeState theme_state;
 -      int bwinx, bwiny;
 -      rcti brect;
 -      bool do_compositing = false;
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      glPushMatrix();
 -
 -      /* set temporary new size */
 -      bwinx = ar->winx;
 -      bwiny = ar->winy;
 -      brect = ar->winrct;
 -
 -      ar->winx = winx;
 -      ar->winy = winy;
 -      ar->winrct.xmin = 0;
 -      ar->winrct.ymin = 0;
 -      ar->winrct.xmax = winx;
 -      ar->winrct.ymax = winy;
 -
 -      UI_Theme_Store(&theme_state);
 -      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
 -
 -      /* set flags */
 -      G.f |= G_RENDER_OGL;
 -
 -      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 -              /* free images which can have changed on frame-change
 -               * warning! can be slow so only free animated images - campbell */
 -              GPU_free_images_anim(bmain);
 -      }
 -
 -      /* setup view matrices before fx or unbinding the offscreen buffers will cause issues */
 -      if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
 -              view3d_stereo3d_setup_offscreen(scene, v3d, ar, winmat, viewname);
 -      else
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, NULL);
 -
 -      /* framebuffer fx needed, we need to draw offscreen first */
 -      if (v3d->fx_settings.fx_flag && fx) {
 -              GPUSSAOSettings *ssao = NULL;
 -
 -              if (v3d->drawtype < OB_SOLID) {
 -                      ssao = v3d->fx_settings.ssao;
 -                      v3d->fx_settings.ssao = NULL;
 -              }
 -
 -              do_compositing = GPU_fx_compositor_initialize_passes(fx, &ar->winrct, NULL, fx_settings);
 -
 -              if (ssao)
 -                      v3d->fx_settings.ssao = ssao;
 -      }
 -
 -      /* clear opengl buffers */
 -      if (do_sky) {
 -              view3d_main_region_clear(scene, v3d, ar);
 -      }
 -      else {
 -              glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 -              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -      }
 -
 -      /* main drawing call */
 -      view3d_draw_objects(NULL, bmain, scene, v3d, ar, NULL, do_bgpic, true, do_compositing ? fx : NULL);
 -
 -      /* post process */
 -      if (do_compositing) {
 -              if (!winmat)
 -                      is_persp = rv3d->is_persp;
 -              GPU_fx_do_composite_pass(fx, winmat, is_persp, scene, ofs);
 -      }
 -
 -      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 -              /* draw grease-pencil stuff */
 -              ED_region_pixelspace(ar);
 -
 -
 -              if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 -                      /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
 -                      ED_gpencil_draw_view3d(NULL, scene, v3d, ar, false);
 -              }
 -
 -              /* freeing the images again here could be done after the operator runs, leaving for now */
 -              GPU_free_images_anim(bmain);
 -      }
 -
 -      /* restore size */
 -      ar->winx = bwinx;
 -      ar->winy = bwiny;
 -      ar->winrct = brect;
 -
 -      glPopMatrix();
 -
 -      UI_Theme_Restore(&theme_state);
 -
 -      G.f &= ~G_RENDER_OGL;
 -}
 -
 -/**
 - * Set the correct matrices
 - */
 -void ED_view3d_draw_setup_view(
 -        wmWindow *win, Scene *scene, ARegion *ar, View3D *v3d, float viewmat[4][4], float winmat[4][4], const rcti *rect)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      /* Setup the view matrix. */
 -      if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
 -              view3d_stereo3d_setup(scene, v3d, ar, rect);
 -      }
 -      else {
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, rect);
 -      }
 -}
 -
 -/**
 - * Utility func for ED_view3d_draw_offscreen
 - *
 - * \param ofs: Optional off-screen buffer, can be NULL.
 - * (avoids re-creating when doing multiple GL renders).
 - */
 -ImBuf *ED_view3d_draw_offscreen_imbuf(
 -        Main *bmain, Scene *scene,
 -        View3D *v3d, ARegion *ar, int sizex, int sizey,
 -        unsigned int flag, unsigned int draw_flags,
 -        int alpha_mode, int samples, const char *viewname,
 -        /* output vars */
 -        GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      ImBuf *ibuf;
 -      const bool draw_sky = (alpha_mode == R_ADDSKY);
 -      const bool draw_background = (draw_flags & V3D_OFSDRAW_USE_BACKGROUND);
 -      const bool use_full_sample = (draw_flags & V3D_OFSDRAW_USE_FULL_SAMPLE);
 -
 -      /* view state */
 -      GPUFXSettings fx_settings = v3d->fx_settings;
 -      bool is_ortho = false;
 -      float winmat[4][4];
 -
 -      if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
 -              /* sizes differ, can't reuse */
 -              ofs = NULL;
 -      }
 -
 -      const bool own_ofs = (ofs == NULL);
 -
 -      if (own_ofs) {
 -              /* bind */
 -              ofs = GPU_offscreen_create(sizex, sizey, use_full_sample ? 0 : samples, err_out);
 -              if (ofs == NULL) {
 -                      return NULL;
 -              }
 -      }
 -
 -      ED_view3d_draw_offscreen_init(bmain, scene, v3d);
 -
 -      GPU_offscreen_bind(ofs, true);
 -
 -      /* read in pixels & stamp */
 -      ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
 -
 -      /* render 3d view */
 -      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 -              CameraParams params;
 -              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
 -
 -              BKE_camera_params_init(&params);
 -              /* fallback for non camera objects */
 -              params.clipsta = v3d->near;
 -              params.clipend = v3d->far;
 -              BKE_camera_params_from_object(&params, camera);
 -              BKE_camera_multiview_params(&scene->r, &params, camera, viewname);
 -              BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
 -              BKE_camera_params_compute_matrix(&params);
 -
 -              BKE_camera_to_gpu_dof(camera, &fx_settings);
 -
 -              is_ortho = params.is_ortho;
 -              copy_m4_m4(winmat, params.winmat);
 -      }
 -      else {
 -              rctf viewplane;
 -              float clipsta, clipend;
 -
 -              is_ortho = ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
 -              if (is_ortho) {
 -                      orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
 -              }
 -              else {
 -                      perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
 -              }
 -      }
 -
 -      if ((samples && use_full_sample) == 0) {
 -              /* Single-pass render, common case */
 -              ED_view3d_draw_offscreen(
 -                      bmain, scene, v3d, ar, sizex, sizey, NULL, winmat,
 -                      draw_background, draw_sky, !is_ortho, viewname,
 -                      fx, &fx_settings, ofs);
 -
 -              if (ibuf->rect_float) {
 -                      GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
 -              }
 -              else if (ibuf->rect) {
 -                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
 -              }
 -      }
 -      else {
 -              /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
 -               * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
 -              static float jit_ofs[32][2];
 -              float winmat_jitter[4][4];
 -              /* use imbuf as temp storage, before writing into it from accumulation buffer */
 -              unsigned char *rect_temp = ibuf->rect ? (void *)ibuf->rect : (void *)ibuf->rect_float;
 -              unsigned int *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(int[4]), "accum1");
 -              unsigned int i;
 -              int j;
 -
 -              BLI_jitter_init(jit_ofs, samples);
 -
 -              /* first sample buffer, also initializes 'rv3d->persmat' */
 -              ED_view3d_draw_offscreen(
 -                      bmain, scene, v3d, ar, sizex, sizey, NULL, winmat,
 -                      draw_background, draw_sky, !is_ortho, viewname,
 -                      fx, &fx_settings, ofs);
 -              GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
 -
 -              i = sizex * sizey * 4;
 -              while (i--) {
 -                      accum_buffer[i] = rect_temp[i];
 -              }
 -
 -              /* skip the first sample */
 -              for (j = 1; j < samples; j++) {
 -                      copy_m4_m4(winmat_jitter, winmat);
 -                      window_translate_m4(
 -                              winmat_jitter, rv3d->persmat,
 -                              (jit_ofs[j][0] * 2.0f) / sizex,
 -                              (jit_ofs[j][1] * 2.0f) / sizey);
 -
 -                      ED_view3d_draw_offscreen(
 -                              bmain, scene, v3d, ar, sizex, sizey, NULL, winmat_jitter,
 -                              draw_background, draw_sky, !is_ortho, viewname,
 -                              fx, &fx_settings, ofs);
 -                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
 -
 -                      i = sizex * sizey * 4;
 -                      while (i--) {
 -                              accum_buffer[i] += rect_temp[i];
 -                      }
 -              }
 -
 -              if (ibuf->rect_float) {
 -                      float *rect_float = ibuf->rect_float;
 -                      i = sizex * sizey * 4;
 -                      while (i--) {
 -                              rect_float[i] = (float)(accum_buffer[i] / samples) * (1.0f / 255.0f);
 -                      }
 -              }
 -              else {
 -                      unsigned char *rect_ub = (unsigned char *)ibuf->rect;
 -                      i = sizex * sizey * 4;
 -                      while (i--) {
 -                              rect_ub[i] = accum_buffer[i] / samples;
 -                      }
 -              }
  
 -              MEM_freeN(accum_buffer);
 -      }
 -
 -      /* unbind */
 -      GPU_offscreen_unbind(ofs, true);
 -
 -      if (own_ofs) {
 -              GPU_offscreen_free(ofs);
 -      }
 -
 -      if (ibuf->rect_float && ibuf->rect)
 -              IMB_rect_from_float(ibuf);
 -
 -      return ibuf;
 -}
 -
 -/**
 - * Creates own fake 3d views (wrapping #ED_view3d_draw_offscreen_imbuf)
 - *
 - * \param ofs: Optional off-screen buffer can be NULL.
 - * (avoids re-creating when doing multiple GL renders).
 - *
 - * \note used by the sequencer
 - */
 -ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
 -        Main *bmain, Scene *scene,
 -        Object *camera, int width, int height,
 -        unsigned int flag, unsigned int draw_flags, int drawtype,
 -        int alpha_mode, int samples, const char *viewname,
 -        GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
 -{
 -      View3D v3d = {NULL};
 -      ARegion ar = {NULL};
 -      RegionView3D rv3d = {{{0}}};
 -
 -      /* connect data */
 -      v3d.regionbase.first = v3d.regionbase.last = &ar;
 -      ar.regiondata = &rv3d;
 -      ar.regiontype = RGN_TYPE_WINDOW;
 -
 -      v3d.camera = camera;
 -      v3d.lay = scene->lay;
 -      v3d.drawtype = drawtype;
 -      v3d.flag2 = V3D_RENDER_OVERRIDE;
 -
 -      if (draw_flags & V3D_OFSDRAW_USE_GPENCIL) {
 -              v3d.flag2 |= V3D_SHOW_GPENCIL;
 -      }
 -      if (draw_flags & V3D_OFSDRAW_USE_SOLID_TEX) {
 -              v3d.flag2 |= V3D_SOLID_TEX;
 -      }
 -      if (draw_flags & V3D_OFSDRAW_USE_BACKGROUND) {
 -              v3d.flag3 |= V3D_SHOW_WORLD;
 -      }
 -      if (draw_flags & V3D_OFSDRAW_USE_CAMERA_DOF) {
 -              if (camera->type == OB_CAMERA) {
 -                      v3d.fx_settings.dof = &((Camera *)camera->data)->gpu_dof;
 -                      v3d.fx_settings.fx_flag |= GPU_FX_FLAG_DOF;
 -              }
 -      }
 -
 -      rv3d.persp = RV3D_CAMOB;
 +      view3d_draw_border(C, ar);
 +      view3d_draw_grease_pencil(C);
  
 -      copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
 -      normalize_m4(rv3d.viewinv);
 -      invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
 +      BLF_batch_draw_begin();
  
 +      if (((U.uiflag & USER_SHOW_ROTVIEWICON) != 0) &&
 +          ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
 +          /* No need to display manipulator and this info. */
 +          ((U.manipulator_flag & USER_MANIPULATOR_DRAW_NAVIGATE) == 0))
        {
 -              CameraParams params;
 -              Object *view_camera = BKE_camera_multiview_render(scene, v3d.camera, viewname);
 -
 -              BKE_camera_params_init(&params);
 -              BKE_camera_params_from_object(&params, view_camera);
 -              BKE_camera_multiview_params(&scene->r, &params, view_camera, viewname);
 -              BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
 -              BKE_camera_params_compute_matrix(&params);
 -
 -              copy_m4_m4(rv3d.winmat, params.winmat);
 -              v3d.near = params.clipsta;
 -              v3d.far = params.clipend;
 -              v3d.lens = params.lens;
 +              draw_view_axis(rv3d, &rect);
        }
  
 -      mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
 -      invert_m4_m4(rv3d.persinv, rv3d.viewinv);
 -
 -      return ED_view3d_draw_offscreen_imbuf(
 -              bmain, scene, &v3d, &ar, width, height, flag, draw_flags,
 -              alpha_mode, samples, viewname, fx, ofs, err_out);
 -}
 -
 -
 -/**
 - * \note The info that this uses is updated in #ED_refresh_viewport_fps,
 - * which currently gets called during #SCREEN_OT_animation_step.
 - */
 -void ED_scene_draw_fps(Scene *scene, const rcti *rect)
 -{
 -      ScreenFrameRateInfo *fpsi = scene->fps_info;
 -      float fps;
 -      char printable[16];
 -      int i, tot;
 +      if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0 &&
 +          (v3d->overlay.flag & V3D_OVERLAY_HIDE_TEXT) == 0)
 +      {
 +              if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
 +                      ED_scene_draw_fps(scene, &rect);
 +              }
 +              else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
 +                      draw_viewport_name(ar, v3d, &rect);
 +              }
  
 -      if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
 -              return;
 +              if (U.uiflag & USER_DRAWVIEWINFO) {
 +                      ViewLayer *view_layer = CTX_data_view_layer(C);
 +                      Object *ob = OBACT(view_layer);
 +                      draw_selected_name(scene, ob, &rect);
 +              }
  
 -      printable[0] = '\0';
 +#if 0 /* TODO */
 +              if (grid_unit) { /* draw below the viewport name */
 +                      char numstr[32] = "";
  
 -#if 0
 -      /* this is too simple, better do an average */
 -      fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
 -#else
 -      fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
 +                      UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
 +                      if (v3d->grid != 1.0f) {
 +                              BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
 +                      }
  
 -      for (i = 0, tot = 0, fps = 0.0f; i < REDRAW_FRAME_AVERAGE; i++) {
 -              if (fpsi->redrawtimes_fps[i]) {
 -                      fps += fpsi->redrawtimes_fps[i];
 -                      tot++;
 +                      BLF_draw_default_ascii(
 +                              rect.xmin + U.widget_unit,
 +                              rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
 +                              numstr[0] ? numstr : grid_unit, sizeof(numstr));
                }
 -      }
 -      if (tot) {
 -              fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
 -
 -              //fpsi->redrawtime_index++;
 -              //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
 -              //      fpsi->redrawtime = 0;
 -
 -              fps = fps / tot;
 -      }
  #endif
 -
 -      /* is this more than half a frame behind? */
 -      if (fps + 0.5f < (float)(FPS)) {
 -              UI_ThemeColor(TH_REDALERT);
 -              BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %.2f"), fps);
 -      }
 -      else {
 -              UI_ThemeColor(TH_TEXT_HI);
 -              BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %i"), (int)(fps + 0.5f));
        }
  
 -#ifdef WITH_INTERNATIONAL
 -      BLF_draw_default(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
 -#else
 -      BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
 -#endif
 +      BLF_batch_draw_end();
  }
  
 -static bool view3d_main_region_do_render_draw(const Scene *scene)
 +static void view3d_draw_view(const bContext *C, ARegion *ar)
  {
 -      RenderEngineType *type = RE_engines_find(scene->r.engine);
 +      ED_view3d_draw_setup_view(CTX_wm_window(C), CTX_data_depsgraph(C), CTX_data_scene(C), ar, CTX_wm_view3d(C), NULL, NULL, NULL);
  
 -      return (type && type->view_update && type->view_draw);
 +      /* Only 100% compliant on new spec goes bellow */
 +      DRW_draw_view(C);
  }
  
 -bool ED_view3d_calc_render_border(
 -        const Scene *scene, const View3D *v3d, const ARegion *ar,
 -        rcti *rect)
 +RenderEngineType *ED_view3d_engine_type(Scene *scene, int drawtype)
  {
 -      RegionView3D *rv3d = ar->regiondata;
 -      rctf viewborder;
 -      bool use_border;
 -
 -      /* test if there is a 3d view rendering */
 -      if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene))
 -              return false;
 -
 -      /* test if there is a border render */
 -      if (rv3d->persp == RV3D_CAMOB)
 -              use_border = (scene->r.mode & R_BORDER) != 0;
 -      else
 -              use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
 -
 -      if (!use_border)
 -              return false;
 -
 -      /* compute border */
 -      if (rv3d->persp == RV3D_CAMOB) {
 -              ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
 -
 -              rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
 -              rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
 -              rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
 -              rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
 -      }
 -      else {
 -              rect->xmin = v3d->render_border.xmin * ar->winx;
 -              rect->xmax = v3d->render_border.xmax * ar->winx;
 -              rect->ymin = v3d->render_border.ymin * ar->winy;
 -              rect->ymax = v3d->render_border.ymax * ar->winy;
 +      /*
 +       * Tempory viewport draw modes until we have a proper system.
 +       * all modes are done in the draw manager, except
 +       * cycles material as it is an external render engine.
 +       */
 +      if (strcmp(scene->r.engine, RE_engine_id_CYCLES) == 0 && drawtype == OB_MATERIAL) {
 +              return RE_engines_find(RE_engine_id_BLENDER_EEVEE);
        }
 -
 -      BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
 -      BLI_rcti_isect(&ar->winrct, rect, rect);
 -
 -      return true;
 +      return RE_engines_find(scene->r.engine);
  }
  
 -static bool view3d_main_region_draw_engine(const bContext *C, Scene *scene,
 -                                         ARegion *ar, View3D *v3d,
 -                                         bool clip_border, const rcti *border_rect)
 +void view3d_main_region_draw(const bContext *C, ARegion *ar)
  {
 -      RegionView3D *rv3d = ar->regiondata;
 -      RenderEngineType *type;
 -      GLint scissor[4];
 -
 -      /* create render engine */
 -      if (!rv3d->render_engine) {
 -              RenderEngine *engine;
++      Main *bmain = CTX_data_main(C);
 +      View3D *v3d = CTX_wm_view3d(C);
  
 -              type = RE_engines_find(scene->r.engine);
 +      view3d_draw_view(C, ar);
  
-       GPU_free_images_old();
 -              if (!(type->view_update && type->view_draw))
 -                      return false;
++      GPU_free_images_old(bmain);
 +      GPU_pass_cache_garbage_collect();
  
 -              engine = RE_engine_create_ex(type, true);
 +      /* XXX This is in order to draw UI batches with the DRW
 +       * olg context since we now use it for drawing the entire area */
 +      gpu_batch_presets_reset();
  
 -              engine->tile_x = scene->r.tilex;
 -              engine->tile_y = scene->r.tiley;
 +      /* No depth test for drawing action zones afterwards. */
 +      glDisable(GL_DEPTH_TEST);
  
 -              type->view_update(engine, C);
 +      v3d->flag |= V3D_INVALID_BACKBUF;
 +}
  
 -              rv3d->render_engine = engine;
 -      }
 +/* -------------------------------------------------------------------- */
  
 -      /* setup view matrices */
 -      view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL, NULL);
 +/** \name Offscreen Drawing
 + * \{ */
  
 -      /* background draw */
 -      ED_region_pixelspace(ar);
 +static void view3d_stereo3d_setup_offscreen(
 +        Depsgraph *depsgraph, Scene *scene, View3D *v3d, ARegion *ar,
 +        float winmat[4][4], const char *viewname)
 +{
 +      /* update the viewport matrices with the new camera */
 +      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 +              float viewmat[4][4];
 +              const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
  
 -      if (clip_border) {
 -              /* for border draw, we only need to clear a subset of the 3d view */
 -              if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
 -                      glGetIntegerv(GL_SCISSOR_BOX, scissor);
 -                      glScissor(border_rect->xmin, border_rect->ymin,
 -                                BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
 -              }
 -              else {
 -                      return false;
 -              }
 +              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 +              view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, NULL);
        }
 +      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 +              float viewmat[4][4];
 +              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
  
 -      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 -      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -
 -      if (v3d->flag & V3D_DISPBGPICS)
 -              view3d_draw_bgpic_test(scene, ar, v3d, false, true);
 -      else
 -              fdrawcheckerboard(0, 0, ar->winx, ar->winy);
 -
 -      /* render result draw */
 -      type = rv3d->render_engine->type;
 -      type->view_draw(rv3d->render_engine, C);
 -
 -      if (v3d->flag & V3D_DISPBGPICS)
 -              view3d_draw_bgpic_test(scene, ar, v3d, true, true);
 -
 -      if (clip_border) {
 -              /* restore scissor as it was before */
 -              glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
 +              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 +              view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, NULL);
        }
 -
 -      return true;
  }
  
 -static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
 +void ED_view3d_draw_offscreen(
 +        Depsgraph *depsgraph, Scene *scene,
 +        int drawtype,
 +        View3D *v3d, ARegion *ar, int winx, int winy,
 +        float viewmat[4][4], float winmat[4][4],
 +        bool do_sky, bool UNUSED(is_persp), const char *viewname,
 +        GPUFXSettings *UNUSED(fx_settings),
 +        GPUOffScreen *ofs, GPUViewport *viewport)
  {
 -      float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
 -
 -      if (!rv3d->render_engine || !rv3d->render_engine->text[0])
 -              return;
 -
 -      if (render_border) {
 -              /* draw darkened background color. no alpha because border render does
 -               * partial redraw and will not redraw the region behind this info bar */
 -              float alpha = 1.0f - fill_color[3];
 -              Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
 -
 -              if (camera) {
 -                      if (camera->flag & CAM_SHOWPASSEPARTOUT) {
 -                              alpha *= (1.0f - camera->passepartalpha);
 -                      }
 -              }
 +      RegionView3D *rv3d = ar->regiondata;
 +      RenderEngineType *engine_type = ED_view3d_engine_type(scene, drawtype);
  
 -              UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
 -              mul_v3_fl(fill_color, alpha);
 -              fill_color[3] = 1.0f;
 -      }
 +      /* set temporary new size */
 +      int bwinx = ar->winx;
 +      int bwiny = ar->winy;
 +      rcti brect = ar->winrct;
  
 -      ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
 -}
 +      ar->winx = winx;
 +      ar->winy = winy;
 +      ar->winrct.xmin = 0;
 +      ar->winrct.ymin = 0;
 +      ar->winrct.xmax = winx;
 +      ar->winrct.ymax = winy;
  
 -static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
 -{
 -      if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 -              return false;
 -      }
 +      struct bThemeState theme_state;
 +      UI_Theme_Store(&theme_state);
 +      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
  
 -      if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
 -              return false;
 -      }
 +      /* set flags */
 +      G.f |= G_RENDER_OGL;
  
 -      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;
 +      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 +              /* free images which can have changed on frame-change
 +               * warning! can be slow so only free animated images - campbell */
-               GPU_free_images_anim();
++              GPU_free_images_anim(G.main);  /* XXX :((( */
        }
 -      return true;
 -}
 -
 -/* 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(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;
 -
 -      /* show only left or right camera */
 -      if (v3d->stereo3d_camera != STEREO_3D_ID)
 -              v3d->multiview_eye = v3d->stereo3d_camera;
 -
 -      is_left = v3d->multiview_eye == STEREO_LEFT_ID;
 -      viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
  
 -      /* 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;
 -
 -              data = (Camera *)v3d->camera->data;
 -              shiftx = data->shiftx;
 +      gpuPushProjectionMatrix();
 +      gpuLoadIdentity();
 +      gpuPushMatrix();
 +      gpuLoadIdentity();
  
 -              BLI_thread_lock(LOCK_VIEW3D);
 -              data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
 +      if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
 +              view3d_stereo3d_setup_offscreen(depsgraph, scene, v3d, ar, winmat, viewname);
 +      else
 +              view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, NULL);
  
 -              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL, rect);
 +      /* main drawing call */
 +      DRW_draw_render_loop_offscreen(
 +              depsgraph, engine_type, ar, v3d,
 +              do_sky, ofs, viewport);
  
 -              data->shiftx = shiftx;
 -              BLI_thread_unlock(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);
 +      /* restore size */
 +      ar->winx = bwinx;
 +      ar->winy = bwiny;
 +      ar->winrct = brect;
  
 -              BLI_thread_lock(LOCK_VIEW3D);
 -              v3d->camera = camera;
 +      gpuPopProjectionMatrix();
 +      gpuPopMatrix();
  
 -              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL, rect);
 +      UI_Theme_Restore(&theme_state);
  
 -              v3d->camera = view_ob;
 -              BLI_thread_unlock(LOCK_VIEW3D);
 -      }
 +      G.f &= ~G_RENDER_OGL;
  }
  
 -static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
 -                                            float winmat[4][4], const char *viewname)
 +/**
 + * Utility func for ED_view3d_draw_offscreen
 + *
 + * \param ofs: Optional off-screen buffer, can be NULL.
 + * (avoids re-creating when doing multiple GL renders).
 + */
 +ImBuf *ED_view3d_draw_offscreen_imbuf(
 +        Depsgraph *depsgraph, Scene *scene,
 +        int drawtype,
 +        View3D *v3d, ARegion *ar, int sizex, int sizey,
 +        unsigned int flag, unsigned int draw_flags,
 +        int alpha_mode, int samples, const char *viewname,
 +        /* output vars */
 +        GPUOffScreen *ofs, char err_out[256])
  {
 -      /* update the viewport matrices with the new camera */
 -      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 -              float viewmat[4][4];
 -              const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
 +      RegionView3D *rv3d = ar->regiondata;
 +      const bool draw_sky = (alpha_mode == R_ADDSKY);
 +      const bool use_full_sample = (draw_flags & V3D_OFSDRAW_USE_FULL_SAMPLE);
  
 -              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, NULL);
 -      }
 -      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 -              float viewmat[4][4];
 -              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
 +      /* view state */
 +      GPUFXSettings fx_settings = v3d->fx_settings;
 +      bool is_ortho = false;
 +      float winmat[4][4];
  
 -              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, NULL);
 +      if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
 +              /* sizes differ, can't reuse */
 +              ofs = NULL;
        }
 -}
  
 -#ifdef WITH_GAMEENGINE
 -static void update_lods(Scene *scene, float camera_pos[3])
 -{
 -      Scene *sce_iter;
 -      Base *base;
 -      Object *ob;
 +      const bool own_ofs = (ofs == NULL);
 +      DRW_opengl_context_enable();
  
 -      for (SETLOOPER(scene, sce_iter, base)) {
 -              ob = base->object;
 -              BKE_object_lod_update(ob, camera_pos);
 +      if (own_ofs) {
 +              /* bind */
 +              ofs = GPU_offscreen_create(sizex, sizey, use_full_sample ? 0 : samples, true, false, err_out);
 +              if (ofs == NULL) {
 +                      DRW_opengl_context_disable();
 +                      return NULL;
 +              }
        }
 -}
 -#endif
 -
 -static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, View3D *v3d,
 -                                          ARegion *ar, const char **grid_unit)
 -{
 -      Main *bmain = CTX_data_main(C);
 -      wmWindow *win = CTX_wm_window(C);
 -      RegionView3D *rv3d = ar->regiondata;
 -      unsigned int lay_used = v3d->lay_used;
  
 -      /* post processing */
 -      bool do_compositing = false;
 +      GPU_offscreen_bind(ofs, true);
  
 -      /* shadow buffers, before we setup matrices */
 -      if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
 -              gpu_update_lamps_shadows_world(bmain, scene, v3d);
 +      /* read in pixels & stamp */
 +      ImBuf *ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
  
 -      /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
 -      if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
 -              rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
 -              GPU_default_lights();
 -      }
 +      /* render 3d view */
 +      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 +              CameraParams params;
 +              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
 +              const Object *camera_eval = DEG_get_evaluated_object(
 +                                              depsgraph,
 +                                              camera);
  
 -      /* Setup the view matrix. */
 -      ED_view3d_draw_setup_view(CTX_wm_window(C), scene, ar, v3d, NULL, NULL, NULL);
 +              BKE_camera_params_init(&params);
 +              /* fallback for non camera objects */
 +              params.clipsta = v3d->near;
 +              params.clipend = v3d->far;
 +              BKE_camera_params_from_object(&params, camera_eval);
 +              BKE_camera_multiview_params(&scene->r, &params, camera_eval, viewname);
 +              BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
 +              BKE_camera_params_compute_matrix(&params);
  
 -      rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
 -#ifdef WITH_GAMEENGINE
 -      if (STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME)) {
 -              rv3d->rflag |= RV3D_IS_GAME_ENGINE;
 +              BKE_camera_to_gpu_dof(camera, &fx_settings);
  
 -              /* Make sure LoDs are up to date */
 -              update_lods(scene, rv3d->viewinv[3]);
 +              is_ortho = params.is_ortho;
 +              copy_m4_m4(winmat, params.winmat);
        }
 -#endif
 -
 -      /* framebuffer fx needed, we need to draw offscreen first */
 -      if (v3d->fx_settings.fx_flag && v3d->drawtype >= OB_SOLID) {
 -              GPUFXSettings fx_settings;
 -              BKE_screen_gpu_fx_validate(&v3d->fx_settings);
 -              fx_settings = v3d->fx_settings;
 -              if (!rv3d->compositor)
 -                      rv3d->compositor = GPU_fx_compositor_create();
 +      else {
 +              rctf viewplane;
 +              float clipsta, clipend;
  
 -              if (rv3d->persp == RV3D_CAMOB && v3d->camera)
 -                      BKE_camera_to_gpu_dof(v3d->camera, &fx_settings);
 +              is_ortho = ED_view3d_viewplane_get(depsgraph, v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
 +              if (is_ortho) {
 +                      orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
 +              }
                else {
 -                      fx_settings.dof = NULL;
 +                      perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
                }
 -
 -              do_compositing = GPU_fx_compositor_initialize_passes(rv3d->compositor, &ar->winrct, &ar->drawrct, &fx_settings);
        }
  
 -      /* clear the background */
 -      view3d_main_region_clear(scene, v3d, ar);
 +      if ((samples && use_full_sample) == 0) {
 +              /* Single-pass render, common case */
 +              ED_view3d_draw_offscreen(
 +                      depsgraph, scene, drawtype,
 +                      v3d, ar, sizex, sizey, NULL, winmat,
 +                      draw_sky, !is_ortho, viewname,
 +                      &fx_settings, ofs, NULL);
  
 -      /* enables anti-aliasing for 3D view drawing */
 -      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 -              glEnable(GL_MULTISAMPLE);
 +              if (ibuf->rect_float) {
 +                      GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
 +              }
 +              else if (ibuf->rect) {
 +                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
 +              }
        }
 +      else {
 +              /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
 +               * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
 +              static float jit_ofs[32][2];
 +              float winmat_jitter[4][4];
 +              float *rect_temp = (ibuf->rect_float) ? ibuf->rect_float : MEM_mallocN(sizex * sizey * sizeof(float[4]), "rect_temp");
 +              float *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(float[4]), "accum_buffer");
 +              GPUViewport *viewport = GPU_viewport_create_from_offscreen(ofs);
  
 -      /* main drawing call */
 -      view3d_draw_objects(C, bmain, scene, v3d, ar, grid_unit, true, false, do_compositing ? rv3d->compositor : NULL);
 -
 -      /* post process */
 -      if (do_compositing) {
 -              GPU_fx_do_composite_pass(rv3d->compositor, rv3d->winmat, rv3d->is_persp, scene, NULL);
 -      }
 +              BLI_jitter_init(jit_ofs, samples);
  
 -      /* Disable back anti-aliasing */
 -      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 -              glDisable(GL_MULTISAMPLE);
 -      }
 +              /* first sample buffer, also initializes 'rv3d->persmat' */
 +              ED_view3d_draw_offscreen(
 +                      depsgraph, scene, drawtype,
 +                      v3d, ar, sizex, sizey, NULL, winmat,
 +                      draw_sky, !is_ortho, viewname,
 +                      &fx_settings, ofs, viewport);
 +              GPU_offscreen_read_pixels(ofs, GL_FLOAT, accum_buffer);
  
 -      if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
 -              /* find header and force tag redraw */
 -              ScrArea *sa = CTX_wm_area(C);
 -              ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
 -              ED_region_tag_redraw(ar_header); /* can be NULL */
 -      }
 +              /* skip the first sample */
 +              for (int j = 1; j < samples; j++) {
 +                      copy_m4_m4(winmat_jitter, winmat);
 +                      window_translate_m4(
 +                              winmat_jitter, rv3d->persmat,
 +                              (jit_ofs[j][0] * 2.0f) / sizex,
 +                              (jit_ofs[j][1] * 2.0f) / sizey);
  
 -      if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
 -              BDR_drawSketch(C);
 -      }
 +                      ED_view3d_draw_offscreen(
 +                              depsgraph, scene, drawtype,
 +                              v3d, ar, sizex, sizey, NULL, winmat_jitter,
 +                              draw_sky, !is_ortho, viewname,
 +                              &fx_settings, ofs, viewport);
 +                      GPU_offscreen_read_pixels(ofs, GL_FLOAT, rect_temp);
  
 -#ifdef WITH_INPUT_NDOF
 -      if ((U.ndof_flag & NDOF_SHOW_GUIDE) && ((rv3d->viewlock & RV3D_LOCKED) == 0) && (rv3d->persp != RV3D_CAMOB))
 -              /* TODO: draw something else (but not this) during fly mode */
 -              draw_rotation_guide(rv3d);
 -#endif
 -}
 +                      unsigned int i = sizex * sizey * 4;
 +                      while (i--) {
 +                              accum_buffer[i] += rect_temp[i];
 +                      }
 +              }
  
 -static bool is_cursor_visible(Scene *scene)
 -{
 -      if (U.app_flag & USER_APP_VIEW3D_HIDE_CURSOR) {
 -              return false;
 -      }
 +              {
 +                      /* don't free data owned by 'ofs' */
 +                      GPU_viewport_clear_from_offscreen(viewport);
 +                      GPU_viewport_free(viewport);
 +              }
  
 -      Object *ob = OBACT;
 +              if (ibuf->rect_float == NULL) {
 +                      MEM_freeN(rect_temp);
 +              }
  
 -      /* don't draw cursor in paint modes, but with a few exceptions */
 -      if (ob && ob->mode & OB_MODE_ALL_PAINT) {
 -              /* exception: object is in weight paint and has deforming armature in pose mode */
 -              if (ob->mode & OB_MODE_WEIGHT_PAINT) {
 -                      if (BKE_object_pose_armature_get(ob) != NULL) {
 -                              return true;
 +              if (ibuf->rect_float) {
 +                      float *rect_float = ibuf->rect_float;
 +                      unsigned int i = sizex * sizey * 4;
 +                      while (i--) {
 +                              rect_float[i] = accum_buffer[i] / samples;
                        }
                }
 -              /* exception: object in texture paint mode, clone brush, use_clone_layer disabled */
 -              else if (ob->mode & OB_MODE_TEXTURE_PAINT) {
 -                      const Paint *p = BKE_paint_get_active(scene);
 -
 -                      if (p && p->brush && p->brush->imagepaint_tool == PAINT_TOOL_CLONE) {
 -                              if ((scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_LAYER_CLONE) == 0) {
 -                                      return true;
 -                              }
 +              else {
 +                      unsigned char *rect_ub = (unsigned char *)ibuf->rect;
 +                      unsigned int i = sizex * sizey * 4;
 +                      while (i--) {
 +                              rect_ub[i] = (unsigned char)(255.0f * accum_buffer[i] / samples);
                        }
                }
  
index 613a07dc86922f0bf373bfeb2407aff3a884dbd7,82acca722b658ce133bc2cb79ccc0b86e8d4ac2e..448945cd7ba538e236a217e09731cd3b4e28b99c
@@@ -39,9 -39,9 +39,10 @@@ extern "C" 
  struct ImBuf;
  struct Image;
  struct ImageUser;
 -struct MTexPoly;
++struct Main;
  struct Object;
  struct Scene;
 +struct ViewLayer;
  struct View3D;
  struct RegionView3D;
  struct SmokeModifierData;
@@@ -103,8 -153,13 +104,8 @@@ void GPU_free_smoke(struct SmokeModifie
  void GPU_create_smoke(struct SmokeModifierData *smd, int highres);
  
  /* Delayed free of OpenGL buffers by main thread */
- void GPU_free_unused_buffers(void);
+ void GPU_free_unused_buffers(struct Main *bmain);
  
 -#ifdef WITH_OPENSUBDIV
 -struct DerivedMesh;
 -void GPU_draw_update_fvar_offset(struct DerivedMesh *dm);
 -#endif
 -
  /* utilities */
  void  GPU_select_index_set(int index);
  void  GPU_select_index_get(int index, int *r_col);
index 0805cc25d04f649d308a029a40cc7b8e49cb00b1,c94d6429f5965a35810b27e3d24ce45a04350b04..a65c09152ee16017950a6ee82bc54b9781e41e41
@@@ -43,10 -43,12 +43,11 @@@ extern "C" 
  
  struct Image;
  struct ImageUser;
 +struct ListBase;
+ struct Main;
  struct Material;
  struct Object;
 -struct Image;
  struct Scene;
 -struct SceneRenderLayer;
  struct GPUVertexAttribs;
  struct GPUNode;
  struct GPUNodeLink;
@@@ -230,42 -211,33 +231,42 @@@ GPUNodeLink *GPU_opengl_builtin(GPUOpen
  void GPU_node_link_set_type(GPUNodeLink *link, GPUType type);
  
  bool GPU_link(GPUMaterial *mat, const char *name, ...);
 -bool GPU_stack_link(GPUMaterial *mat, const char *name, GPUNodeStack *in, GPUNodeStack *out, ...);
 +bool GPU_stack_link(GPUMaterial *mat, struct bNode *node, const char *name, GPUNodeStack *in, GPUNodeStack *out, ...);
 +GPUNodeLink *GPU_uniformbuffer_link_out(
 +        struct GPUMaterial *mat, struct bNode *node,
 +        struct GPUNodeStack *stack, const int index);
  
  void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link);
 -void GPU_material_enable_alpha(GPUMaterial *material);
  GPUBuiltin GPU_get_material_builtins(GPUMaterial *material);
 -GPUBlendMode GPU_material_alpha_blend(GPUMaterial *material, float obcol[4]);
  
 -/* High level functions to create and use GPU materials */
 -GPUMaterial *GPU_material_world(struct Scene *scene, struct World *wo);
 +void GPU_material_sss_profile_create(GPUMaterial *material, float radii[3], short *falloff_type, float *sharpness);
 +struct GPUUniformBuffer *GPU_material_sss_profile_get(
 +        GPUMaterial *material, int sample_ct, struct GPUTexture **tex_profile);
  
 -GPUMaterial *GPU_material_from_blender(struct Scene *scene, struct Material *ma, bool use_opensubdiv);
 -GPUMaterial *GPU_material_matcap(struct Scene *scene, struct Material *ma, bool use_opensubdiv);
 +/* High level functions to create and use GPU materials */
 +GPUMaterial *GPU_material_from_nodetree_find(
 +        struct ListBase *gpumaterials, const void *engine_type, int options);
 +GPUMaterial *GPU_material_from_nodetree(
 +        struct Scene *scene, struct bNodeTree *ntree, struct ListBase *gpumaterials, const void *engine_type, int options,
 +        const char *vert_code, const char *geom_code, const char *frag_lib, const char *defines);
 +void GPU_material_compile(GPUMaterial *mat);
  void GPU_material_free(struct ListBase *gpumaterial);
  
- void GPU_materials_free(void);
+ void GPU_materials_free(struct Main *bmain);
  
 -bool GPU_lamp_visible(GPULamp *lamp, struct SceneRenderLayer *srl, struct Material *ma);
 -void GPU_material_bind(
 -        GPUMaterial *material, int oblay, int viewlay, double time, int mipmap,
 -        float viewmat[4][4], float viewinv[4][4], float cameraborder[4], bool scenelock);
 -void GPU_material_bind_uniforms(
 -        GPUMaterial *material, float obmat[4][4], float viewmat[4][4], float obcol[4],
 -        float autobumpscale, GPUParticleInfo *pi, float object_info[3]);
 -void GPU_material_unbind(GPUMaterial *material);
 -bool GPU_material_bound(GPUMaterial *material);
 +void GPU_material_orphans_init(void);
 +void GPU_material_orphans_exit(void);
 +/* This has to be called from a thread with an ogl context bound. */
 +void GPU_material_orphans_delete(void);
 +
  struct Scene *GPU_material_scene(GPUMaterial *material);
  GPUMatType GPU_Material_get_type(GPUMaterial *material);
 +struct GPUPass *GPU_material_get_pass(GPUMaterial *material);
 +struct ListBase *GPU_material_get_inputs(GPUMaterial *material);
 +GPUMaterialStatus GPU_material_status(GPUMaterial *mat);
 +
 +struct GPUUniformBuffer *GPU_material_uniform_buffer_get(GPUMaterial *material);
 +void GPU_material_uniform_buffer_create(GPUMaterial *material, ListBase *inputs);
  
  void GPU_material_vertex_attributes(GPUMaterial *material,
        struct GPUVertexAttribs *attrib);
index 83fd689e3b7ae3a9e13fdc2b331fd396a168ae9a,022de6c72fef98bd4ffb5600fab7d6bfe6596c30..7383868843d68edb745d568b8c6dac728458ca49
@@@ -145,17 -279,40 +145,17 @@@ void GPU_set_gpu_mipmapping(Main *bmain
        int old_value = GTS.gpu_mipmap;
  
        /* only actually enable if it's supported */
 -      GTS.gpu_mipmap = gpu_mipmap && GLEW_EXT_framebuffer_object;
 +      GTS.gpu_mipmap = gpu_mipmap;
  
        if (old_value != GTS.gpu_mipmap) {
-               GPU_free_images();
+               GPU_free_images(bmain);
        }
  }
  
- void GPU_set_mipmap(bool mipmap)
 -static void gpu_generate_mipmap(GLenum target)
 -{
 -      const bool is_ati = GPU_type_matches(GPU_DEVICE_ATI, GPU_OS_ANY, GPU_DRIVER_ANY);
 -      int target_enabled = 0;
 -
 -      /* work around bug in ATI driver, need to have GL_TEXTURE_2D enabled
 -       * http://www.opengl.org/wiki/Common_Mistakes#Automatic_mipmap_generation */
 -      if (is_ati) {
 -              target_enabled = glIsEnabled(target);
 -              if (!target_enabled)
 -                      glEnable(target);
 -      }
 -
 -      /* TODO: simplify when we transition to GL >= 3 */
 -      if (GLEW_VERSION_3_0 || GLEW_ARB_framebuffer_object)
 -              glGenerateMipmap(target);
 -      else if (GLEW_EXT_framebuffer_object)
 -              glGenerateMipmapEXT(target);
 -
 -      if (is_ati && !target_enabled)
 -              glDisable(target);
 -}
 -
+ void GPU_set_mipmap(Main *bmain, bool mipmap)
  {
        if (GTS.domipmap != mipmap) {
-               GPU_free_images();
+               GPU_free_images(bmain);
                GTS.domipmap = mipmap;
        }
  }
@@@ -690,14 -1160,18 +690,14 @@@ void GPU_paint_set_mipmap(Main *bmain, 
        GTS.texpaint = !mipmap;
  
        if (mipmap) {
-               for (Image *ima = G.main->image.first; ima; ima = ima->id.next) {
+               for (Image *ima = bmain->image.first; ima; ima = ima->id.next) {
 -                      if (BKE_image_has_bindcode(ima)) {
 +                      if (BKE_image_has_opengl_texture(ima)) {
                                if (ima->tpageflag & IMA_MIPMAP_COMPLETE) {
 -                                      if (ima->bindcode[TEXTARGET_TEXTURE_2D]) {
 -                                              glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
 +                                      if (ima->gputexture[TEXTARGET_TEXTURE_2D]) {
 +                                              GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0);
                                                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
                                                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
 -                                      }
 -                                      if (ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]) {
 -                                              glBindTexture(GL_TEXTURE_CUBE_MAP, ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]);
 -                                              glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
 -                                              glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
 +                                              GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]);
                                        }
                                }
                                else
  
        }
        else {
-               for (Image *ima = G.main->image.first; ima; ima = ima->id.next) {
+               for (Image *ima = bmain->image.first; ima; ima = ima->id.next) {
 -                      if (BKE_image_has_bindcode(ima)) {
 -                              if (ima->bindcode[TEXTARGET_TEXTURE_2D]) {
 -                                      glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
 +                      if (BKE_image_has_opengl_texture(ima)) {
 +                              if (ima->gputexture[TEXTARGET_TEXTURE_2D]) {
 +                                      GPU_texture_bind(ima->gputexture[TEXTARGET_TEXTURE_2D], 0);
                                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
 -                              }
 -                              if (ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]) {
 -                                      glBindTexture(GL_TEXTURE_CUBE_MAP, ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]);
 -                                      glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 -                                      glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
 +                                      GPU_texture_unbind(ima->gputexture[TEXTARGET_TEXTURE_2D]);
                                }
                        }
                        else
index 302ddc6218887dc127ad8cc2b8ee1381a1308c54,9db9ed1f5e70820bd5ef02c09ed72c16586de92f..9c776e64ba0df99c39f9a9d8de2e4d8ebaad7103
@@@ -700,31 -1918,307 +700,31 @@@ GPUMaterial *GPU_material_from_nodetree
        return mat;
  }
  
 -static void do_world_tex(GPUShadeInput *shi, struct World *wo, GPUNodeLink **hor, GPUNodeLink **zen, GPUNodeLink **blend)
 +void GPU_material_compile(GPUMaterial *mat)
  {
 -      GPUMaterial *mat = shi->gpumat;
 -      GPUNodeLink *texco, *tin, *trgb, *stencil, *tcol, *zenfac;
 -      MTex *mtex;
 -      Tex *tex;
 -      float ofs[3], zero = 0.0f;
 -      int tex_nr, rgbnor;
 -
 -      GPU_link(mat, "set_value_one", &stencil);
 -      /* go over texture slots */
 -      for (tex_nr = 0; tex_nr < MAX_MTEX; tex_nr++) {
 -              if (wo->mtex[tex_nr]) {
 -                      mtex = wo->mtex[tex_nr];
 -                      tex = mtex->tex;
 -                      if (tex == NULL || !tex->ima || (tex->type != TEX_IMAGE && tex->type != TEX_ENVMAP))
 -                              continue;
 -                      /* which coords */
 -                      if (mtex->texco == TEXCO_VIEW || mtex->texco == TEXCO_GLOB) {
 -                              if (tex->type == TEX_IMAGE)
 -                                      texco = GPU_builtin(GPU_VIEW_POSITION);
 -                              else if (tex->type == TEX_ENVMAP)
 -                                      GPU_link(mat, "background_transform_to_world", GPU_builtin(GPU_VIEW_POSITION), &texco);
 -                      }
 -                      else if (mtex->texco == TEXCO_EQUIRECTMAP || mtex->texco == TEXCO_ANGMAP) {
 -                              if ((tex->type == TEX_IMAGE && wo->skytype & WO_SKYREAL) || tex->type == TEX_ENVMAP)
 -                                      GPU_link(mat, "background_transform_to_world", GPU_builtin(GPU_VIEW_POSITION), &texco);
 -                              else
 -                                      texco = GPU_builtin(GPU_VIEW_POSITION);
 -                      }
 -                      else
 -                              continue;
 -                      GPU_link(mat, "texco_norm", texco, &texco);
 -                      if (tex->type == TEX_IMAGE && !(wo->skytype & WO_SKYREAL)) {
 -                              GPU_link(mat, "mtex_2d_mapping", texco, &texco);
 -                      }
 -                      if (mtex->size[0] != 1.0f || mtex->size[1] != 1.0f || mtex->size[2] != 1.0f) {
 -                              float size[3] = { mtex->size[0], mtex->size[1], mtex->size[2] };
 -                              if (tex->type == TEX_ENVMAP) {
 -                                      size[1] = mtex->size[2];
 -                                      size[2] = mtex->size[1];
 -                              }
 -                              GPU_link(mat, "mtex_mapping_size", texco, GPU_uniform(size), &texco);
 -                      }
 -                      ofs[0] = mtex->ofs[0] + 0.5f - 0.5f * mtex->size[0];
 -                      if (tex->type == TEX_ENVMAP) {
 -                              ofs[1] = -mtex->ofs[2] + 0.5f - 0.5f * mtex->size[2];
 -                              ofs[2] = mtex->ofs[1] + 0.5f - 0.5f * mtex->size[1];
 -                      }
 -                      else {
 -                              ofs[1] = mtex->ofs[1] + 0.5f - 0.5f * mtex->size[1];
 -                              ofs[2] = 0.0;
 -                      }
 -                      if (ofs[0] != 0.0f || ofs[1] != 0.0f || ofs[2] != 0.0f)
 -                              GPU_link(mat, "mtex_mapping_ofs", texco, GPU_uniform(ofs), &texco);
 -                      if (mtex->texco == TEXCO_EQUIRECTMAP) {
 -                              GPU_link(mat, "node_tex_environment_equirectangular", texco, GPU_image(tex->ima, &tex->iuser, false), &trgb);
 -                      }
 -                      else if (mtex->texco == TEXCO_ANGMAP) {
 -                              GPU_link(mat, "node_tex_environment_mirror_ball", texco, GPU_image(tex->ima, &tex->iuser, false), &trgb);
 -                      }
 -                      else {
 -                              if (tex->type == TEX_ENVMAP)
 -                                      GPU_link(mat, "mtex_cube_map", texco, GPU_cube_map(tex->ima, &tex->iuser, false), &tin, &trgb);
 -                              else if (tex->type == TEX_IMAGE)
 -                                      GPU_link(mat, "mtex_image", texco, GPU_image(tex->ima, &tex->iuser, false), &tin, &trgb);
 -                      }
 -                      rgbnor = TEX_RGB;
 -                      if (tex->type == TEX_IMAGE || tex->type == TEX_ENVMAP)
 -                              if (GPU_material_do_color_management(mat))
 -                                      GPU_link(mat, "srgb_to_linearrgb", trgb, &trgb);
 -                      /* texture output */
 -                      if ((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) {
 -                              GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
 -                              rgbnor -= TEX_RGB;
 -                      }
 -                      if (mtex->texflag & MTEX_NEGATIVE) {
 -                              if (rgbnor & TEX_RGB)
 -                                      GPU_link(mat, "mtex_rgb_invert", trgb, &trgb);
 -                              else
 -                                      GPU_link(mat, "mtex_value_invert", tin, &tin);
 -                      }
 -                      if (mtex->texflag & MTEX_STENCIL) {
 -                              if (rgbnor & TEX_RGB)
 -                                      GPU_link(mat, "mtex_rgb_stencil", stencil, trgb, &stencil, &trgb);
 -                              else
 -                                      GPU_link(mat, "mtex_value_stencil", stencil, tin, &stencil, &tin);
 -                      }
 -                      else {
 -                              if (rgbnor & TEX_RGB)
 -                                      GPU_link(mat, "mtex_alpha_multiply_value", trgb, stencil, &trgb);
 -                              else
 -                                      GPU_link(mat, "math_multiply", stencil, tin, &tin);
 -                      }
 -                      /* color mapping */
 -                      if (mtex->mapto & (WOMAP_HORIZ + WOMAP_ZENUP + WOMAP_ZENDOWN)) {
 -                              if ((rgbnor & TEX_RGB) == 0)
 -                                      GPU_link(mat, "set_rgb", GPU_uniform(&mtex->r), &trgb);
 -                              else
 -                                      GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
 -                              GPU_link(mat, "set_rgb", trgb, &tcol);
 -                              if (mtex->mapto & WOMAP_HORIZ) {
 -                                      texture_rgb_blend(mat, tcol, *hor, tin, GPU_uniform(&mtex->colfac), mtex->blendtype, hor);
 -                              }
 -                              if (mtex->mapto & (WOMAP_ZENUP + WOMAP_ZENDOWN)) {
 -                                      GPU_link(mat, "set_value_zero", &zenfac);
 -                                      if (wo->skytype & WO_SKYREAL) {
 -                                              if (mtex->mapto & WOMAP_ZENUP) {
 -                                                      if (mtex->mapto & WOMAP_ZENDOWN) {
 -                                                              GPU_link(mat, "world_zen_mapping", shi->view, GPU_uniform(&mtex->zenupfac),
 -                                                                       GPU_uniform(&mtex->zendownfac), &zenfac);
 -                                                      }
 -                                                      else {
 -                                                              GPU_link(mat, "world_zen_mapping", shi->view, GPU_uniform(&mtex->zenupfac),
 -                                                                       GPU_uniform(&zero), &zenfac);
 -                                                      }
 -                                              }
 -                                              else if (mtex->mapto & WOMAP_ZENDOWN) {
 -                                                      GPU_link(mat, "world_zen_mapping", shi->view, GPU_uniform(&zero),
 -                                                               GPU_uniform(&mtex->zendownfac), &zenfac);
 -                                              }
 -                                      }
 -                                      else {
 -                                              if (mtex->mapto & WOMAP_ZENUP)
 -                                                      GPU_link(mat, "set_value", GPU_uniform(&mtex->zenupfac), &zenfac);
 -                                              else if (mtex->mapto & WOMAP_ZENDOWN)
 -                                                      GPU_link(mat, "set_value", GPU_uniform(&mtex->zendownfac), &zenfac);
 -                                      }
 -                                      texture_rgb_blend(mat, tcol, *zen, tin, zenfac, mtex->blendtype, zen);
 -                              }
 -                      }
 -                      if (mtex->mapto & WOMAP_BLEND && wo->skytype & WO_SKYBLEND) {
 -                              if (rgbnor & TEX_RGB)
 -                                      GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
 -                              texture_value_blend(mat, GPU_uniform(&mtex->def_var), *blend, tin, GPU_uniform(&mtex->blendfac), mtex->blendtype, blend);
 -                      }
 -              }
 -      }
 -}
 -
 -static void gpu_material_old_world(struct GPUMaterial *mat, struct World *wo)
 -{
 -      GPUShadeInput shi;
 -      GPUShadeResult shr;
 -      GPUNodeLink *hor, *zen, *ray, *blend;
 -
 -      shi.gpumat = mat;
 -
 -      for (int i = 0; i < MAX_MTEX; i++) {
 -              if (wo->mtex[i] && wo->mtex[i]->tex) {
 -                      wo->skytype |= WO_SKYTEX;
 -                      break;
 -              }
 -      }
 -      if ((wo->skytype & (WO_SKYBLEND + WO_SKYTEX)) == 0) {
 -              GPU_link(mat, "set_rgb", GPU_dynamic_uniform(&wo->horr, GPU_DYNAMIC_HORIZON_COLOR, NULL), &shr.combined);
 -      }
 -      else {
 -              GPU_link(mat, "set_rgb_zero", &shi.rgb);
 -              GPU_link(mat, "background_transform_to_world", GPU_builtin(GPU_VIEW_POSITION), &ray);
 -              if (wo->skytype & WO_SKYPAPER)
 -                      GPU_link(mat, "world_paper_view", GPU_builtin(GPU_VIEW_POSITION), &shi.view);
 -              else
 -                      GPU_link(mat, "shade_view", ray, &shi.view);
 -              if (wo->skytype & WO_SKYBLEND) {
 -                      if (wo->skytype & WO_SKYPAPER) {
 -                              if (wo->skytype & WO_SKYREAL)
 -                                      GPU_link(mat, "world_blend_paper_real", GPU_builtin(GPU_VIEW_POSITION), &blend);
 -                              else
 -                                      GPU_link(mat, "world_blend_paper", GPU_builtin(GPU_VIEW_POSITION), &blend);
 -                      }
 -                      else {
 -                              if (wo->skytype & WO_SKYREAL)
 -                                      GPU_link(mat, "world_blend_real", ray, &blend);
 -                              else
 -                                      GPU_link(mat, "world_blend", ray, &blend);
 -                      }
 -              }
 -              else {
 -                      GPU_link(mat, "set_value_zero", &blend);
 -              }
 -              GPU_link(mat, "set_rgb", GPU_dynamic_uniform(&wo->horr, GPU_DYNAMIC_HORIZON_COLOR, NULL), &hor);
 -              GPU_link(mat, "set_rgb", GPU_dynamic_uniform(&wo->zenr, GPU_DYNAMIC_ZENITH_COLOR, NULL), &zen);
 -              do_world_tex(&shi, wo, &hor, &zen, &blend);
 -              if (wo->skytype & WO_SKYBLEND)
 -                      GPU_link(mat, "node_mix_shader", blend, hor, zen, &shi.rgb);
 -              else
 -                      GPU_link(mat, "set_rgb", hor, &shi.rgb);
 -              GPU_link(mat, "set_rgb", shi.rgb, &shr.combined);
 -      }
 -      GPU_material_output_link(mat, shr.combined);
 -}
 -
 -GPUMaterial *GPU_material_world(struct Scene *scene, struct World *wo)
 -{
 -      LinkData *link;
 -      GPUMaterial *mat;
 -
 -      for (link = wo->gpumaterial.first; link; link = link->next)
 -              if (((GPUMaterial *)link->data)->scene == scene)
 -                      return link->data;
 -
 -      /* allocate material */
 -      mat = GPU_material_construct_begin(NULL);
 -      mat->scene = scene;
 -      mat->type = GPU_MATERIAL_TYPE_WORLD;
 -
 -      /* create nodes */
 -      if (BKE_scene_use_new_shading_nodes(scene) && wo->nodetree && wo->use_nodes) {
 -              ntreeGPUMaterialNodes(wo->nodetree, mat, NODE_NEW_SHADING);
 -      }
 -      else {
 -              gpu_material_old_world(mat, wo);
 -      }
 -
 -      if (GPU_material_do_color_management(mat))
 -              if (mat->outlink)
 -                      GPU_link(mat, "linearrgb_to_srgb", mat->outlink, &mat->outlink);
 -
 -      gpu_material_construct_end(mat, wo->id.name);
 -
 -      /* note that even if building the shader fails in some way, we still keep
 -       * it to avoid trying to compile again and again, and simple do not use
 -       * the actual shader on drawing */
 -
 -      link = MEM_callocN(sizeof(LinkData), "GPUMaterialLink");
 -      link->data = mat;
 -      BLI_addtail(&wo->gpumaterial, link);
 -
 -      return mat;
 -}
 -
 -
 -GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma, bool use_opensubdiv)
 -{
 -      GPUMaterial *mat;
 -      GPUNodeLink *outlink;
 -      LinkData *link;
 +      /* Only run once! */
 +      BLI_assert(mat->status == GPU_MAT_QUEUED);
 +      BLI_assert(mat->pass);
  
 -      for (link = ma->gpumaterial.first; link; link = link->next) {
 -              GPUMaterial *current_material = (GPUMaterial *)link->data;
 -              if (current_material->scene == scene &&
 -                  current_material->is_opensubdiv == use_opensubdiv)
 -              {
 -                      return current_material;
 -              }
 -      }
 +      /* NOTE: The shader may have already been compiled here since we are
 +       * sharing GPUShader across GPUMaterials. In this case it's a no-op. */
 +      GPU_pass_compile(mat->pass);
 +      GPUShader *sh = GPU_pass_shader_get(mat->pass);
  
 -      /* allocate material */
 -      mat = GPU_material_construct_begin(ma);
 -      mat->scene = scene;
 -      mat->type = GPU_MATERIAL_TYPE_MESH;
 -      mat->is_opensubdiv = use_opensubdiv;
 -
 -      /* render pipeline option */
 -      bool new_shading_nodes = BKE_scene_use_new_shading_nodes(scene);
 -      if (!new_shading_nodes && (ma->mode & MA_TRANSP))
 -              GPU_material_enable_alpha(mat);
 -      else if (new_shading_nodes && ma->alpha < 1.0f)
 -              GPU_material_enable_alpha(mat);
 -
 -      if (!(scene->gm.flag & GAME_GLSL_NO_NODES) && ma->nodetree && ma->use_nodes) {
 -              /* create nodes */
 -              if (new_shading_nodes)
 -                      ntreeGPUMaterialNodes(ma->nodetree, mat, NODE_NEW_SHADING);
 -              else
 -                      ntreeGPUMaterialNodes(ma->nodetree, mat, NODE_OLD_SHADING);
 +      if (sh != NULL) {
 +              mat->status = GPU_MAT_SUCCESS;
 +              GPU_nodes_extract_dynamic_inputs(sh, &mat->inputs, &mat->nodes);
        }
        else {
 -              if (new_shading_nodes) {
 -                      /* create simple diffuse material instead of nodes */
 -                      outlink = gpu_material_diffuse_bsdf(mat, ma);
 -              }
 -              else {
 -                      /* create blender material */
 -                      outlink = GPU_blender_material(mat, ma);
 -              }
 -
 -              GPU_material_output_link(mat, outlink);
 +              mat->status = GPU_MAT_FAILED;
 +              GPU_pass_free_nodes(&mat->nodes);
 +              GPU_pass_release(mat->pass);
 +              mat->pass = NULL;
        }
 -
 -      if (GPU_material_do_color_management(mat))
 -              if (mat->outlink)
 -                      GPU_link(mat, "linearrgb_to_srgb", mat->outlink, &mat->outlink);
 -
 -      gpu_material_construct_end(mat, ma->id.name);
 -
 -      /* note that even if building the shader fails in some way, we still keep
 -       * it to avoid trying to compile again and again, and simple do not use
 -       * the actual shader on drawing */
 -
 -      link = MEM_callocN(sizeof(LinkData), "GPUMaterialLink");
 -      link->data = mat;
 -      BLI_addtail(&ma->gpumaterial, link);
 -
 -      return mat;
  }
  
- void GPU_materials_free(void)
+ void GPU_materials_free(Main *bmain)
  {
 -      Object *ob;
        Material *ma;
        World *wo;
        extern Material defmaterial;
index 4190303beb9e18a072a16140fefa768aac2ebbd0,617d44a8626c941f16852b7693c01fcb3ed4461d..809de3681dda7ff275e1321240525c8f33e3ed0c
@@@ -214,9 -210,15 +214,9 @@@ static void rna_userdef_load_ui_update(
        else G.fileflags &= ~G_FILE_NO_UI;
  }
  
 -static void rna_userdef_mipmap_update(Main *bmain, Scene *scene, PointerRNA *ptr)
 -{
 -      GPU_set_mipmap(bmain, !(U.gameflags & USER_DISABLE_MIPMAP));
 -      rna_userdef_update(bmain, scene, ptr);
 -}
 -
  static void rna_userdef_anisotropic_update(Main *bmain, Scene *scene, PointerRNA *ptr)
  {
-       GPU_set_anisotropic(U.anisotropic_filter);
+       GPU_set_anisotropic(bmain, U.anisotropic_filter);
        rna_userdef_update(bmain, scene, ptr);
  }
  
index a2142b2d569f11ac4432a3b8c7ef136b0010388e,3324fec4cac86e4d96db630deeb50d28012fd1b1..6b1825edf3e861820a6dcccb7996b85fbf384a67
@@@ -94,9 -84,9 +94,9 @@@ void          WM_exit                         (struct bContext *C) A
  
  void          WM_main                         (struct bContext *C) ATTR_NORETURN;
  
 -bool          WM_init_game            (struct bContext *C);
  void          WM_init_splash          (struct bContext *C);
  
- void          WM_init_opengl          (void);
++void          WM_init_opengl          (struct Main *bmain);
  
  void          WM_check                        (struct bContext *C);
  
index 5efe9330f525ce4c2291757e4bf429057ebd9adc,0f8c49c082d0fa5320c75f069ad25b8743f31358..a7500a55bda34a48880fdbbc4772e7e010c76aca
@@@ -780,8 -940,15 +780,9 @@@ void WM_paint_cursor_tag_redraw(wmWindo
        }
  }
  
 -void WM_paint_cursor_tag_redraw(wmWindow *win, ARegion *ar)
 -{
 -      win->screen->do_draw_paintcursor = true;
 -      wm_tag_redraw_overlay(win, ar);
 -}
 -
  void wm_draw_update(bContext *C)
  {
+       Main *bmain = CTX_data_main(C);
        wmWindowManager *wm = CTX_wm_manager(C);
        wmWindow *win;
  
index a14cbed638128f61ad641a7e36513890657175b6,449a0a91a010c3b87d2e66bfb254654a4d13ba3e..cae0bc066914fc00b30964b553dc6ad81e562156
@@@ -158,42 -153,6 +158,42 @@@ static void wm_free_reports(bContext *C
  
  bool wm_start_with_console = false; /* used in creator.c */
  
- void WM_init_opengl(void)
 +/**
 + * Since we cannot know in advance if we will require the draw manager
 + * context when starting blender in background mode (specially true with
 + * scripts) we deferre the ghost initialization the most as possible
 + * so that it does not break anything that can run in headless mode (as in
 + * without display server attached).
 + **/
 +static bool opengl_is_init = false;
 +
-       GPU_set_mipmap(true);
++void WM_init_opengl(Main *bmain)
 +{
 +      /* must be called only once */
 +      BLI_assert(opengl_is_init == false);
 +
 +      if (G.background) {
 +              /* Ghost is still not init elsewhere in background mode. */
 +              wm_ghost_init(NULL);
 +      }
 +
 +      /* Needs to be first to have an ogl context bound. */
 +      DRW_opengl_context_create();
 +
 +      GPU_init();
-       GPU_set_anisotropic(U.anisotropic_filter);
-       GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
++      GPU_set_mipmap(bmain, true);
 +      GPU_set_linear_mipmap(true);
++      GPU_set_anisotropic(bmain, U.anisotropic_filter);
++      GPU_set_gpu_mipmapping(bmain, U.use_gpu_mipmap);
 +
 +      GPU_pass_cache_init();
 +
 +#ifdef WITH_OPENSUBDIV
 +      BKE_subsurf_osd_init();
 +#endif
 +      opengl_is_init = true;
 +}
 +
  /* only called once, for startup */
  void WM_init(bContext *C, int argc, const char **argv)
  {
                /* sets 3D mouse deadzone */
                WM_ndof_deadzone_set(U.ndof_deadzone);
  #endif
-               WM_init_opengl();
 -
 -              GPU_init();
 -
 -              GPU_set_mipmap(G_MAIN, !(U.gameflags & USER_DISABLE_MIPMAP));
 -              GPU_set_linear_mipmap(true);
 -              GPU_set_anisotropic(G_MAIN, U.anisotropic_filter);
 -              GPU_set_gpu_mipmapping(G_MAIN, U.use_gpu_mipmap);
 -
 -#ifdef WITH_OPENSUBDIV
 -              BKE_subsurf_osd_init();
 -#endif
++              WM_init_opengl(G_MAIN);
  
                UI_init();
 +              BKE_studiolight_init();
        }
        else {
                /* Note: Currently only inits icons, which we now want in background mode too
@@@ -486,16 -545,6 +486,16 @@@ void WM_exit_ext(bContext *C, const boo
        COM_deinitialize();
  #endif
  
-               GPU_free_unused_buffers();
 +      if (opengl_is_init) {
 +#ifdef WITH_OPENSUBDIV
 +              BKE_subsurf_osd_cleanup();
 +#endif
 +
++              GPU_free_unused_buffers(G_MAIN);
 +
 +              GPU_exit();
 +      }
 +
        BKE_blender_free();  /* blender.c, does entire library and spacetypes */
  //    free_matcopybuf();
        ANIM_fcurves_copybuf_free();