Merge branch 'blender2.7'
[blender.git] / source / blender / gpu / intern / gpu_select_pick.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2017 Blender Foundation.
19  * All rights reserved.
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/gpu/intern/gpu_select_pick.c
25  *  \ingroup gpu
26  *
27  * Custom select code for picking small regions (not efficient for large regions).
28  * `gpu_select_pick_*` API.
29  */
30 #include <string.h>
31 #include <stdlib.h>
32 #include <float.h>
33
34 #include "GPU_immediate.h"
35 #include "GPU_draw.h"
36 #include "GPU_select.h"
37 #include "GPU_extensions.h"
38 #include "GPU_glew.h"
39
40 #include "MEM_guardedalloc.h"
41
42 #include "BLI_rect.h"
43 #include "BLI_listbase.h"
44 #include "BLI_math_vector.h"
45 #include "BLI_utildefines.h"
46
47 #include "gpu_select_private.h"
48
49 #include "BLI_strict_flags.h"
50
51 /* #define DEBUG_PRINT */
52
53 /* Alloc number for depths */
54 #define ALLOC_DEPTHS 200
55
56 /* Z-depth of cleared depth buffer */
57 #define DEPTH_MAX 0xffffffff
58
59 /* ----------------------------------------------------------------------------
60  * SubRectStride
61  */
62
63 /* For looping over a sub-region of a rect, could be moved into 'rct.c'*/
64 typedef struct SubRectStride {
65         uint start;     /* start here */
66         uint span;      /* read these */
67         uint span_len;  /* len times (read span 'len' times). */
68         uint skip;      /* skip those */
69 } SubRectStride;
70
71 /* we may want to change back to float if uint isn't well supported */
72 typedef uint depth_t;
73
74 /**
75  * Calculate values needed for looping over a sub-region (smaller buffer within a larger buffer).
76  *
77  * 'src' must be bigger than 'dst'.
78  */
79 static void rect_subregion_stride_calc(const rcti *src, const rcti *dst, SubRectStride *r_sub)
80 {
81         const int src_x = BLI_rcti_size_x(src);
82         // const int src_y = BLI_rcti_size_y(src);
83         const int dst_x = BLI_rcti_size_x(dst);
84         const int dst_y = BLI_rcti_size_y(dst);
85         const int x = dst->xmin - src->xmin;
86         const int y = dst->ymin - src->ymin;
87
88         BLI_assert(src->xmin <= dst->xmin && src->ymin <= dst->ymin &&
89                    src->xmax >= dst->xmax && src->ymax >= dst->ymax);
90         BLI_assert(x >= 0 && y >= 0);
91
92         r_sub->start    = (uint)((src_x * y) + x);
93         r_sub->span     = (uint)dst_x;
94         r_sub->span_len = (uint)dst_y;
95         r_sub->skip     = (uint)(src_x - dst_x);
96 }
97
98 /**
99  * Ignore depth clearing as a change,
100  * only check if its been changed _and_ filled in (ignore clearing since XRAY does this).
101  */
102 BLI_INLINE bool depth_is_filled(const depth_t *prev, const depth_t *curr)
103 {
104         return (*prev != *curr) && (*curr != DEPTH_MAX);
105 }
106
107 /* ----------------------------------------------------------------------------
108  * DepthBufCache
109  *
110  * Result of reading glReadPixels,
111  * use for both cache and non-cached storage.
112  */
113
114 /* store result of glReadPixels */
115 typedef struct DepthBufCache {
116         struct DepthBufCache *next, *prev;
117         uint id;
118         depth_t buf[0];
119 } DepthBufCache;
120
121 static DepthBufCache *depth_buf_malloc(uint rect_len)
122 {
123         DepthBufCache *rect = MEM_mallocN(sizeof(DepthBufCache) + sizeof(depth_t) * rect_len, __func__);
124         rect->id = SELECT_ID_NONE;
125         return rect;
126 }
127
128 static bool depth_buf_rect_depth_any(
129         const DepthBufCache *rect_depth,
130         uint rect_len)
131 {
132         const depth_t *curr = rect_depth->buf;
133         for (uint i = 0; i < rect_len; i++, curr++) {
134                 if (*curr != DEPTH_MAX) {
135                         return true;
136                 }
137         }
138         return false;
139 }
140
141 static bool depth_buf_subrect_depth_any(
142         const DepthBufCache *rect_depth,
143         const SubRectStride *sub_rect)
144 {
145         const depth_t *curr = rect_depth->buf + sub_rect->start;
146         for (uint i = 0; i < sub_rect->span_len; i++) {
147                 const depth_t *curr_end = curr + sub_rect->span;
148                 for (; curr < curr_end; curr++, curr++) {
149                         if (*curr != DEPTH_MAX) {
150                                 return true;
151                         }
152                 }
153                 curr += sub_rect->skip;
154         }
155         return false;
156 }
157
158 static bool depth_buf_rect_depth_any_filled(
159         const DepthBufCache *rect_prev, const DepthBufCache *rect_curr,
160         uint rect_len)
161 {
162 #if 0
163         return memcmp(rect_depth_a->buf, rect_depth_b->buf, rect_len * sizeof(depth_t)) != 0;
164 #else
165         const depth_t *prev = rect_prev->buf;
166         const depth_t *curr = rect_curr->buf;
167         for (uint i = 0; i < rect_len; i++, curr++, prev++) {
168                 if (depth_is_filled(prev, curr)) {
169                         return true;
170                 }
171         }
172         return false;
173 #endif
174 }
175
176 /**
177  * Both buffers are the same size, just check if the sub-rect contains any differences.
178  */
179 static bool depth_buf_subrect_depth_any_filled(
180         const DepthBufCache *rect_src, const DepthBufCache *rect_dst,
181         const SubRectStride *sub_rect)
182 {
183         /* same as above but different rect sizes */
184         const depth_t *prev = rect_src->buf + sub_rect->start;
185         const depth_t *curr = rect_dst->buf + sub_rect->start;
186         for (uint i = 0; i < sub_rect->span_len; i++) {
187                 const depth_t *curr_end = curr + sub_rect->span;
188                 for (; curr < curr_end; prev++, curr++) {
189                         if (depth_is_filled(prev, curr)) {
190                                 return true;
191                         }
192                 }
193                 prev += sub_rect->skip;
194                 curr += sub_rect->skip;
195         }
196         return false;
197 }
198
199 /* ----------------------------------------------------------------------------
200  * DepthID
201  *
202  * Internal structure for storing hits.
203  */
204
205 typedef struct DepthID {
206         uint id;
207         depth_t depth;
208 } DepthID;
209
210 static int depth_id_cmp(const void *v1, const void *v2)
211 {
212         const DepthID *d1 = v1, *d2 = v2;
213         if (d1->id < d2->id) {
214                 return -1;
215         }
216         else if (d1->id > d2->id) {
217                 return 1;
218         }
219         else {
220                 return 0;
221         }
222 }
223
224 static int depth_cmp(const void *v1, const void *v2)
225 {
226         const DepthID *d1 = v1, *d2 = v2;
227         if (d1->depth < d2->depth) {
228                 return -1;
229         }
230         else if (d1->depth > d2->depth) {
231                 return 1;
232         }
233         else {
234                 return 0;
235         }
236 }
237
238 /* depth sorting */
239 typedef struct GPUPickState {
240         /* cache on initialization */
241         uint (*buffer)[4];
242
243         /* buffer size (stores number of integers, for actual size multiply by sizeof integer)*/
244         uint bufsize;
245         /* mode of operation */
246         char mode;
247
248         /* OpenGL drawing, never use when (is_cached == true). */
249         struct {
250                 /* The current depth, accumulated as we draw */
251                 DepthBufCache *rect_depth;
252                 /* Scratch buffer, avoid allocs every time (when not caching) */
253                 DepthBufCache *rect_depth_test;
254
255                 /* Pass to glReadPixels (x, y, w, h) */
256                 int clip_readpixels[4];
257
258                 /* Set after first draw */
259                 bool is_init;
260                 uint prev_id;
261         } gl;
262
263         /* src: data stored in 'cache' and 'gl',
264          * dst: use when cached region is smaller (where src -> dst isn't 1:1) */
265         struct {
266                 rcti clip_rect;
267                 uint rect_len;
268         } src, dst;
269
270         /* Store cache between `GPU_select_cache_begin/end` */
271         bool use_cache;
272         bool is_cached;
273         struct {
274                 /* Cleanup used for iterating over both source and destination buffers:
275                  * src.clip_rect -> dst.clip_rect */
276                 SubRectStride sub_rect;
277
278                 /* List of DepthBufCache, sized of 'src.clip_rect' */
279                 ListBase bufs;
280         } cache;
281
282         /* Pickign methods */
283         union {
284                 /* GPU_SELECT_PICK_ALL */
285                 struct {
286                         DepthID *hits;
287                         uint hits_len;
288                         uint hits_len_alloc;
289                 } all;
290
291                 /* GPU_SELECT_PICK_NEAREST */
292                 struct {
293                         uint *rect_id;
294                 } nearest;
295         };
296 } GPUPickState;
297
298
299 static GPUPickState g_pick_state = {0};
300
301 void gpu_select_pick_begin(
302         uint (*buffer)[4], uint bufsize,
303         const rcti *input, char mode)
304 {
305         GPUPickState *ps = &g_pick_state;
306
307 #ifdef DEBUG_PRINT
308         printf("%s: mode=%d, use_cache=%d, is_cache=%d\n", __func__, mode, ps->use_cache, ps->is_cached);
309 #endif
310
311         ps->bufsize = bufsize;
312         ps->buffer = buffer;
313         ps->mode = mode;
314
315         const uint rect_len = (uint)(BLI_rcti_size_x(input) * BLI_rcti_size_y(input));
316         ps->dst.clip_rect = *input;
317         ps->dst.rect_len = rect_len;
318
319         /* Restrict OpenGL operations for when we don't have cache */
320         if (ps->is_cached == false) {
321                 gpuPushAttrib(GPU_DEPTH_BUFFER_BIT | GPU_VIEWPORT_BIT);
322
323                 /* disable writing to the framebuffer */
324                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
325
326                 glEnable(GL_DEPTH_TEST);
327                 glDepthMask(GL_TRUE);
328
329                 if (mode == GPU_SELECT_PICK_ALL) {
330                         /* Note that other depth settings (such as #GL_LEQUAL) work too,
331                          * since the depth is always cleared.
332                          * Noting this for cases when depth picking is used where drawing calls change depth settings. */
333                         glDepthFunc(GL_ALWAYS);
334                 }
335                 else {
336                         glDepthFunc(GL_LEQUAL);
337                 }
338
339                 float viewport[4];
340                 glGetFloatv(GL_VIEWPORT, viewport);
341
342                 ps->src.clip_rect = *input;
343                 ps->src.rect_len = rect_len;
344
345                 ps->gl.clip_readpixels[0] = (int)viewport[0];
346                 ps->gl.clip_readpixels[1] = (int)viewport[1];
347                 ps->gl.clip_readpixels[2] = BLI_rcti_size_x(&ps->src.clip_rect);
348                 ps->gl.clip_readpixels[3] = BLI_rcti_size_y(&ps->src.clip_rect);
349
350                 glViewport(UNPACK4(ps->gl.clip_readpixels));
351
352                 /* It's possible we don't want to clear depth buffer,
353                  * so existing elements are masked by current z-buffer. */
354                 glClear(GL_DEPTH_BUFFER_BIT);
355
356                 /* scratch buffer (read new values here) */
357                 ps->gl.rect_depth_test = depth_buf_malloc(rect_len);
358                 ps->gl.rect_depth = depth_buf_malloc(rect_len);
359
360                 /* set initial 'far' value */
361 #if 0
362                 glReadPixels(UNPACK4(ps->gl.clip_readpixels), GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, ps->gl.rect_depth->buf);
363 #else
364                 for (uint i = 0; i < rect_len; i++) {
365                         ps->gl.rect_depth->buf[i] = DEPTH_MAX;
366                 }
367 #endif
368
369                 ps->gl.is_init = false;
370                 ps->gl.prev_id = 0;
371         }
372         else {
373                 /* Using cache (ps->is_cached == true) */
374                 /* src.clip_rect -> dst.clip_rect */
375                 rect_subregion_stride_calc(&ps->src.clip_rect, &ps->dst.clip_rect, &ps->cache.sub_rect);
376                 BLI_assert(ps->gl.rect_depth == NULL);
377                 BLI_assert(ps->gl.rect_depth_test == NULL);
378         }
379
380         if (mode == GPU_SELECT_PICK_ALL) {
381                 ps->all.hits = MEM_mallocN(sizeof(*ps->all.hits) * ALLOC_DEPTHS, __func__);
382                 ps->all.hits_len = 0;
383                 ps->all.hits_len_alloc = ALLOC_DEPTHS;
384         }
385         else {
386                 /* Set to 0xff for SELECT_ID_NONE */
387                 ps->nearest.rect_id = MEM_mallocN(sizeof(uint) * ps->dst.rect_len, __func__);
388                 memset(ps->nearest.rect_id, 0xff, sizeof(uint) * ps->dst.rect_len);
389         }
390 }
391
392 /**
393  * Given 2x depths, we know are different - update the depth information
394  * use for both cached/uncached depth buffers.
395  */
396 static void gpu_select_load_id_pass_all(const DepthBufCache *rect_curr)
397 {
398         GPUPickState *ps = &g_pick_state;
399         const uint id = rect_curr->id;
400         /* find the best depth for this pass and store in 'all.hits' */
401         depth_t depth_best = DEPTH_MAX;
402
403 #define EVAL_TEST() \
404         if (depth_best > *curr) { \
405                 depth_best = *curr; \
406         } ((void)0)
407
408         if (ps->is_cached == false) {
409                 const depth_t *curr = rect_curr->buf;
410                 BLI_assert(ps->src.rect_len == ps->dst.rect_len);
411                 const uint rect_len = ps->src.rect_len;
412                 for (uint i = 0; i < rect_len; i++, curr++) {
413                         EVAL_TEST();
414                 }
415         }
416         else {
417                 /* same as above but different rect sizes */
418                 const depth_t *curr = rect_curr->buf + ps->cache.sub_rect.start;
419                 for (uint i = 0; i < ps->cache.sub_rect.span_len; i++) {
420                         const depth_t *curr_end = curr + ps->cache.sub_rect.span;
421                         for (; curr < curr_end; curr++) {
422                                 EVAL_TEST();
423                         }
424                         curr += ps->cache.sub_rect.skip;
425                 }
426         }
427
428 #undef EVAL_TEST
429
430         /* ensure enough space */
431         if (UNLIKELY(ps->all.hits_len == ps->all.hits_len_alloc)) {
432                 ps->all.hits_len_alloc += ALLOC_DEPTHS;
433                 ps->all.hits = MEM_reallocN(ps->all.hits, ps->all.hits_len_alloc * sizeof(*ps->all.hits));
434         }
435         DepthID *d = &ps->all.hits[ps->all.hits_len++];
436         d->id = id;
437         d->depth = depth_best;
438 }
439
440 static void gpu_select_load_id_pass_nearest(const DepthBufCache *rect_prev, const DepthBufCache *rect_curr)
441 {
442         GPUPickState *ps = &g_pick_state;
443         const uint id = rect_curr->id;
444         /* keep track each pixels ID in 'nearest.rect_id' */
445         if (id != SELECT_ID_NONE) {
446                 uint *id_ptr = ps->nearest.rect_id;
447
448                 /* Check against DEPTH_MAX because XRAY will clear the buffer,
449                  * so previously set values will become unset.
450                  * In this case just leave those id's left as-is. */
451 #define EVAL_TEST() \
452                 if (depth_is_filled(prev, curr)) { \
453                         *id_ptr = id; \
454                 } ((void)0)
455
456                 if (ps->is_cached == false) {
457                         const depth_t *prev = rect_prev->buf;
458                         const depth_t *curr = rect_curr->buf;
459                         BLI_assert(ps->src.rect_len == ps->dst.rect_len);
460                         const uint rect_len = ps->src.rect_len;
461                         for (uint i = 0; i < rect_len; i++, curr++, prev++, id_ptr++) {
462                                 EVAL_TEST();
463                         }
464                 }
465                 else {
466                         /* same as above but different rect sizes */
467                         const depth_t *prev = rect_prev->buf + ps->cache.sub_rect.start;
468                         const depth_t *curr = rect_curr->buf + ps->cache.sub_rect.start;
469                         for (uint i = 0; i < ps->cache.sub_rect.span_len; i++) {
470                                 const depth_t *curr_end = curr + ps->cache.sub_rect.span;
471                                 for (; curr < curr_end; prev++, curr++, id_ptr++) {
472                                         EVAL_TEST();
473                                 }
474                                 prev += ps->cache.sub_rect.skip;
475                                 curr += ps->cache.sub_rect.skip;
476                         }
477                 }
478
479 #undef EVAL_TEST
480         }
481 }
482
483
484 bool gpu_select_pick_load_id(uint id)
485 {
486         GPUPickState *ps = &g_pick_state;
487         if (ps->gl.is_init) {
488                 const uint rect_len = ps->src.rect_len;
489                 glReadPixels(UNPACK4(ps->gl.clip_readpixels), GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, ps->gl.rect_depth_test->buf);
490                 /* perform initial check since most cases the array remains unchanged  */
491
492                 bool do_pass = false;
493                 if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
494                         if (depth_buf_rect_depth_any(ps->gl.rect_depth_test, rect_len)) {
495                                 ps->gl.rect_depth_test->id = ps->gl.prev_id;
496                                 gpu_select_load_id_pass_all(ps->gl.rect_depth_test);
497                                 do_pass = true;
498                         }
499                 }
500                 else {
501                         if (depth_buf_rect_depth_any_filled(ps->gl.rect_depth, ps->gl.rect_depth_test, rect_len)) {
502                                 ps->gl.rect_depth_test->id = ps->gl.prev_id;
503                                 gpu_select_load_id_pass_nearest(ps->gl.rect_depth, ps->gl.rect_depth_test);
504                                 do_pass = true;
505                         }
506                 }
507
508                 if (do_pass) {
509                         /* Store depth in cache */
510                         if (ps->use_cache) {
511                                 BLI_addtail(&ps->cache.bufs, ps->gl.rect_depth);
512                                 ps->gl.rect_depth = depth_buf_malloc(ps->src.rect_len);
513                         }
514
515                         SWAP(DepthBufCache *, ps->gl.rect_depth, ps->gl.rect_depth_test);
516
517                         if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
518                                 /* we want new depths every time */
519                                 glClear(GL_DEPTH_BUFFER_BIT);
520                         }
521                 }
522         }
523
524         ps->gl.is_init = true;
525         ps->gl.prev_id = id;
526
527         return true;
528 }
529
530 uint gpu_select_pick_end(void)
531 {
532         GPUPickState *ps = &g_pick_state;
533
534 #ifdef DEBUG_PRINT
535         printf("%s\n", __func__);
536 #endif
537
538         if (ps->is_cached == false) {
539                 if (ps->gl.is_init) {
540                         /* force finishing last pass */
541                         gpu_select_pick_load_id(ps->gl.prev_id);
542                 }
543                 gpuPopAttrib();
544                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
545         }
546
547         /* assign but never free directly since it may be in cache */
548         DepthBufCache *rect_depth_final;
549
550         /* Store depth in cache */
551         if (ps->use_cache && !ps->is_cached) {
552                 BLI_addtail(&ps->cache.bufs, ps->gl.rect_depth);
553                 ps->gl.rect_depth = NULL;
554                 rect_depth_final = ps->cache.bufs.last;
555         }
556         else if (ps->is_cached) {
557                 rect_depth_final = ps->cache.bufs.last;
558         }
559         else {
560                 /* common case, no cache */
561                 rect_depth_final = ps->gl.rect_depth;
562         }
563
564         uint maxhits = g_pick_state.bufsize;
565         DepthID *depth_data;
566         uint depth_data_len = 0;
567
568         if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
569                 depth_data = ps->all.hits;
570                 depth_data_len = ps->all.hits_len;
571                 /* move ownership */
572                 ps->all.hits = NULL;
573                 ps->all.hits_len = 0;
574                 ps->all.hits_len_alloc = 0;
575         }
576         else {
577                 /* GPU_SELECT_PICK_NEAREST */
578
579                 /* Over alloc (unlikely we have as many depths as pixels) */
580                 uint depth_data_len_first_pass = 0;
581                 depth_data = MEM_mallocN(ps->dst.rect_len * sizeof(*depth_data), __func__);
582
583                 /* Partially de-duplicating copy,
584                  * when contiguous ID's are found - update their closest depth.
585                  * This isn't essential but means there is less data to sort. */
586
587 #define EVAL_TEST(i_src, i_dst) \
588                 { \
589                         const uint id = ps->nearest.rect_id[i_dst]; \
590                         if (id != SELECT_ID_NONE) { \
591                                 const depth_t depth = rect_depth_final->buf[i_src]; \
592                                 if (depth_last == NULL || depth_last->id != id) { \
593                                         DepthID *d = &depth_data[depth_data_len_first_pass++]; \
594                                         d->id = id; \
595                                         d->depth = depth; \
596                                 } \
597                                 else if (depth_last->depth > depth) { \
598                                         depth_last->depth = depth; \
599                                 } \
600                         } \
601                 } ((void)0)
602
603                 {
604                         DepthID *depth_last = NULL;
605                         if (ps->is_cached == false) {
606                                 for (uint i = 0; i < ps->src.rect_len; i++) {
607                                         EVAL_TEST(i, i);
608                                 }
609                         }
610                         else {
611                                 /* same as above but different rect sizes */
612                                 uint i_src = ps->cache.sub_rect.start, i_dst = 0;
613                                 for (uint j = 0; j < ps->cache.sub_rect.span_len; j++) {
614                                         const uint i_src_end = i_src + ps->cache.sub_rect.span;
615                                         for (; i_src < i_src_end; i_src++, i_dst++) {
616                                                 EVAL_TEST(i_src, i_dst);
617                                         }
618                                         i_src += ps->cache.sub_rect.skip;
619                                 }
620                         }
621                 }
622
623 #undef EVAL_TEST
624
625                 qsort(depth_data, depth_data_len_first_pass, sizeof(DepthID), depth_id_cmp);
626
627                 /* Sort by ID's then keep the best depth for each ID */
628                 depth_data_len = 0;
629                 {
630                         DepthID *depth_last = NULL;
631                         for (uint i = 0; i < depth_data_len_first_pass; i++) {
632                                 if (depth_last == NULL || depth_last->id != depth_data[i].id) {
633                                         depth_last = &depth_data[depth_data_len++];
634                                         *depth_last = depth_data[i];
635                                 }
636                                 else if (depth_last->depth > depth_data[i].depth) {
637                                         depth_last->depth = depth_data[i].depth;
638                                 }
639                         }
640                 }
641         }
642
643         /* Finally sort each unique (id, depth) pair by depth
644          * so the final hit-list is sorted by depth (nearest first) */
645         uint hits = 0;
646
647         if (depth_data_len > maxhits) {
648                 hits = (uint)-1;
649         }
650         else {
651                 /* leave sorting up to the caller */
652                 qsort(depth_data, depth_data_len, sizeof(DepthID), depth_cmp);
653
654                 for (uint i = 0; i < depth_data_len; i++) {
655 #ifdef DEBUG_PRINT
656                         printf("  hit: %u: depth %u\n", depth_data[i].id,  depth_data[i].depth);
657 #endif
658                         /* first 3 are dummy values */
659                         g_pick_state.buffer[hits][0] = 1;
660                         g_pick_state.buffer[hits][1] = 0x0;  /* depth_data[i].depth; */ /* unused */
661                         g_pick_state.buffer[hits][2] = 0x0;  /* z-far is currently never used. */
662                         g_pick_state.buffer[hits][3] = depth_data[i].id;
663                         hits++;
664                 }
665                 BLI_assert(hits < maxhits);
666         }
667
668         MEM_freeN(depth_data);
669
670         MEM_SAFE_FREE(ps->gl.rect_depth);
671         MEM_SAFE_FREE(ps->gl.rect_depth_test);
672
673         if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
674                 /* 'hits' already freed as 'depth_data' */
675         }
676         else {
677                 MEM_freeN(ps->nearest.rect_id);
678                 ps->nearest.rect_id = NULL;
679         }
680
681         if (ps->use_cache) {
682                 ps->is_cached = true;
683         }
684
685         return hits;
686 }
687
688 /* ----------------------------------------------------------------------------
689  * Caching
690  *
691  * Support multiple begin/end's reusing depth buffers.
692  */
693
694 void gpu_select_pick_cache_begin(void)
695 {
696         BLI_assert(g_pick_state.use_cache == false);
697 #ifdef DEBUG_PRINT
698         printf("%s\n", __func__);
699 #endif
700         g_pick_state.use_cache = true;
701         g_pick_state.is_cached = false;
702 }
703
704 void gpu_select_pick_cache_end(void)
705 {
706 #ifdef DEBUG_PRINT
707         printf("%s: with %d buffers\n", __func__, BLI_listbase_count(&g_pick_state.cache.bufs));
708 #endif
709         g_pick_state.use_cache = false;
710         g_pick_state.is_cached = false;
711
712         BLI_freelistN(&g_pick_state.cache.bufs);
713 }
714
715 /* is drawing needed? */
716 bool gpu_select_pick_is_cached(void)
717 {
718         return g_pick_state.is_cached;
719 }
720
721 void gpu_select_pick_cache_load_id(void)
722 {
723         BLI_assert(g_pick_state.is_cached == true);
724         GPUPickState *ps = &g_pick_state;
725 #ifdef DEBUG_PRINT
726         printf("%s (building depth from cache)\n", __func__);
727 #endif
728         for (DepthBufCache *rect_depth = ps->cache.bufs.first; rect_depth; rect_depth = rect_depth->next) {
729                 if (rect_depth->next != NULL) {
730                         /* we know the buffers differ, but this sub-region may not.
731                          * double check before adding an id-pass */
732                         if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
733                                 if (depth_buf_subrect_depth_any(rect_depth->next, &ps->cache.sub_rect)) {
734                                         gpu_select_load_id_pass_all(rect_depth->next);
735                                 }
736                         }
737                         else {
738                                 if (depth_buf_subrect_depth_any_filled(rect_depth, rect_depth->next, &ps->cache.sub_rect)) {
739                                         gpu_select_load_id_pass_nearest(rect_depth, rect_depth->next);
740                                 }
741                         }
742                 }
743         }
744 }