Depsgraph: remove EvaluationContext, pass Depsgraph instead.
[blender.git] / source / blender / editors / sculpt_paint / sculpt_undo.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) 2006 by Nicholas Bishop
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  * Implements the Sculpt Mode tools
28  *
29  */
30
31 /** \file blender/editors/sculpt_paint/sculpt_undo.c
32  *  \ingroup edsculpt
33  */
34
35 #include <stddef.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_math.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_string.h"
42 #include "BLI_listbase.h"
43 #include "BLI_ghash.h"
44 #include "BLI_task.h"
45 #include "BLI_threads.h"
46
47 #include "DNA_meshdata_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_space_types.h"
53 #include "DNA_workspace_types.h"
54
55 #include "BKE_ccg.h"
56 #include "BKE_context.h"
57 #include "BKE_multires.h"
58 #include "BKE_paint.h"
59 #include "BKE_key.h"
60 #include "BKE_mesh.h"
61 #include "BKE_subsurf.h"
62 #include "BKE_undo_system.h"
63
64 #include "DEG_depsgraph.h"
65
66 #include "WM_api.h"
67 #include "WM_types.h"
68
69 #include "GPU_buffers.h"
70
71 #include "ED_paint.h"
72 #include "ED_object.h"
73 #include "ED_sculpt.h"
74 #include "ED_undo.h"
75
76 #include "bmesh.h"
77 #include "paint_intern.h"
78 #include "sculpt_intern.h"
79
80
81 typedef struct UndoSculpt {
82         ListBase nodes;
83
84         size_t undo_size;
85 } UndoSculpt;
86
87 static UndoSculpt *sculpt_undo_get_nodes(void);
88
89 static void update_cb(PBVHNode *node, void *rebuild)
90 {
91         BKE_pbvh_node_mark_update(node);
92         if (*((bool *)rebuild))
93                 BKE_pbvh_node_mark_rebuild_draw(node);
94         BKE_pbvh_node_fully_hidden_set(node, 0);
95 }
96
97 struct PartialUpdateData {
98         PBVH *pbvh;
99         bool rebuild;
100 };
101
102 /**
103  * A version of #update_cb that tests for 'ME_VERT_PBVH_UPDATE'
104  */
105 static void update_cb_partial(PBVHNode *node, void *userdata)
106 {
107         struct PartialUpdateData *data = userdata;
108         if (BKE_pbvh_node_vert_update_check_any(data->pbvh, node)) {
109                 update_cb(node, &(data->rebuild));
110         }
111 }
112
113 static bool test_swap_v3_v3(float a[3], float b[3])
114 {
115         /* no need for float comparison here (memory is exactly equal or not) */
116         if (memcmp(a, b, sizeof(float[3])) != 0) {
117                 swap_v3_v3(a, b);
118                 return true;
119         }
120         else {
121                 return false;
122         }
123 }
124
125 static bool sculpt_undo_restore_deformed(
126         const SculptSession *ss,
127         SculptUndoNode *unode,
128         int uindex, int oindex,
129         float coord[3])
130 {
131         if (test_swap_v3_v3(coord, unode->orig_co[uindex])) {
132                 copy_v3_v3(unode->co[uindex], ss->deform_cos[oindex]);
133                 return true;
134         }
135         else {
136                 return false;
137         }
138 }
139
140 static bool sculpt_undo_restore_coords(bContext *C, DerivedMesh *dm, SculptUndoNode *unode)
141 {
142         Scene *scene = CTX_data_scene(C);
143         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
144         Object *ob = CTX_data_active_object(C);
145         Depsgraph *depsgraph = CTX_data_depsgraph(C);
146         SculptSession *ss = ob->sculpt;
147         MVert *mvert;
148         int *index;
149         
150         if (unode->maxvert) {
151                 /* regular mesh restore */
152
153                 if (ss->kb && !STREQ(ss->kb->name, unode->shapeName)) {
154                         /* shape key has been changed before calling undo operator */
155
156                         Key *key = BKE_key_from_object(ob);
157                         KeyBlock *kb = key ? BKE_keyblock_find_name(key, unode->shapeName) : NULL;
158
159                         if (kb) {
160                                 ob->shapenr = BLI_findindex(&key->block, kb) + 1;
161
162                                 BKE_sculpt_update_mesh_elements(depsgraph, scene, sd, ob, 0, false);
163                                 WM_event_add_notifier(C, NC_OBJECT | ND_DATA, ob);
164                         }
165                         else {
166                                 /* key has been removed -- skip this undo node */
167                                 return 0;
168                         }
169                 }
170
171                 /* no need for float comparison here (memory is exactly equal or not) */
172                 index = unode->index;
173                 mvert = ss->mvert;
174
175                 if (ss->kb) {
176                         float (*vertCos)[3];
177                         vertCos = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
178
179                         if (unode->orig_co) {
180                                 if (ss->modifiers_active) {
181                                         for (int i = 0; i < unode->totvert; i++) {
182                                                 sculpt_undo_restore_deformed(ss, unode, i, index[i], vertCos[index[i]]);
183                                         }
184                                 }
185                                 else {
186                                         for (int i = 0; i < unode->totvert; i++) {
187                                                 swap_v3_v3(vertCos[index[i]], unode->orig_co[i]);
188                                         }
189                                 }
190                         }
191                         else {
192                                 for (int i = 0; i < unode->totvert; i++) {
193                                         swap_v3_v3(vertCos[index[i]], unode->co[i]);
194                                 }
195                         }
196
197                         /* propagate new coords to keyblock */
198                         sculpt_vertcos_to_key(ob, ss->kb, vertCos);
199
200                         /* pbvh uses it's own mvert array, so coords should be */
201                         /* propagated to pbvh here */
202                         BKE_pbvh_apply_vertCos(ss->pbvh, vertCos);
203
204                         MEM_freeN(vertCos);
205                 }
206                 else {
207                         if (unode->orig_co) {
208                                 if (ss->modifiers_active) {
209                                         for (int i = 0; i < unode->totvert; i++) {
210                                                 if (sculpt_undo_restore_deformed(ss, unode, i, index[i], mvert[index[i]].co)) {
211                                                         mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
212                                                 }
213                                         }
214                                 }
215                                 else {
216                                         for (int i = 0; i < unode->totvert; i++) {
217                                                 if (test_swap_v3_v3(mvert[index[i]].co, unode->orig_co[i])) {
218                                                         mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
219                                                 }
220                                         }
221                                 }
222                         }
223                         else {
224                                 for (int i = 0; i < unode->totvert; i++) {
225                                         if (test_swap_v3_v3(mvert[index[i]].co, unode->co[i])) {
226                                                 mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
227                                         }
228                                 }
229                         }
230                 }
231         }
232         else if (unode->maxgrid && dm->getGridData) {
233                 /* multires restore */
234                 CCGElem **grids, *grid;
235                 CCGKey key;
236                 float (*co)[3];
237                 int gridsize;
238
239                 grids = dm->getGridData(dm);
240                 gridsize = dm->getGridSize(dm);
241                 dm->getGridKey(dm, &key);
242
243                 co = unode->co;
244                 for (int j = 0; j < unode->totgrid; j++) {
245                         grid = grids[unode->grids[j]];
246
247                         for (int i = 0; i < gridsize * gridsize; i++, co++) {
248                                 swap_v3_v3(CCG_elem_offset_co(&key, grid, i), co[0]);
249                         }
250                 }
251         }
252
253         return 1;
254 }
255
256 static bool sculpt_undo_restore_hidden(
257         bContext *C, DerivedMesh *dm,
258         SculptUndoNode *unode)
259 {
260         Object *ob = CTX_data_active_object(C);
261         SculptSession *ss = ob->sculpt;
262         int i;
263
264         if (unode->maxvert) {
265                 MVert *mvert = ss->mvert;
266                 
267                 for (i = 0; i < unode->totvert; i++) {
268                         MVert *v = &mvert[unode->index[i]];
269                         if ((BLI_BITMAP_TEST(unode->vert_hidden, i) != 0) != ((v->flag & ME_HIDE) != 0)) {
270                                 BLI_BITMAP_FLIP(unode->vert_hidden, i);
271                                 v->flag ^= ME_HIDE;
272                                 v->flag |= ME_VERT_PBVH_UPDATE;
273                         }
274                 }
275         }
276         else if (unode->maxgrid && dm->getGridData) {
277                 BLI_bitmap **grid_hidden = dm->getGridHidden(dm);
278                 
279                 for (i = 0; i < unode->totgrid; i++) {
280                         SWAP(BLI_bitmap *,
281                              unode->grid_hidden[i],
282                              grid_hidden[unode->grids[i]]);
283                         
284                 }
285         }
286
287         return 1;
288 }
289
290 static bool sculpt_undo_restore_mask(bContext *C, DerivedMesh *dm, SculptUndoNode *unode)
291 {
292         Object *ob = CTX_data_active_object(C);
293         SculptSession *ss = ob->sculpt;
294         MVert *mvert;
295         float *vmask;
296         int *index, i, j;
297         
298         if (unode->maxvert) {
299                 /* regular mesh restore */
300
301                 index = unode->index;
302                 mvert = ss->mvert;
303                 vmask = ss->vmask;
304
305                 for (i = 0; i < unode->totvert; i++) {
306                         if (vmask[index[i]] != unode->mask[i]) {
307                                 SWAP(float, vmask[index[i]], unode->mask[i]);
308                                 mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
309                         }
310                 }
311         }
312         else if (unode->maxgrid && dm->getGridData) {
313                 /* multires restore */
314                 CCGElem **grids, *grid;
315                 CCGKey key;
316                 float *mask;
317                 int gridsize;
318
319                 grids = dm->getGridData(dm);
320                 gridsize = dm->getGridSize(dm);
321                 dm->getGridKey(dm, &key);
322
323                 mask = unode->mask;
324                 for (j = 0; j < unode->totgrid; j++) {
325                         grid = grids[unode->grids[j]];
326
327                         for (i = 0; i < gridsize * gridsize; i++, mask++)
328                                 SWAP(float, *CCG_elem_offset_mask(&key, grid, i), *mask);
329                 }
330         }
331
332         return 1;
333 }
334
335 static void sculpt_undo_bmesh_restore_generic_task_cb(
336         void *__restrict userdata,
337         const int n,
338         const ParallelRangeTLS *__restrict UNUSED(tls))
339 {
340         PBVHNode **nodes = userdata;
341
342         BKE_pbvh_node_mark_redraw(nodes[n]);
343 }
344
345 static void sculpt_undo_bmesh_restore_generic(bContext *C,
346                                               SculptUndoNode *unode,
347                                               Object *ob,
348                                               SculptSession *ss)
349 {
350         if (unode->applied) {
351                 BM_log_undo(ss->bm, ss->bm_log);
352                 unode->applied = false;
353         }
354         else {
355                 BM_log_redo(ss->bm, ss->bm_log);
356                 unode->applied = true;
357         }
358
359         if (unode->type == SCULPT_UNDO_MASK) {
360                 int totnode;
361                 PBVHNode **nodes;
362                 Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
363
364                 BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
365
366                 ParallelRangeSettings settings;
367                 BLI_parallel_range_settings_defaults(&settings);
368                 settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
369                 BLI_task_parallel_range(
370                             0, totnode,
371                             nodes,
372                             sculpt_undo_bmesh_restore_generic_task_cb,
373                             &settings);
374
375                 if (nodes)
376                         MEM_freeN(nodes);
377         }
378         else {
379                 sculpt_pbvh_clear(ob);
380         }
381 }
382
383 /* Create empty sculpt BMesh and enable logging */
384 static void sculpt_undo_bmesh_enable(
385         Object *ob, SculptUndoNode *unode)
386 {
387         SculptSession *ss = ob->sculpt;
388         Mesh *me = ob->data;
389
390         sculpt_pbvh_clear(ob);
391
392         /* Create empty BMesh and enable logging */
393         ss->bm = BM_mesh_create(
394                 &bm_mesh_allocsize_default,
395                 &((struct BMeshCreateParams){.use_toolflags = false,}));
396         BM_data_layer_add(ss->bm, &ss->bm->vdata, CD_PAINT_MASK);
397         sculpt_dyntopo_node_layers_add(ss);
398         me->flag |= ME_SCULPT_DYNAMIC_TOPOLOGY;
399
400         /* Restore the BMLog using saved entries */
401         ss->bm_log = BM_log_from_existing_entries_create(ss->bm,
402                                                          unode->bm_entry);
403 }
404
405 static void sculpt_undo_bmesh_restore_begin(bContext *C,
406                                             SculptUndoNode *unode,
407                                             Object *ob,
408                                             SculptSession *ss)
409 {
410         if (unode->applied) {
411                 sculpt_dynamic_topology_disable(C, unode);
412                 unode->applied = false;
413         }
414         else {
415                 sculpt_undo_bmesh_enable(ob, unode);
416
417                 /* Restore the mesh from the first log entry */
418                 BM_log_redo(ss->bm, ss->bm_log);
419
420                 unode->applied = true;
421         }
422 }
423
424 static void sculpt_undo_bmesh_restore_end(bContext *C,
425                                           SculptUndoNode *unode,
426                                           Object *ob,
427                                           SculptSession *ss)
428 {
429         if (unode->applied) {
430                 sculpt_undo_bmesh_enable(ob, unode);
431
432                 /* Restore the mesh from the last log entry */
433                 BM_log_undo(ss->bm, ss->bm_log);
434
435                 unode->applied = false;
436         }
437         else {
438                 /* Disable dynamic topology sculpting */
439                 sculpt_dynamic_topology_disable(C, NULL);
440                 unode->applied = true;
441         }
442 }
443
444 /* Handle all dynamic-topology updates
445  *
446  * Returns true if this was a dynamic-topology undo step, otherwise
447  * returns false to indicate the non-dyntopo code should run. */
448 static int sculpt_undo_bmesh_restore(bContext *C,
449                                      SculptUndoNode *unode,
450                                      Object *ob,
451                                      SculptSession *ss)
452 {
453         switch (unode->type) {
454                 case SCULPT_UNDO_DYNTOPO_BEGIN:
455                         sculpt_undo_bmesh_restore_begin(C, unode, ob, ss);
456                         return true;
457
458                 case SCULPT_UNDO_DYNTOPO_END:
459                         sculpt_undo_bmesh_restore_end(C, unode, ob, ss);
460                         return true;
461
462                 default:
463                         if (ss->bm_log) {
464                                 sculpt_undo_bmesh_restore_generic(C, unode, ob, ss);
465                                 return true;
466                         }
467                         break;
468         }
469
470         return false;
471 }
472
473 static void sculpt_undo_restore_list(bContext *C, ListBase *lb)
474 {
475         Scene *scene = CTX_data_scene(C);
476         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
477         Object *ob = CTX_data_active_object(C);
478         Depsgraph *depsgraph = CTX_data_depsgraph(C);
479         DerivedMesh *dm;
480         SculptSession *ss = ob->sculpt;
481         SculptUndoNode *unode;
482         bool update = false, rebuild = false;
483         bool need_mask = false;
484         bool partial_update = true;
485
486         for (unode = lb->first; unode; unode = unode->next) {
487                 if (STREQ(unode->idname, ob->id.name)) {
488                         if (unode->type == SCULPT_UNDO_MASK) {
489                                 /* is possible that we can't do the mask undo (below)
490                                  * because of the vertex count */
491                                 need_mask = true;
492                                 break;
493                         }
494                 }
495         }
496
497         BKE_sculpt_update_mesh_elements(depsgraph, scene, sd, ob, 0, need_mask);
498
499         /* call _after_ sculpt_update_mesh_elements() which may update 'ob->derivedFinal' */
500         dm = mesh_get_derived_final(depsgraph, scene, ob, 0);
501
502         if (lb->first && sculpt_undo_bmesh_restore(C, lb->first, ob, ss))
503                 return;
504
505         for (unode = lb->first; unode; unode = unode->next) {
506                 if (!STREQ(unode->idname, ob->id.name))
507                         continue;
508
509                 /* check if undo data matches current data well enough to
510                  * continue */
511                 if (unode->maxvert) {
512                         if (ss->totvert != unode->maxvert)
513                                 continue;
514                 }
515                 else if (unode->maxgrid && dm->getGridData) {
516                         if ((dm->getNumGrids(dm) != unode->maxgrid) ||
517                             (dm->getGridSize(dm) != unode->gridsize))
518                         {
519                                 continue;
520                         }
521
522                         /* multi-res can't do partial updates since it doesn't flag edited vertices */
523                         partial_update = false;
524                 }
525
526                 switch (unode->type) {
527                         case SCULPT_UNDO_COORDS:
528                                 if (sculpt_undo_restore_coords(C, dm, unode))
529                                         update = true;
530                                 break;
531                         case SCULPT_UNDO_HIDDEN:
532                                 if (sculpt_undo_restore_hidden(C, dm, unode))
533                                         rebuild = true;
534                                 break;
535                         case SCULPT_UNDO_MASK:
536                                 if (sculpt_undo_restore_mask(C, dm, unode))
537                                         update = true;
538                                 break;
539
540                         case SCULPT_UNDO_DYNTOPO_BEGIN:
541                         case SCULPT_UNDO_DYNTOPO_END:
542                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
543                                 BLI_assert(!"Dynamic topology should've already been handled");
544                                 break;
545                 }
546         }
547
548         if (update || rebuild) {
549                 bool tag_update = false;
550                 /* we update all nodes still, should be more clever, but also
551                  * needs to work correct when exiting/entering sculpt mode and
552                  * the nodes get recreated, though in that case it could do all */
553                 if (partial_update) {
554                         struct PartialUpdateData data = {
555                                 .rebuild = rebuild,
556                                 .pbvh = ss->pbvh,
557                         };
558                         BKE_pbvh_search_callback(ss->pbvh, NULL, NULL, update_cb_partial, &data);
559                 }
560                 else {
561                         BKE_pbvh_search_callback(ss->pbvh, NULL, NULL, update_cb, &rebuild);
562                 }
563                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw, NULL);
564
565                 if (BKE_sculpt_multires_active(scene, ob)) {
566                         if (rebuild)
567                                 multires_mark_as_modified(ob, MULTIRES_HIDDEN_MODIFIED);
568                         else
569                                 multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
570                 }
571
572                 tag_update |= ((Mesh *)ob->data)->id.us > 1;
573
574                 if (ss->kb || ss->modifiers_active) {
575                         Mesh *mesh = ob->data;
576                         BKE_mesh_calc_normals(mesh);
577
578                         BKE_sculptsession_free_deformMats(ss);
579                         tag_update |= true;
580                 }
581
582                 if (tag_update) {
583                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
584                 }
585                 else {
586                         sculpt_update_object_bounding_box(ob);
587                 }
588
589                 /* for non-PBVH drawing, need to recreate VBOs */
590                 GPU_drawobject_free(ob->derivedFinal);
591         }
592 }
593
594 static void sculpt_undo_free_list(ListBase *lb)
595 {
596         SculptUndoNode *unode;
597         int i;
598
599         for (unode = lb->first; unode; unode = unode->next) {
600                 if (unode->co)
601                         MEM_freeN(unode->co);
602                 if (unode->no)
603                         MEM_freeN(unode->no);
604                 if (unode->index)
605                         MEM_freeN(unode->index);
606                 if (unode->grids)
607                         MEM_freeN(unode->grids);
608                 if (unode->orig_co)
609                         MEM_freeN(unode->orig_co);
610                 if (unode->vert_hidden)
611                         MEM_freeN(unode->vert_hidden);
612                 if (unode->grid_hidden) {
613                         for (i = 0; i < unode->totgrid; i++) {
614                                 if (unode->grid_hidden[i])
615                                         MEM_freeN(unode->grid_hidden[i]);
616                         }
617                         MEM_freeN(unode->grid_hidden);
618                 }
619                 if (unode->mask)
620                         MEM_freeN(unode->mask);
621
622                 if (unode->bm_entry) {
623                         BM_log_entry_drop(unode->bm_entry);
624                 }
625
626                 if (unode->bm_enter_totvert)
627                         CustomData_free(&unode->bm_enter_vdata, unode->bm_enter_totvert);
628                 if (unode->bm_enter_totedge)
629                         CustomData_free(&unode->bm_enter_edata, unode->bm_enter_totedge);
630                 if (unode->bm_enter_totloop)
631                         CustomData_free(&unode->bm_enter_ldata, unode->bm_enter_totloop);
632                 if (unode->bm_enter_totpoly)
633                         CustomData_free(&unode->bm_enter_pdata, unode->bm_enter_totpoly);
634         }
635 }
636
637 /* Most likely we don't need this. */
638 #if 0
639 static bool sculpt_undo_cleanup(bContext *C, ListBase *lb)
640 {
641         Object *ob = CTX_data_active_object(C);
642         SculptUndoNode *unode;
643
644         unode = lb->first;
645
646         if (unode && !STREQ(unode->idname, ob->id.name)) {
647                 if (unode->bm_entry)
648                         BM_log_cleanup_entry(unode->bm_entry);
649
650                 return true;
651         }
652
653         return false;
654 }
655 #endif
656
657 SculptUndoNode *sculpt_undo_get_node(PBVHNode *node)
658 {
659         UndoSculpt *usculpt = sculpt_undo_get_nodes();
660
661         if (usculpt == NULL) {
662                 return NULL;
663         }
664
665         return BLI_findptr(&usculpt->nodes, node, offsetof(SculptUndoNode, node));
666 }
667
668 static void sculpt_undo_alloc_and_store_hidden(PBVH *pbvh,
669                                                SculptUndoNode *unode)
670 {
671         PBVHNode *node = unode->node;
672         BLI_bitmap **grid_hidden;
673         int i, *grid_indices, totgrid;
674
675         grid_hidden = BKE_pbvh_grid_hidden(pbvh);
676
677         BKE_pbvh_node_get_grids(pbvh, node, &grid_indices, &totgrid,
678                                 NULL, NULL, NULL);
679                         
680         unode->grid_hidden = MEM_mapallocN(sizeof(*unode->grid_hidden) * totgrid,
681                                            "unode->grid_hidden");
682                 
683         for (i = 0; i < totgrid; i++) {
684                 if (grid_hidden[grid_indices[i]])
685                         unode->grid_hidden[i] = MEM_dupallocN(grid_hidden[grid_indices[i]]);
686                 else
687                         unode->grid_hidden[i] = NULL;
688         }
689 }
690
691 static SculptUndoNode *sculpt_undo_alloc_node(
692         Object *ob, PBVHNode *node,
693         SculptUndoType type)
694 {
695         UndoSculpt *usculpt = sculpt_undo_get_nodes();
696         SculptUndoNode *unode;
697         SculptSession *ss = ob->sculpt;
698         int totvert, allvert, totgrid, maxgrid, gridsize, *grids;
699         
700         unode = MEM_callocN(sizeof(SculptUndoNode), "SculptUndoNode");
701         BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
702         unode->type = type;
703         unode->node = node;
704
705         if (node) {
706                 BKE_pbvh_node_num_verts(ss->pbvh, node, &totvert, &allvert);
707                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
708                                         &maxgrid, &gridsize, NULL);
709
710                 unode->totvert = totvert;
711         }
712         else
713                 maxgrid = 0;
714         
715         /* we will use this while sculpting, is mapalloc slow to access then? */
716
717         /* general TODO, fix count_alloc */
718         switch (type) {
719                 case SCULPT_UNDO_COORDS:
720                         unode->co = MEM_mapallocN(sizeof(float[3]) * allvert, "SculptUndoNode.co");
721                         unode->no = MEM_mapallocN(sizeof(short[3]) * allvert, "SculptUndoNode.no");
722
723                         usculpt->undo_size = (sizeof(float[3]) + sizeof(short[3]) + sizeof(int)) * allvert;
724                         break;
725                 case SCULPT_UNDO_HIDDEN:
726                         if (maxgrid)
727                                 sculpt_undo_alloc_and_store_hidden(ss->pbvh, unode);
728                         else
729                                 unode->vert_hidden = BLI_BITMAP_NEW(allvert, "SculptUndoNode.vert_hidden");
730         
731                         break;
732                 case SCULPT_UNDO_MASK:
733                         unode->mask = MEM_mapallocN(sizeof(float) * allvert, "SculptUndoNode.mask");
734
735                         usculpt->undo_size += (sizeof(float) * sizeof(int)) * allvert;
736
737                         break;
738                 case SCULPT_UNDO_DYNTOPO_BEGIN:
739                 case SCULPT_UNDO_DYNTOPO_END:
740                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
741                         BLI_assert(!"Dynamic topology should've already been handled");
742                         break;
743         }
744         
745         BLI_addtail(&usculpt->nodes, unode);
746
747         if (maxgrid) {
748                 /* multires */
749                 unode->maxgrid = maxgrid;
750                 unode->totgrid = totgrid;
751                 unode->gridsize = gridsize;
752                 unode->grids = MEM_mapallocN(sizeof(int) * totgrid, "SculptUndoNode.grids");
753         }
754         else {
755                 /* regular mesh */
756                 unode->maxvert = ss->totvert;
757                 unode->index = MEM_mapallocN(sizeof(int) * allvert, "SculptUndoNode.index");
758         }
759
760         if (ss->modifiers_active)
761                 unode->orig_co = MEM_callocN(allvert * sizeof(*unode->orig_co), "undoSculpt orig_cos");
762
763         return unode;
764 }
765
766 static void sculpt_undo_store_coords(Object *ob, SculptUndoNode *unode)
767 {
768         SculptSession *ss = ob->sculpt;
769         PBVHVertexIter vd;
770
771         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
772         {
773                 copy_v3_v3(unode->co[vd.i], vd.co);
774                 if (vd.no) copy_v3_v3_short(unode->no[vd.i], vd.no);
775                 else normal_float_to_short_v3(unode->no[vd.i], vd.fno);
776
777                 if (ss->modifiers_active)
778                         copy_v3_v3(unode->orig_co[vd.i], ss->orig_cos[unode->index[vd.i]]);
779         }
780         BKE_pbvh_vertex_iter_end;
781 }
782
783 static void sculpt_undo_store_hidden(Object *ob, SculptUndoNode *unode)
784 {
785         PBVH *pbvh = ob->sculpt->pbvh;
786         PBVHNode *node = unode->node;
787
788         if (unode->grids) {
789                 /* already stored during allocation */
790         }
791         else {
792                 MVert *mvert;
793                 const int *vert_indices;
794                 int allvert;
795                 int i;
796                 
797                 BKE_pbvh_node_num_verts(pbvh, node, NULL, &allvert);
798                 BKE_pbvh_node_get_verts(pbvh, node, &vert_indices, &mvert);
799                 for (i = 0; i < allvert; i++) {
800                         BLI_BITMAP_SET(unode->vert_hidden, i,
801                                           mvert[vert_indices[i]].flag & ME_HIDE);
802                 }
803         }
804 }
805
806 static void sculpt_undo_store_mask(Object *ob, SculptUndoNode *unode)
807 {
808         SculptSession *ss = ob->sculpt;
809         PBVHVertexIter vd;
810
811         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
812         {
813                 unode->mask[vd.i] = *vd.mask;
814         }
815         BKE_pbvh_vertex_iter_end;
816 }
817
818 static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
819                                               PBVHNode *node,
820                                               SculptUndoType type)
821 {
822         UndoSculpt *usculpt = sculpt_undo_get_nodes();
823         SculptSession *ss = ob->sculpt;
824         PBVHVertexIter vd;
825
826         SculptUndoNode *unode = usculpt->nodes.first;
827
828         if (unode == NULL) {
829                 unode = MEM_callocN(sizeof(*unode), __func__);
830
831                 BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
832                 unode->type = type;
833                 unode->applied = true;
834
835                 if (type == SCULPT_UNDO_DYNTOPO_END) {
836                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
837                         BM_log_before_all_removed(ss->bm, ss->bm_log);
838                 }
839                 else if (type == SCULPT_UNDO_DYNTOPO_BEGIN) {
840                         Mesh *me = ob->data;
841
842                         /* Store a copy of the mesh's current vertices, loops, and
843                          * polys. A full copy like this is needed because entering
844                          * dynamic-topology immediately does topological edits
845                          * (converting polys to triangles) that the BMLog can't
846                          * fully restore from */
847                         CustomData_copy(&me->vdata, &unode->bm_enter_vdata, CD_MASK_MESH,
848                                         CD_DUPLICATE, me->totvert);
849                         CustomData_copy(&me->edata, &unode->bm_enter_edata, CD_MASK_MESH,
850                                         CD_DUPLICATE, me->totedge);
851                         CustomData_copy(&me->ldata, &unode->bm_enter_ldata, CD_MASK_MESH,
852                                         CD_DUPLICATE, me->totloop);
853                         CustomData_copy(&me->pdata, &unode->bm_enter_pdata, CD_MASK_MESH,
854                                         CD_DUPLICATE, me->totpoly);
855                         unode->bm_enter_totvert = me->totvert;
856                         unode->bm_enter_totedge = me->totedge;
857                         unode->bm_enter_totloop = me->totloop;
858                         unode->bm_enter_totpoly = me->totpoly;
859
860                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
861                         BM_log_all_added(ss->bm, ss->bm_log);
862                 }
863                 else {
864                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
865                 }
866
867                 BLI_addtail(&usculpt->nodes, unode);
868         }
869
870         if (node) {
871                 switch (type) {
872                         case SCULPT_UNDO_COORDS:
873                         case SCULPT_UNDO_MASK:
874                                 /* Before any vertex values get modified, ensure their
875                                  * original positions are logged */
876                                 BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) {
877                                         BM_log_vert_before_modified(ss->bm_log, vd.bm_vert, vd.cd_vert_mask_offset);
878                                 }
879                                 BKE_pbvh_vertex_iter_end;
880                                 break;
881
882                         case SCULPT_UNDO_HIDDEN:
883                         {
884                                 GSetIterator gs_iter;
885                                 GSet *faces = BKE_pbvh_bmesh_node_faces(node);
886                                 BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) {
887                                         BM_log_vert_before_modified(ss->bm_log, vd.bm_vert, vd.cd_vert_mask_offset);
888                                 }
889                                 BKE_pbvh_vertex_iter_end;
890
891                                 GSET_ITER (gs_iter, faces) {
892                                         BMFace *f = BLI_gsetIterator_getKey(&gs_iter);
893                                         BM_log_face_modified(ss->bm_log, f);
894                                 }
895                                 break;
896                         }
897
898                         case SCULPT_UNDO_DYNTOPO_BEGIN:
899                         case SCULPT_UNDO_DYNTOPO_END:
900                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
901                                 break;
902                 }
903         }
904
905         return unode;
906 }
907
908 SculptUndoNode *sculpt_undo_push_node(
909         Object *ob, PBVHNode *node,
910         SculptUndoType type)
911 {
912         SculptSession *ss = ob->sculpt;
913         SculptUndoNode *unode;
914
915         /* list is manipulated by multiple threads, so we lock */
916         BLI_thread_lock(LOCK_CUSTOM1);
917
918         if (ss->bm ||
919             ELEM(type,
920                  SCULPT_UNDO_DYNTOPO_BEGIN,
921                  SCULPT_UNDO_DYNTOPO_END))
922         {
923                 /* Dynamic topology stores only one undo node per stroke,
924                  * regardless of the number of PBVH nodes modified */
925                 unode = sculpt_undo_bmesh_push(ob, node, type);
926                 BLI_thread_unlock(LOCK_CUSTOM1);
927                 return unode;
928         }
929         else if ((unode = sculpt_undo_get_node(node))) {
930                 BLI_thread_unlock(LOCK_CUSTOM1);
931                 return unode;
932         }
933
934         unode = sculpt_undo_alloc_node(ob, node, type);
935         
936         BLI_thread_unlock(LOCK_CUSTOM1);
937
938         /* copy threaded, hopefully this is the performance critical part */
939
940         if (unode->grids) {
941                 int totgrid, *grids;
942                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
943                                         NULL, NULL, NULL);
944                 memcpy(unode->grids, grids, sizeof(int) * totgrid);
945         }
946         else {
947                 const int *vert_indices;
948                 int allvert;
949                 BKE_pbvh_node_num_verts(ss->pbvh, node, NULL, &allvert);
950                 BKE_pbvh_node_get_verts(ss->pbvh, node, &vert_indices, NULL);
951                 memcpy(unode->index, vert_indices, sizeof(int) * unode->totvert);
952         }
953
954         switch (type) {
955                 case SCULPT_UNDO_COORDS:
956                         sculpt_undo_store_coords(ob, unode);
957                         break;
958                 case SCULPT_UNDO_HIDDEN:
959                         sculpt_undo_store_hidden(ob, unode);
960                         break;
961                 case SCULPT_UNDO_MASK:
962                         sculpt_undo_store_mask(ob, unode);
963                         break;
964                 case SCULPT_UNDO_DYNTOPO_BEGIN:
965                 case SCULPT_UNDO_DYNTOPO_END:
966                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
967                         BLI_assert(!"Dynamic topology should've already been handled");
968                         break;
969         }
970
971         /* store active shape key */
972         if (ss->kb) BLI_strncpy(unode->shapeName, ss->kb->name, sizeof(ss->kb->name));
973         else unode->shapeName[0] = '\0';
974
975         return unode;
976 }
977
978 void sculpt_undo_push_begin(const char *name)
979 {
980         UndoStack *ustack = ED_undo_stack_get();
981         bContext *C = NULL; /* special case, we never read from this. */
982         BKE_undosys_step_push_init_with_type(ustack, C, name, BKE_UNDOSYS_TYPE_SCULPT);
983 }
984
985 void sculpt_undo_push_end(void)
986 {
987         UndoSculpt *usculpt = sculpt_undo_get_nodes();
988         SculptUndoNode *unode;
989
990         /* we don't need normals in the undo stack */
991         for (unode = usculpt->nodes.first; unode; unode = unode->next) {
992                 if (unode->no) {
993                         MEM_freeN(unode->no);
994                         unode->no = NULL;
995                 }
996
997                 if (unode->node)
998                         BKE_pbvh_node_layer_disp_free(unode->node);
999         }
1000
1001         UndoStack *ustack = ED_undo_stack_get();
1002         BKE_undosys_step_push(ustack, NULL, NULL);
1003 }
1004
1005 /* -------------------------------------------------------------------- */
1006 /** \name Implements ED Undo System
1007  * \{ */
1008
1009 typedef struct SculptUndoStep {
1010         UndoStep step;
1011         /* note: will split out into list for multi-object-sculpt-mode. */
1012         UndoSculpt data;
1013 } SculptUndoStep;
1014
1015 static bool sculpt_undosys_poll(bContext *C)
1016 {
1017         ScrArea *sa = CTX_wm_area(C);
1018         if (sa && (sa->spacetype == SPACE_VIEW3D)) {
1019                 Object *obact = CTX_data_active_object(C);
1020                 if (obact && (obact->mode & OB_MODE_SCULPT)) {
1021                         return true;
1022                 }
1023         }
1024         return false;
1025 }
1026
1027 static void sculpt_undosys_step_encode_init(struct bContext *UNUSED(C), UndoStep *us_p)
1028 {
1029         SculptUndoStep *us = (SculptUndoStep *)us_p;
1030         /* dummy, memory is cleared anyway. */
1031         BLI_listbase_clear(&us->data.nodes);
1032 }
1033
1034 static bool sculpt_undosys_step_encode(struct bContext *UNUSED(C), UndoStep *us_p)
1035 {
1036         /* dummy, encoding is done along the way by adding tiles
1037          * to the current 'SculptUndoStep' added by encode_init. */
1038         SculptUndoStep *us = (SculptUndoStep *)us_p;
1039         us->step.data_size = us->data.undo_size;
1040         return true;
1041 }
1042
1043 static void sculpt_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
1044 {
1045         /* TODO(campbell): undo_system: use low-level API to set mode. */
1046         ED_object_mode_set(C, OB_MODE_SCULPT);
1047         BLI_assert(sculpt_undosys_poll(C));
1048
1049         SculptUndoStep *us = (SculptUndoStep *)us_p;
1050         sculpt_undo_restore_list(C, &us->data.nodes);
1051 }
1052
1053 static void sculpt_undosys_step_free(UndoStep *us_p)
1054 {
1055         SculptUndoStep *us = (SculptUndoStep *)us_p;
1056         sculpt_undo_free_list(&us->data.nodes);
1057 }
1058
1059 /* Export for ED_undo_sys. */
1060 void ED_sculpt_undosys_type(UndoType *ut)
1061 {
1062         ut->name = "Sculpt";
1063         ut->poll = sculpt_undosys_poll;
1064         ut->step_encode_init = sculpt_undosys_step_encode_init;
1065         ut->step_encode = sculpt_undosys_step_encode;
1066         ut->step_decode = sculpt_undosys_step_decode;
1067         ut->step_free = sculpt_undosys_step_free;
1068
1069         ut->mode = BKE_UNDOTYPE_MODE_ACCUMULATE;
1070         ut->use_context = true;
1071
1072         ut->step_size = sizeof(SculptUndoStep);
1073 }
1074
1075 /** \} */
1076
1077 /* -------------------------------------------------------------------- */
1078 /** \name Utilities
1079  * \{ */
1080
1081 static UndoSculpt *sculpt_undosys_step_get_nodes(UndoStep *us_p)
1082 {
1083         SculptUndoStep *us = (SculptUndoStep *)us_p;
1084         return &us->data;
1085 }
1086
1087 static UndoSculpt *sculpt_undo_get_nodes(void)
1088 {
1089         UndoStack *ustack = ED_undo_stack_get();
1090         UndoStep *us = BKE_undosys_stack_init_or_active_with_type(ustack, BKE_UNDOSYS_TYPE_SCULPT);
1091         return sculpt_undosys_step_get_nodes(us);
1092 }
1093
1094 /** \} */